8 First programs
If for some reason you are having any difficulties with your ESP32, you can simulate any code using this simulator:
https://wokwi.com/projects/new/esp32
8.1 Blink
It’s time to run a first example.
- Go to
File > Examples > 01.Basics, click onBlink. - Press the “right arrow” button on the top left to upload the code onto the ESP32.
- When you see “Connecting” on the bottom of the screen, press the right button on the ESP32.
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(500); // wait for 500 milliseconds
}The following is a slight variation of the code above. It requires you to:
- connect the ESP32 to a breadboard
- connect the long leg of an LED to the A4 pin
- connect a 330-ohm resistor between the short LED leg and ground
const int LED_pin = A4;
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_pin, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_pin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_pin, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}8.2 Printing increasing numbers
Upload the following code to your ESP32, then click on the on the top right corner. This is called “Serial Monitor”.
Download code// This is a one-line comment
/*
This
comment
spans
many
rows
*/
int num = 0; // integer
void setup() {
/* initialize serial communication with computer
* baud rate 9600 = 9600 bits per second
*/
Serial.begin(9600);
}
void loop() {
// print num and break line
Serial.println(num);
// print num, don't break line
// Serial.print(num);
delay(1000); // 1000 ms delay
num = num + 1; // increase num by 1
}
/*
* 1. To see the numbers go to
* Tools > Serial Plotter
* 2. After you see the numbers,
* press the ESP32 reset button and see what happens
* 3. In the Serial Plotter window,
* change baud rate to another number, see what happens
*/8.3 Printing random numbers, then plotting!
- Upload the following code to your ESP32.
- Open the Serial Monitor (). Now close it, and
- Go to
Tools > Serial Plotter.
int num1 = 0, num2 = 0;
void setup() {
// initialize serial communication with computer:
Serial.begin(9600);
}
void loop() {
// random(min, max)
num1 = num1 + random(-5, 5);
num2 = num2 + random(-10, 10);
// print num1, then tab, then num2, then break line
Serial.print(num1);
Serial.print("\t");
Serial.println(num2);
delay(100); // 1000 ms delay
}
/*
* 1. See the random numbers on the Serial Monitor
* 2. Open the Serial Plotter
* 3. Reset ESP32 while looking at the graph
*/8.4 Floats, functions, conditionals
We will now learn how to deal with floats, how to define our own functions, and how to write conditionals (if/else).
Download code// initialize 4 floats (decimals)
// time and 3 more variables to be plotted
float t = 0, x1 = 0, x2 = 0, x3 = 0;
void setup() {
// initialize serial communication with computer:
Serial.begin(9600);
}
/*
* This is how you define a function.
* In this case, the function returns a float (decimal)
*/
float my_sine(float time) {
return sin(time);
}
float my_cosine(float time) {
float double_time; // you can define internal variables,
double_time = 2.0 * time; // write as many commands as you want
return 2.0 * cos(double_time); // in the end, return float
}
void loop() {
x1 = my_sine(t);
x2 = my_cosine(t);
// now let's make a square wave
if (x1 > 0) {
x3 = -1.0;
} else {
x3 = 1.0;
}
Serial.print("sin:"); Serial.print(x1); Serial.print("\t");
Serial.print("cos:"); Serial.print(x2); Serial.print("\t");
Serial.print("square:"); Serial.print(x3);
Serial.println();
delay(50); // 1000 ms delay
t += 0.05;
}8.5 Serial read
We can also read data from the Serial Monitor and use it to control the behavior of the ESP32. In this example, the ESP32 waits for you to type a number into the Serial Monitor and then blinks that number of times.
Download code// serial-read-blink.ino
String inputString = "";
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(115200);
Serial.println("Type a number and press Enter:");
}
void loop() {
// check if data is available in the Serial Monitor
if (Serial.available()) {
inputString = Serial.readStringUntil('\n');
int n = inputString.toInt(); // convert text to integer
Serial.print("Blinking ");
Serial.print(n);
Serial.println(" times");
for (int i = 0; i < n; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(200);
digitalWrite(LED_BUILTIN, LOW);
delay(200);
}
Serial.println("Done. Type another number:");
}
}8.6 WiFi, read time
Download code//-----------------------------------------------------------------------------------
// WIFI setup:
#include <WiFi.h>
const char* ssid = "HUJI-guest"; // your wifi SSID name
const char* password = "" ;// wifi pasword
String formattedTime;
float rand_int = 0, cumulative = 0;
WiFiClient client;
//-------------------------------------------------------------------------------------
// Set time
#include <NTPClient.h>
#include <WiFiUdp.h>
const long utcOffsetInSeconds = 3600 * 2; // For UTC +2.00 : 2 * 60 * 60
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);
int time_s ; // variable for the second
void setup() {
Serial.begin(9600);
//---------------------------------------------------------------------------
//wifi conection:
WiFi.disconnect();
delay(10);
WiFi.begin(ssid, password);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("NodeMcu connected to wifi...");
Serial.println(ssid);
Serial.println();
//-----------------------------------------------------------------------
// stings for time:
timeClient.begin();
}
void loop() {
timeClient.update();
time_s = timeClient.getSeconds();
if (time_s == 0) {
formattedTime = timeClient.getFormattedTime();
Serial.print("A new minute has started!\nFull time = ");
Serial.println(formattedTime);
}
Serial.print("second = ");
Serial.print(time_s);
rand_int = random(10, 20);
cumulative += rand_int;
Serial.print("\trand = ");
Serial.print(rand_int);
Serial.print("\trunning sum = ");
Serial.println(cumulative);
if (time_s%10==9) {
Serial.print("Average = ");
Serial.println(cumulative / 10);
cumulative = 0;
}
delay(1000);
}8.7 Home assignment
Go to Assignment 1.