1ère Générale NSI

 

Term. Générale NSI

 

Terminale STI2D SIN

Bts Ccst

Technico-commercial 3.0

[[{"text":"

Chaîne d'information


\"\"


","title":"","posi":0},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"
  1. L'information source est d'abord acquise grâce à un capteur, qui va effectuer des mesures de la grandeur physique d'intérêt. Le capteur produit, comme résultat de ses mesures, un signal électrique de type logique, analogique ou numérique.
  2. Le signal produit par le capteur est ensuite traité, typiquement par un programme exécuté sur un microcontrôleur, dans le cadre de petits systèmes, voire sur un ordinateur plus puissant, doté d'un ou plusieurs microprocesseurs, pour de gros systèmes.
  3. Enfin, une fois le signal traité, vient une phase de communication du résultat du traitement. L'information peut, par exemple, être restituée sous forme d'une visualisation, après avoir été stockée dans une base de données. Un autre scénario possible est l'envoi d'une consigne vers un système, pour commander une action ou configurer des paramètres de ce dernier.
\"Chaine
La chaine d'information commence par l'acquisition d'une mesure de la grandeur physique d'intérêt, puis vient un traitement des données collectées et enfin, une communication des résultats du traitement.


","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Acquérir des données du capteur


La première étape de la chaine de transmission consiste donc en l'acquisition de données à partir des différents capteurs choisis. Dans le cadre du système développé dans ce cours, trois capteurs ont été choisis et présentés dans le chapitre précédent. La température est mesurée à l'aide d'un LM35, l'humidité relative à l'aide d'un DHT11 et, enfin, le niveau sonore avec un module de détection sonore.

Pour choisir le capteur le plus adéquat, pour mesurer une grandeur physique donnée, plusieurs critères peuvent être pris en compte :

  • Il faut évidemment d'abord vérifier que la plage de mesures du capteur couvre les valeurs qu'il faudra être capable de mesurer, dans le cadre du système développé.
  • Ensuite, il faut s'intéresser aux éventuelles contraintes imposées par le projet, et s'assurer que les caractéristiques du capteur soient compatibles avec ces dernières. Il se peut, par exemple, qu'un certain niveau de précision, qu'une résolution minimale ou encore qu'un temps de réponse minimal soit imposé.
  • On peut également prendre en compte les caractéristiques en lien avec la qualité du capteur, telles que sa fiabilité, sa fidélité ou encore sa gamme de températures d'utilisation. En fonction du système développé, un simple capteur pourrait suffire, ou alors il se peut qu'il faille monter en qualité.
  • Enfin, il ne faut pas non plus négliger le prix du capteur, notamment par rapport au budget total prévu pour développer le système. Ce budget pourrait être plus faible dans le cadre d'un prototype et ensuite plus élevé dans le cadre d'une version plus avancée, une fois que la preuve de concept a été faite et validée.

On peut aussi s'intéresser au nombre de capteurs qui seront nécessaires pour le système à développer. Comme on l'a vu au chapitre précédent, certains capteurs peuvent mesurer plusieurs grandeurs physiques, comme le DHT11 qui mesure l'humidité relative et la température. N'avoir qu'un capteur au lieu de deux peut rendre plus faciles les traitements effectués dans la suite de la chaine d'information, pour autant que ses caractéristiques satisfont les demandes du projet, évidemment. Cette question particulière de la mesure de la température, avec le LM35 ou le DHT11 est abordée plus loin, à la section 2.3.

Enfin, il faut également s'assurer que les différents capteurs choisis sont compatibles entre eux, le plus possible en tout cas, notamment par rapport à leur type de signal de sortie et à leurs tensions d' alimentation possibles. Au plus il y aura de l'hétérogénéité, au plus la suite de la chaine d'information sera complexe à réaliser.

Donner la liste des capteurs du kit arduino. 

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Traiter des données par l'Arduino


La deuxième étape de la chaine de transmission consiste donc à traiter les données qui proviennent des capteurs. Cette étape est typiquement réalisée par un programme exécuté sur une machine, que ce soit un simple microcontrôleur ou un ordinateur plus puissant composé d'un ou plusieurs microprocesseurs.

Le but de cette étape est de récupérer toutes les données provenant de plusieurs capteurs pour les traiter, et pour les analyser et prendre des décisions. Le traitement des données consiste en une interprétation des signaux électriques reçus des capteurs, selon leur type. Les données de type numérique vont souvent nécessiter plus de travail que les données logiques ou analogiques. On peut également, parfois, devoir transformer, interpréter ou vérifier les données reçues. Rappelez-vous, par exemple, du DHT11, vu à la section 1.3, qui envoie des trames de 40 bits contenant les valeurs mesurées de l'humidité relative et de la température (chacune sur 16 bits), ainsi qu'un code de 8 bits utilisé pour vérifier s'il y a eu des erreurs de transmission sur le bus 1-Wire. Le traitement des données provenant de ce capteur nécessitera beaucoup de travail.

Dans ce cours, on va travailler avec l'Arduino Uno , présentée sur la figure 2, une simple carte électronique open source sur laquelle se trouve un microcontrôleur ATmega328P d'architecture Atmel, autour duquel se trouvent toute une série d'autres composants, qui vont faciliter sa programmation et son interfaçage avec d'autres circuits extérieurs.

\"Arduino
L'Arduino Uno est une simple carte électronique open source composée d'un microcontrôleur ATmega328P et d'une série de composants facilitant sa programmation et son interfaçage avec d'autres circuits extérieurs.

L'Arduino possède de nombreuses pins, lui permettant de communiquer avec d'autres circuits, notamment des capteurs. L'Arduino Uno possède précisément 14\" role=\"presentation\" style=\"display: inline; line-height: normal; text-align: left; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; position: relative;\">14 pins numériques et 6\" role=\"presentation\" style=\"display: inline; line-height: normal; text-align: left; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; position: relative;\">6 pins analogiques, toutes capables de fonctionner en entrée ou en sortie. D'autres versions de l'Arduino possèdent un plus grand nombre de pins. La tension de fonctionnement de ces 20\" role=\"presentation\" style=\"display: inline; line-height: normal; text-align: left; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; position: relative;\">20 pins est de 5 V, la même que celle de l'Arduino. On pourra donc aisément utiliser les trois capteurs que l'on a sélectionné pour le système de surveillance sonore développé dans ce cours.

Enfin, l'Arduino se programme très facilement grâce à l' environnement de développement intégré Arduino IDE et au langage de programmation Arduino, une version spécifique du langage C++, avec une librairie standard contenant des fonctions spécifiques à l'Arduino. Un programme Arduino, appelé sketch, est compilé puis chargé sur le microcontrôleur de l'Arduino pour y être exécuté. Un sketch se compose de trois parties, inspirées du langage de programmation Processing : (a) une partie en-tête, avec notamment des imports de librairies et des définitions de variables globales, (b) la fonction d'initialisation (setup) exécutée une seule fois au lancement du sketch, (c) et, enfin, la fonction boucle principale (loop) dont le contenu est exécuté en boucle, se répétant indéfiniment.

La figure 3 montre un exemple de sketch Arduino, qui fait clignoter une LED connectée à la pin numérique 7\" role=\"presentation\" style=\"display: inline; line-height: normal; text-align: left; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; position: relative;\">7, en produisant un signal électrique qui alterne entre un signal haut et un signal bas, en attendant une seconde entre les transitions :

  • Dans l'en-tête du sketch, on définit simplement le mot LED comme étant équivalent à 7\" role=\"presentation\" style=\"display: inline; line-height: normal; text-align: left; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; position: relative;\">7, le numéro de la pin numérique sur laquelle la LED a été connectée.
  • Dans la fonction d'initialisation, on configure la pin~7\" role=\"presentation\" style=\"display: inline; line-height: normal; text-align: left; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; position: relative;\">7 en mode sortie, à l'aide de la fonction pinMode, c'est-à-dire que le microcontrôleur de l'Arduino va pouvoir envoyer un signal vers le monde extérieur via cette pin, en l'occurrence alimenter ou non la LED avec une tension de 5 V.
  • Enfin, dans la fonction boucle principale, on va répéter indéfiniment quatre opérations : (a) envoyer un signal haut vers la pin~7\" role=\"presentation\" style=\"display: inline; line-height: normal; text-align: left; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; position: relative;\">7 avec la fonction digitalWrite, appelée avec HIGH comme second paramètre, (b) attendre 1000 ms, c'est-à-dire une seconde, (c) envoyer un signal bas vers la pin~7\" role=\"presentation\" style=\"display: inline; line-height: normal; text-align: left; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; position: relative;\">7, de nouveau avec digitalWrite, mais appelée cette fois-ci avec LOW comme second paramètre, (d) et, enfin, encore attendre 1000 ms.

Ce très simple exemple de sketch vous montre la facilité avec laquelle on peut programmer la carte électronique Arduino Uno.

1
#define LED 7
2
3
void setup() {
4
    pinMode(LED, OUTPUT);
5
}
6
7
void loop() {
8
    digitalWrite(LED, HIGH);
9
    delay(1000);
10
    digitalWrite(LED, LOW);
11
    delay(1000);
12
}
Un sketch Arduino se compose de trois parties, à savoir une en-tête, la fonction d'initialisation qui s'exécute une fois au lancement et la fonction boucle principale dont le contenu se répète en boucle indéfiniment.

Avec l'Arduino Uno, on va donc pouvoir, sans problèmes, collecter les données provenant du LM35, du DHT11 et du module de détection sonore, dans le cadre du système de surveillance du niveau sonore aux alentours d'un aéroport développé dans ce livre. On verra comment traiter les données envoyées par chacun des capteurs dans la section 2.2.

Donner des exemples de microcontroller. 

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Communiquer des données vers l'extérieur


La dernière étape de la chaine de transmission est la communication des données qui ont été collectées, analysées et traitées. Elle peut prendre plusieurs formes, selon la communication qui est faite.

Une première possibilité de communication est l'envoi d'une consigne, ou d'un signal de commande, depuis la machine qui a traité les données du capteur vers une autre machine, un appareil, un moteur, etc. Par exemple, un thermostat mesure la température ambiante et la compare ensuite avec une température seuil configurée. Si la température mesurée est inférieure au seuil, le thermostat envoie un signal vers la chaudière pour la démarrer, pour chauffer la pièce.

La communication peut aussi simplement consister en l'envoi des données collectées vers une autre machine, plus puissante, qui va pouvoir faire des traitements plus avancés. Par exemple, un serveur dans le cloud peut stocker des données reçues et proposer une interface de visualisation de ces dernières, sous forme d'un dashboard. La figure 4 montre un exemple de dashboard qui présente des données d'inscriptions à un collège. Il a été généré sur le service cloud Visualize Free (disponible ici : https://www.visualizefree.com), qui permet de gratuitement réaliser des visualisations.


Donner des exemples d'interfaces hommes machines 

","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

Application 1

Plug and Play Unboxing Demo

The Grove Beginner Kit has a plug and plays unboxing demo, where you first plug in the power to the board, you get the chance to experience all the sensors in one go! Use the button and rotary potentiometer to experience each sensor demo!

\"\"

  • Scroll -> Rotating Rotary Potentiometer
  • Select -> Short Press Button
  • Exit Current Demo -> Long Press Button

Buzzer and LED module are used for key prompt.



","title":""},{"edit":"

Mettre le résultat ici (code et figure).

"}],[{"text":"

How to Get Started With Arduino

Install the Arduino IDE

  • Arduino IDE is an integrated development environment for Arduino, which is used for single-chip microcomputer software programming, downloading, testing and so on.
  • Download and Install Arduino IDE for your desired operating system here.

\"\"

Install the USB driver

  • Arduino connects to the PC via a USB cable. The USB driver depends on the type of USB chip you're using on your Arduino. Note: USB chips are usually printed on the back of the development board.

  • Download the CP2102 USB DriverNote: Download according to your OS.

  • After the driver installation is completed, connect Arduino to the USB port of PC with a USB cable.
    • For Windows users: You can see it in My Computer -> Properties -> Hardware -> Device Management. A COM will appear.
    • For Mac OS users: You can navigate to  on the top left corner, and choose About this Mac -> System Report... -> USB. A CP2102 USB Driver should appear.
  • If the driver is not installed, or if the driver is installed incorrectly (not matching the chip model), it will appear as an \"unknown device\" in the device manager. At this point, the driver should be reinstalled.

Start the Arduino IDE

1.Open the Arduino IDE on your PC. 2.Click on Tools -> Board-> Arduino AVR Boards-> Arduino Uno to select the correct Development Board Model. Select Arduino Uno as Board.

\"\"

3.Click Tools -> Port to select the correct Port (the Serial Port showed in Device Manager in the previous step). In this case, COM11 is selected. For Mac OS users, it should be /dev/cu.SLAB_USBtoUART.

\"\"

4.Create a new Arduino file and name it Hello.ino, then copy the following code into it:

void setup() {
Serial.begin(9600); // initializes the serial port with a baud rate of 9600
}
void loop() {
Serial.println(\"hello, world\"); // prints a string to a serial port
delay(1000); //delay of 1 second
}

5.In the upper left corner of the Arduino IDE, there are two buttons, Verify and Upload. First, press the Verify button(✓) to compile. After the compilation is successful, press the upload button(→).

\"\"

6.Navigate to Tools -> Serial Monitor, or click the Serial Monitor in the upper right corner(Magnifier Symbol), you can see the program running results:

\"\"

Note: If you installed the portable Arduino IDE from our USB Drive, you can find all the module demos in the Files -> Sketch Book, as well as all the module libraries, are pre-installed with Arduino IDE!

\"\"

Note: All modules are pre-wired on a single circuit board, so no cables and soldering are needed. However, if you break out the modules and want to connect them with Grove cables, please kindly check the Breakout Guide.

"},{"edit":" "}],[{"text":"

Application 2 : Blinking with the LED

We have completed the output \"Hello world\" program. Now let's learn how to light the LED module. We know the three basic components of a control system: Input, Control, and Output. But lighting up LED uses only the output, not the input. Seeeduino is the control unit, the LED module is the output unit and the output signal is a digital signal.

Background Information:

  • What is Digital Signal

Digital signal: Digital signal refers to the value of the amplitude is discrete, the amplitude is limited to a finite number of values. In our controller, the digital signal has two states: LOW(0V) for 0; HIGH(5V) for 1. So sending a HIGH signal to LED can light it up.

\"Alt

  • Components Involved
    1. Seeeduino Lotus
    2. Grove LED
    3. Grove Cable(If Broken out)

\"\"

  • Hardware connection

    • Module connection
      • Default connection by PCB stamp hole.
    • Connect the Seeeduino to the computer through the USB cable.
  • Software Code

    • Open Arduino IDE.
    • Copy the following code, click Verify to check for syntax errors. Verify that there are no errors, and you can upload the code.
//LED Blink
//The LED will turn on for one second and then turn off for one second
int ledPin = 4;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}
  • Code Analysis
setup(){
}

The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start using libraries, etc. The setup() function will only run once, after each powerup or reset of the Arduino board.

loop(){
}

After creating a setup() function, which initializes and sets the initial values, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board.

int ledPin = 4;\n

Description:

Converts a value to the int data type.

Syntax:

int(x) or (int)x (C-style type conversion)

Parameters:

x: a value. Allowed data types: any type.

Assigned an int type 4 to variable named ledPin.

pinMode(ledPin, OUTPUT);\n

Description:

Configures the specified pin to behave either as an input or an output. See the Digital Pins page for details on the functionality of the pins.

As of Arduino 1.0.1, it is possible to enable the internal pull-up resistors with the mode INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pullups.

Syntax:

pinMode(pin, mode)

Parameters:

pin: the Arduino pin number to set the mode of.

modeINPUTOUTPUT, or INPUT_PULLUP.

Setting ledPin to the output mode.

digitalWrite(ledPin, HIGH);\n

Description:

Write a HIGH or a LOW value to a digital pin.

If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.

If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the internal pullup on the input pin. It is recommended to set the pinMode() to INPUT_PULLUP to enable the internal pull-up resistor. See the Digital Pins tutorial for more information.

If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling digitalWrite(HIGH), the LED may appear dim. Without explicitly setting pinMode(), digitalWrite() will have enabled the internal pull-up resistor, which acts as a large current-limiting resistor.

Syntax:

digitalWrite(pin, value)

Parameters:

pin: the Arduino pin number.

valueHIGH or LOW.

When we set the ledPin as output, HIGH means sending high level to the pin, LED turns on.

digitalWrite(ledPin, LOW);\n

When we set the led as output, low stands for sending low level to the pin, LED turns off.

delay(1000);\n

Description:

Pauses the program for the amount of time (in milliseconds) specified as a parameter. (There are 1000 milliseconds in a second.)

Syntax:

delay(ms)

Parameters:

ms: the number of milliseconds to pause. Allowed data types: unsigned long.

Delay the program by 1000ms(1s).

Demo Effect and Serial Print Result:

The LED module will be 1 second on and 1 second off.

LED Brightness Adjustment:


On the Grove LED module, there is a variable resistor that can be adjusted using a screw driver. Twist it to make the LED light up brighter!

  • Breakout Guide

If modules are broken out from the board. Use a Grove cable to connect the Grove LED to Seeeduino Lotus's digital interface D4.


"},{"edit":" "}],[{"text":"

Application 3: Pressing Button to Light Up LED

The first thing we need to know is that the input of the button is a digital signal, and there are only two states, 0 or 1, so we can control the output based on those two states.

  • Practice: Use button to turn ON and OFF the LED module

  • Components Involved

    1. Seeeduino Lotus
    2. Grove LED
    3. Grove Button
    4. Grove Cables(If broken out)

\"\"

  • Hardware connection

    • Module connection:
      • Default connection by PCB stamp hole.
    • The Seeeduino is then connected to the computer via a USB cable.
  • Hardware analysis:

    • Input: Button
    • Control: Seeeduino
    • Output: LED module

Both the sensor and the LED use digital signals, so they should be connected to digital interfaces.

  • Software code:
    • Open Arduino IDE.
    • Copy the following code, click Verify to check for syntax errors. Verify that there are no errors, and you can upload the code.
//Button to turn ON/OFF LED
//Constants won't change. They're used here to set pin numbers:
const int buttonPin = 6; // the number of the pushbutton pin
const int ledPin = 4; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
  • Code Analysis
pinMode(ledPin, OUTPUT);\n

Define LED as the output unit.

pinMode(buttonPin, INPUT);\n

Define button as the input unit.

buttonState = digitalRead(buttonPin);\n

Description:

Reads the value from a specified digital pin, either HIGH or LOW.

Syntax:

digitalRead(pin)

Parameters:

pin: the Arduino pin number you want to read

This function is used to read the states of digital pins, either HIGH or LOW. When the button is pressed, the state is HIGH, otherwise is LOW.

if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}

Description:

The if…​else allows greater control over the flow of code than the basic if statement, by allowing multiple tests to be grouped. An else clause (if at all exists) will be executed if the condition in the if statement results in false. The else can proceed another if test, so that multiple, mutually exclusive tests can be run at the same time.

Each test will proceed to the next one until a true test is encountered. When a true test is found, its associated block of code is run, and the program then skips to the line following the entire if/else construction. If no test proves to be true, the default else block is executed, if one is present, and sets the default behaviour.

Note that an else if block may be used with or without a terminating else block and vice versa. An unlimited number of such else if branches are allowed.

Syntax:

if (condition1) {
// do Thing A
}
else if (condition2) {
// do Thing B
}
else {
// do Thing C
}

The usage of the statement is: if the logical expression in parentheses is true, execute the statement in curly braces after if, if not, execute the statement in curly braces after the else. If the state of the button is high, the LED pin outputs a high level and turn the LED on, else turn LED off.

Demo Effect and Serial Print Result:

Pressing the button will turn the LED module on.

  • Breakout Guide

Use a Grove cable to connect the Grove LED to Seeeduino Lotus's digital interface D4. Connect the Grove Button to digital interface D6.


"},{"edit":" "}],[{"text":"

Application 4: Controlling the Frequency of the Blink

In the last section, we studied that button only has two states, ON/OFF state corresponding 0V and 5V, but in practice, we often counter the need for many states, not just 0V and 5V. Then you need to use Analog Signal! Rotary Potentiometer is a classic example that uses an analog signal.

Background Information:

  • What is Analog Signal

Analog signals: Signals vary continuously in time and value, and the amplitude, frequency, or phase of the signal changes continuously at any time, such as the current broadcast sound signal, or image signal, etc. The analog signal has sine wave and triangle wave and so on. The analog pins of your microcontroller can have between 0V and 5V is mapped to a range between 0 and 1023 where 1023 is mapped as 5V and 512 is mapped as 2.5v and etc.

\"Alt

  • Components Involved
    1. Seeeduino Lotus
    2. Grove LED
    3. Grove Rotary Switch
    4. Grove Cables(If broken out)

\"\"

  • Hardware connection

    • Module connection:
      • Default connection by PCB stamp hole.
    • The Seeeduino is then connected to the computer via a USB cable.
  • Hardware analysis:

    • Input: Rotary Potentiometer
    • Control: Seeeduino Lotus
    • Output: LED module

The input is an analog signal, so it is connected to the analog signal interface, the LED module is connected to the digital signal interface.

  • Software Code
    • Open Arduino IDE.
    • Copy the following code, click Verify to check for syntax errors. Verify that there are no errors, and you can upload the code.
//Rotary controls LED
int rotaryPin = A0; // select the input pin for the rotary
int ledPin = 4; // select the pin for the LED
int rotaryValue = 0; // variable to store the value coming from the rotary
void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
pinMode(rotaryPin, INPUT);
}
void loop() {
// read the value from the sensor:
rotaryValue = analogRead(rotaryPin);
// turn the ledPin on
digitalWrite(ledPin, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(rotaryValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(rotaryValue);
}
  • Code Analysis

int rotaryPin = A0; // select the input pin for the rotary
int ledPin = 4; // select the pin for the LED
Description:

You may find that we define rotatePin and ledPin in different ways. This is because Rotary Potentiometer generates an analog signal, and the LED is controlled by a digital signal.

To define for Analog Pin, use A + the number of the Pin (For Example here A0).

To define for Digital Pin, use just the number of the pin (For Example here 4).

rotaryValue = analogRead(rotaryPin);\n

Description:

Reads the value from the specified analog pin. Arduino boards contain a multichannel, 10-bit analog to digital converter. This means that it will map input voltages between 0 and the operating voltage(5V or 3.3V) into integer values between 0 and 1023. On an Arduino UNO, for example, this yields a resolution between readings of: 5 volts / 1024 units or, 0.0049 volts (4.9 mV) per unit.

Syntax:

analogRead(pin)

Parameters:

pin: the name of the analog input pin to read from (A0 to A5 on most boards).

Returns: The analog reading on the pin. Although it is limited to the resolution of the analog to digital converter (0-1023 for 10 bits or 0-4095 for 12 bits). Data type: int.

This function is used to read the value of Analog pins(the rotary sensor position), the range of values is: 0 ~ 1023.

delay(rotaryValue);\n

Delay function, The millisecond duration of the delay is the value in parentheses. Because the value is the value of the analog signal of the knob pin being read, so the delay time can be controlled by the knob.

Demo Effect and Serial Print Result:

Turning the Potentiometer will change the frequency of LED flickering.

  • Breakout Guide

Use a Grove cable to connect LED to Seeeduino Lotus's digital interface D4, and a Grove cable to connect the Grove Rotary Switch to analog signal interface A0.


"},{"edit":" "}],[{"text":"

Application 5: Displaying Data on OLED

OLED Display can be used for many situations, where you could use it to visualize sensor readings!

Background Information:

  • What is Arduino Libraries

The Arduino environment can be extended through the use of libraries, just like most other programming platforms. Libraries provide extra functionalities for use in sketches, i.e. working with specific hardware or manipulating data. To use a library in a sketch, select it from Sketch ->Include Library.

\"\"

For more information, please also visit How to install Arduino Libraries.

  • Components Involved
    1. Seeeduino Lotus
    2. Grove OLED
    3. Grove cable(If broken out)

\"\"

  • Hardware connection

    • Module connection:
      • Default connection by PCB stamp hole.
    • The Seeeduino is then connected to the computer via a USB cable.
  • Software Code

    • Open Arduino IDE.
    • Install the U8g2 library: Navigate to Sketch -> Include Library -> Manage Libraries... and Search for the keyword \"U8g2\" in the Library Manager. It's the u8g2 library by oliver, and click then install.

\"\"

  • Copy the following code, click Verify to check for syntax errors. Verify that there are no errors, and you can upload the code.
#include <Arduino.h>
#include <U8x8lib.h>
U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
// U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // OLEDs without Reset of the Display
void setup(void) {
//u8x8.setBusClock(100000); // If you breakout other modules, please enable this line
u8x8.begin();
u8x8.setFlipMode(1);
}
void loop(void) {
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8.setCursor(0, 0);
u8x8.print(\"Hello World!\");
}

Attention

If you breakout all the modules and use the Grove OLED separately, you may find it won't work with this code. If you encounter such a problem, please refer to the end of this section: Breakout Guide.

  • Code analysis
#include <>\n

Description:

#include is used to include outside libraries in your sketch. This gives the programmer access to a large group of standard C libraries (groups of pre-made functions), and also libraries written especially for Arduino.

Note that #include, similar to #define, has no semicolon terminator, and the compiler will yield cryptic error messages if you add one.

#include <U8x8lib.h>\n

#include is an instruction that introduces a header file. Here we use the U8x8lib.h library.

U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);  \n

Note

If you break out other modules and only use OLED, you have to software I2C:

// U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);

Description:

Once the object is declared, you can use functions from the library.

u8x8.begin();\n

Description:

Simplified setup procedure of the display for the Arduino environment. See the setup guide for the selection of a suitable U8g2 constructor.

Syntax:

u8x8.begin()

Initialize the u8g2 library

u8x8.setFlipMode(1);\n

Description:

Some displays support a 180-degree rotation of the internal frame buffer. This hardware feature can be controlled with this procedure. Important: Redraw the complete display after changing the flip mode. Best is to clear the display first, then change the flip mode and finally redraw the content. Results will be undefined for any existing content on the screen.

Syntax:

u8x8.setFlipMode(mode)

Parameters:

mode0 or 1

Flips the display 180 degrees.

u8x8.setCursor();\n

Description:

Define the cursor for the print function. Any output of the print function will start at this position.

Syntax:

u8x8.setCursor(x, y)

Parameters:

x, y: Column/row position for the cursor of the print function.

Sets the draw cursor position.

u8x8.setFont()\n

Description:

Define a u8x8 font for the glyph and string drawing functions.

Syntax:

u8x8.setFont(font_8x8)

Set the font for display.

u8x8.print();\n

Draw the content on the OLED.

Demo Effect and Serial Print Result:

Prints Hello World onto the OLED Display.

U8g2 Library Reference

If you want to more information about U8g2 library, please refer to here.

  • Breakout Guide

Use Grove cable to connect the OLED to Seeeduino Lotus's I2C interface (Note: I2C's default address is 0x78).

Note

  • If you breakout other modoule to use the OLED and it do not work, or you want to use fastest OLED I2C (default: 40KHZ), please follow this instrcution:

Click \"This PC\" -> Documents -> Arduino -> libraries -> U8g2 -> src -> U8x8lib.cpp -> Sliding to 1334 line -> delete or disable this line -> save the file.

Wire.setClock(u8x8->bus_clock);   // just delete or disable this line\n

Or you can set the bus lock to 100000 then add in the setup().

void setup(void) {
u8x8.setBusClock(100000); // it for limit the I2C bus clock
u8x8.begin();
u8x8.setFlipMode(1);
}
\n

"},{"edit":" "}],[{"text":"
Source :
https://wiki.seeedstudio.com/Grove-Beginner-Kit-For-Arduino/
"},{"edit":" "}]]

En poursuivant votre navigation sur mon site, vous acceptez l’utilisation des Cookies et autres traceurs  pour réaliser des statistiques de visites et enregistrer sur votre machine vos activités pédagogiques. En savoir plus.