Flashing MicroPython Firmware with esptool.py on ESP32 and ESP8266
This posts shows how to flash MicroPython firmware on ESP32/ESP8266 boards using the esptool.py. It works on Windows, Mac OS X, and Linux. For the official documentation, you can visit the esptool.py GitHub page.
Tip: for an easier method to flash the ESP32/ESP8266 with MicroPython, we recommend reading this guide to flash MicroPython with uPyCraft IDE. However, we’ve recently received comments from our readers about having trouble installing/using uPyCraft IDE. For that reason, we’re posting an alternative method using the esptool.py software.
Installing esptool.py in your computer
To work with esptool.py, you’ll need either Python 2.7, Python 3.4 or a newer Python installation on your system. We recommend using Python 3.7.X, so go to Python’s website and install it in your computer.
With Python 3 installed, open a Terminal window and install the latest stable esptool.py release with pip:
pip install esptool
Note: with some Python installations that command may not work and you’ll receive an error. If that’s the case, try to install esptool.py with:
pip3 install esptool
python -m pip install esptool
pip2 install esptool
After installing, you will have esptool.py installed into the default Python executables directory and you should be able to run it with the command esptool.py. In your Terminal window, run the following command:
esptool.py
If it was installed properly, it should display a similar message (regardless of your operating system):
With esptool.py installed in your computer, you can easily flash your ESP32 or ESP8266 boards with the MicroPython firmware. This post is divided in two parts, read Part 1 or Part 2 depending on your board:
Part 1 – ESP32
Part 2 – ESP8266
Note: after installing MicroPython firmware on your ESP32 or ESP8266, you can go back and use Arduino IDE again. You just need to upload code using Arduino IDE. Then, if you want to use MicroPython again, you need to flash MicroPython firmware.
[Part 1 – ESP32] Downloading and Flashing the MicroPython Firmware on ESP32
To download the latest version of MicroPython firmware for the ESP32, go to the MicroPython Downloads page and scroll all the way down to the ESP32 section.
You should see a similar web page (see figure below) with the latest link to download the ESP32 .bin file – for example: esp32-20181007-v1.9.4-631-g338635ccc.bin.
Note: if you’re using a different board (like a PyBoard, WiPy, or other), go to MicroPython Downloads page and download the right firmware for your board.
Finding the Serial Port Name
It’s a bit different to find the Serial port name in each operating system, so for simplicity reasons we recommend finding your ESP serial port name through the Arduino IDE. Follow these steps:
Connect your board to your computer
Open the Arduino IDE
Go to Tools > Port
Save your ESP32 serial port name (in our case it’s COM7)
Close your Arduino IDE software
Important: if you plug your ESP32 board to your computer, but you can’t find the ESP32 Port available in your Arduino IDE, it might be one of these two problems: 1. USB drivers missing or 2. USB cable without data wires.
1. If you don’t see your ESP’s COM port available, this often means you don’t have the USB drivers installed. Take a closer look at the chip next to the voltage regulator on board and check its name.
Go to Google and search for your specific chip to find the drivers and install them in your operating system.
You can download the CP2102 drivers on the Silicon Labs website.
After they are installed, restart the Arduino IDE and you should see the serial port in the Tools > Port menu.
2. If you have the drivers installed, but you can’t see your device, double-check that you’re using a USB cable with data wires.
USB cables from powerbanks often don’t have data wires (they are charge only). So, your computer will never establish a serial communication with your ESP32. Using a proper USB cable should solve your problem.
Finding your MicroPython .bin file
After downloading the ESP32 .bin file, it should be in your Downloads folder. So, with your Terminal window, you’ll need to navigate to the Downloads folder using the cd command:
cd Downloads
List all files in your Downloads folder to ensure that’s where the .bin file is located. In Windows, you use:
dir
On Mac OS X or Linux, run the next command:
ls
As you can see in the preceding screenshot, the ESP32 .bin file is located in the Downloads folder: esp32-20190113-v1.9.4-779-g5064df207.bin.
Erasing ESP32 Flash Memory
Before flashing the MicroPython firmware, you need to erase the ESP32 flash memory. So, with your ESP32 connected to your computer, hold-down the “BOOT/FLASH” button in your ESP32 board:
While holding down the “BOOT/FLASH” button, run the following command to erase the ESP32 flash memory:
esptool.py --chip esp32 erase_flash
When the “Erasing” process begins, you can release the “BOOT/FLASH” button. After a few seconds, the ESP32 flash memory will be erased.
Note: if after the “Connecting …” message you keep seeing new dots appearing, it means that your ESP32 is not in flashing mode. You need to repeat all the steps described earlier and hold the “BOOT/FLASH” button again to ensure that your ESP32 goes into flashing mode and completes the erasing process successfully.
Flashing MicroPython Firmware on ESP32 with esptool.py
With your ESP32 flash memory erased, you can finally flash the MicroPython firmware. You need your serial port name (COM7 in our case) and the ESP32 .bin file location. Replace the next command with your details:
Hold down the “BOOT/FLASH“, before running the flash command. After a few seconds this is what you should see:
Your ESP32 was successfully flashed with MicroPython firmware!
Note: if you receive an error trying to flash the firmware, run the command again and make sure you are holding down the ESP32 “BOOT/FLASH” button.
[Part 2 – ESP8266] Downloading and Flashing the MicroPython Firmware on ESP8266
To download the latest version of MicroPython firmware for the ESP8266, go to the MicroPython Downloads page and scroll all the way down to the ESP8266 section.
You should see a similar web page (see figure below) with the latest link to download the ESP8266 .bin file – for example: esp8266-20180511-v1.9.4.bin.
Note: if you’re using a different board (like a PyBoard, WiPy, or other), go to MicroPython Downloads page and download the right firmware for your board.
Finding the Serial Port Name
It’s a bit different to find the Serial port name in each operating system, so for simplicity reasons we recommend finding your ESP serial port name through the Arduino IDE. Follow these steps:
Connect your board to your computer
Open the Arduino IDE
Go to Tools > Port
Save your ESP8266 serial port name (in our case it’s COM4)
Close your Arduino IDE software
Important: if you plug your ESP8266 board to your computer, but you can’t find the ESP8266 Port available in your Arduino, it might be one of these two problems: 1. USB drivers missing or 2. USB cable without data wires.
1. If you don’t see your ESP’s COM port available, this often means you don’t have the USB drivers installed. Take a closer look at the chip next to the voltage regulator on board and check its name.
Go to Google and search for your specific chip to find the drivers and install them in your operating system.
You can download the CP2102 drivers on the Silicon Labs website.
After they are installed, restart the Arduino IDE and you should see the serial port in the Tools > Port menu.
2. If you have the drivers installed, but you can’t see your device, double-check that you’re using a USB cable with data wires.
USB cables from powerbanks often don’t have data wires (they are charge only). So, your computer will never establish a serial communication with your ESP8266. Using a proper USB cable should solve your problem.
Finding your MicroPython .bin file
After downloading the ESP8266 .bin file, it should be in your Downloads folder. So, with your Terminal window, you’ll need to navigate to the Downloads folder using the cd command:
cd Downloads
List all files in your Downloads folder to ensure that’s where the .bin file is located. In Windows, you use:
dir
On Mac OS X or Linux, run the next command:
ls
As you can see in the preceding screenshot, the ESP8266 .bin file is located in the Downloads folder: esp8266-20180511-v1.9.4.bin.
Erasing ESP8266 Flash Memory
Before flashing the MicroPython firmware, you need to erase the ESP8266 flash memory. So, with your ESP8266 connected to your computer, hold-down the “BOOT/FLASH” button in your ESP8266 board:
While holding down the “BOOT/FLASH” button, run the following command to erase the ESP8266 flash memory:
esptool.py --chip esp8266 erase_flash
When the “Erasing” process begins, you can release the “BOOT/FLASH” button. After a few seconds, the ESP8266 flash memory will be erased.
Note: if after the “Connecting …” message you keep seeing new dots appearing, it means that your ESP8266 is not in flashing mode. You need to repeat all the steps described earlier and hold the “BOOT/FLASH” button again to ensure that your ESP8266 goes into flashing mode and completes the erasing process successfully.
Flashing MicroPython Firmware on ESP8266 with esptool.py
With your ESP8266 flash memory erased, you can finally flash the MicroPython firmware. You need your serial port name (COM7 in our case) and the ESP8266 .bin file location. Replace the next command with your details:
Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »
Enjoyed this project? Stay updated by subscribing our newsletter!
9 thoughts on “Flashing MicroPython Firmware with esptool.py on ESP32 and ESP8266”
Worked perfectly while using Thonny 3.1.2 on Ubuntu; watch out for the micro USB cable without the data wires!! (luckily I have like 10 cables)
A way to check if your issue is with your cable is before you plug in the ESP, type in terminal lsusb and then plug in your ESP and type lsusb again and compare the two. If nothing changes try another cable.
Great ! I tried once and work perfectly For me as beginner I suggest to add commands “pip install rshell” then “rshell -p COMx repl” once flashing completed, so beginner can test the micropython firmware on their board.
Hello and thank you. This is the tutorial that works on the first connection. Only info to USB cables, I will confirm what has already been mentioned and all USB cables need to be sorted and marked, or for example divided into plastic bags, together only charging and together data and some older ones can also be thrown away in separate collection.
The firmware download page for the ESP32, https://micropython.org/download/esp32/ offers multiple versions of the firmware. The most current version at this time, esp32-20210418-v1.15.bin, is missing some standard modules, including urequests. You can install the urequests module (from PyPI) in the /lib folder of your ESP32 using “Manage packages…” under the “Tools” tab of Thonny. You will be offered multiple choices. I’m currently testing micropython-urequests, version 0.9.1 from Paul Sokolovsky.
Furthermore, in some situations, such as using the _thread module for multithreading, you can expect problems that differ depending on the firmware that you are using on the ESP32. In my situation, using firmware: esp32-idf4-20210202-v1.14.bin or esp32-idf3-20210202-v1.14.bin results in corruption of the WiFi DNS settings and OSErrors in the urequest modules packaged in those firmware versions. Others see this on other boards: https://github.com/micropython/micropython/issues/6492
Le PHP : Hypertext Preprocessor, est un langage de programmation libre, principalement utilisé pour produire des pages Web dynamiques via un serveur HTTP.
Vous travaillerez avec le vps sur ovhcloud.
Donnez l'acronyme de vps:
","title":"PHP et Interaction Client-serveur","tagtitle":"h1"},{"edit":"
Réponse ici.
"}],[{"text":"
Le PHP, acronyme récursif pour PHPHypertext Preprocessor est un langage de scripts spécialement conçu pour le développement d'applications web. Il peut être intégré facilement au HTML.
Le langage PHP a été créé en 1994 par Rasmus Lerdorf, un programmeur groenlandais et canadien pour son site web personnel.
Un exemple de code PHP
On petit exemple en PHP qui
Calcule la somme de deux varariables, $var1=5 et $var2=7 ;
Affiche la somme avec la fonction avec la fonction echo ;
Calcule et affiche la somme de deux entiers choisis aléatoirement entre 1 et 100, avec la fonction rand(1 , 100).
<!DOCTYPEhtml>
<html>
<head>
<title>
Exemple de variables
</title>
<metacharset=\"utf-8\"/>
</head>
<body>
<h1> Un premier programme en PHP : pour les tests</h1>
<?php
// Commentaires en php
// Utilisation de variables, avec le dollard $
$var1=5;
$var2=7;
$somme=$var1+$var2;
// echo permet d'afficher sur la page
// On peut méler du texte et des variables
echo \"<p>La somme de $var1 et $var2 est $somme.</p>\";
$nombre1=rand(1,100); // rand(a,b) génère un entier aléatoire entre a et b (inclus)
echo \"<p>Le 1er nombre choisi au hasard est $nombre1.</p>\";
$nombre2=rand(1,100);
echo \"<p>Le 2e nombre choisi au hasard est $nombre2.</p>\";
$somme=$nombre1+$nombre2;
// On affiche la somme
echo \"<p>La somme de $nombre1 et $nombre2 est $somme.</p>\";
L'affichage en PHP utilise la fonction echo \" texte et $variables \". On peut afficher du texte et des variables $var simultanément très simplement.
Les lignes se terminent par un point virgule ;.
Les variables se définissent avec le dollard $var1 et peuvent s'intégrer facilement au texte.
Petit exercice important
Affichez le code source (Click droit) de la page PHP-Exemple1.php.
Vous remarquez que le code source propose juste l'affichage, sans les lignes de code PHP.
Actualisez la page, on voit que le contenu change car la fonction rand(1 , 100) est appelée.
C'est magique, le client, c'est à dire notre ordinateur ne s'aperçoit pas qu'il y a un calcul d'effectué
"},{"edit":" Mettre le résultat ici. "}],[{"text":"
Un fonctionnement distant
Le PHP fonctionne en fait sur serveur distant. On ne peut pas avoir un fonctionnement immédiat sur notre disque comme avec le HTML, le CSS ou le JavaScript.
Ce qui distingue PHP des langages de script comme le Javascript, est que le code est exécuté sur le serveur, générant ainsi le HTML, qui sera ensuite envoyé au client. Le client ne reçoit que le résultat du script, sans aucun moyen d'avoir accès au code qui a produit ce résultat. Vous pouvez configurer votre serveur web afin qu'il analyse tous vos fichiers HTML comme des fichiers PHP. Ainsi, il n'y a aucun moyen de distinguer les pages qui sont produites dynamiquement des pages statiques.
le serveur doit donc être capable de repérer les parties de codes PHP, cela se fera grâce à des balises. Le code PHP est donc inclus entre une balise de début <?php et une balise de fin ?> qui permettent au serveur web de passer en mode PHP, ce que ne fait pas votre navigateur sur votre disque dur.
","title":""},{"edit":"
Mettre le résultat ici (code et figure).
"}],[{"text":"
Le fonctionnement du PHP
Vous pouvez maintenant tranquillement lire cette page qui expose le fonctionnement du PHP.
Il va donc nous falloir préparer un environement de travail afin de pouvoir lire les fichiers PHP.
Plusieurs solutions sont possibles, si vous avez déjà un site en ligne, tout sera plus facile, sinon, vous allez devoir installer plusieurs émulateurs de serveurs distants.
Cas 1 : j'ai un site en ligne
Si vous avez un site en ligne, tout est très simple, il vous suffit d'envoyer vos fichiers sur votre espace et de les ouvrir via votre navigateur. Chaque site à un interpréteur PHP.
Pour télécharger facilement vos fichiers, vous pouvez :
Soit vous connecter chez votre hébergeur ;
Soit utiliser un client FTP. Je vous conseil d'installer FileZilla, gratuit et très simple d'utilisation. Il vous faudra cependant récuprérer chez votre hébergeur vos identifiants de connexion. C'est un peu long la première fois mais ensuite c'est très rapide.
Il ne suffit pas d'ouvrir un fichier avec son navigateur pour que cela fonctionne, on doit généralement lancer l'émulateur puis tapper dans son navigateur :
http://localhost/MonFichier.php
WampServeur
Création automatique d’un répertoire « www » lors de l’installation (typiquement c:\\wamp\\www).
Créez un sous répertoire pour votre projet et déposez-y vos fichiers PHP
Cliquez sur le lien « Localhost » du menu de WampServer ou ouvrez votre navigateur à l’adresse :
http://localhost/MonFichier.php
Bases de données. Au lancement de PhpMyAdmin, il vous sera demandé un nom utilisateur et un mot de passe. Après installation de Wampserver 3,
le nom utilisateur par défaut est \"root\" (Sans les guillemets)
et il n'y a pas de mot de passe, ce qui veut dire que vous devez laisser la case Mot de passe du formulaire d'accès vide.
Xampp
Placer les projets dans le dossier htdocs qui est dans C:\\xampp\\htdocs
Pour ouvrir un fichier nommé MonFichier.php qui est dans le répertoire htdocs, tapper dans votre navigateur :
http://localhost/MonFichier.php
Bases de données. Pour accéder à la base de données => Admin Mysql
","title":""},{"edit":"
Mettre le résultat ici (code et figure).
"}],[{"text":" On code ici :
— un petit formulaire HTML
— et sa réponse en PHP.
Créer une page form1.html sur le serveur:
<!doctypehtml>
<html>
<head>
<metacharset=\"utf-8\"/>
<title>
Formulaire html
</title>
</head>
<body>
<formaction=\"reponse.php\"method=\"GET\">
Votre nom :<inputtype=\"text\"name=\"nom\">
Votre âge :<inputtype=\"text\"name=\"age\">
<br>
<inputtype=submitvalue=\"Envoyer\">
</form>
</body>
</html>
Créer une page réponse.php et mettre le code ci-dessous:
<!doctypehtml>
<html>
<head>
<metacharset=\"utf-8\"/>
<title>
Test Formulaire PHP
</title>
</head>
<body>
<h1>Bonjour, <?php echo $_GET['nom'] ?></h1>
<h2>Vous semblez avoir <?php echo $_GET['age'] ?></h2>
<?php
$n = $_GET['nom'];
$a = $_GET['age'];
?>
Votre nom est stocké dans la variable $n
dont le type est <?php echo gettype($n) ?>
(suite sur la page suivante)
Votre âge est stocké dans la variable <b>$a</b>
<br/> dont le type est <i><?php echo gettype($a); ?></i>
<br/> On peut la transformer en <i>integer</i> en faisant :
<?php settype($a,\"integer\"); ?>
<br/>
Type de $a :<?php echo gettype($a); ?>
</body>
</html>
Lancer la page form1.html
Remplisser les différents champ et cliquer sur le bouton.
","title":"Un formulaire HTML et sa réponse en PHP"},{"edit":"
Mettre le résultat ici.
"}],[{"text":"
Déclaration simple avec $:
<?php
$variable = \"une variable en PHP\";
// Une autre variable :
$Variable = 1000;
?>
Existence de variables, la fonction isset() :
<?php
$a = \"une variable en PHP\";
if(isset($a)) echo \"la variable a existe\";
unset($a);
echo \"la variable a a été supprimée ...\";
?>
Test de variables, la fonction empty() :
<?php
$a = \"une variable en PHP\";
if (!empty($a)) echo \" La variable existe et elle n\\'est
pas vide !\";
?>
Attention: La fonction empty() répond vrai si la variable n’existe pas et ceci sans faire aucun warning!
Portée des variables:
- Par défaut, toutes les variables sont locales.
- Leur portée se réduit à la fonction ou au bloc de leur déclaration
— Pour déclarer une variable globale, on peut utiliser le tableau $_GLOBALS[]
<?php $_GLOBALS['MaVar']=\"Bonjour\"; ?>
Constante:
<?php
define(\"USER\",\"TOTO\");
echo USER; // Notez l'absence de $ ici
?>
Tester le code ci-dessous.
","title":"Les variables en PHP"},{"edit":"
Mettre le résultat ici (code et figure).
"}],[{"text":"
Les bases :
Guillemets \" ou Cotes' :
<?php
$var=\"Hello PHP\";
$machaine=\"le contenu de \\$var est $var<br>\";
echo $machaine;
//ou avec des ' ':
$mystring='le contenu de $var est '.$var;
echo $mystring;
?>
dont le résultat sera toujours:
le contenu de $var est Hello PHP
La concaténation :
A l’aide de .
<?php
$a = \"bonjour\";
$b = \"monde\";
echo $a.\" le \".$b;
?>
La longueur d’une chaine:
<?php int lg=strlen($chaine); ?>
Accéder au caractère i d’une chaine :
<?php echo $chaine[i]; ?>
La chaine est traitée comme un tableau indéxé par un entier
La plupart des tableaux de PHP sont indéxés par des chaines...
Mettre en majuscules/minuscules :
— avec strtoupper() pour obtenir des majuscules
— avec strtolower() pour mettre en minuscules
— avec ucfirst() pour mettre en majuscule la première lettre d’une chaine
— avec ucwords() pour mettre en majuscule la première lettre de chaque mot dans une
chaine
","title":"Les chaînes en PHP"},{"edit":"
Mettre le résultat ici (code et figure).
"}],[{"text":"Ecrire un programme php avec une condition.","title":"Les conditions","tagtitle":"h1"},{"edit":"
Mettre le résultat ici (code et figure).
"}],[{"text":"Ecrire un programme php avec une boucle for, while et do while.","title":"Les boucles"},{"edit":"
Mettre le résultat ici (code et figure).
"}],[{"text":"Ecrire un programme php avec une fonction.","title":"Les fonctions"},{"edit":"
Grove Beginner Kit for Arduino is one of the best Arduino Beginner Kit for beginners. It includes one Arduino compatible Board and 10 additional Arduino sensors and all in one-piece of PCB design. All the modules have been connected to the Seeeduino through the PCB stamp holes so no Grove cables are needed to connect. Of course, you can also take the modules out and use Grove cables to connect the modules. You can build any Arduino project you like with this Grove Beginner Kit For Arduino.
Grove - OLED Display 0.96": 128×64 dot resolution High brightness,self-emission and high contrast ratio Big screen on a compact design Low power consumption.
Note: By default, Grove modules are connected to Seeeduino via PCB stamp holes. This means you don't need to use Grove cables to connect if not broken out. The default pins are as follow:
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!
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.
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 Driver. Note: 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.
1.Open the Arduino IDE on your PC. 2.Click on Tools -> Board to select the correct Development Board Model. Select Arduino/Genuino 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, COM6 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:
voidsetup(){
Serial.begin(9600);// initializes the serial port with a baud rate of 9600
}
voidloop(){
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.
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.
Components Involved
Seeeduino Lotus
Grove LED
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
intledPin=4;
voidsetup(){
pinMode(ledPin,OUTPUT);
}
voidloop(){
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.
intledPin=4;
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);
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.
mode: INPUT, OUTPUT, or INPUT_PULLUP.
Setting ledPin to the output mode.
digitalWrite(ledPin,HIGH);
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.
value: HIGH or LOW.
When we set the ledPin as output, HIGH means sending high level to the pin, LED turns on.
digitalWrite(ledPin,LOW);
When we set the led as output, low stands for sending low level to the pin, LED turns off.
delay(1000);
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.
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
Seeeduino Lotus
Grove LED
Grove Button
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:
constintbuttonPin=6;// the number of the pushbutton pin
constintledPin=4;// the number of the LED pin
// variables will change:
intbuttonState=0;// variable for reading the pushbutton status
voidsetup(){
// initialize the LED pin as an output:
pinMode(ledPin,OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin,INPUT);
}
voidloop(){
// 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);
Define LED as the output unit.
pinMode(buttonPin,INPUT);
Define button as the input unit.
buttonState=digitalRead(buttonPin);
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
}
elseif(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.
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.
Components Involved
Seeeduino Lotus
Grove LED
Grove Rotary Switch
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
introtaryPin=A0;// select the input pin for the rotary
intledPin=4;// select the pin for the LED
introtaryValue=0;// variable to store the value coming from the rotary
voidsetup(){
// declare the ledPin as an OUTPUT:
pinMode(ledPin,OUTPUT);
pinMode(rotaryPin,INPUT);
}
voidloop(){
// 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
introtaryPin=A0;// select the input pin for the rotary
intledPin=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);
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);
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.
Just like the LED module, Buzzer is also an output module, instead of lighting up it produces a beep sound. This can be used for many situations for indication purposes.Let's learn how to generate sound using the buzzer!
Background Information:
What is the difference between Active and Passive Buzzer
There are two types of buzzers, one is active and the other is passive. Both active and passive buzzers are used to make sound to electronics.
The active buzzer has an internal oscillation source that makes the buzzer sound whenever power is applied. Active buzzers are widely used in computers, printers, copiers, alarms, electronic toys, car electronics, telephones, timers and other electronic product sounding devices.
A passive buzzer has no internal source of oscillation and needs to be driven by a square wave and a different frequency. It acts like an electromagnetic speaker, and the changing input signal produces sound, rather than a tone automatically.
In this kit, the Grove-Buzzer is a passive buzzer so that it needs an AC signal to control it. This then leads to the next question, how to generate Square Wave(AC signals) with Arduino! Well, an easy way is to use PWM.
What is PWM
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means. Digital control is used to create a square wave, a signal switched between on and off. This on-off pattern can simulate voltages in between full on (5 Volts) and off (0 Volts) by changing the portion of the time the signal spends on versus the time that the signal spends off. The duration of "on time" is called the pulse width. To get varying analog values, you change, or modulate, that pulse width. If you repeat this on-off pattern fast enough, the result is as if the signal is a steady voltage between 0 and 5v as a AC signal. Reference: Arduino. This PWM signal can then be used to control the passive buzzer with ease.
To generate PWM signals in Arduino, you can use analogWrite(), in contrast to using digitalWrite() to generate DC signals.
There are six digital pins on your Seeeduino that are marked with the symbol “~”, which means they can send out a PWM signal : 3,5,6,9,10,11. They are celled PWM pins.
Components Involved
Seeeduino Lotus
Grove Buzzer
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.
intBuzzerPin=5;
voidsetup(){
pinMode(BuzzerPin,OUTPUT);
}
voidloop(){
analogWrite(BuzzerPin,128);
delay(1000);
analogWrite(BuzzerPin,0);
delay(0);
}
Code Analysis
analogWrite(BuzzerPin,128);
Description:
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady rectangular wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite()) on the same pin.
Syntax:
analogWrite(pin, value)
Parameters:
pin: the Arduino pin to write to. Allowed data types: int.
value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data types: int.
Writes an analog value (PWM wave) to the Buzzer.
Demo Effect and Serial Print Result:
The Buzzer beeps.
Breakout Guide
Use a Grove cable to connect the Grove Buzzer to Seeeduino Lotus's digital interface D5.
PWM Usage
Now that we have learned the use of PWM, in addition to using PWM to control the passive buzzer, we can also use PWM to control the speed of the motor and the brightness of the LED lights and etc.
As the diagram indicates below, use analogWrite() to generate PWM waves, the higher the percentage of Duty Cycle, the brighter the LED.
However, the LED Module on the Grove Beginner Kit cannot be directly controlled by PWM, because the LED module is connected to D4, and as mentioned above, the PWM pins are 3, 5, 6, 9, 10, 11, and pin 4 is not a PWM pin. If you want to control the LED with PWM, you need to pull it down and use the Grove cable to connect to the Grove port with PWM function.
For example, let's connect Grove-LED to D3 using a Grove cable:
Note
D3 is also inter-connected to the Grove-Temperature & Humidity Sensor, and therefore this example cannot be used with Grove-Temperature & Humidity Sensor together.
intLED=3;// Cable connection from LED to D3
intPotentiometer=A0;
voidsetup(){
pinMode(LED,OUTPUT);
pinMode(Potentiometer,INPUT);
}
voidloop(){
intpotentioValue,Value;
potentioValue=analogRead(Potentiometer);
Value=map(potentioValue,0,1023,0,255);//Mapping potentiometer value to PWM signal value
analogWrite(LED,Value);
}
Compile and upload the code you should be able to twist and adjust the LED brightness using PWM signals!
Code Analysis
Value=map(potentioValue,0,1023,0,255);
Description:
Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.
Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.
Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers, for example
y = map(x, 1, 50, 50, 1);
The function also handles negative numbers well, so that this example
y = map(x, 1, 50, 50, -100);
is also valid and works well.
The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated and are not rounded or averaged.
Syntax:
map(value, fromLow, fromHigh, toLow, toHigh)
Parameters:
value: the number to map.
fromLow: the lower bound of the value’s current range.
fromHigh: the upper bound of the value’s current range.
toLow: the lower bound of the value’s target range.
toHigh: the upper bound of the value’s target range.
Mapping Potentiometer sensor analog signal(0 to 1023)to the loudness of Light(0 to 255).
Demo Effect and Serial Print Result:
Adjust the potentiometer to adjust the LED brightness.
All in all, when you want to use the PWM function, make sure to select those pins with a "~" symbol in front of their names.
The light sensor contains a photosensitive resistor to measure the intensity of light. The resistance of the photosensitive resistor decreases with the increase of light intensity. The LED will light up if the surrounding is dark, and stays off if the surrounding is bright.
In the following sections, we will use Serial Monitor to observe results from our sensors so here comes the brief introduction!
Background Information:
What is Serial Monitor
Serial Monitor is a useful tool to observe results on Arduino, it can be very useful in terms of printing results from the sensors or debugging in general. You can also send data back to the controller via the serial monitor to do certain tasks! Note: Make sure the Serial data transfer match with the code.
You can open the Serial Monitor by clicking Tools -> Serial Monitor.
Components Involved
Seeeduino Lotus
Grove LED
Grove Light Sensor
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.
Hardware analysis:
Input: Light Sensor
Control: Seeeduino Lotus
Output: LED module
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.
// Light Switch
intsensorpin=A6;// Analog input pin that the sensor is attached to
intledPin=4;// LED port
intsensorValue=0;// value read from the port
intoutputValue=0;// value output to the PWM (analog out)
voidsetup(){
pinMode(ledPin,OUTPUT);
pinMode(sensorpin,INPUT);
Serial.begin(9600);
}
voidloop(){
// read the analog in value:
sensorValue=analogRead(sensorpin);
Serial.println(sensorValue);
if(sensorValue<200){
digitalWrite(ledPin,HIGH);
}
else{
digitalWrite(ledPin,LOW);
}
delay(200);
}
You can also see the light intensity readings from the Serial Monitor, navigate to Tools -> Serial Monitor.
Code Analysis
Serial.begin(9600);
Description:
Sets the data rate in bits per second (baud) for serial data transmission. For communicating with Serial Monitor, make sure to use one of the baud rates listed in the menu at the bottom right corner of its screen. You can, however, specify other rates - for example, to communicate over pins 0 and 1 with a component that requires a particular baud rate.
An optional second argument configures the data, parity, and stop bits. The default is 8 data bits, no parity, one stop bit.
The software running on the computer communicates with the development board, and the baud rate is 9600.
Syntax:
Serial.begin(speed)
Parameters:
speed: Speed of Serial communication. i.e 9600, 115200 and etc.
Set the Serial baud rate to 9600.
Serial.println(sensorValue);
Description:
Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes the same forms as Serial.print().
Syntax:
Serial.println(val) or Serial.println(val, format)
Parameters:
val: the value to print. Allowed data types: any data type.
format: specifies the number base (for integral data types) or the number of decimal places (for floating point types).
Serial port print the Light sensor’s value. So you open the serial monitor on the IDE interface, and you see the value of the output sensor.
Demo Effect and Serial Print Result:
The LED module will light up if it's dark and stay off if it's bright.
Breakout Guide
Use Grove Cable to connect the Grove LED to Seeeduino Lotus's digital signal interface D4,connect the Grove Light Sensor to Seeeduino Lotus's analog signal interface A6.
The sound sensor can detect the sound intensity of the environment, and its output is also simulated. I'm sure you've all been exposed to the sound control lights, but now we can do one ourselves, and with the basics, this experiment will be easy for you. Here used Serial Plotter to visualize results.
Background Information:
What is Serial Plotter
Serial Plotter is similar to Serial Monitor, allowing you to natively graph serial data from your Arduino to your computer in real-time. This is very useful when data needs to be visualized.
You can open the Serial Plotter by clicking Tools -> Serial Plotter.
Practice: The LED lights light up when the sound is made. When there is no sound and it is very quiet, the LED lights go off.
Components Involved
Seeeduino Lotus
Grove LED
Grove Sound Sensor
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.
Copy the following code, click Verify to check for syntax errors. Verify that there are no errors, and you can upload the code.
//Sound Control Light
intsoundPin=A2;// Analog sound sensor is to be attached to analog
intledPin=4;// Digital LED is to be attached to digital
voidsetup(){
pinMode(ledPin,OUTPUT);
pinMode(soundPin,INPUT);
Serial.begin(9600);
}
voidloop(){
intsoundState=analogRead(soundPin);// Read sound sensor’s value
Serial.println(soundState);
// if the sound sensor’s value is greater than 400, the light will be on.
//Otherwise, the light will be turned off
if(soundState>400){
digitalWrite(ledPin,HIGH);
delay(100);
}else{
digitalWrite(ledPin,LOW);
}
}
You can also see the light intensity readings from the Serial Plotter, navigate to Tools -> Serial Plotter.
Note: You can also adjust the value according to your surrounding light intensity.
Code Analysis
Serial.begin(9600);
The software running on the computer communicates with the development board, and the baud rate is 9600.
Serial.print(" ");
This function is used to output data from the serial port, the output is what is contained in the double quotation marks.
Serial.println();
This statement is similar to the one above, except that serial.println has a newline return.
Serial.println(soundState);
Serial port print the sound sensor’s value. So you open the serial monitor on the IDE interface, and you see the value of the output sensor.
Demo Effect and Serial Print Result:
The LED module will light up if the surrounding is loud enough.
Breakout Guide
Use Grove cables to connect the Grove LED to Seeeduino Lotus's digital signal interface D4, Connect the Grove Sound Sensor to Seeeduino Lotus's analog signal interface A2.
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.
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.
// U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // OLEDs without Reset of the Display
voidsetup(void){
//u8x8.setBusClock(100000); // If you breakout other modules, please enable this line
u8x8.begin();
u8x8.setFlipMode(1);
}
voidloop(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<>
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>
#include is an instruction that introduces a header file. Here we use the U8x8lib.h library.
Once the object is declared, you can use functions from the library.
u8x8.begin();
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);
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:
mode: 0 or 1
Flips the display 180 degrees.
u8x8.setCursor();
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()
Description:
Define a u8x8 font for the glyph and string drawing functions.
Syntax:
u8x8.setFont(font_8x8)
Set the font for display.
u8x8.print();
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:
Clink "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
Or you can set the bus lock to 100000 then add in the setup().
voidsetup(void){
u8x8.setBusClock(100000);// it for limit the I2C bus clock
u8x8.begin();
u8x8.setFlipMode(1);
}
Lesson 8: Detecting Surrounding Temperature & Humidity¶
Have you ever wondered about the temperature and humidity of your surroundings? Want to know the exact number? Want to wear a skirt or coat today depending on the temperature? Let's make a temperature meter!
Background Information:
What is Protocol Signal (I2C)
Protocol signal: the protocol signal we use is I2C, so here is a brief introduction to I2C. I2C bus just needs two wires in the transmission of information connection between the devices: the SDA (Serial Data Line) and SCL (Serial Clock Line).
These two lines are bidirectional I/O lines, the main component used to start the bus transfer data, and generate the clock to open transmission device, any devices that are addressing at this time is considered from the device.
The relationship between master and slave(sender and receiver) on the bus is not constant but depends on the direction of data transmission. If the host wants to send data to the slave device, the host first addresses the slave device, then actively sends data to the slave device, and finally terminates the data transmission by the host. If the host is to receive data from the slave, the slave is first addressed by the master.
The host then receives the data sent from the device, and the host terminates the receiving process. In this case. The host is responsible for generating the timing clock and terminating the data transfer.
Practice: Let your OLED Display display the current ambient temperature and humidity.
Components Involved
Seeeduino Lotus
Grove OLED
Grove Temperature and Temperature Sensor
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 Grove Temperature and Humidity Sensor(DHT11) library: Navigate to Sketch -> Include Library -> Manage Libraries... and Search for the keyword "Grove Temperature and Humidity Sensor(DHT11)" in the Library Manager, 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.
Functions to be used to read temperature and humidity values from the sensor.
Syntax:
dht.readTemperature() and dht.readHumidity(). Return type: float.
Call these functions to read the temperature and humidity and store them in defined variables.
Demo Effect and Serial Print Result:
The surrounding temperature and humidity appear on the OLED screen.
Breakout Guide
Use Grove cable to connect the OLED to Seeeduino Lotus's I2C interface (Note: I2C's default address is 0x78). Connect the Grove Temperature and Humidity Sensor to Seeeduino Lotus's digital signal interface D3.
Grove Air Pressure Sensor(BMP280) is a breakout board for Bosch BMP280 high-precision and low-power digital barometer. This module can be used to measure temperature and atmospheric pressure accurately. As the atmospheric pressure changes with altitude, it can also measure the approximate altitude of a place.
Components Involved
Seeeduino Lotus
Grove Air Pressure Sensor
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 Grove Barometer Sensor library: Navigate to Sketch -> Include Library -> Manage Libraries... and Search for the keyword "Grove BMP280" in the Library Manager, 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.
In this program, Barometer sensor information is sent from the sensor to Seeeduino via I2C bus and then Seeeduino printed them onto the serial monitor. Open the serial monitor to check the result.
//Air pressure detection
#include"Seeed_BMP280.h"
#include<Wire.h>
BMP280bmp280;
voidsetup(){
Serial.begin(9600);
if(!bmp280.init()){
Serial.println("Device not connected or broken!");
}
}
voidloop(){
floatpressure;
//get and print temperatures
Serial.print("Temp: ");
Serial.print(bmp280.getTemperature());
Serial.println("C");// The unit for Celsius because original arduino don't support speical symbols
//get and print atmospheric pressure data
Serial.print("Pressure: ");
Serial.print(pressure=bmp280.getPressure());
Serial.println("Pa");
//get and print altitude data
Serial.print("Altitude: ");
Serial.print(bmp280.calcAltitude(pressure));
Serial.println("m");
Serial.println("\n");//add a line between output of different times.
delay(1000);
}
Code Analysis
#include<Wire.h>
#include is an instruction that introduces a header file. Here we use the library, this library is included in Arduino IDE.
#include"Seeed_BMP280.h"
Represents the Seeed_BMP280.h header file that introduces the current path.
if(!bmp280.init()){
Serial.println("Device not connected or broken!");
}
Description:
To initialize the air pressure sensor using bmp280.init(). Further, using if condition to check if it started properly then skips the message. If having trouble to initiate then prints the message as ! means NOT in programming.
Syntax:
bmp280.init()
if the Air pressure sensor did not start properly, then prints out an error to the serial monitor.
Serial.print(bmp280.getTemperature());
Description:
Functions to be used to read temperature value from the sensor.
Syntax:
bmp280.getTemperature(). Return type: float
Prints the temperature data to the serial monitor.
Serial.print(pressure=bmp280.getPressure());
Description:
Functions to be used to read air pressure value from the sensor.
Syntax:
bmp280.getPressure(). Return type: float
Prints the current air pressure.
Serial.print(bmp280.calcAltitude(pressure));
Description:
Takes the pressure value can convert to altitude.
Syntax:
bmp280.calcAltitude(float). Return type: float
Parameter:
float: Pressure value.
Prints the amplitude.
Demo Effect and Serial Print Result:
The Air pressure readings are display on the Serial Monitor.
Breakout Guide
Use Grove cable to connect Grove Air Pressure Sensor to Seeeduino Lotus's I2C interface using a Grove cable (note: I2C default address is 0x77 or 0x76).
This is the last sensor, the triaxial accelerometer, and with this module, you can easily add motion monitoring to your design. So we can do a lot of interesting little experiments on the basis of the motion.
Practice: when motion is detected, the buzzer gives an alarm indicating that the object is in motion.
Components Involved
Seeeduino Lotus
Grove 3-axis Accelerometer
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.
Copy the following code, click Verify to check for syntax errors. Verify that there are no errors, and you can upload the code.
In this program, acceleration information is sent from the sensor to Seeeduino via I2C bus and then Seeeduino printed them onto the serial monitor. Open the serial monitor to check the result.
Project description: In this experiment, we will make the buzzer play pleasant music and the led lights flash according to the music frequency and beat.
Components Involved
Seeeduino Lotus
Grove LED
Buzzer
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.
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.
//Music Dynamic Rhythm Lamp
#define NTD0 -1
#define NTD1 294
#define NTD2 330
#define NTD3 350
#define NTD4 393
#define NTD5 441
#define NTD6 495
#define NTD7 556
#define NTDL1 147
#define NTDL2 165
#define NTDL3 175
#define NTDL4 196
#define NTDL5 221
#define NTDL6 248
#define NTDL7 278
#define NTDH1 589
#define NTDH2 661
#define NTDH3 700
#define NTDH4 786
#define NTDH5 882
#define NTDH6 990
#define NTDH7 112
#define WHOLE 1
#define HALF 0.5
#define QUARTER 0.25
#define EIGHTH 0.25
#define SIXTEENTH 0.625
inttune[]=
{
NTD3,NTD3,NTD4,NTD5,
NTD5,NTD4,NTD3,NTD2,
NTD1,NTD1,NTD2,NTD3,
NTD3,NTD2,NTD2,
NTD3,NTD3,NTD4,NTD5,
NTD5,NTD4,NTD3,NTD2,
NTD1,NTD1,NTD2,NTD3,
NTD2,NTD1,NTD1,
NTD2,NTD2,NTD3,NTD1,
NTD2,NTD3,NTD4,NTD3,NTD1,
NTD2,NTD3,NTD4,NTD3,NTD2,
NTD1,NTD2,NTDL5,NTD0,
NTD3,NTD3,NTD4,NTD5,
NTD5,NTD4,NTD3,NTD4,NTD2,
NTD1,NTD1,NTD2,NTD3,
NTD2,NTD1,NTD1
};
floatdurt[]=
{
1,1,1,1,
1,1,1,1,
1,1,1,1,
1+0.5,0.5,1+1,
1,1,1,1,
1,1,1,1,
1,1,1,1,
1+0.5,0.5,1+1,
1,1,1,1,
1,0.5,0.5,1,1,
1,0.5,0.5,1,1,
1,1,1,1,
1,1,1,1,
1,1,1,0.5,0.5,
1,1,1,1,
1+0.5,0.5,1+1,
};
intlength;
inttonepin=5;
intledp=4;
voidsetup()
{
pinMode(tonepin,OUTPUT);
pinMode(ledp,OUTPUT);
length=sizeof(tune)/sizeof(tune[0]);
}
voidloop()
{
for(intx=0;x<length;x++)
{
tone(tonepin,tune[x]);
digitalWrite(ledp,HIGH);
delay(400*durt[x]);
digitalWrite(ledp,LOW);
delay(100*durt[x]);
noTone(tonepin);
}
delay(4000);
}
Code Analysis
#define NTD
Here is the definition of the frequency of the D key, which is divided into bass, alto, and treble.
#define WHOLE 1
#define HALF 0.5
#define QUARTER 0.25
#define EIGHTH 0.25
#define SIXTEENTH 0.625
Note: rhythm is divided into one beat, half beat, ¼ beat, ⅛ beat, we specify a beat note time is 1;Half beat is 0.5;¼ beat is 0.25;⅛ of 0.125.
inttune[]=...
List the frequencies according to the spectrum.
floatdurt[]=...
List the beats according to the spectrum.
delay(100*durt[x]);
Control LED lights on and off respectively.
Demo Effect and Serial Print Result:
The buzzer will beep a tune while the LED module will flicker with same frequency.
Breakout Guide
Connect Grove LED to Seeeduino Lotus's digital signal interface D4, connect Buzzer to Seeeduino Lotus's digital signal interface D5.
Project 2: Make an intelligent sound-light induction desk lamp¶
Project description: as the name implies, this project is to make a small lamp controlled by Sound and Light. We need to use the LED module as output. Light sensor and sound sensor are used for input signals. In this way, you can achieve the function of the smart desk lamp: if the surrounding sound level is above certain pre-set value, then the LED light up, or if the surrounding light intensity is below certain value, the LED module also light up.
Components Involved
Seeeduino Lotus
Grove LED
Light Sensor
Sound Sensor
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.
Copy the following code, click Verify to check for syntax errors. Verify that there are no errors, and you can upload the code.
//light Induction Desk Lamp
intsoundPin=A2;// Analog sound sensor is to be attached to analog
intlightPin=A6;//Analog light sensor is to be attached to analog
intledPin=4;// Digital LED is to be attached to digital
voidsetup(){
pinMode(ledPin,OUTPUT);
pinMode(lightPin,INPUT);
pinMode(soundPin,INPUT);
}
voidloop(){
intsoundState=analogRead(soundPin);// Read sound sensor’s value
intlightState=analogRead(lightPin);// Read light sensor’s value
// if the sound sensor's value is greater than 500 or the sound sensor's is less than 200, the light will be on.
//Otherwise, the light will be turned off
if(soundState>500||lightState<200){
digitalWrite(ledPin,HIGH);
delay(500);//You can add the "//" to remove the delay
}else{
digitalWrite(ledPin,LOW);
}
}
Code Analysis
if(soundState>500||lightState<200){
...
}
In parentheses is a logical expression. Both && and || are commonly used in logical expressions. The common usage is if (expression 1 || expression 2) and if (expression 1 && expression 2).
|| represents "or", satisfies one of them, the whole expression is true, and satisfies the condition of the if judgment.
&& means "and", the statement in if{} is executed only if all expressions in parentheses are true.
Demo Effect and Serial Print Result:
If the surrounding sound is loud enough or light intensity is low, the LED module will light up more intensity.
Breakout Guide
Connect the Grove LED to Seeeduino Lotus's digital signal interface D4, Connect the Light Sensor to Seeeduino Lotus's analog signal interface A1. Connect the Sound Sensor to Seeeduino Lotus's analog signal interface A2 using a Grove cable.
After this period of study, you already have a systematic understanding of Arduino and open-source hardware, so why not go further and try to make your own module or development board?
To design your own board, you will need to design your own module's schematics, which requires an EDA tool to do so. Here recommends an open-source EDA software.
KiCAD
KiCad is a free software suite for electronic design automation. It facilitates the design of schematics for electronic circuits and their conversion to PCB designs. It features an integrated environment for schematic capture and PCB layout design. The programs handle Schematic Capture and PCB Layout with Gerber output. The suite runs on Windows, Linux, and macOS and is licensed under GNU GPL v3.
Upverter
If you don’t want to work on schematic or layout yourself, but you want to convert your prototype based on Seeed’s modules into an integrated product, we highly recommend you to try Upverter.
After you’re done with your design, check out the Seeed Fusion PCBA service, which can help translate your designs into an actual functioning device.
Seeed Studio has its very own Open Parts Library (OPL) which is a collection of over 10,000 commonly used components specifically sourced for the Seeed Fusion PCBA Service. To speed up the process of PCB design, Seeed is building the component libraries for KiCad and Eagle. When all components are sourced from Seeed’s PCBA OPL and used with the Seeed Fusion PCB Assembly (PCBA) service, the entire PCBA production time can be reduced from 20 working days to a mere 7 days.
"},{"radio":[{"label":"Cascading Style Sheet","sol":true},{"label":"C'est Son Style","sol":false},{"label":"Cascading Style Shine","sol":false},{"label":"Cascade Sur Style","sol":false}]}],[{"chrono":90},{"text":"
Quelle est la signification de l'acronyme HTML?
"},{"radio":[{"label":"HyperText Markup Language","sol":true},{"label":"HyperTexture Market Language","sol":false},{"label":"HyperText Market Line","sol":false},{"label":"Hyper Texture Markup Line","sol":false}]}],[{"chrono":90},{"text":" Qu'est-ce qu'internet?"},{"radio":[{"label":"Un gigantesque réseau d'ordinateurs","sol":true},{"label":"Le web","sol":false},{"label":"Un ensemble d'information constitué par des milliards de documents reliés les uns aux autres.","sol":false},{"label":"L'Adsl","sol":false}]}],[{"chrono":90},{"text":"
Quels sont les services supportés par internet?
"},{"chekbox":[{"label":"Le web","sol":true},{"label":"Le courier électronique","sol":true},{"label":"Le streaming","sol":true},{"label":"L'échange de fichiers par ftp","sol":true},{"label":"Les communications téléphoniques","sol":false}]}],[{"chrono":90},{"text":"Qu'est-ce que le web?"},{"radio":[{"label":"Un ensemble d'information constitué par des milliards de documents reliés les uns aux autres.","sol":true},{"label":"Un gigantesque réseau d'ordinateurs","sol":false},{"label":"Une page internet","sol":false},{"label":"Un réseau informatique qui transporte l'information","sol":false}]}],[{"chrono":90},{"text":"
Qu'est-ce qu'un site?
"},{"chekbox":[{"label":"Un site web","sol":true},{"label":"Un ensemble de page contenant de l'information.","sol":true},{"label":"Un site internet","sol":false},{"label":"Un réseau internet","sol":false}]}],[{"chrono":90},{"text":"Comment sont reliés entre eux les documents sur le web?"},{"radio":[{"label":"A l'aide d'hypertextes","sol":true},{"label":"A l'aide de fils","sol":false},{"label":"A l'aide de mots","sol":false},{"label":"A l'aide du CSS","sol":false}]}],[{"chrono":90},{"text":"Où sont stockés les sites web?"},{"radio":[{"label":"Dans un serveur","sol":true},{"label":"Dans la stratosphère","sol":false},{"label":"Dans mon ordinateur","sol":false},{"label":"Dans le web","sol":false}]}],[{"chrono":90},{"text":"Comment appelle-t-on le faite de demander une informaton à un serveur?"},{"radio":[{"label":"Une requête ","sol":true},{"label":"Un appel","sol":false},{"label":"Un signal","sol":false},{"label":"Une commande","sol":false}]}],[{"chrono":90},{"text":"
Qu'est-ce qu'un client web?
"},{"radio":[{"label":"Un navigateur","sol":true},{"label":"Un serveur"},{"label":"Un acheteur","sol":false},{"label":"Un ordinateur","sol":false}]}],[{"chrono":90},{"text":"Quel est ie protocole utilisé pour que les clients web et les serveurs web communiquent entre eux?"},{"radio":[{"label":"Le http","sol":true},{"label":"Le html","sol":false},{"label":"Le css","sol":false},{"label":"L'url","sol":false}]}],[{"chrono":90},{"text":"En quelle année a été créé le concept d'hypertexte numérique?"},{"radio":[{"label":"1965","sol":true},{"label":"1995","sol":false},{"label":"1935","sol":false},{"label":"1905","sol":false}]}],[{"chrono":90},{"text":"
En quelle année a été créé le world wide web ( www )?
"},{"radio":[{"label":"1989","sol":true},{"label":"2001","sol":false},{"label":"1889","sol":false},{"label":"1939","sol":false}]}],[{"chrono":90},{"text":"Qui a inventé le world wide web ( www ) et le html?"},{"radio":[{"label":"Tim Berners-Lee","sol":true},{"label":"Bill Gate","sol":false},{"label":"Steeve Job","sol":false},{"label":"Mark Zuckerberg","sol":false}]}],[{"chrono":90},{"text":"
C'est quoi le world wide web?
"},{"radio":[{"label":"Une collection de documents électroniques","sol":true},{"label":"Le réseau internet"},{"label":"Le html","sol":false},{"label":"Une page web","sol":false}]}],[{"chrono":90},{"text":"
"},{"radio":[{"label":"Mosaic","sol":true},{"label":"Chrome"},{"label":"Mozilla","sol":false},{"label":"Aol","sol":false}]}],[{"chrono":90},{"text":"Quel est l'acronyme de DOM pour les pages web?"},{"radio":[{"label":"Document Object Model","sol":true},{"label":" Département d'Outre-Mer ","sol":false},{"label":"Document Open Market","sol":false},{"label":"Departement Object Model","sol":false}]}]]
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.
Worked perfectly while using Thonny 3.1.2 on Ubuntu; watch out for the micro USB cable without the data wires!! (luckily I have like 10 cables)
A way to check if your issue is with your cable is before you plug in the ESP, type in terminal lsusb and then plug in your ESP and type lsusb again and compare the two. If nothing changes try another cable.
Using USB without data wires is a frequent mistake.
Thanks for sharing that tip.
Regards,
Sara
Your tutorials are great! Thank you!
Thanks
Great ! I tried once and work perfectly
For me as beginner I suggest to add commands “pip install rshell” then “rshell -p COMx repl” once flashing completed, so beginner can test the micropython firmware on their board.
Thanks
Thank you worked first time. Good job
Hi,
When trying to flash ESP32, get the following result:
‘could not open port 17 FileNotFound Error (2, The system cannot find the file specified, None, 2)’
Have checked & port 17 is the correct port.
Hello and thank you.
This is the tutorial that works on the first connection.
Only info to USB cables, I will confirm what has already been mentioned and all USB cables need to be sorted and marked, or for example divided into plastic bags, together only charging and together data and some older ones can also be thrown away in separate collection.
The firmware download page for the ESP32, https://micropython.org/download/esp32/ offers multiple versions of the firmware. The most current version at this time, esp32-20210418-v1.15.bin, is missing some standard modules, including urequests. You can install the urequests module (from PyPI) in the /lib folder of your ESP32 using “Manage packages…” under the “Tools” tab of Thonny. You will be offered multiple choices. I’m currently testing micropython-urequests, version 0.9.1 from Paul Sokolovsky.
Furthermore, in some situations, such as using the _thread module for multithreading, you can expect problems that differ depending on the firmware that you are using on the ESP32. In my situation, using firmware: esp32-idf4-20210202-v1.14.bin or esp32-idf3-20210202-v1.14.bin results in corruption of the WiFi DNS settings and OSErrors in the urequest modules packaged in those firmware versions. Others see this on other boards: https://github.com/micropython/micropython/issues/6492