├── README.md ├── code ├── Analog_Input_Pot │ ├── Analog_Input_Pot.ino │ └── Analog_Input_Pot.png ├── BLE_Client_OLED │ ├── BLE_Client_OLED.ino │ └── BLE_Client_OLED.png ├── BLE_Examples │ ├── BLE_notify │ │ └── BLE_notify.ino │ └── BLE_scan │ │ └── BLE_scan.ino ├── BLE_Server_DHT │ ├── BLE_Server_DHT.ino │ └── BLE_Server_DHT.png ├── Blink_LED │ ├── Blink_LED.ino │ └── blinkin_LED_schematic_bb.png ├── Blink_LED_PlatformIO │ └── Blink_LED_PlatformIO.ino ├── Blink_Without_Delay │ ├── Blink_Without_Delay.ino │ └── Blink_Without_Delay.png ├── Bluetooth_Classic_Example │ └── Bluetooth_Classic_Example.ino ├── Bluetooth_Classic_Project │ ├── Bluetooth_Classic_LED_DS18B20.png │ └── Bluetooth_Classic_Project.ino ├── Button_LED │ ├── Button_LED.ino │ └── led_button_bb.png ├── DeepSleep │ ├── ExternalWakeUp │ │ └── ExternalWakeUp.ino │ ├── ExternalWakeUp_ext1_with_GPIO │ │ └── ExternalWakeUp_ext1_with_GPIO.ino │ ├── TimerWakeUp │ │ └── TimerWakeUp.ino │ └── TouchWakeUp │ │ └── TouchWakeUp.ino ├── Dual_Core │ ├── Dual_Core_Blinking_LEDs │ │ ├── Dual_Core_Blinking_LEDs.ino │ │ └── Dual_Core_Blinking_LEDs_schematics.png │ └── Get_Core_ID │ │ └── Get_Core_ID.ino ├── EEPROM_Last_LED_State │ ├── EEPROM_Last_LED_State.ino │ └── EEPROM_Last_LED_State.png ├── ESP32_BLE_Inputs_and_Outputs │ ├── ESP32_BLE_Code.zip │ ├── ESP32_BLE_Inputs_and_Outputs.aia │ ├── ESP32_BLE_Inputs_and_Outputs.apk │ ├── ESP32_BLE_Inputs_and_Outputs.ino │ ├── ESP32_BLE_Inputs_and_Outputs.png │ ├── light_bulb_off.png │ └── light_bulb_on.png ├── ESP32_Fixed_Static_IP_Address │ └── ESP32_Fixed_Static_IP_Address.ino ├── ESP32_HTTP_GET_POST │ ├── ESP32_HTTP_GET_OpenWeatherMap │ │ └── ESP32_HTTP_GET_OpenWeatherMap.ino │ ├── ESP32_HTTP_GET_ThingSpeak │ │ └── ESP32_HTTP_GET_ThingSpeak.ino │ ├── ESP32_HTTP_POST_IFTTT │ │ └── ESP32_HTTP_POST_IFTTT.ino │ └── ESP32_HTTP_POST_ThingSpeak │ │ └── ESP32_HTTP_POST_ThingSpeak.ino ├── ESP32_NodeRED │ ├── ESP32_NodeRED.ino │ ├── ESP32_NodeRED.png │ └── ESP32_NodeRED_Flow.txt ├── ESP32_WiFi_Multisensor │ ├── ESP32_WiFi_Multisensor.ino │ ├── ESP32_WiFi_Multisensor_LED.png │ ├── ESP32_WiFi_Multisensor_Relay.png │ └── Enclosure_ESP32_WiFi_Multisensor.zip ├── ESP32_Wi_Fi_Client_Server │ ├── Wi_Fi_Client │ │ └── Wi_Fi_Client.ino │ └── Wi_Fi_Server │ │ └── Wi_Fi_Server.ino ├── ESP_Async_Web_Server │ └── ESP_Async_Web_Server.ino ├── ESP_NOW │ ├── Get_MAC_Address │ │ └── Get_MAC_Address.ino │ ├── Unit_1 │ │ ├── ESP32_Receiver │ │ │ └── ESP32_Receiver.ino │ │ └── ESP32_Sender │ │ │ └── ESP32_Sender.ino │ ├── Unit_2 │ │ └── ESP_NOW_Sender_Receiver_Two_Way │ │ │ └── ESP_NOW_Sender_Receiver_Two_Way.ino │ ├── Unit_3 │ │ ├── ESP_NOW_Receiver │ │ │ └── ESP_NOW_Receiver.ino │ │ ├── ESP_NOW_Sender_Multiple_Boards_Different_Message │ │ │ └── ESP_NOW_Sender_Multiple_Boards_Different_Message.ino │ │ └── ESP_NOW_Sender_Multiple_Boards_Same_Message │ │ │ └── ESP_NOW_Sender_Multiple_Boards_Same_Message.ino │ ├── Unit_4 │ │ ├── ESP_NOW_Receiver_Multiple_Boards │ │ │ └── ESP_NOW_Receiver_Multiple_Boards.ino │ │ └── ESP_NOW_Sender │ │ │ └── ESP_NOW_Sender.ino │ └── Unit_5 │ │ ├── ESP_NOW_Receiver_Web_Server │ │ └── ESP_NOW_Receiver_Web_Server.ino │ │ └── ESP_NOW_Sender │ │ └── ESP_NOW_Sender.ino ├── Hall_Effect_Sensor │ └── Hall_Effect_Sensor.ino ├── LED_PWM_Example_1 │ ├── LED_PWM_Example_1.ino │ └── LED_PWM_Example_1.png ├── LED_PWM_Example_2 │ ├── LED_PWM_Example_2.ino │ └── LED_PWM_Example_2.png ├── LoRa_Project │ ├── LoRa_Receiver │ │ ├── LoRa_Receiver.ino │ │ ├── LoRa_Receiver_Step_1.png │ │ └── LoRa_Receiver_Step_2.png │ └── LoRa_Sender │ │ ├── LoRa_Sender.ino │ │ ├── LoRa_Sender_Step_1.png │ │ ├── LoRa_Sender_Step_2.png │ │ ├── LoRa_Sender_Step_3.png │ │ ├── LoRa_Sender_Step_4.PNG │ │ ├── LoRa_Sender_Step_5.PNG │ │ ├── LoRa_Sender_Step_6.PNG │ │ ├── LoRa_Sender_Step_7.PNG │ │ └── LoRa_Sender_Step_8.PNG ├── LoRa_RFM95 │ ├── LoRa_Receiver │ │ ├── LoRa_Receiver.ino │ │ └── LoRa_Receiver.png │ └── LoRa_Sender │ │ ├── LoRa_Sender.ino │ │ └── LoRa_Sender.png ├── MQTT │ ├── ESP32_Client_1_LED_DS18B20 │ │ ├── ESP32_Client_1_LED_DS18B20.ino │ │ └── ESP32_MQTT_Client_1.png │ └── ESP32_Client_2_LCD_PUSHBUTTON │ │ ├── ESP32_Client_2_LCD_PUSHBUTTON.ino │ │ └── ESP32_MQTT_Client_2.png ├── OTA │ ├── OTA_Web_Updater │ │ └── OTA_Web_Updater.ino │ └── OTA_Web_Updater_LED │ │ └── OTA_Web_Updater_LED.ino ├── PIR_Interrupts_Timers │ ├── PIR_Interrupts_Timers.ino │ └── PIR_Interrupts_Timers.png ├── Print_ESP32_MAC_Address │ └── Print_ESP32_MAC_Address.ino ├── Project_Robot │ ├── Project_Robot.ino │ └── Project_Robot_Schematics.png ├── Project_Robot_AP │ └── Project_Robot_AP.ino ├── SPIFFS │ ├── ESP32_Async_Web_Server.zip │ ├── ESP32_Async_Web_Server │ │ ├── ESP32_Async_Web_Server.ino │ │ └── data │ │ │ ├── index.html │ │ │ └── style.css │ ├── SPIFFS_Manipulating_Files │ │ └── SPIFFS_Manipulating_Files.ino │ └── SPIFFS_Test │ │ └── SPIFFS_Test.ino ├── Servo │ ├── ESP32_Servo_Motor.png │ ├── Sweep │ │ └── Sweep.ino │ ├── WiFi_Web_Server_Servo │ │ └── WiFi_Web_Server_Servo.ino │ └── slider.html ├── TouchRead │ └── TouchRead.ino ├── Touch_Sensitive_LED │ ├── Touch_Sensitive_LED.ino │ └── Touch_Sensitive_LED.png ├── WiFi_Web_Server_Color_Picker │ ├── ESP32_RGB_LED_Strip.png │ └── WiFi_Web_Server_Color_Picker.ino ├── WiFi_Web_Server_DHT │ ├── ESP32_DHT_Sensor.png │ └── WiFi_Web_Server_DHT.ino ├── WiFi_Web_Server_Outputs │ ├── WiFi_Web_Server_Outputs.ino │ ├── WiFi_Web_Server_Outputs.png │ └── index.html ├── WiFi_Web_Server_Outputs_PP_Port8888 │ └── WiFi_Web_Server_Outputs_PP_Port8888.ino ├── WiFi_Web_Server_Outputs_Password_Protected │ └── WiFi_Web_Server_Outputs_Password_Protected.ino ├── WiFi_Web_Server_Relays │ ├── WiFi_Web_Server_Relays.ino │ └── WiFi_Web_Server_Relays.png ├── WiFi_Web_Server_Sensor_Readings │ ├── WiFi_Web_Server_Sensor_Readings.ino │ ├── WiFi_Web_Server_Sensor_Readings.png │ ├── table_with_css.html │ └── table_without_css.html └── bme280test │ ├── WiFi_Web_Server_Sensor_Readings.png │ └── bme280test.ino └── img ├── ESP32-DOIT-DEVKIT-V1-Board-Pinout-30-GPIOs.png ├── ESP32-DOIT-DEVKIT-V1-Board-Pinout-36-GPIOs.png └── ESP32-DOIT-DEVKIT-V1-Board-Pinout.pdf /README.md: -------------------------------------------------------------------------------- 1 | # Learn ESP32 with Arduino IDE Course (2nd Edition) 2 | 3 | More information about the Course » https://RandomNerdTutorials.com/learn-esp32-with-arduino-ide/ 4 | -------------------------------------------------------------------------------- /code/Analog_Input_Pot/Analog_Input_Pot.ino: -------------------------------------------------------------------------------- 1 | // Potentiometer is connected to GPIO 34 (Analog ADC1_CH6) 2 | const int potPin = 34; 3 | 4 | // variable for storing the potentiometer value 5 | int potValue = 0; 6 | 7 | void setup() { 8 | Serial.begin(115200); 9 | delay(1000); 10 | } 11 | 12 | void loop() { 13 | // Reading potentiometer value 14 | potValue = analogRead(potPin); 15 | Serial.println(potValue); 16 | delay(500); 17 | } 18 | -------------------------------------------------------------------------------- /code/Analog_Input_Pot/Analog_Input_Pot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Analog_Input_Pot/Analog_Input_Pot.png -------------------------------------------------------------------------------- /code/BLE_Client_OLED/BLE_Client_OLED.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/BLE_Client_OLED/BLE_Client_OLED.png -------------------------------------------------------------------------------- /code/BLE_Examples/BLE_notify/BLE_notify.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Video: https://www.youtube.com/watch?v=oCMOYS71NIU 3 | Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp 4 | Ported to Arduino ESP32 by Evandro Copercini 5 | updated by chegewara 6 | 7 | Create a BLE server that, once we receive a connection, will send periodic notifications. 8 | The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b 9 | And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8 10 | 11 | The design of creating the BLE server is: 12 | 1. Create a BLE Server 13 | 2. Create a BLE Service 14 | 3. Create a BLE Characteristic on the Service 15 | 4. Create a BLE Descriptor on the characteristic 16 | 5. Start the service. 17 | 6. Start advertising. 18 | 19 | A connect hander associated with the server starts a background task that performs notification 20 | every couple of seconds. 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | BLEServer* pServer = NULL; 29 | BLECharacteristic* pCharacteristic = NULL; 30 | bool deviceConnected = false; 31 | bool oldDeviceConnected = false; 32 | uint32_t value = 0; 33 | 34 | // See the following for generating UUIDs: 35 | // https://www.uuidgenerator.net/ 36 | 37 | #define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" 38 | #define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" 39 | 40 | 41 | class MyServerCallbacks: public BLEServerCallbacks { 42 | void onConnect(BLEServer* pServer) { 43 | deviceConnected = true; 44 | }; 45 | 46 | void onDisconnect(BLEServer* pServer) { 47 | deviceConnected = false; 48 | } 49 | }; 50 | 51 | void setup() { 52 | Serial.begin(115200); 53 | 54 | // Create the BLE Device 55 | BLEDevice::init("ESP32"); 56 | 57 | // Create the BLE Server 58 | pServer = BLEDevice::createServer(); 59 | pServer->setCallbacks(new MyServerCallbacks()); 60 | 61 | // Create the BLE Service 62 | BLEService *pService = pServer->createService(SERVICE_UUID); 63 | 64 | // Create a BLE Characteristic 65 | pCharacteristic = pService->createCharacteristic( 66 | CHARACTERISTIC_UUID, 67 | BLECharacteristic::PROPERTY_READ | 68 | BLECharacteristic::PROPERTY_WRITE | 69 | BLECharacteristic::PROPERTY_NOTIFY | 70 | BLECharacteristic::PROPERTY_INDICATE 71 | ); 72 | 73 | // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml 74 | // Create a BLE Descriptor 75 | pCharacteristic->addDescriptor(new BLE2902()); 76 | 77 | // Start the service 78 | pService->start(); 79 | 80 | // Start advertising 81 | BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); 82 | pAdvertising->addServiceUUID(SERVICE_UUID); 83 | pAdvertising->setScanResponse(false); 84 | pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter 85 | BLEDevice::startAdvertising(); 86 | Serial.println("Waiting a client connection to notify..."); 87 | } 88 | 89 | void loop() { 90 | // notify changed value 91 | if (deviceConnected) { 92 | pCharacteristic->setValue((uint8_t*)&value, 4); 93 | pCharacteristic->notify(); 94 | value++; 95 | delay(3); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms 96 | } 97 | // disconnecting 98 | if (!deviceConnected && oldDeviceConnected) { 99 | delay(500); // give the bluetooth stack the chance to get things ready 100 | pServer->startAdvertising(); // restart advertising 101 | Serial.println("start advertising"); 102 | oldDeviceConnected = deviceConnected; 103 | } 104 | // connecting 105 | if (deviceConnected && !oldDeviceConnected) { 106 | // do stuff here on connecting 107 | oldDeviceConnected = deviceConnected; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /code/BLE_Examples/BLE_scan/BLE_scan.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp 3 | Ported to Arduino ESP32 by Evandro Copercini 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | int scanTime = 5; // in seconds 12 | BLEScan* pBLEScan; 13 | 14 | class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { 15 | void onResult(BLEAdvertisedDevice advertisedDevice) { 16 | Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str()); 17 | } 18 | }; 19 | 20 | void setup() { 21 | Serial.begin(115200); 22 | Serial.println("Scanning..."); 23 | 24 | BLEDevice::init(""); 25 | pBLEScan = BLEDevice::getScan(); //create new scan 26 | pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); 27 | pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster 28 | pBLEScan->setInterval(100); 29 | pBLEScan->setWindow(99); // less or equal setInterval value 30 | } 31 | 32 | void loop() { 33 | // put your main code here, to run repeatedly: 34 | BLEScanResults *foundDevices = pBLEScan->start(scanTime, false); 35 | Serial.print("Devices found: "); 36 | Serial.println(foundDevices->getCount()); 37 | Serial.println("Scan done!"); 38 | pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory 39 | delay(2000); 40 | } 41 | -------------------------------------------------------------------------------- /code/BLE_Server_DHT/BLE_Server_DHT.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "DHT.h" 11 | 12 | //BLE server name 13 | #define bleServerName "ESP32_DHT" 14 | 15 | // Uncomment one of the lines below for whatever DHT sensor type you're using! 16 | #define DHTTYPE DHT11 // DHT 11 17 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) 18 | //#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 19 | 20 | // Default UUID for Environmental Sensing Service 21 | // https://www.bluetooth.com/specifications/assigned-numbers/ 22 | #define SERVICE_UUID (BLEUUID((uint16_t)0x181A)) 23 | 24 | // Temperature Characteristic and Descriptor (default UUID) 25 | // Check the default UUIDs here: https://www.bluetooth.com/specifications/assigned-numbers/ 26 | BLECharacteristic dhtTemperatureCharacteristic(BLEUUID((uint16_t)0x2A6E), BLECharacteristic::PROPERTY_NOTIFY); 27 | BLEDescriptor dhtTemperatureDescriptor(BLEUUID((uint16_t)0x2902)); 28 | 29 | // Humidity Characteristic and Descriptor (default UUID) 30 | BLECharacteristic dhtHumidityCharacteristic(BLEUUID((uint16_t)0x2A6F), BLECharacteristic::PROPERTY_NOTIFY); 31 | BLEDescriptor dhtHumidityDescriptor(BLEUUID((uint16_t)0x2902)); 32 | 33 | // DHT Sensor 34 | const int DHTPin = 14; 35 | 36 | // Initialize DHT sensor. 37 | DHT dht(DHTPin, DHTTYPE); 38 | 39 | bool deviceConnected = false; 40 | 41 | //Setup callbacks onConnect and onDisconnect 42 | class MyServerCallbacks: public BLEServerCallbacks { 43 | void onConnect(BLEServer* pServer) { 44 | deviceConnected = true; 45 | Serial.println("Device Connected"); 46 | }; 47 | void onDisconnect(BLEServer* pServer) { 48 | deviceConnected = false; 49 | Serial.println("Device Disconnected"); 50 | } 51 | }; 52 | 53 | void setup() { 54 | // Start DHT sensor 55 | dht.begin(); 56 | 57 | // Start serial communication 58 | Serial.begin(115200); 59 | 60 | // Create the BLE Device 61 | BLEDevice::init(bleServerName); 62 | 63 | // Create the BLE Server 64 | BLEServer *pServer = BLEDevice::createServer(); 65 | pServer->setCallbacks(new MyServerCallbacks()); 66 | 67 | // Create the BLE Service 68 | BLEService *dhtService = pServer->createService(SERVICE_UUID); 69 | 70 | // Create BLE Characteristics and corresponding Descriptors 71 | dhtService->addCharacteristic(&dhtTemperatureCharacteristic); 72 | dhtTemperatureCharacteristic.addDescriptor(&dhtTemperatureDescriptor); 73 | 74 | dhtService->addCharacteristic(&dhtHumidityCharacteristic); 75 | dhtHumidityCharacteristic.addDescriptor(&dhtHumidityDescriptor); 76 | 77 | // Start the service 78 | dhtService->start(); 79 | 80 | // Start advertising 81 | pServer->getAdvertising()->start(); 82 | Serial.println("Waiting a client connection to notify..."); 83 | } 84 | 85 | void loop() { 86 | if (deviceConnected) { 87 | // Read temperature as Celsius (the default) 88 | float t = dht.readTemperature(); 89 | // Read temperature as Fahrenheit (isFahrenheit = true) 90 | float f = dht.readTemperature(true); 91 | // Read humidity 92 | float h = dht.readHumidity(); 93 | 94 | // Check if any reads failed and exit early (to try again). 95 | if (isnan(h) || isnan(t) || isnan(f)) { 96 | Serial.println("Failed to read from DHT sensor!"); 97 | return; 98 | } 99 | 100 | //Notify temperature reading from DHT sensor 101 | uint16_t temperatureCTemp = (uint16_t)t; 102 | //Set temperature Characteristic value and notify connected client 103 | dhtTemperatureCharacteristic.setValue(temperatureCTemp); 104 | dhtTemperatureCharacteristic.notify(); 105 | Serial.print("Temperature Celsius: "); 106 | Serial.print(t); 107 | Serial.print(" *C"); 108 | 109 | 110 | //Notify humidity reading from DHT 111 | uint16_t humidityTemp = (uint16_t)h; 112 | //Set humidity Characteristic value and notify connected client 113 | dhtHumidityCharacteristic.setValue(humidityTemp); 114 | dhtHumidityCharacteristic.notify(); 115 | Serial.print(" - Humidity: "); 116 | Serial.print(h); 117 | Serial.println(" %"); 118 | 119 | delay(10000); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /code/BLE_Server_DHT/BLE_Server_DHT.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/BLE_Server_DHT/BLE_Server_DHT.png -------------------------------------------------------------------------------- /code/Blink_LED/Blink_LED.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Blink 3 | */ 4 | 5 | // ledPin refers to ESP32 GPIO 23 6 | const int ledPin = 23; 7 | 8 | // the setup function runs once when you press reset or power the board 9 | void setup() { 10 | // initialize digital pin ledPin as an output. 11 | pinMode(ledPin, OUTPUT); 12 | } 13 | 14 | // the loop function runs over and over again forever 15 | void loop() { 16 | digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level) 17 | delay(1000); // wait for a second 18 | digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW 19 | delay(1000); // wait for a second 20 | } 21 | -------------------------------------------------------------------------------- /code/Blink_LED/blinkin_LED_schematic_bb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Blink_LED/blinkin_LED_schematic_bb.png -------------------------------------------------------------------------------- /code/Blink_LED_PlatformIO/Blink_LED_PlatformIO.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // ledPin refers to ESP32 GPIO 23 4 | const int ledPin = 23; 5 | 6 | // the setup function runs once when you press reset or power the board 7 | void setup() { 8 | // initialize digital pin ledPin as an output. 9 | pinMode(ledPin, OUTPUT); 10 | } 11 | 12 | // the loop function runs over and over again forever 13 | void loop() { 14 | digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level) 15 | delay(1000); // wait for a second 16 | digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW 17 | delay(1000); // wait for a second 18 | } 19 | -------------------------------------------------------------------------------- /code/Blink_Without_Delay/Blink_Without_Delay.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // constants won't change. Used here to set a pin number : 7 | const int ledPin = 26; // the number of the LED pin 8 | 9 | // Variables will change : 10 | int ledState = LOW; // ledState used to set the LED 11 | 12 | // Generally, you should use "unsigned long" for variables that hold time 13 | // The value will quickly become too large for an int to store 14 | unsigned long previousMillis = 0; // will store last time LED was updated 15 | 16 | // constants won't change : 17 | const long interval = 1000; // interval at which to blink (milliseconds) 18 | 19 | void setup() { 20 | // set the digital pin as output: 21 | pinMode(ledPin, OUTPUT); 22 | } 23 | 24 | void loop() { 25 | // here is where you'd put code that needs to be running all the time. 26 | 27 | // check to see if it's time to blink the LED; that is, if the 28 | // difference between the current time and last time you blinked 29 | // the LED is bigger than the interval at which you want to 30 | // blink the LED. 31 | unsigned long currentMillis = millis(); 32 | 33 | if (currentMillis - previousMillis >= interval) { 34 | // save the last time you blinked the LED 35 | previousMillis = currentMillis; 36 | 37 | // if the LED is off turn it on and vice-versa: 38 | if (ledState == LOW) { 39 | ledState = HIGH; 40 | } else { 41 | ledState = LOW; 42 | } 43 | 44 | // set the LED with the ledState of the variable: 45 | digitalWrite(ledPin, ledState); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /code/Blink_Without_Delay/Blink_Without_Delay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Blink_Without_Delay/Blink_Without_Delay.png -------------------------------------------------------------------------------- /code/Bluetooth_Classic_Example/Bluetooth_Classic_Example.ino: -------------------------------------------------------------------------------- 1 | //This example code is in the Public Domain (or CC0 licensed, at your option.) 2 | //By Evandro Copercini - 2018 3 | // 4 | //This example creates a bridge between Serial and Classical Bluetooth (SPP) 5 | //and also demonstrate that SerialBT have the same functionalities of a normal Serial 6 | 7 | #include "BluetoothSerial.h" 8 | 9 | #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) 10 | #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it 11 | #endif 12 | 13 | BluetoothSerial SerialBT; 14 | 15 | void setup() { 16 | Serial.begin(115200); 17 | SerialBT.begin("ESP32test"); //Bluetooth device name 18 | Serial.println("The device started, now you can pair it with bluetooth!"); 19 | } 20 | 21 | void loop() { 22 | if (Serial.available()) { 23 | SerialBT.write(Serial.read()); 24 | } 25 | if (SerialBT.available()) { 26 | Serial.write(SerialBT.read()); 27 | } 28 | delay(20); 29 | } 30 | -------------------------------------------------------------------------------- /code/Bluetooth_Classic_Project/Bluetooth_Classic_LED_DS18B20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Bluetooth_Classic_Project/Bluetooth_Classic_LED_DS18B20.png -------------------------------------------------------------------------------- /code/Bluetooth_Classic_Project/Bluetooth_Classic_Project.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Load libraries 7 | #include "BluetoothSerial.h" 8 | #include 9 | #include 10 | 11 | // Check if Bluetooth configs are enabled 12 | #if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) 13 | #error Bluetooth is not enabled! Please run `make menuconfig` to and enable it 14 | #endif 15 | 16 | // Bluetooth Serial object 17 | BluetoothSerial SerialBT; 18 | 19 | // GPIO where LED is connected to 20 | const int ledPin = 25; 21 | 22 | // GPIO where the DS18B20 is connected to 23 | const int oneWireBus = 32; 24 | // Setup a oneWire instance to communicate with any OneWire devices 25 | OneWire oneWire(oneWireBus); 26 | // Pass our oneWire reference to Dallas Temperature sensor 27 | DallasTemperature sensors(&oneWire); 28 | 29 | // Handle received and sent messages 30 | String message = ""; 31 | char incomingChar; 32 | String temperatureString = ""; 33 | 34 | // Timer: auxiliar variables 35 | unsigned long previousMillis = 0; // Stores last time temperature was published 36 | const long interval = 10000; // interval at which to publish sensor readings 37 | 38 | void setup() { 39 | pinMode(ledPin, OUTPUT); 40 | Serial.begin(115200); 41 | // Bluetooth device name 42 | SerialBT.begin("ESP32"); 43 | Serial.println("The device started, now you can pair it with bluetooth!"); 44 | } 45 | 46 | void loop() { 47 | unsigned long currentMillis = millis(); 48 | // Send temperature readings 49 | if (currentMillis - previousMillis >= interval){ 50 | previousMillis = currentMillis; 51 | sensors.requestTemperatures(); 52 | temperatureString = String(sensors.getTempCByIndex(0)) + "C " + String(sensors.getTempFByIndex(0)) + "F"; 53 | SerialBT.println(temperatureString); 54 | } 55 | // Read received messages (LED control command) 56 | if (SerialBT.available()){ 57 | char incomingChar = SerialBT.read(); 58 | if (incomingChar != '\n'){ 59 | message += String(incomingChar); 60 | } 61 | else{ 62 | message = ""; 63 | } 64 | Serial.write(incomingChar); 65 | } 66 | // Check received message and control output accordingly 67 | if (message =="led_on"){ 68 | digitalWrite(ledPin, HIGH); 69 | } 70 | else if (message =="led_off"){ 71 | digitalWrite(ledPin, LOW); 72 | } 73 | delay(20); 74 | } 75 | -------------------------------------------------------------------------------- /code/Button_LED/Button_LED.ino: -------------------------------------------------------------------------------- 1 | // set pin numbers 2 | const int buttonPin = 4; // the number of the pushbutton pin 3 | const int ledPin = 16; // the number of the LED pin 4 | 5 | // variable for storing the pushbutton status 6 | int buttonState = 0; 7 | 8 | void setup() { 9 | Serial.begin(115200); 10 | // initialize the pushbutton pin as an input 11 | pinMode(buttonPin, INPUT); 12 | // initialize the LED pin as an output 13 | pinMode(ledPin, OUTPUT); 14 | } 15 | 16 | void loop() { 17 | // read the state of the pushbutton value 18 | buttonState = digitalRead(buttonPin); 19 | Serial.println(buttonState); 20 | // check if the pushbutton is pressed. 21 | // if it is, the buttonState is HIGH 22 | if (buttonState == HIGH) { 23 | // turn LED on 24 | digitalWrite(ledPin, HIGH); 25 | } else { 26 | // turn LED off 27 | digitalWrite(ledPin, LOW); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /code/Button_LED/led_button_bb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Button_LED/led_button_bb.png -------------------------------------------------------------------------------- /code/DeepSleep/ExternalWakeUp/ExternalWakeUp.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Deep Sleep with External Wake Up 3 | ===================================== 4 | This code displays how to use deep sleep with 5 | an external trigger as a wake up source and how 6 | to store data in RTC memory to use it over reboots 7 | 8 | This code is under Public Domain License. 9 | 10 | Hardware Connections 11 | ====================== 12 | Push Button to GPIO 33 pulled down with a 10K Ohm 13 | resistor 14 | 15 | NOTE: 16 | ====== 17 | Only RTC IO can be used as a source for external wake 18 | source. They are pins: 0,2,4,12-15,25-27,32-39. 19 | 20 | Author: 21 | Pranav Cherukupalli 22 | */ 23 | 24 | #define BUTTON_PIN_BITMASK 0x200000000 // 2^33 in hex 25 | 26 | RTC_DATA_ATTR int bootCount = 0; 27 | 28 | /* 29 | Method to print the reason by which ESP32 30 | has been awaken from sleep 31 | */ 32 | void print_wakeup_reason(){ 33 | esp_sleep_wakeup_cause_t wakeup_reason; 34 | 35 | wakeup_reason = esp_sleep_get_wakeup_cause(); 36 | 37 | switch(wakeup_reason) 38 | { 39 | case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; 40 | case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; 41 | case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; 42 | case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; 43 | case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; 44 | default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; 45 | } 46 | } 47 | 48 | void setup(){ 49 | Serial.begin(115200); 50 | delay(1000); //Take some time to open up the Serial Monitor 51 | 52 | //Increment boot number and print it every reboot 53 | ++bootCount; 54 | Serial.println("Boot number: " + String(bootCount)); 55 | 56 | //Print the wakeup reason for ESP32 57 | print_wakeup_reason(); 58 | 59 | /* 60 | First we configure the wake up source 61 | We set our ESP32 to wake up for an external trigger. 62 | There are two types for ESP32, ext0 and ext1 . 63 | ext0 uses RTC_IO to wakeup thus requires RTC peripherals 64 | to be on while ext1 uses RTC Controller so doesnt need 65 | peripherals to be powered on. 66 | Note that using internal pullups/pulldowns also requires 67 | RTC peripherals to be turned on. 68 | */ 69 | esp_sleep_enable_ext0_wakeup(GPIO_NUM_33,1); //1 = High, 0 = Low 70 | 71 | //If you were to use ext1, you would use it like 72 | //esp_sleep_enable_ext1_wakeup(BUTTON_PIN_BITMASK,ESP_EXT1_WAKEUP_ANY_HIGH); 73 | 74 | //Go to sleep now 75 | Serial.println("Going to sleep now"); 76 | delay(1000); 77 | esp_deep_sleep_start(); 78 | Serial.println("This will never be printed"); 79 | } 80 | 81 | void loop(){ 82 | //This is not going to be called 83 | } 84 | -------------------------------------------------------------------------------- /code/DeepSleep/ExternalWakeUp_ext1_with_GPIO/ExternalWakeUp_ext1_with_GPIO.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Deep Sleep with External Wake Up 3 | ===================================== 4 | This code displays how to use deep sleep with 5 | an external trigger as a wake up source and how 6 | to store data in RTC memory to use it over reboots 7 | 8 | This code is under Public Domain License. 9 | 10 | Hardware Connections 11 | ====================== 12 | Push Button to GPIO 33 pulled down with a 10K Ohm 13 | resistor 14 | 15 | NOTE: 16 | ====== 17 | Only RTC IO can be used as a source for external wake 18 | source. They are pins: 0,2,4,12-15,25-27,32-39. 19 | 20 | Author: 21 | Pranav Cherukupalli 22 | */ 23 | 24 | #define BUTTON_PIN_BITMASK 0x8004 // GPIOs 2 and 15 25 | 26 | RTC_DATA_ATTR int bootCount = 0; 27 | 28 | /* 29 | Method to print the reason by which ESP32 30 | has been awaken from sleep 31 | */ 32 | void print_wakeup_reason(){ 33 | esp_sleep_wakeup_cause_t wakeup_reason; 34 | 35 | wakeup_reason = esp_sleep_get_wakeup_cause(); 36 | 37 | switch(wakeup_reason) 38 | { 39 | case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; 40 | case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; 41 | case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; 42 | case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; 43 | case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; 44 | default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; 45 | } 46 | } 47 | 48 | /* 49 | Method to print the GPIO that triggered the wakeup 50 | */ 51 | void print_GPIO_wake_up(){ 52 | uint64_t GPIO_reason = esp_sleep_get_ext1_wakeup_status(); 53 | Serial.print("GPIO that triggered the wake up: GPIO "); 54 | Serial.println((log(GPIO_reason))/log(2), 0); 55 | } 56 | 57 | void setup(){ 58 | Serial.begin(115200); 59 | delay(1000); //Take some time to open up the Serial Monitor 60 | 61 | //Increment boot number and print it every reboot 62 | ++bootCount; 63 | Serial.println("Boot number: " + String(bootCount)); 64 | 65 | //Print the wakeup reason for ESP32 66 | print_wakeup_reason(); 67 | 68 | //Print the GPIO used to wake up 69 | print_GPIO_wake_up(); 70 | 71 | /* 72 | First we configure the wake up source 73 | We set our ESP32 to wake up for an external trigger. 74 | There are two types for ESP32, ext0 and ext1 . 75 | ext0 uses RTC_IO to wakeup thus requires RTC peripherals 76 | to be on while ext1 uses RTC Controller so doesnt need 77 | peripherals to be powered on. 78 | Note that using internal pullups/pulldowns also requires 79 | RTC peripherals to be turned on. 80 | */ 81 | //esp_deep_sleep_enable_ext0_wakeup(GPIO_NUM_15,1); //1 = High, 0 = Low 82 | 83 | //If you were to use ext1, you would use it like 84 | esp_sleep_enable_ext1_wakeup(BUTTON_PIN_BITMASK,ESP_EXT1_WAKEUP_ANY_HIGH); 85 | 86 | //Go to sleep now 87 | Serial.println("Going to sleep now"); 88 | delay(1000); 89 | esp_deep_sleep_start(); 90 | Serial.println("This will never be printed"); 91 | } 92 | 93 | void loop(){ 94 | //This is not going to be called 95 | } 96 | -------------------------------------------------------------------------------- /code/DeepSleep/TimerWakeUp/TimerWakeUp.ino: -------------------------------------------------------------------------------- 1 | /* Simple Deep Sleep with Timer Wake Up 2 | ESP32 offers a deep sleep mode for effective power saving as power is an important factor for IoT applications. In this mode CPUs, most of the RAM, and all the digital peripherals which are clocked 3 | from APB_CLK are powered off. The only parts of the chip which can still be powered on are: RTC controller, RTC peripherals ,and RTC memories This code displays the most basic deep sleep with a timer to wake it up and how to store data in RTC memory to use it over reboots This code is under Public Domain License. 4 | Author: Pranav Cherukupalli */ 5 | 6 | #define uS_TO_S_FACTOR 1000000ULL // Conversion factor for micro seconds to seconds 7 | #define TIME_TO_SLEEP 5 // Time ESP32 will go to sleep (in seconds) 8 | 9 | RTC_DATA_ATTR int bootCount = 0; 10 | 11 | // Method to print the reason by which ESP32 has been awaken from sleep 12 | void print_wakeup_reason(){ 13 | esp_sleep_wakeup_cause_t wakeup_reason; 14 | 15 | wakeup_reason = esp_sleep_get_wakeup_cause(); 16 | 17 | switch(wakeup_reason) 18 | { 19 | case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; 20 | case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; 21 | case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; 22 | case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; 23 | case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; 24 | default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; 25 | } 26 | } 27 | 28 | void setup(){ 29 | Serial.begin(115200); 30 | delay(1000); // Take some time to open up the Serial Monitor 31 | 32 | // Increment boot number and print it every reboot 33 | ++bootCount; 34 | Serial.println("Boot number: " + String(bootCount)); 35 | 36 | // Print the wakeup reason for ESP32 37 | print_wakeup_reason(); 38 | 39 | // First we configure the wake up source We set our ESP32 to wake up every 5 seconds 40 | esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); 41 | Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) + 42 | " Seconds"); 43 | 44 | /* 45 | Next we decide what all peripherals to shut down/keep on 46 | By default, ESP32 will automatically power down the peripherals 47 | not needed by the wakeup source, but if you want to be a poweruser 48 | this is for you. Read in detail at the API docs 49 | http://esp-idf.readthedocs.io/en/latest/api-reference/system/deep_sleep.html 50 | Left the line commented as an example of how to configure peripherals. 51 | The line below turns off all RTC peripherals in deep sleep. 52 | */ 53 | //esp_deep_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF); 54 | //Serial.println("Configured all RTC Peripherals to be powered down in sleep"); 55 | 56 | // Now that we have setup a wake cause and if needed setup the peripherals state in deep sleep, we can now start going to deep sleep. 57 | // In the case that no wake up sources were provided but deep sleep was started, it will sleep forever unless hardware reset occurs. 58 | Serial.println("Going to sleep now"); 59 | delay(1000); 60 | Serial.flush(); 61 | esp_deep_sleep_start(); 62 | Serial.println("This will never be printed"); 63 | } 64 | 65 | void loop(){ 66 | // This is not going to be called 67 | } 68 | -------------------------------------------------------------------------------- /code/DeepSleep/TouchWakeUp/TouchWakeUp.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Deep Sleep with Touch Wake Up 3 | This code displays how to use deep sleep with a touch as a wake up source and how to store data in RTC memory to use it over reboots 4 | ESP32 can have multiple touch pads enabled as wakeup source 5 | ESP32-S2 and ESP32-S3 supports only 1 touch pad as wakeup source enabled 6 | This code is under Public Domain License. Author: Pranav Cherukupalli 7 | */ 8 | 9 | #if CONFIG_IDF_TARGET_ESP32 10 | #define THRESHOLD 40 /* Greater the value, more the sensitivity */ 11 | #else //ESP32-S2 and ESP32-S3 + default for other chips (to be adjusted) */ 12 | #define THRESHOLD 5000 /* Lower the value, more the sensitivity */ 13 | #endif 14 | 15 | RTC_DATA_ATTR int bootCount = 0; 16 | touch_pad_t touchPin; 17 | /* 18 | Method to print the reason by which ESP32 19 | has been awaken from sleep 20 | */ 21 | void print_wakeup_reason(){ 22 | esp_sleep_wakeup_cause_t wakeup_reason; 23 | 24 | wakeup_reason = esp_sleep_get_wakeup_cause(); 25 | 26 | switch(wakeup_reason) 27 | { 28 | case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; 29 | case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; 30 | case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; 31 | case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; 32 | case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; 33 | default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break; 34 | } 35 | } 36 | 37 | /* 38 | Method to print the touchpad by which ESP32 39 | has been awaken from sleep 40 | */ 41 | void print_wakeup_touchpad(){ 42 | touchPin = esp_sleep_get_touchpad_wakeup_status(); 43 | 44 | #if CONFIG_IDF_TARGET_ESP32 45 | switch(touchPin) 46 | { 47 | case 0 : Serial.println("Touch detected on GPIO 4"); break; 48 | case 1 : Serial.println("Touch detected on GPIO 0"); break; 49 | case 2 : Serial.println("Touch detected on GPIO 2"); break; 50 | case 3 : Serial.println("Touch detected on GPIO 15"); break; 51 | case 4 : Serial.println("Touch detected on GPIO 13"); break; 52 | case 5 : Serial.println("Touch detected on GPIO 12"); break; 53 | case 6 : Serial.println("Touch detected on GPIO 14"); break; 54 | case 7 : Serial.println("Touch detected on GPIO 27"); break; 55 | case 8 : Serial.println("Touch detected on GPIO 33"); break; 56 | case 9 : Serial.println("Touch detected on GPIO 32"); break; 57 | default : Serial.println("Wakeup not by touchpad"); break; 58 | } 59 | #else 60 | if(touchPin < TOUCH_PAD_MAX) 61 | { 62 | Serial.printf("Touch detected on GPIO %d\n", touchPin); 63 | } 64 | else 65 | { 66 | Serial.println("Wakeup not by touchpad"); 67 | } 68 | #endif 69 | } 70 | 71 | void setup(){ 72 | Serial.begin(115200); 73 | delay(1000); //Take some time to open up the Serial Monitor 74 | 75 | //Increment boot number and print it every reboot 76 | ++bootCount; 77 | Serial.println("Boot number: " + String(bootCount)); 78 | 79 | //Print the wakeup reason for ESP32 and touchpad too 80 | print_wakeup_reason(); 81 | print_wakeup_touchpad(); 82 | 83 | #if CONFIG_IDF_TARGET_ESP32 84 | //Setup sleep wakeup on Touch Pad 3 + 7 (GPIO15 + GPIO 27) 85 | touchSleepWakeUpEnable(T3,THRESHOLD); 86 | touchSleepWakeUpEnable(T7,THRESHOLD); 87 | 88 | #else //ESP32-S2 + ESP32-S3 89 | //Setup sleep wakeup on Touch Pad 3 (GPIO3) 90 | touchSleepWakeUpEnable(T3,THRESHOLD); 91 | 92 | #endif 93 | 94 | //Go to sleep now 95 | Serial.println("Going to sleep now"); 96 | esp_deep_sleep_start(); 97 | Serial.println("This will never be printed"); 98 | } 99 | 100 | void loop(){ 101 | //This will never be reached 102 | } 103 | -------------------------------------------------------------------------------- /code/Dual_Core/Dual_Core_Blinking_LEDs/Dual_Core_Blinking_LEDs.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | TaskHandle_t Task1; 7 | TaskHandle_t Task2; 8 | 9 | // LED pins 10 | const int led1 = 2; 11 | const int led2 = 4; 12 | 13 | void setup() { 14 | Serial.begin(115200); 15 | pinMode(led1, OUTPUT); 16 | pinMode(led2, OUTPUT); 17 | 18 | //create a task that will be executed in the Task1code() function, with priority 1 and executed on core 0 19 | xTaskCreatePinnedToCore( 20 | Task1code, /* Task function. */ 21 | "Task1", /* name of task. */ 22 | 10000, /* Stack size of task */ 23 | NULL, /* parameter of the task */ 24 | 1, /* priority of the task */ 25 | &Task1, /* Task handle to keep track of created task */ 26 | 0); /* pin task to core 0 */ 27 | delay(500); 28 | 29 | //create a task that will be executed in the Task2code() function, with priority 1 and executed on core 1 30 | xTaskCreatePinnedToCore( 31 | Task2code, /* Task function. */ 32 | "Task2", /* name of task. */ 33 | 10000, /* Stack size of task */ 34 | NULL, /* parameter of the task */ 35 | 1, /* priority of the task */ 36 | &Task2, /* Task handle to keep track of created task */ 37 | 1); /* pin task to core 1 */ 38 | delay(500); 39 | } 40 | 41 | //Task1code: blinks an LED every 1000 ms 42 | void Task1code( void * pvParameters ){ 43 | Serial.print("Task1 running on core "); 44 | Serial.println(xPortGetCoreID()); 45 | 46 | for(;;){ 47 | digitalWrite(led1, HIGH); 48 | delay(1000); 49 | digitalWrite(led1, LOW); 50 | delay(1000); 51 | } 52 | } 53 | 54 | //Task2code: blinks an LED every 700 ms 55 | void Task2code( void * pvParameters ){ 56 | Serial.print("Task2 running on core "); 57 | Serial.println(xPortGetCoreID()); 58 | 59 | for(;;){ 60 | digitalWrite(led2, HIGH); 61 | delay(700); 62 | digitalWrite(led2, LOW); 63 | delay(700); 64 | } 65 | } 66 | 67 | void loop() { 68 | 69 | } 70 | -------------------------------------------------------------------------------- /code/Dual_Core/Dual_Core_Blinking_LEDs/Dual_Core_Blinking_LEDs_schematics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Dual_Core/Dual_Core_Blinking_LEDs/Dual_Core_Blinking_LEDs_schematics.png -------------------------------------------------------------------------------- /code/Dual_Core/Get_Core_ID/Get_Core_ID.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | void setup() { 7 | Serial.begin(115200); 8 | Serial.print("setup() running on core "); 9 | Serial.println(xPortGetCoreID()); 10 | } 11 | 12 | void loop() { 13 | Serial.print("loop() running on core "); 14 | Serial.println(xPortGetCoreID()); 15 | } 16 | -------------------------------------------------------------------------------- /code/EEPROM_Last_LED_State/EEPROM_Last_LED_State.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // include library to read and write from flash memory 7 | #include 8 | 9 | // define the number of bytes you want to access 10 | #define EEPROM_SIZE 1 11 | 12 | // constants won't change. They're used here to set pin numbers: 13 | const int buttonPin = 4; // the number of the pushbutton pin 14 | const int ledPin = 16; // the number of the LED pin 15 | 16 | // Variables will change: 17 | int ledState = HIGH; // the current state of the output pin 18 | int buttonState; // the current reading from the input pin 19 | int lastButtonState = LOW; // the previous reading from the input pin 20 | 21 | // the following variables are unsigned longs because the time, measured in 22 | // milliseconds, will quickly become a bigger number than can be stored in an int. 23 | unsigned long lastDebounceTime = 0; // the last time the output pin was toggled 24 | unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers 25 | 26 | void setup() { 27 | Serial.begin(115200); 28 | 29 | // initialize EEPROM with predefined size 30 | EEPROM.begin(EEPROM_SIZE); 31 | 32 | pinMode(buttonPin, INPUT); 33 | pinMode(ledPin, OUTPUT); 34 | 35 | // read the last LED state from flash memory 36 | ledState = EEPROM.read(0); 37 | // set the LED to the last stored state 38 | digitalWrite(ledPin, ledState); 39 | } 40 | 41 | void loop() { 42 | // read the state of the switch into a local variable: 43 | int reading = digitalRead(buttonPin); 44 | 45 | // check to see if you just pressed the button 46 | // (i.e. the input went from LOW to HIGH), and you've waited long enough 47 | // since the last press to ignore any noise: 48 | 49 | // If the switch changed, due to noise or pressing: 50 | if (reading != lastButtonState) { 51 | // reset the debouncing timer 52 | lastDebounceTime = millis(); 53 | } 54 | 55 | if ((millis() - lastDebounceTime) > debounceDelay) { 56 | // whatever the reading is at, it's been there for longer than the debounce 57 | // delay, so take it as the actual current state: 58 | 59 | // if the button state has changed: 60 | if (reading != buttonState) { 61 | buttonState = reading; 62 | 63 | // only toggle the LED if the new button state is HIGH 64 | if (buttonState == HIGH) { 65 | ledState = !ledState; 66 | } 67 | } 68 | } 69 | // save the reading. Next time through the loop, it'll be the lastButtonState: 70 | lastButtonState = reading; 71 | 72 | // if the ledState variable is different from the current LED state 73 | if (digitalRead(ledPin)!= ledState) { 74 | Serial.println("State changed"); 75 | // change the LED state 76 | digitalWrite(ledPin, ledState); 77 | // save the LED state in flash memory 78 | EEPROM.write(0, ledState); 79 | EEPROM.commit(); 80 | Serial.println("State saved in flash memory"); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /code/EEPROM_Last_LED_State/EEPROM_Last_LED_State.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/EEPROM_Last_LED_State/EEPROM_Last_LED_State.png -------------------------------------------------------------------------------- /code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Code.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Code.zip -------------------------------------------------------------------------------- /code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Inputs_and_Outputs.aia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Inputs_and_Outputs.aia -------------------------------------------------------------------------------- /code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Inputs_and_Outputs.apk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Inputs_and_Outputs.apk -------------------------------------------------------------------------------- /code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Inputs_and_Outputs.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Include necessary libraries 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | // DO NOT CHANGE THE NEXT UUIDs 15 | // Otherwise, you also need to modify the Android application used in this project 16 | #define SERVICE_UUID "C6FBDD3C-7123-4C9E-86AB-005F1A7EDA01" 17 | #define CHARACTERISTIC_UUID_RX "B88E098B-E464-4B54-B827-79EB2B150A9F" 18 | #define CHARACTERISTIC_UUID_TX "D769FACF-A4DA-47BA-9253-65359EE480FB" 19 | 20 | // Data wire is plugged into ESP32 GPIO 21 | #define ONE_WIRE_BUS 27 22 | // Setup a oneWire instance to communicate with any OneWire devices 23 | OneWire oneWire(ONE_WIRE_BUS); 24 | // Pass our oneWire reference to Dallas Temperature 25 | DallasTemperature sensors(&oneWire); 26 | 27 | BLECharacteristic *pCharacteristic; 28 | bool deviceConnected = false; 29 | 30 | // Temperature Sensor variable 31 | float temperature = 0; 32 | const int ledPin = 26; 33 | 34 | // Setup callbacks onConnect and onDisconnect 35 | class MyServerCallbacks: public BLEServerCallbacks { 36 | void onConnect(BLEServer* pServer) { 37 | deviceConnected = true; 38 | }; 39 | void onDisconnect(BLEServer* pServer) { 40 | deviceConnected = false; 41 | } 42 | }; 43 | 44 | // Setup callback when new value is received (from the Android application) 45 | class MyCallbacks: public BLECharacteristicCallbacks { 46 | void onWrite(BLECharacteristic *pCharacteristic) { 47 | String rxValue = pCharacteristic->getValue(); 48 | if(rxValue.length() > 0) { 49 | Serial.print("Received value: "); 50 | for(int i = 0; i < rxValue.length(); i++) { 51 | Serial.print(rxValue[i]); 52 | } 53 | // Turn the LED ON or OFF according to the command received 54 | if(rxValue.indexOf("ON") >= 0) { 55 | Serial.println(" - LED ON"); 56 | digitalWrite(ledPin, HIGH); 57 | } 58 | else if(rxValue.indexOf("OFF") >= 0) { 59 | Serial.println(" - LED OFF"); 60 | digitalWrite(ledPin, LOW); 61 | } 62 | } 63 | } 64 | }; 65 | 66 | void setup() { 67 | Serial.begin(115200); 68 | pinMode(ledPin, OUTPUT); 69 | sensors.begin(); 70 | 71 | // Create the BLE Device 72 | BLEDevice::init("ESP32_Board"); 73 | 74 | // Create the BLE Server 75 | BLEServer *pServer = BLEDevice::createServer(); 76 | pServer->setCallbacks(new MyServerCallbacks()); 77 | 78 | // Create the BLE Service 79 | BLEService *pService = pServer->createService(SERVICE_UUID); 80 | 81 | // Create a BLE Characteristic 82 | pCharacteristic = pService->createCharacteristic( 83 | CHARACTERISTIC_UUID_TX, 84 | BLECharacteristic::PROPERTY_NOTIFY); 85 | 86 | pCharacteristic->addDescriptor(new BLE2902()); 87 | 88 | BLECharacteristic *pCharacteristic = pService->createCharacteristic( 89 | CHARACTERISTIC_UUID_RX, 90 | BLECharacteristic::PROPERTY_WRITE); 91 | 92 | pCharacteristic->setCallbacks(new MyCallbacks()); 93 | 94 | // Start the service 95 | pService->start(); 96 | 97 | // Start advertising 98 | pServer->getAdvertising()->start(); 99 | Serial.println("Waiting to connect..."); 100 | } 101 | 102 | void loop() { 103 | // When the device is connected 104 | if(deviceConnected) { 105 | // Measure temperature 106 | sensors.requestTemperatures(); 107 | 108 | // Temperature in Celsius 109 | temperature = sensors.getTempCByIndex(0); 110 | // Uncomment the next line to set temperature in Fahrenheit 111 | // (and comment the previous temperature line) 112 | //temperature = sensors.getTempFByIndex(0); // Temperature in Fahrenheit 113 | 114 | // Convert the value to a char array 115 | char txString[8]; 116 | dtostrf(temperature, 1, 2, txString); 117 | 118 | // Set new characteristic value 119 | pCharacteristic->setValue(txString); 120 | // Send the value to the Android application 121 | pCharacteristic->notify(); 122 | Serial.print("Sent value: "); 123 | Serial.println(txString); 124 | } 125 | delay(5000); 126 | } 127 | -------------------------------------------------------------------------------- /code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Inputs_and_Outputs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_BLE_Inputs_and_Outputs/ESP32_BLE_Inputs_and_Outputs.png -------------------------------------------------------------------------------- /code/ESP32_BLE_Inputs_and_Outputs/light_bulb_off.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_BLE_Inputs_and_Outputs/light_bulb_off.png -------------------------------------------------------------------------------- /code/ESP32_BLE_Inputs_and_Outputs/light_bulb_on.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_BLE_Inputs_and_Outputs/light_bulb_on.png -------------------------------------------------------------------------------- /code/ESP32_Fixed_Static_IP_Address/ESP32_Fixed_Static_IP_Address.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Load Wi-Fi library 7 | #include 8 | 9 | // Replace with your network credentials 10 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 11 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 12 | 13 | // Set web server port number to 80 14 | WiFiServer server(80); 15 | 16 | // Variable to store the HTTP request 17 | String header; 18 | 19 | // Auxiliar variables to store the current output state 20 | String output26State = "off"; 21 | String output27State = "off"; 22 | 23 | // Assign output variables to GPIO pins 24 | const int output26 = 26; 25 | const int output27 = 27; 26 | 27 | // Set your Static IP address 28 | IPAddress local_IP(192, 168, 1, 184); 29 | // Set your Gateway IP address 30 | IPAddress gateway(192, 168, 1, 1); 31 | 32 | IPAddress subnet(255, 255, 0, 0); 33 | IPAddress primaryDNS(8, 8, 8, 8); //optional 34 | IPAddress secondaryDNS(8, 8, 4, 4); //optional 35 | 36 | void setup() { 37 | Serial.begin(115200); 38 | // Initialize the output variables as outputs 39 | pinMode(output26, OUTPUT); 40 | pinMode(output27, OUTPUT); 41 | // Set outputs to LOW 42 | digitalWrite(output26, LOW); 43 | digitalWrite(output27, LOW); 44 | 45 | // Configures static IP address 46 | if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) { 47 | Serial.println("STA Failed to configure"); 48 | } 49 | 50 | // Connect to Wi-Fi network with SSID and password 51 | Serial.print("Connecting to "); 52 | Serial.println(ssid); 53 | WiFi.begin(ssid, password); 54 | while (WiFi.status() != WL_CONNECTED) { 55 | delay(500); 56 | Serial.print("."); 57 | } 58 | // Print local IP address and start web server 59 | Serial.println(""); 60 | Serial.println("WiFi connected."); 61 | Serial.println("IP address: "); 62 | Serial.println(WiFi.localIP()); 63 | server.begin(); 64 | } 65 | 66 | void loop(){ 67 | WiFiClient client = server.available(); // Listen for incoming clients 68 | 69 | if (client) { // If a new client connects, 70 | Serial.println("New Client."); // print a message out in the serial port 71 | String currentLine = ""; // make a String to hold incoming data from the client 72 | while (client.connected()) { // loop while the client's connected 73 | if (client.available()) { // if there's bytes to read from the client, 74 | char c = client.read(); // read a byte, then 75 | Serial.write(c); // print it out the serial monitor 76 | header += c; 77 | if (c == '\n') { // if the byte is a newline character 78 | // if the current line is blank, you got two newline characters in a row. 79 | // that's the end of the client HTTP request, so send a response: 80 | if (currentLine.length() == 0) { 81 | // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) 82 | // and a content-type so the client knows what's coming, then a blank line: 83 | client.println("HTTP/1.1 200 OK"); 84 | client.println("Content-type:text/html"); 85 | client.println("Connection: close"); 86 | client.println(); 87 | 88 | // turns the GPIOs on and off 89 | if (header.indexOf("GET /26/on") >= 0) { 90 | Serial.println("GPIO 26 on"); 91 | output26State = "on"; 92 | digitalWrite(output26, HIGH); 93 | } else if (header.indexOf("GET /26/off") >= 0) { 94 | Serial.println("GPIO 26 off"); 95 | output26State = "off"; 96 | digitalWrite(output26, LOW); 97 | } else if (header.indexOf("GET /27/on") >= 0) { 98 | Serial.println("GPIO 27 on"); 99 | output27State = "on"; 100 | digitalWrite(output27, HIGH); 101 | } else if (header.indexOf("GET /27/off") >= 0) { 102 | Serial.println("GPIO 27 off"); 103 | output27State = "off"; 104 | digitalWrite(output27, LOW); 105 | } 106 | 107 | // Display the HTML web page 108 | client.println(""); 109 | client.println(""); 110 | client.println(""); 111 | // CSS to style the on/off buttons 112 | // Feel free to change the background-color and font-size attributes to fit your preferences 113 | client.println(""); 117 | 118 | // Web Page Heading 119 | client.println("

ESP32 Web Server

"); 120 | 121 | // Display current state, and ON/OFF buttons for GPIO 26 122 | client.println("

GPIO 26 - State " + output26State + "

"); 123 | // If the output26State is off, it displays the ON button 124 | if (output26State=="off") { 125 | client.println("

"); 126 | } else { 127 | client.println("

"); 128 | } 129 | 130 | // Display current state, and ON/OFF buttons for GPIO 27 131 | client.println("

GPIO 27 - State " + output27State + "

"); 132 | // If the output27State is off, it displays the ON button 133 | if (output27State=="off") { 134 | client.println("

"); 135 | } else { 136 | client.println("

"); 137 | } 138 | client.println(""); 139 | 140 | // The HTTP response ends with another blank line 141 | client.println(); 142 | // Break out of the while loop 143 | break; 144 | } else { // if you got a newline, then clear currentLine 145 | currentLine = ""; 146 | } 147 | } else if (c != '\r') { // if you got anything else but a carriage return character, 148 | currentLine += c; // add it to the end of the currentLine 149 | } 150 | } 151 | } 152 | // Clear the header variable 153 | header = ""; 154 | // Close the connection 155 | client.stop(); 156 | Serial.println("Client disconnected."); 157 | Serial.println(""); 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /code/ESP32_HTTP_GET_POST/ESP32_HTTP_GET_OpenWeatherMap/ESP32_HTTP_GET_OpenWeatherMap.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 11 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 12 | 13 | // Your Domain name with URL path or IP address with path 14 | String openWeatherMapApiKey = "REPLACE_WITH_YOUR_OPEN_WEATHER_MAP_API_KEY"; 15 | // Example: 16 | //String openWeatherMapApiKey = "bd939aa3d23ff33d3c8f5dd1dd43"; 17 | 18 | // Replace with your country code and city 19 | String city = "Porto"; 20 | String countryCode = "PT"; 21 | 22 | // THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES 23 | // For a final application, check the API call limits per hour/minute to avoid getting blocked/banned 24 | unsigned long lastTime = 0; 25 | // Timer set to 10 minutes (600000) 26 | //unsigned long timerDelay = 600000; 27 | // Set timer to 10 seconds (10000) 28 | unsigned long timerDelay = 10000; 29 | 30 | String jsonBuffer; 31 | 32 | void setup() { 33 | Serial.begin(115200); 34 | 35 | WiFi.begin(ssid, password); 36 | Serial.println("Connecting"); 37 | while(WiFi.status() != WL_CONNECTED) { 38 | delay(500); 39 | Serial.print("."); 40 | } 41 | Serial.println(""); 42 | Serial.print("Connected to WiFi network with IP Address: "); 43 | Serial.println(WiFi.localIP()); 44 | 45 | Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading."); 46 | } 47 | 48 | void loop() { 49 | // Send an HTTP GET request 50 | if ((millis() - lastTime) > timerDelay) { 51 | // Check WiFi connection status 52 | if(WiFi.status()== WL_CONNECTED){ 53 | String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey; 54 | 55 | jsonBuffer = httpGETRequest(serverPath.c_str()); 56 | Serial.println(jsonBuffer); 57 | JSONVar myObject = JSON.parse(jsonBuffer); 58 | 59 | // JSON.typeof(jsonVar) can be used to get the type of the var 60 | if (JSON.typeof(myObject) == "undefined") { 61 | Serial.println("Parsing input failed!"); 62 | return; 63 | } 64 | 65 | Serial.print("JSON object = "); 66 | Serial.println(myObject); 67 | Serial.print("Temperature: "); 68 | Serial.println(myObject["main"]["temp"]); 69 | Serial.print("Pressure: "); 70 | Serial.println(myObject["main"]["pressure"]); 71 | Serial.print("Humidity: "); 72 | Serial.println(myObject["main"]["humidity"]); 73 | Serial.print("Wind Speed: "); 74 | Serial.println(myObject["wind"]["speed"]); 75 | } 76 | else { 77 | Serial.println("WiFi Disconnected"); 78 | } 79 | lastTime = millis(); 80 | } 81 | } 82 | 83 | String httpGETRequest(const char* serverName) { 84 | WiFiClient client; 85 | HTTPClient http; 86 | 87 | // Your Domain name with URL path or IP address with path 88 | http.begin(client, serverName); 89 | 90 | // Send HTTP POST request 91 | int httpResponseCode = http.GET(); 92 | 93 | String payload = "{}"; 94 | 95 | if (httpResponseCode>0) { 96 | Serial.print("HTTP Response code: "); 97 | Serial.println(httpResponseCode); 98 | payload = http.getString(); 99 | } 100 | else { 101 | Serial.print("Error code: "); 102 | Serial.println(httpResponseCode); 103 | } 104 | // Free resources 105 | http.end(); 106 | 107 | return payload; 108 | } 109 | -------------------------------------------------------------------------------- /code/ESP32_HTTP_GET_POST/ESP32_HTTP_GET_ThingSpeak/ESP32_HTTP_GET_ThingSpeak.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 10 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 11 | 12 | // REPLACE WITH THINGSPEAK.COM API KEY 13 | String serverName = "http://api.thingspeak.com/update?api_key=REPLACE_WITH_YOUR_API_KEY"; 14 | // EXAMPLE: 15 | //String serverName = "http://api.thingspeak.com/update?api_key=7HQJM49R8JAP"; 16 | 17 | // THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES 18 | // For a final application, check the API call limits per hour/minute to avoid getting blocked/banned 19 | unsigned long lastTime = 0; 20 | // Timer set to 10 minutes (600000) 21 | //unsigned long timerDelay = 600000; 22 | // Set timer to 10 seconds (10000) 23 | unsigned long timerDelay = 10000; 24 | 25 | void setup() { 26 | Serial.begin(115200); 27 | 28 | WiFi.begin(ssid, password); 29 | Serial.println("Connecting"); 30 | while(WiFi.status() != WL_CONNECTED) { 31 | delay(500); 32 | Serial.print("."); 33 | } 34 | Serial.println(""); 35 | Serial.print("Connected to WiFi network with IP Address: "); 36 | Serial.println(WiFi.localIP()); 37 | 38 | Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading."); 39 | 40 | // Random seed is a number used to initialize a pseudorandom number generator 41 | randomSeed(analogRead(33)); 42 | } 43 | 44 | void loop() { 45 | // Send an HTTP GET request 46 | if ((millis() - lastTime) > timerDelay) { 47 | // Check WiFi connection status 48 | if(WiFi.status()== WL_CONNECTED){ 49 | WiFiClient client; 50 | HTTPClient http; 51 | 52 | String serverPath = serverName + "&field1=" + String(random(40)); 53 | 54 | // Your Domain name with URL path or IP address with path 55 | http.begin(client, serverPath.c_str()); 56 | 57 | // Send HTTP GET request 58 | int httpResponseCode = http.GET(); 59 | 60 | if (httpResponseCode>0) { 61 | Serial.print("HTTP Response code: "); 62 | Serial.println(httpResponseCode); 63 | String payload = http.getString(); 64 | Serial.println(payload); 65 | } 66 | else { 67 | Serial.print("Error code: "); 68 | Serial.println(httpResponseCode); 69 | } 70 | // Free resources 71 | http.end(); 72 | } 73 | else { 74 | Serial.println("WiFi Disconnected"); 75 | } 76 | lastTime = millis(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /code/ESP32_HTTP_GET_POST/ESP32_HTTP_POST_IFTTT/ESP32_HTTP_POST_IFTTT.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 10 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 11 | 12 | // Domain Name with full URL Path for HTTP POST Request 13 | // REPLACE WITH YOUR EVENT NAME AND API KEY - open the documentation: https://ifttt.com/maker_webhooks 14 | const char* serverName = "http://maker.ifttt.com/trigger/REPLACE_WITH_YOUR_EVENT/with/key/REPLACE_WITH_YOUR_API_KEY"; 15 | // Example: 16 | //const char* serverName = "http://maker.ifttt.com/trigger/test_event/with/key/nAZjOphL3d-ZO4N3k64-1A7gTlNSrxMJdmqy3tC"; 17 | 18 | // THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES 19 | // For a final application, check the API call limits per hour/minute to avoid getting blocked/banned 20 | unsigned long lastTime = 0; 21 | // Set timer to 10 minutes (600000) 22 | //unsigned long timerDelay = 600000; 23 | // Timer set to 10 seconds (10000) 24 | unsigned long timerDelay = 10000; 25 | 26 | void setup() { 27 | Serial.begin(115200); 28 | 29 | WiFi.begin(ssid, password); 30 | Serial.println("Connecting"); 31 | while (WiFi.status() != WL_CONNECTED) { 32 | delay(500); 33 | Serial.print("."); 34 | } 35 | Serial.println(""); 36 | Serial.print("Connected to WiFi network with IP Address: "); 37 | Serial.println(WiFi.localIP()); 38 | 39 | Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading."); 40 | 41 | // Random seed is a number used to initialize a pseudorandom number generator 42 | randomSeed(analogRead(33)); 43 | } 44 | 45 | void loop() { 46 | //Send an HTTP POST request every 10 seconds 47 | if ((millis() - lastTime) > timerDelay) { 48 | //Check WiFi connection status 49 | if (WiFi.status() == WL_CONNECTED) { 50 | WiFiClient client; 51 | HTTPClient http; 52 | 53 | // Your Domain name with URL path or IP address with path 54 | http.begin(client, serverName); 55 | 56 | // Specify content-type header 57 | http.addHeader("Content-Type", "application/x-www-form-urlencoded"); 58 | // Data to send with HTTP POST 59 | String httpRequestData = "value1=" + String(random(40)) + "&value2=" + String(random(40)) + "&value3=" + String(random(40)); 60 | // Send HTTP POST request 61 | int httpResponseCode = http.POST(httpRequestData); 62 | 63 | /* 64 | // If you need an HTTP request with a content type: application/json, use the following: 65 | http.addHeader("Content-Type", "application/json"); 66 | // JSON data to send with HTTP POST 67 | String httpRequestData = "{\"value1\":\"" + String(random(40)) + "\",\"value2\":\"" + String(random(40)) + "\",\"value3\":\"" + String(random(40)) + "\"}"; 68 | // Send HTTP POST request 69 | int httpResponseCode = http.POST(httpRequestData); 70 | */ 71 | 72 | Serial.print("HTTP Response code: "); 73 | Serial.println(httpResponseCode); 74 | 75 | // Free resources 76 | http.end(); 77 | } 78 | else { 79 | Serial.println("WiFi Disconnected"); 80 | } 81 | lastTime = millis(); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /code/ESP32_HTTP_GET_POST/ESP32_HTTP_POST_ThingSpeak/ESP32_HTTP_POST_ThingSpeak.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 10 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 11 | 12 | // Domain Name with full URL Path for HTTP POST Request 13 | const char* serverName = "http://api.thingspeak.com/update"; 14 | // Service API Key 15 | String apiKey = "REPLACE_WITH_YOUR_API_KEY"; 16 | 17 | // THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES 18 | // For a final application, check the API call limits per hour/minute to avoid getting blocked/banned 19 | unsigned long lastTime = 0; 20 | // Set timer to 10 minutes (600000) 21 | //unsigned long timerDelay = 600000; 22 | // Timer set to 10 seconds (10000) 23 | unsigned long timerDelay = 10000; 24 | 25 | void setup() { 26 | Serial.begin(115200); 27 | 28 | WiFi.begin(ssid, password); 29 | Serial.println("Connecting"); 30 | while(WiFi.status() != WL_CONNECTED) { 31 | delay(500); 32 | Serial.print("."); 33 | } 34 | Serial.println(""); 35 | Serial.print("Connected to WiFi network with IP Address: "); 36 | Serial.println(WiFi.localIP()); 37 | 38 | Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading."); 39 | 40 | // Random seed is a number used to initialize a pseudorandom number generator 41 | randomSeed(analogRead(33)); 42 | } 43 | 44 | void loop() { 45 | //Send an HTTP POST request every 10 seconds 46 | if ((millis() - lastTime) > timerDelay) { 47 | //Check WiFi connection status 48 | if(WiFi.status()== WL_CONNECTED){ 49 | WiFiClient client; 50 | HTTPClient http; 51 | 52 | // Your Domain name with URL path or IP address with path 53 | http.begin(client, serverName); 54 | 55 | // Specify content-type header 56 | http.addHeader("Content-Type", "application/x-www-form-urlencoded"); 57 | // Data to send with HTTP POST 58 | String httpRequestData = "api_key=" + apiKey + "&field1=" + String(random(40)); 59 | // Send HTTP POST request 60 | int httpResponseCode = http.POST(httpRequestData); 61 | 62 | /* 63 | // If you need an HTTP request with a content type: application/json, use the following: 64 | http.addHeader("Content-Type", "application/json"); 65 | // JSON data to send with HTTP POST 66 | String httpRequestData = "{\"api_key\":\"" + apiKey + "\",\"field1\":\"" + String(random(40)) + "\"}"; 67 | // Send HTTP POST request 68 | int httpResponseCode = http.POST(httpRequestData);*/ 69 | 70 | Serial.print("HTTP Response code: "); 71 | Serial.println(httpResponseCode); 72 | 73 | // Free resources 74 | http.end(); 75 | } 76 | else { 77 | Serial.println("WiFi Disconnected"); 78 | } 79 | lastTime = millis(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /code/ESP32_NodeRED/ESP32_NodeRED.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_NodeRED/ESP32_NodeRED.png -------------------------------------------------------------------------------- /code/ESP32_NodeRED/ESP32_NodeRED_Flow.txt: -------------------------------------------------------------------------------- 1 | [{"id":"9e58624.7faaba","type":"mqtt out","z":"c02b79b2.501998","name":"","topic":"esp32/led","qos":"","retain":"","broker":"10e78a89.5b4fd5","x":740,"y":520,"wires":[]},{"id":"abf7079a.653be8","type":"mqtt in","z":"c02b79b2.501998","name":"","topic":"esp32/temperature","qos":"2","broker":"10e78a89.5b4fd5","x":430,"y":300,"wires":[["cc79021b.9a751","46e7770d.86d9e8"]]},{"id":"83cf37cf.c76988","type":"ui_switch","z":"c02b79b2.501998","name":"","label":"LED","group":"61285987.c20328","order":0,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"","style":"","onvalue":"on","onvalueType":"str","onicon":"","oncolor":"","offvalue":"off","offvalueType":"str","officon":"","offcolor":"","x":590,"y":520,"wires":[["9e58624.7faaba"]]},{"id":"cc79021b.9a751","type":"debug","z":"c02b79b2.501998","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":630,"y":260,"wires":[]},{"id":"dd25cb97.5921d8","type":"mqtt in","z":"c02b79b2.501998","name":"","topic":"esp32/led/toggle","qos":"2","broker":"10e78a89.5b4fd5","x":420,"y":480,"wires":[["83cf37cf.c76988","b9659d3c.bf3d3"]]},{"id":"b9659d3c.bf3d3","type":"debug","z":"c02b79b2.501998","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":610,"y":440,"wires":[]},{"id":"46e7770d.86d9e8","type":"ui_chart","z":"c02b79b2.501998","name":"","group":"61285987.c20328","order":0,"width":0,"height":0,"label":"Temperature","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":630,"y":340,"wires":[[],[]]},{"id":"10e78a89.5b4fd5","type":"mqtt-broker","z":"","name":"","broker":"localhost","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closeQos":"0","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"61285987.c20328","type":"ui_group","z":"","name":"Main","tab":"e7c46d5e.a1283","disp":true,"width":"6","collapse":false},{"id":"e7c46d5e.a1283","type":"ui_tab","z":"","name":"Dashboard","icon":"dashboard"}] 2 | -------------------------------------------------------------------------------- /code/ESP32_WiFi_Multisensor/ESP32_WiFi_Multisensor_LED.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_WiFi_Multisensor/ESP32_WiFi_Multisensor_LED.png -------------------------------------------------------------------------------- /code/ESP32_WiFi_Multisensor/ESP32_WiFi_Multisensor_Relay.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_WiFi_Multisensor/ESP32_WiFi_Multisensor_Relay.png -------------------------------------------------------------------------------- /code/ESP32_WiFi_Multisensor/Enclosure_ESP32_WiFi_Multisensor.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/ESP32_WiFi_Multisensor/Enclosure_ESP32_WiFi_Multisensor.zip -------------------------------------------------------------------------------- /code/ESP32_Wi_Fi_Client_Server/Wi_Fi_Client/Wi_Fi_Client.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | const char* ssid = "ESP32-Access-Point"; 10 | const char* password = "123456789"; 11 | 12 | //Your IP address or domain name with URL path 13 | const char* serverNameTemp = "http://192.168.4.1/temperature"; 14 | const char* serverNameHumi = "http://192.168.4.1/humidity"; 15 | const char* serverNamePres = "http://192.168.4.1/pressure"; 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | #define SCREEN_WIDTH 128 // OLED display width, in pixels 22 | #define SCREEN_HEIGHT 64 // OLED display height, in pixels 23 | 24 | // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) 25 | #define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin) 26 | Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); 27 | 28 | String temperature; 29 | String humidity; 30 | String pressure; 31 | 32 | unsigned long previousMillis = 0; 33 | const long interval = 5000; 34 | 35 | void setup() { 36 | Serial.begin(115200); 37 | 38 | // Address 0x3C for 128x64, you might need to change this value (use an I2C scanner) 39 | if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { 40 | Serial.println(F("SSD1306 allocation failed")); 41 | for(;;); // Don't proceed, loop forever 42 | } 43 | display.clearDisplay(); 44 | display.setTextColor(WHITE); 45 | 46 | WiFi.begin(ssid, password); 47 | Serial.println("Connecting"); 48 | while(WiFi.status() != WL_CONNECTED) { 49 | delay(500); 50 | Serial.print("."); 51 | } 52 | Serial.println(""); 53 | Serial.print("Connected to WiFi network with IP Address: "); 54 | Serial.println(WiFi.localIP()); 55 | } 56 | 57 | void loop() { 58 | unsigned long currentMillis = millis(); 59 | 60 | if(currentMillis - previousMillis >= interval) { 61 | // Check WiFi connection status 62 | if(WiFi.status()== WL_CONNECTED ){ 63 | temperature = httpGETRequest(serverNameTemp); 64 | humidity = httpGETRequest(serverNameHumi); 65 | pressure = httpGETRequest(serverNamePres); 66 | Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa"); 67 | 68 | display.clearDisplay(); 69 | 70 | // display temperature 71 | display.setTextSize(2); 72 | display.setTextColor(WHITE); 73 | display.setCursor(0,0); 74 | display.print("T: "); 75 | display.print(temperature); 76 | display.print(" "); 77 | display.setTextSize(1); 78 | display.cp437(true); 79 | display.write(248); 80 | display.setTextSize(2); 81 | display.print("C"); 82 | 83 | // display humidity 84 | display.setTextSize(2); 85 | display.setCursor(0, 25); 86 | display.print("H: "); 87 | display.print(humidity); 88 | display.print(" %"); 89 | 90 | // display pressure 91 | display.setTextSize(2); 92 | display.setCursor(0, 50); 93 | display.print("P:"); 94 | display.print(pressure); 95 | display.setTextSize(1); 96 | display.setCursor(110, 56); 97 | display.print("hPa"); 98 | 99 | display.display(); 100 | 101 | // save the last HTTP GET Request 102 | previousMillis = currentMillis; 103 | } 104 | else { 105 | Serial.println("WiFi Disconnected"); 106 | } 107 | } 108 | } 109 | 110 | String httpGETRequest(const char* serverName) { 111 | HTTPClient http; 112 | 113 | // Your IP address with path or Domain name with URL path 114 | http.begin(serverName); 115 | 116 | // Send HTTP POST request 117 | int httpResponseCode = http.GET(); 118 | 119 | String payload = "--"; 120 | 121 | if (httpResponseCode>0) { 122 | Serial.print("HTTP Response code: "); 123 | Serial.println(httpResponseCode); 124 | payload = http.getString(); 125 | } 126 | else { 127 | Serial.print("Error code: "); 128 | Serial.println(httpResponseCode); 129 | } 130 | // Free resources 131 | http.end(); 132 | 133 | return payload; 134 | } 135 | -------------------------------------------------------------------------------- /code/ESP32_Wi_Fi_Client_Server/Wi_Fi_Server/Wi_Fi_Server.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | // Import required libraries 7 | #include "WiFi.h" 8 | #include "ESPAsyncWebServer.h" 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | // Set your access point network credentials 15 | const char* ssid = "ESP32-Access-Point"; 16 | const char* password = "123456789"; 17 | 18 | /*#include 19 | #define BME_SCK 18 20 | #define BME_MISO 19 21 | #define BME_MOSI 23 22 | #define BME_CS 5*/ 23 | 24 | Adafruit_BME280 bme; // I2C 25 | //Adafruit_BME280 bme(BME_CS); // hardware SPI 26 | //Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI 27 | 28 | // Create AsyncWebServer object on port 80 29 | AsyncWebServer server(80); 30 | 31 | String readTemp() { 32 | return String(bme.readTemperature()); 33 | //return String(1.8 * bme.readTemperature() + 32); 34 | } 35 | 36 | String readHumi() { 37 | return String(bme.readHumidity()); 38 | } 39 | 40 | String readPres() { 41 | return String(bme.readPressure() / 100.0F); 42 | } 43 | 44 | void setup(){ 45 | // Serial port for debugging purposes 46 | Serial.begin(115200); 47 | Serial.println(); 48 | 49 | // Setting the ESP as an access point 50 | Serial.print("Setting AP (Access Point)…"); 51 | // Remove the password parameter, if you want the AP (Access Point) to be open 52 | WiFi.softAP(ssid, password); 53 | 54 | IPAddress IP = WiFi.softAPIP(); 55 | Serial.print("AP IP address: "); 56 | Serial.println(IP); 57 | 58 | server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){ 59 | request->send_P(200, "text/plain", readTemp().c_str()); 60 | }); 61 | server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){ 62 | request->send_P(200, "text/plain", readHumi().c_str()); 63 | }); 64 | server.on("/pressure", HTTP_GET, [](AsyncWebServerRequest *request){ 65 | request->send_P(200, "text/plain", readPres().c_str()); 66 | }); 67 | 68 | bool status; 69 | 70 | // default settings 71 | // (you can also pass in a Wire library object like &Wire2) 72 | status = bme.begin(0x76); 73 | if (!status) { 74 | Serial.println("Could not find a valid BME280 sensor, check wiring!"); 75 | while (1); 76 | } 77 | 78 | // Start server 79 | server.begin(); 80 | } 81 | 82 | void loop(){ 83 | 84 | } 85 | -------------------------------------------------------------------------------- /code/ESP_Async_Web_Server/ESP_Async_Web_Server.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | // Import required libraries 7 | #include 8 | #include 9 | #include 10 | 11 | // Replace with your network credentials 12 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 13 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 14 | 15 | const char* PARAM_INPUT_1 = "output"; 16 | const char* PARAM_INPUT_2 = "state"; 17 | 18 | // Create AsyncWebServer object on port 80 19 | AsyncWebServer server(80); 20 | 21 | const char index_html[] PROGMEM = R"rawliteral( 22 | 23 | 24 | ESP Web Server 25 | 26 | 27 | 39 | 40 | 41 |

ESP Web Server

42 | %BUTTONPLACEHOLDER% 43 | 50 | 51 | 52 | )rawliteral"; 53 | 54 | // Replaces placeholder with button section in your web page 55 | String processor(const String& var){ 56 | //Serial.println(var); 57 | if(var == "BUTTONPLACEHOLDER"){ 58 | String buttons = ""; 59 | buttons += "

Output - GPIO 2

"; 60 | buttons += "

Output - GPIO 4

"; 61 | buttons += "

Output - GPIO 33

"; 62 | return buttons; 63 | } 64 | return String(); 65 | } 66 | 67 | String outputState(int output){ 68 | if(digitalRead(output)){ 69 | return "checked"; 70 | } 71 | else { 72 | return ""; 73 | } 74 | } 75 | 76 | void setup(){ 77 | // Serial port for debugging purposes 78 | Serial.begin(115200); 79 | 80 | pinMode(2, OUTPUT); 81 | digitalWrite(2, LOW); 82 | pinMode(4, OUTPUT); 83 | digitalWrite(4, LOW); 84 | pinMode(33, OUTPUT); 85 | digitalWrite(33, LOW); 86 | 87 | // Connect to Wi-Fi 88 | WiFi.begin(ssid, password); 89 | while (WiFi.status() != WL_CONNECTED) { 90 | delay(1000); 91 | Serial.println("Connecting to WiFi.."); 92 | } 93 | 94 | // Print ESP Local IP Address 95 | Serial.println(WiFi.localIP()); 96 | 97 | // Route for root / web page 98 | server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ 99 | request->send_P(200, "text/html", index_html, processor); 100 | }); 101 | 102 | // Send a GET request to /update?output=&state= 103 | server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) { 104 | String inputMessage1; 105 | String inputMessage2; 106 | // GET input1 value on /update?output=&state= 107 | if (request->hasParam(PARAM_INPUT_1) && request->hasParam(PARAM_INPUT_2)) { 108 | inputMessage1 = request->getParam(PARAM_INPUT_1)->value(); 109 | inputMessage2 = request->getParam(PARAM_INPUT_2)->value(); 110 | digitalWrite(inputMessage1.toInt(), inputMessage2.toInt()); 111 | } 112 | else { 113 | inputMessage1 = "No message sent"; 114 | inputMessage2 = "No message sent"; 115 | } 116 | Serial.print("GPIO: "); 117 | Serial.print(inputMessage1); 118 | Serial.print(" - Set to: "); 119 | Serial.println(inputMessage2); 120 | request->send(200, "text/plain", "OK"); 121 | }); 122 | 123 | // Start server 124 | server.begin(); 125 | } 126 | 127 | void loop() { 128 | 129 | } 130 | -------------------------------------------------------------------------------- /code/ESP_NOW/Get_MAC_Address/Get_MAC_Address.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | void readMacAddress(){ 10 | uint8_t baseMac[6]; 11 | esp_err_t ret = esp_wifi_get_mac(WIFI_IF_STA, baseMac); 12 | if (ret == ESP_OK) { 13 | Serial.printf("%02x:%02x:%02x:%02x:%02x:%02x\n", 14 | baseMac[0], baseMac[1], baseMac[2], 15 | baseMac[3], baseMac[4], baseMac[5]); 16 | } else { 17 | Serial.println("Failed to read MAC address"); 18 | } 19 | } 20 | 21 | void setup(){ 22 | Serial.begin(115200); 23 | 24 | WiFi.mode(WIFI_STA); 25 | WiFi.STA.begin(); 26 | 27 | Serial.print("[DEFAULT] ESP32 Board MAC Address: "); 28 | readMacAddress(); 29 | } 30 | 31 | void loop(){ 32 | 33 | } 34 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_1/ESP32_Receiver/ESP32_Receiver.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | // Structure example to receive data 10 | // Must match the sender structure 11 | typedef struct struct_message { 12 | char a[32]; 13 | int b; 14 | float c; 15 | bool d; 16 | } struct_message; 17 | 18 | // Create a struct_message called myData 19 | struct_message myData; 20 | 21 | // callback function that will be executed when data is received 22 | void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) { 23 | memcpy(&myData, incomingData, sizeof(myData)); 24 | Serial.print("Bytes received: "); 25 | Serial.println(len); 26 | Serial.print("Char: "); 27 | Serial.println(myData.a); 28 | Serial.print("Int: "); 29 | Serial.println(myData.b); 30 | Serial.print("Float: "); 31 | Serial.println(myData.c); 32 | Serial.print("Bool: "); 33 | Serial.println(myData.d); 34 | Serial.println(); 35 | } 36 | 37 | void setup() { 38 | // Initialize Serial Monitor 39 | Serial.begin(115200); 40 | 41 | // Set device as a Wi-Fi Station 42 | WiFi.mode(WIFI_STA); 43 | 44 | // Init ESP-NOW 45 | if (esp_now_init() != ESP_OK) { 46 | Serial.println("Error initializing ESP-NOW"); 47 | return; 48 | } 49 | 50 | // Once ESPNow is successfully Init, we will register for recv CB to 51 | // get recv packer info 52 | esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv)); 53 | } 54 | 55 | void loop() { 56 | 57 | } 58 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_1/ESP32_Sender/ESP32_Sender.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | // REPLACE WITH YOUR RECEIVER MAC Address 10 | uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 11 | 12 | // Structure example to send data 13 | // Must match the receiver structure 14 | typedef struct struct_message { 15 | char a[32]; 16 | int b; 17 | float c; 18 | bool d; 19 | } struct_message; 20 | 21 | // Create a struct_message called myData 22 | struct_message myData; 23 | 24 | esp_now_peer_info_t peerInfo; 25 | 26 | // callback when data is sent 27 | void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { 28 | Serial.print("\r\nLast Packet Send Status:\t"); 29 | Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); 30 | } 31 | 32 | void setup() { 33 | // Init Serial Monitor 34 | Serial.begin(115200); 35 | 36 | // Set device as a Wi-Fi Station 37 | WiFi.mode(WIFI_STA); 38 | 39 | // Init ESP-NOW 40 | if (esp_now_init() != ESP_OK) { 41 | Serial.println("Error initializing ESP-NOW"); 42 | return; 43 | } 44 | 45 | // Once ESPNow is successfully Init, we will register for Send CB to 46 | // get the status of Trasnmitted packet 47 | esp_now_register_send_cb(OnDataSent); 48 | 49 | // Register peer 50 | memcpy(peerInfo.peer_addr, broadcastAddress, 6); 51 | peerInfo.channel = 0; 52 | peerInfo.encrypt = false; 53 | 54 | // Add peer 55 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 56 | Serial.println("Failed to add peer"); 57 | return; 58 | } 59 | } 60 | 61 | void loop() { 62 | // Set values to send 63 | strcpy(myData.a, "THIS IS A CHAR"); 64 | myData.b = random(1,20); 65 | myData.c = 1.2; 66 | myData.d = false; 67 | 68 | // Send message via ESP-NOW 69 | esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData)); 70 | 71 | if (result == ESP_OK) { 72 | Serial.println("Sent with success"); 73 | } 74 | else { 75 | Serial.println("Error sending the data"); 76 | } 77 | delay(2000); 78 | } 79 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_2/ESP_NOW_Sender_Receiver_Two_Way/ESP_NOW_Sender_Receiver_Two_Way.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #include 14 | #include 15 | 16 | #define SCREEN_WIDTH 128 // OLED display width, in pixels 17 | #define SCREEN_HEIGHT 64 // OLED display height, in pixels 18 | 19 | // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) 20 | Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); 21 | 22 | Adafruit_BME280 bme; 23 | 24 | // REPLACE WITH THE MAC Address of your receiver 25 | uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 26 | 27 | // Define variables to store BME280 readings to be sent 28 | float temperature; 29 | float humidity; 30 | float pressure; 31 | 32 | // Define variables to store incoming readings 33 | float incomingTemp; 34 | float incomingHum; 35 | float incomingPres; 36 | 37 | // Variable to store if sending data was successful 38 | String success; 39 | 40 | //Structure example to send data 41 | //Must match the receiver structure 42 | typedef struct struct_message { 43 | float temp; 44 | float hum; 45 | float pres; 46 | } struct_message; 47 | 48 | // Create a struct_message called BME280Readings to hold sensor readings 49 | struct_message BME280Readings; 50 | 51 | // Create a struct_message to hold incoming sensor readings 52 | struct_message incomingReadings; 53 | 54 | esp_now_peer_info_t peerInfo; 55 | 56 | // Callback when data is sent 57 | void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { 58 | Serial.print("\r\nLast Packet Send Status:\t"); 59 | Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); 60 | if (status ==0){ 61 | success = "Delivery Success :)"; 62 | } 63 | else{ 64 | success = "Delivery Fail :("; 65 | } 66 | } 67 | 68 | // Callback when data is received 69 | void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) { 70 | memcpy(&incomingReadings, incomingData, sizeof(incomingReadings)); 71 | Serial.print("Bytes received: "); 72 | Serial.println(len); 73 | incomingTemp = incomingReadings.temp; 74 | incomingHum = incomingReadings.hum; 75 | incomingPres = incomingReadings.pres; 76 | } 77 | 78 | void setup() { 79 | // Init Serial Monitor 80 | Serial.begin(115200); 81 | 82 | // Init BME280 sensor 83 | bool status = bme.begin(0x76); 84 | if (!status) { 85 | Serial.println("Could not find a valid BME280 sensor, check wiring!"); 86 | while (1); 87 | } 88 | 89 | // Init OLED display 90 | if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { 91 | Serial.println(F("SSD1306 allocation failed")); 92 | for(;;); 93 | } 94 | 95 | // Set device as a Wi-Fi Station 96 | WiFi.mode(WIFI_STA); 97 | 98 | // Init ESP-NOW 99 | if (esp_now_init() != ESP_OK) { 100 | Serial.println("Error initializing ESP-NOW"); 101 | return; 102 | } 103 | 104 | // Once ESPNow is successfully Init, we will register for Send CB to 105 | // get the status of Trasnmitted packet 106 | esp_now_register_send_cb(OnDataSent); 107 | 108 | // Register peer 109 | memcpy(peerInfo.peer_addr, broadcastAddress, 6); 110 | peerInfo.channel = 0; 111 | peerInfo.encrypt = false; 112 | 113 | // Add peer 114 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 115 | Serial.println("Failed to add peer"); 116 | return; 117 | } 118 | // Register for a callback function that will be called when data is received 119 | esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv)); 120 | } 121 | 122 | void loop() { 123 | getReadings(); 124 | 125 | // Set values to send 126 | BME280Readings.temp = temperature; 127 | BME280Readings.hum = humidity; 128 | BME280Readings.pres = pressure; 129 | 130 | // Send message via ESP-NOW 131 | esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &BME280Readings, sizeof(BME280Readings)); 132 | 133 | if (result == ESP_OK) { 134 | Serial.println("Sent with success"); 135 | } 136 | else { 137 | Serial.println("Error sending the data"); 138 | } 139 | updateDisplay(); 140 | delay(10000); 141 | } 142 | void getReadings(){ 143 | temperature = bme.readTemperature(); 144 | humidity = bme.readHumidity(); 145 | pressure = (bme.readPressure() / 100.0F); 146 | } 147 | 148 | void updateDisplay(){ 149 | // Display Readings on OLED Display 150 | display.clearDisplay(); 151 | display.setTextSize(1); 152 | display.setTextColor(WHITE); 153 | display.setCursor(0, 0); 154 | display.println("INCOMING READINGS"); 155 | display.setCursor(0, 15); 156 | display.print("Temperature: "); 157 | display.print(incomingTemp); 158 | display.cp437(true); 159 | display.write(248); 160 | display.print("C"); 161 | display.setCursor(0, 25); 162 | display.print("Humidity: "); 163 | display.print(incomingHum); 164 | display.print("%"); 165 | display.setCursor(0, 35); 166 | display.print("Pressure: "); 167 | display.print(incomingPres); 168 | display.print("hPa"); 169 | display.setCursor(0, 56); 170 | display.print(success); 171 | display.display(); 172 | 173 | // Display Readings in Serial Monitor 174 | Serial.println("INCOMING READINGS"); 175 | Serial.print("Temperature: "); 176 | Serial.print(incomingReadings.temp); 177 | Serial.println(" ºC"); 178 | Serial.print("Humidity: "); 179 | Serial.print(incomingReadings.hum); 180 | Serial.println(" %"); 181 | Serial.print("Pressure: "); 182 | Serial.print(incomingReadings.pres); 183 | Serial.println(" hPa"); 184 | Serial.println(); 185 | } 186 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_3/ESP_NOW_Receiver/ESP_NOW_Receiver.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | //Structure example to receive data 10 | //Must match the sender structure 11 | typedef struct test_struct { 12 | int x; 13 | int y; 14 | } test_struct; 15 | 16 | //Create a struct_message called myData 17 | test_struct myData; 18 | 19 | //callback function that will be executed when data is received 20 | void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) { 21 | memcpy(&myData, incomingData, sizeof(myData)); 22 | Serial.print("Bytes received: "); 23 | Serial.println(len); 24 | Serial.print("x: "); 25 | Serial.println(myData.x); 26 | Serial.print("y: "); 27 | Serial.println(myData.y); 28 | Serial.println(); 29 | } 30 | 31 | void setup() { 32 | //Initialize Serial Monitor 33 | Serial.begin(115200); 34 | 35 | //Set device as a Wi-Fi Station 36 | WiFi.mode(WIFI_STA); 37 | 38 | //Init ESP-NOW 39 | if (esp_now_init() != ESP_OK) { 40 | Serial.println("Error initializing ESP-NOW"); 41 | return; 42 | } 43 | 44 | // Once ESPNow is successfully Init, we will register for recv CB to 45 | // get recv packer info 46 | esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv)); 47 | } 48 | 49 | void loop() { 50 | 51 | } 52 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_3/ESP_NOW_Sender_Multiple_Boards_Different_Message/ESP_NOW_Sender_Multiple_Boards_Different_Message.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | // REPLACE WITH YOUR ESP RECEIVER'S MAC ADDRESS 10 | uint8_t broadcastAddress1[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 11 | uint8_t broadcastAddress2[] = {0xFF, , , , , }; 12 | uint8_t broadcastAddress3[] = {0xFF, , , , , }; 13 | 14 | // Variable to add info about peer 15 | esp_now_peer_info_t peerInfo; 16 | 17 | typedef struct test_struct { 18 | int x; 19 | int y; 20 | } test_struct; 21 | 22 | void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { 23 | char macStr[18]; 24 | Serial.print("Packet to: "); 25 | // Copies the sender mac address to a string 26 | snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", 27 | mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); 28 | Serial.print(macStr); 29 | Serial.print(" send status:\t"); 30 | Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); 31 | } 32 | 33 | void setup() { 34 | 35 | Serial.begin(115200); 36 | 37 | WiFi.mode(WIFI_STA); 38 | 39 | if (esp_now_init() != ESP_OK) { 40 | Serial.println("Error initializing ESP-NOW"); 41 | return; 42 | } 43 | 44 | esp_now_register_send_cb(OnDataSent); 45 | 46 | // register peer 47 | peerInfo.channel = 0; 48 | peerInfo.encrypt = false; 49 | 50 | memcpy(peerInfo.peer_addr, broadcastAddress1, 6); 51 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 52 | Serial.println("Failed to add peer"); 53 | return; 54 | } 55 | 56 | memcpy(peerInfo.peer_addr, broadcastAddress2, 6); 57 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 58 | Serial.println("Failed to add peer"); 59 | return; 60 | } 61 | memcpy(peerInfo.peer_addr, broadcastAddress3, 6); 62 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 63 | Serial.println("Failed to add peer"); 64 | return; 65 | } 66 | } 67 | 68 | void loop() { 69 | test_struct test; 70 | test_struct test2; 71 | test_struct test3; 72 | test.x = random(0,20); 73 | test.y = random(0,20); 74 | test2.x = random(0,20); 75 | test2.y = random(0,20); 76 | test3.x = random(0,20); 77 | test3.y = random(0,20); 78 | 79 | esp_err_t result1 = esp_now_send( 80 | broadcastAddress1, 81 | (uint8_t *) &test, 82 | sizeof(test_struct)); 83 | 84 | if (result1 == ESP_OK) { 85 | Serial.println("Sent with success"); 86 | } 87 | else { 88 | Serial.println("Error sending the data"); 89 | } 90 | delay(500); 91 | esp_err_t result2 = esp_now_send( 92 | broadcastAddress2, 93 | (uint8_t *) &test2, 94 | sizeof(test_struct)); 95 | 96 | if (result2 == ESP_OK) { 97 | Serial.println("Sent with success"); 98 | } 99 | else { 100 | Serial.println("Error sending the data"); 101 | } 102 | 103 | delay(500); 104 | esp_err_t result3 = esp_now_send( 105 | broadcastAddress3, 106 | (uint8_t *) &test3, 107 | sizeof(test_struct)); 108 | 109 | if (result3 == ESP_OK) { 110 | Serial.println("Sent with success"); 111 | } 112 | else { 113 | Serial.println("Error sending the data"); 114 | } 115 | delay(2000); 116 | } 117 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_3/ESP_NOW_Sender_Multiple_Boards_Same_Message/ESP_NOW_Sender_Multiple_Boards_Same_Message.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | // REPLACE WITH YOUR ESP RECEIVER'S MAC ADDRESS 10 | uint8_t broadcastAddress1[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 11 | uint8_t broadcastAddress2[] = {0xFF, , , , , }; 12 | uint8_t broadcastAddress3[] = {0xFF, , , , , }; 13 | 14 | // Variable to add info about peer 15 | esp_now_peer_info_t peerInfo; 16 | 17 | typedef struct test_struct { 18 | int x; 19 | int y; 20 | } test_struct; 21 | 22 | test_struct test; 23 | 24 | // callback when data is sent 25 | void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { 26 | char macStr[18]; 27 | Serial.print("Packet to: "); 28 | // Copies the sender mac address to a string 29 | snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", 30 | mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); 31 | Serial.print(macStr); 32 | Serial.print(" send status:\t"); 33 | Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); 34 | } 35 | 36 | void setup() { 37 | Serial.begin(115200); 38 | 39 | WiFi.mode(WIFI_STA); 40 | 41 | if (esp_now_init() != ESP_OK) { 42 | Serial.println("Error initializing ESP-NOW"); 43 | return; 44 | } 45 | 46 | esp_now_register_send_cb(OnDataSent); 47 | 48 | // register peer 49 | peerInfo.channel = 0; 50 | peerInfo.encrypt = false; 51 | // register first peer 52 | memcpy(peerInfo.peer_addr, broadcastAddress1, 6); 53 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 54 | Serial.println("Failed to add peer"); 55 | return; 56 | } 57 | // register second peer 58 | memcpy(peerInfo.peer_addr, broadcastAddress2, 6); 59 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 60 | Serial.println("Failed to add peer"); 61 | return; 62 | } 63 | /// register third peer 64 | memcpy(peerInfo.peer_addr, broadcastAddress3, 6); 65 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 66 | Serial.println("Failed to add peer"); 67 | return; 68 | } 69 | } 70 | 71 | void loop() { 72 | test.x = random(0,20); 73 | test.y = random(0,20); 74 | 75 | esp_err_t result = esp_now_send(0, (uint8_t *) &test, sizeof(test_struct)); 76 | 77 | if (result == ESP_OK) { 78 | Serial.println("Sent with success"); 79 | } 80 | else { 81 | Serial.println("Error sending the data"); 82 | } 83 | delay(2000); 84 | } 85 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_4/ESP_NOW_Receiver_Multiple_Boards/ESP_NOW_Receiver_Multiple_Boards.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | // Structure example to receive data 10 | // Must match the sender structure 11 | typedef struct struct_message { 12 | int id; 13 | int x; 14 | int y; 15 | }struct_message; 16 | 17 | // Create a struct_message called myData 18 | struct_message myData; 19 | 20 | // Create a structure to hold the readings from each board 21 | struct_message board1; 22 | struct_message board2; 23 | struct_message board3; 24 | 25 | // Create an array with all the structures 26 | struct_message boardsStruct[3] = {board1, board2, board3}; 27 | 28 | // callback function that will be executed when data is received 29 | void OnDataRecv(const uint8_t * mac_addr, const uint8_t *incomingData, int len) { 30 | char macStr[18]; 31 | Serial.print("Packet received from: "); 32 | snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", 33 | mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); 34 | Serial.println(macStr); 35 | memcpy(&myData, incomingData, sizeof(myData)); 36 | Serial.printf("Board ID %u: %u bytes\n", myData.id, len); 37 | // Update the structures with the new incoming data 38 | boardsStruct[myData.id-1].x = myData.x; 39 | boardsStruct[myData.id-1].y = myData.y; 40 | Serial.printf("x value: %d \n", boardsStruct[myData.id-1].x); 41 | Serial.printf("y value: %d \n", boardsStruct[myData.id-1].y); 42 | Serial.println(); 43 | } 44 | 45 | void setup() { 46 | //Initialize Serial Monitor 47 | Serial.begin(115200); 48 | 49 | //Set device as a Wi-Fi Station 50 | WiFi.mode(WIFI_STA); 51 | 52 | //Init ESP-NOW 53 | if (esp_now_init() != ESP_OK) { 54 | Serial.println("Error initializing ESP-NOW"); 55 | return; 56 | } 57 | 58 | // Once ESPNow is successfully Init, we will register for recv CB to 59 | // get recv packer info 60 | esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv)); 61 | } 62 | 63 | void loop() { 64 | // Acess the variables for each board 65 | /*int board1X = boardsStruct[0].x; 66 | int board1Y = boardsStruct[0].y; 67 | int board2X = boardsStruct[1].x; 68 | int board2Y = boardsStruct[1].y; 69 | int board3X = boardsStruct[2].x; 70 | int board3Y = boardsStruct[2].y;*/ 71 | 72 | delay(10000); 73 | } 74 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_4/ESP_NOW_Sender/ESP_NOW_Sender.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | // REPLACE WITH THE RECEIVER'S MAC Address 10 | uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 11 | 12 | // Create a peer interface 13 | esp_now_peer_info_t peerInfo; 14 | 15 | // Structure example to send data 16 | // Must match the receiver structure 17 | typedef struct struct_message { 18 | int id; // must be unique for each sender board 19 | int x; 20 | int y; 21 | } struct_message; 22 | 23 | //Create a struct_message called myData 24 | struct_message myData; 25 | 26 | // callback when data is sent 27 | void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { 28 | Serial.print("\r\nLast Packet Send Status:\t"); 29 | Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); 30 | } 31 | 32 | void setup() { 33 | // Init Serial Monitor 34 | Serial.begin(115200); 35 | 36 | // Set device as a Wi-Fi Station 37 | WiFi.mode(WIFI_STA); 38 | 39 | // Init ESP-NOW 40 | if (esp_now_init() != ESP_OK) { 41 | Serial.println("Error initializing ESP-NOW"); 42 | return; 43 | } 44 | 45 | // Once ESPNow is successfully Init, we will register for Send CB to 46 | // get the status of Trasnmitted packet 47 | esp_now_register_send_cb(OnDataSent); 48 | 49 | // Register peer 50 | memcpy(peerInfo.peer_addr, broadcastAddress, 6); 51 | peerInfo.channel = 0; 52 | peerInfo.encrypt = false; 53 | 54 | // Add peer 55 | if (esp_now_add_peer(&peerInfo) != ESP_OK){ 56 | Serial.println("Failed to add peer"); 57 | return; 58 | } 59 | } 60 | 61 | void loop() { 62 | // Set values to send 63 | myData.id = 1; 64 | myData.x = random(0,50); 65 | myData.y = random(0,50); 66 | 67 | // Send message via ESP-NOW 68 | esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData)); 69 | 70 | if (result == ESP_OK) { 71 | Serial.println("Sent with success"); 72 | } 73 | else { 74 | Serial.println("Error sending the data"); 75 | } 76 | delay(10000); 77 | } 78 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_5/ESP_NOW_Receiver_Web_Server/ESP_NOW_Receiver_Web_Server.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | #include "ESPAsyncWebServer.h" 9 | #include 10 | 11 | // Replace with your network credentials (STATION) 12 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 13 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 14 | 15 | // Structure example to receive data 16 | // Must match the sender structure 17 | typedef struct struct_message { 18 | int id; 19 | float temp; 20 | float hum; 21 | unsigned int readingId; 22 | } struct_message; 23 | 24 | struct_message incomingReadings; 25 | 26 | JSONVar board; 27 | 28 | AsyncWebServer server(80); 29 | AsyncEventSource events("/events"); 30 | 31 | // callback function that will be executed when data is received 32 | void OnDataRecv(const uint8_t * mac_addr, const uint8_t *incomingData, int len) { 33 | // Copies the sender mac address to a string 34 | char macStr[18]; 35 | Serial.print("Packet received from: "); 36 | snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x", 37 | mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); 38 | Serial.println(macStr); 39 | memcpy(&incomingReadings, incomingData, sizeof(incomingReadings)); 40 | 41 | board["id"] = incomingReadings.id; 42 | board["temperature"] = incomingReadings.temp; 43 | board["humidity"] = incomingReadings.hum; 44 | board["readingId"] = String(incomingReadings.readingId); 45 | String jsonString = JSON.stringify(board); 46 | events.send(jsonString.c_str(), "new_readings", millis()); 47 | 48 | Serial.printf("Board ID %u: %u bytes\n", incomingReadings.id, len); 49 | Serial.printf("t value: %4.2f \n", incomingReadings.temp); 50 | Serial.printf("h value: %4.2f \n", incomingReadings.hum); 51 | Serial.printf("readingID value: %d \n", incomingReadings.readingId); 52 | Serial.println(); 53 | } 54 | 55 | const char index_html[] PROGMEM = R"rawliteral( 56 | 57 | 58 | ESP-NOW DASHBOARD 59 | 60 | 61 | 62 | 75 | 76 | 77 |
78 |

ESP-NOW DASHBOARD

79 |
80 |
81 |
82 |
83 |

BOARD #1 - TEMPERATURE

°C

Reading ID:

84 |
85 |
86 |

BOARD #1 - HUMIDITY

%

Reading ID:

87 |
88 |
89 |

BOARD #2 - TEMPERATURE

°C

Reading ID:

90 |
91 |
92 |

BOARD #2 - HUMIDITY

%

Reading ID:

93 |
94 |
95 |
96 | 123 | 124 | )rawliteral"; 125 | 126 | void setup() { 127 | // Initialize Serial Monitor 128 | Serial.begin(115200); 129 | 130 | // Set the device as a Station and Soft Access Point simultaneously 131 | WiFi.mode(WIFI_AP_STA); 132 | 133 | // Set device as a Wi-Fi Station 134 | WiFi.begin(ssid, password); 135 | while (WiFi.status() != WL_CONNECTED) { 136 | delay(1000); 137 | Serial.println("Setting as a Wi-Fi Station.."); 138 | } 139 | Serial.print("Station IP Address: "); 140 | Serial.println(WiFi.localIP()); 141 | Serial.print("Wi-Fi Channel: "); 142 | Serial.println(WiFi.channel()); 143 | 144 | // Init ESP-NOW 145 | if (esp_now_init() != ESP_OK) { 146 | Serial.println("Error initializing ESP-NOW"); 147 | return; 148 | } 149 | 150 | // Once ESPNow is successfully Init, we will register for recv CB to 151 | // get recv packer info 152 | esp_now_register_recv_cb(esp_now_recv_cb_t(OnDataRecv)); 153 | 154 | server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ 155 | request->send_P(200, "text/html", index_html); 156 | }); 157 | 158 | events.onConnect([](AsyncEventSourceClient *client){ 159 | if(client->lastId()){ 160 | Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId()); 161 | } 162 | // send event with message "hello!", id current millis 163 | // and set reconnect delay to 1 second 164 | client->send("hello!", NULL, millis(), 10000); 165 | }); 166 | server.addHandler(&events); 167 | server.begin(); 168 | } 169 | 170 | void loop() { 171 | static unsigned long lastEventTime = millis(); 172 | static const unsigned long EVENT_INTERVAL_MS = 5000; 173 | if ((millis() - lastEventTime) > EVENT_INTERVAL_MS) { 174 | events.send("ping",NULL,millis()); 175 | lastEventTime = millis(); 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /code/ESP_NOW/Unit_5/ESP_NOW_Sender/ESP_NOW_Sender.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | // Set your Board ID (ESP32 Sender #1 = BOARD_ID 1, ESP32 Sender #2 = BOARD_ID 2, etc) 13 | #define BOARD_ID 1 14 | 15 | // Digital pin connected to the DHT sensor 16 | #define DHTPIN 4 17 | 18 | // Uncomment the type of sensor in use: 19 | //#define DHTTYPE DHT11 // DHT 11 20 | #define DHTTYPE DHT22 // DHT 22 (AM2302) 21 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) 22 | 23 | DHT dht(DHTPIN, DHTTYPE); 24 | 25 | //MAC Address of the receiver 26 | uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 27 | 28 | // Variable to add info about peer 29 | esp_now_peer_info_t peerInfo; 30 | 31 | //Structure example to send data 32 | //Must match the receiver structure 33 | typedef struct struct_message { 34 | int id; 35 | float temp; 36 | float hum; 37 | int readingId; 38 | } struct_message; 39 | 40 | //Create a struct_message called myData 41 | struct_message myData; 42 | 43 | unsigned long previousMillis = 0; // Stores last time temperature was published 44 | const long interval = 10000; // Interval at which to publish sensor readings 45 | 46 | unsigned int readingId = 0; 47 | 48 | // Insert your SSID 49 | constexpr char WIFI_SSID[] = "REPLACE_WITH_YOUR_SSID"; 50 | 51 | int32_t getWiFiChannel(const char *ssid) { 52 | if (int32_t n = WiFi.scanNetworks()) { 53 | for (uint8_t i=0; i= interval) { 139 | // Save the last time a new reading was published 140 | previousMillis = currentMillis; 141 | //Set values to send 142 | myData.id = BOARD_ID; 143 | myData.temp = readDHTTemperature(); 144 | myData.hum = readDHTHumidity(); 145 | myData.readingId = readingId++; 146 | 147 | //Send message via ESP-NOW 148 | esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData)); 149 | if (result == ESP_OK) { 150 | Serial.println("Sent with success"); 151 | } 152 | else { 153 | Serial.println("Error sending the data"); 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /code/Hall_Effect_Sensor/Hall_Effect_Sensor.ino: -------------------------------------------------------------------------------- 1 | // Simple sketch to access the internal hall effect detector on the esp32. 2 | // values can be quite low. 3 | // Brian Degger / @sctv 4 | 5 | int val = 0; 6 | 7 | void setup() { 8 | Serial.begin(9600); 9 | } 10 | 11 | // put your main code here, to run repeatedly 12 | void loop() { 13 | // read hall effect sensor value 14 | val = hallRead(); 15 | // print the results to the serial monitor 16 | Serial.println(val); 17 | delay(1000); 18 | } 19 | -------------------------------------------------------------------------------- /code/LED_PWM_Example_1/LED_PWM_Example_1.ino: -------------------------------------------------------------------------------- 1 | // the number of the LED pin 2 | const int ledPin = 16; // 16 corresponds to GPIO16 3 | 4 | // setting PWM properties 5 | const int freq = 5000; 6 | const int resolution = 8; 7 | 8 | void setup(){ 9 | // configure LED PWM 10 | ledcAttach(ledPin, freq, resolution); 11 | 12 | // if you want to attach a specific channel, use the following instead 13 | //ledcAttachChannel(ledPin, freq, resolution, 0); 14 | } 15 | 16 | void loop(){ 17 | // increase the LED brightness 18 | for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){ 19 | // changing the LED brightness with PWM 20 | ledcWrite(ledPin, dutyCycle); 21 | delay(15); 22 | } 23 | 24 | // decrease the LED brightness 25 | for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){ 26 | // changing the LED brightness with PWM 27 | ledcWrite(ledPin, dutyCycle); 28 | delay(15); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /code/LED_PWM_Example_1/LED_PWM_Example_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LED_PWM_Example_1/LED_PWM_Example_1.png -------------------------------------------------------------------------------- /code/LED_PWM_Example_2/LED_PWM_Example_2.ino: -------------------------------------------------------------------------------- 1 | // DEPRECATED - This code only works with ESP32 Arduino Core version 2.0.X 2 | 3 | // the number of the LED pin 4 | const int ledPin = 16; // 16 corresponds to GPIO16 5 | const int ledPin2 = 17; // 17 corresponds to GPIO17 6 | const int ledPin3 = 5; // 5 corresponds to GPIO5 7 | 8 | // setting PWM properties 9 | const int freq = 5000; 10 | const int ledChannel = 0; 11 | const int resolution = 8; 12 | 13 | void setup(){ 14 | // configure LED PWM functionalitites 15 | ledcSetup(ledChannel, freq, resolution); 16 | 17 | // attach the channel to the GPIO to be controlled 18 | ledcAttachPin(ledPin, ledChannel); 19 | ledcAttachPin(ledPin2, ledChannel); 20 | ledcAttachPin(ledPin3, ledChannel); 21 | } 22 | 23 | void loop(){ 24 | // increase the LED brightness 25 | for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){ 26 | // changing the LED brightness with PWM 27 | ledcWrite(ledChannel, dutyCycle); 28 | delay(15); 29 | } 30 | 31 | // decrease the LED brightness 32 | for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){ 33 | // changing the LED brightness with PWM 34 | ledcWrite(ledChannel, dutyCycle); 35 | delay(15); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /code/LED_PWM_Example_2/LED_PWM_Example_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LED_PWM_Example_2/LED_PWM_Example_2.png -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Receiver/LoRa_Receiver_Step_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Receiver/LoRa_Receiver_Step_1.png -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Receiver/LoRa_Receiver_Step_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Receiver/LoRa_Receiver_Step_2.png -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Libraries for LoRa Module 7 | #include 8 | #include 9 | 10 | //DS18B20 libraries 11 | #include 12 | #include 13 | 14 | // LoRa Module pin definition 15 | // define the pins used by the transceiver module 16 | #define ss 5 17 | #define rst 14 18 | #define dio0 2 19 | 20 | // LoRa message variable 21 | String message; 22 | 23 | // Save reading number on RTC memory 24 | RTC_DATA_ATTR int readingID = 0; 25 | 26 | // Define deep sleep options 27 | uint64_t uS_TO_S_FACTOR = 1000000; // Conversion factor for micro seconds to seconds 28 | // Sleep for 30 minutes = 0.5 hours = 1800 seconds 29 | uint64_t TIME_TO_SLEEP = 1800; 30 | 31 | // Data wire is connected to ESP32 GPIO15 32 | #define ONE_WIRE_BUS 15 33 | // Setup a oneWire instance to communicate with a OneWire device 34 | OneWire oneWire(ONE_WIRE_BUS); 35 | // Pass our oneWire reference to Dallas Temperature sensor 36 | DallasTemperature sensors(&oneWire); 37 | 38 | // Moisture Sensor variables 39 | const int moisturePin = 26; 40 | const int moisturePowerPin = 12; 41 | int soilMoisture; 42 | 43 | // Temperature Sensor variables 44 | float tempC; 45 | float tempF; 46 | 47 | //Variable to hold battery level; 48 | float batteryLevel; 49 | const int batteryPin = 27; 50 | 51 | void setup() { 52 | pinMode(moisturePowerPin, OUTPUT); 53 | 54 | // Start serial communication for debugging purposes 55 | Serial.begin(115200); 56 | 57 | // Enable Timer wake_up 58 | esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); 59 | 60 | // Start the DallasTemperature library 61 | sensors.begin(); 62 | 63 | // Initialize LoRa 64 | //replace the LoRa.begin(---E-) argument with your location's frequency 65 | //note: the frequency should match the sender's frequency 66 | //433E6 for Asia 67 | //866E6 for Europe 68 | //915E6 for North America 69 | LoRa.setPins(ss, rst, dio0); 70 | Serial.println("initializing LoRa"); 71 | 72 | int counter = 0; 73 | while (!LoRa.begin(866E6) && counter < 10) { 74 | Serial.print("."); 75 | counter++; 76 | delay(500); 77 | } 78 | if (counter == 10) { 79 | // Increment readingID on every new reading 80 | readingID++; 81 | // Start deep sleep 82 | Serial.println("Failed to initialize LoRa. Going to sleep now"); 83 | esp_deep_sleep_start(); 84 | } 85 | // Change sync word (0xF3) to match the receiver 86 | // The sync word assures you don't get LoRa messages from other LoRa transceivers 87 | // ranges from 0-0xFF 88 | LoRa.setSyncWord(0xF3); 89 | Serial.println("LoRa initializing OK!"); 90 | 91 | getReadings(); 92 | Serial.print("Battery level = "); 93 | Serial.println(batteryLevel, 2); 94 | Serial.print("Soil moisture = "); 95 | Serial.println(soilMoisture); 96 | Serial.print("Temperature Celsius = "); 97 | Serial.println(tempC); 98 | Serial.print("Temperature Fahrenheit = "); 99 | Serial.println(tempF); 100 | Serial.print("Reading ID = "); 101 | Serial.println(readingID); 102 | 103 | sendReadings(); 104 | Serial.print("Message sent = "); 105 | Serial.println(message); 106 | 107 | // Increment readingID on every new reading 108 | readingID++; 109 | 110 | // Start deep sleep 111 | Serial.println("DONE! Going to sleep now."); 112 | esp_deep_sleep_start(); 113 | } 114 | 115 | void loop() { 116 | // The ESP32 will be in deep sleep 117 | // it never reaches the loop() 118 | } 119 | 120 | void getReadings() { 121 | digitalWrite(moisturePowerPin, HIGH); 122 | 123 | // Measure temperature 124 | sensors.requestTemperatures(); 125 | tempC = sensors.getTempCByIndex(0); // Temperature in Celsius 126 | tempF = sensors.getTempFByIndex(0); // Temperature in Fahrenheit 127 | 128 | // Measure moisture 129 | soilMoisture = analogRead(moisturePin); 130 | digitalWrite(moisturePowerPin, LOW); 131 | 132 | //Measure battery level 133 | batteryLevel = map(analogRead(batteryPin), 0.0f, 4095.0f, 0, 100); 134 | } 135 | 136 | void sendReadings() { 137 | // Send packet data 138 | // Send temperature in Celsius 139 | message = String(readingID) + "/" + String(tempC) + "&" + 140 | String(soilMoisture) + "#" + String(batteryLevel); 141 | // Uncomment to send temperature in Fahrenheit 142 | //message = String(readingID) + "/" + String(tempF) + "&" + 143 | // String(soilMoisture) + "#" + String(batteryLevel); 144 | delay(1000); 145 | LoRa.beginPacket(); 146 | LoRa.print(message); 147 | LoRa.endPacket(); 148 | } 149 | -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_1.png -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_2.png -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_3.png -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_4.PNG -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_5.PNG -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_6.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_6.PNG -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_7.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_7.PNG -------------------------------------------------------------------------------- /code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_8.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_Project/LoRa_Sender/LoRa_Sender_Step_8.PNG -------------------------------------------------------------------------------- /code/LoRa_RFM95/LoRa_Receiver/LoRa_Receiver.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | //define the pins used by the transceiver module 13 | #define ss 5 14 | #define rst 14 15 | #define dio0 2 16 | 17 | #define SCREEN_WIDTH 128 // OLED display width, in pixels 18 | #define SCREEN_HEIGHT 64 // OLED display height, in pixels 19 | 20 | // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) 21 | #define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin) 22 | Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); 23 | 24 | void setup() { 25 | // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally 26 | if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 27 | Serial.println(F("SSD1306 allocation failed")); 28 | for(;;); // Don't proceed, loop forever 29 | } 30 | 31 | display.clearDisplay(); 32 | display.setTextSize(1); 33 | display.setTextColor(WHITE); 34 | display.setCursor(0,0); 35 | display.println("LoRa Receiver"); 36 | display.display(); 37 | 38 | Serial.begin(115200); 39 | while (!Serial); 40 | Serial.println("LoRa Receiver"); 41 | 42 | //setup LoRa transceiver module 43 | LoRa.setPins(ss, rst, dio0); 44 | 45 | //replace the LoRa.begin(---E-) argument with your location's frequency 46 | //note: the frequency should match the sender's frequency 47 | //433E6 for Asia 48 | //866E6 for Europe 49 | //915E6 for North America 50 | if (!LoRa.begin(866E6)) { 51 | Serial.println("Starting LoRa failed!"); 52 | while (1); 53 | } 54 | Serial.println("LoRa Initializing OK!"); 55 | display.setCursor(0,10); 56 | display.println("LoRa Initializing OK!"); 57 | display.display(); 58 | } 59 | 60 | void loop() { 61 | //try to parse packet 62 | int packetSize = LoRa.parsePacket(); 63 | if (packetSize) { 64 | //received a packet 65 | Serial.print("Received packet "); 66 | display.clearDisplay(); 67 | display.setCursor(0,0); 68 | display.print("Received packet "); 69 | display.display(); 70 | 71 | //read packet 72 | while (LoRa.available()) { 73 | String LoRaData = LoRa.readString(); 74 | Serial.print(LoRaData); 75 | display.setCursor(0,10); 76 | display.print(LoRaData); 77 | display.display(); 78 | } 79 | 80 | //print RSSI of packet 81 | int rssi = LoRa.packetRssi(); 82 | Serial.print(" with RSSI "); 83 | Serial.println(rssi); 84 | display.setCursor(0,20); 85 | display.print("RSSI: "); 86 | display.setCursor(30,20); 87 | display.print(rssi); 88 | display.display(); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /code/LoRa_RFM95/LoRa_Receiver/LoRa_Receiver.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_RFM95/LoRa_Receiver/LoRa_Receiver.png -------------------------------------------------------------------------------- /code/LoRa_RFM95/LoRa_Sender/LoRa_Sender.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | //define the pins used by the transceiver module 10 | #define ss 5 11 | #define rst 14 12 | #define dio0 2 13 | 14 | int counter = 0; 15 | 16 | void setup() { 17 | //initialize Serial Monitor 18 | Serial.begin(115200); 19 | while (!Serial); 20 | Serial.println("LoRa Sender"); 21 | 22 | //setup LoRa transceiver module 23 | LoRa.setPins(ss, rst, dio0); 24 | 25 | //replace the LoRa.begin(---E-) argument with your location's frequency 26 | //433E6 for Asia 27 | //866E6 for Europe 28 | //915E6 for North America 29 | if (!LoRa.begin(866E6)) { 30 | Serial.println("Starting LoRa failed!"); 31 | while (1); 32 | } 33 | Serial.println("LoRa Initializing OK!"); 34 | } 35 | 36 | void loop() { 37 | Serial.print("Sending packet: "); 38 | Serial.println(counter); 39 | 40 | //Send LoRa packet to receiver 41 | LoRa.beginPacket(); 42 | LoRa.print("hello "); 43 | LoRa.print(counter); 44 | LoRa.endPacket(); 45 | 46 | counter++; 47 | 48 | delay(10000); 49 | } 50 | -------------------------------------------------------------------------------- /code/LoRa_RFM95/LoRa_Sender/LoRa_Sender.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/LoRa_RFM95/LoRa_Sender/LoRa_Sender.png -------------------------------------------------------------------------------- /code/MQTT/ESP32_Client_1_LED_DS18B20/ESP32_Client_1_LED_DS18B20.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | #include 7 | extern "C" { 8 | #include "freertos/FreeRTOS.h" 9 | #include "freertos/timers.h" 10 | } 11 | #include 12 | #include 13 | #include 14 | 15 | // Change the credentials below, so your ESP32 connects to your router 16 | #define WIFI_SSID "REPLACE_WITH_YOUR_SSID" 17 | #define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD" 18 | 19 | // Change the MQTT_HOST variable to your Raspberry Pi IP address, 20 | // so it connects to your Mosquitto MQTT broker 21 | #define MQTT_HOST IPAddress(192, 168, 1, XXX) 22 | #define MQTT_PORT 1883 23 | 24 | #define BROKER_USER "REPLACE_WITH_BROKER_USERNAME" 25 | #define BROKER_PASS "REPLACE_WITH_BROKER_PASSWORD" 26 | 27 | // Create objects to handle MQTT client 28 | AsyncMqttClient mqttClient; 29 | TimerHandle_t mqttReconnectTimer; 30 | TimerHandle_t wifiReconnectTimer; 31 | 32 | String temperatureString = ""; // Variable to hold the temperature reading 33 | unsigned long previousMillis = 0; // Stores last time temperature was published 34 | const long interval = 5000; // interval at which to publish sensor readings 35 | 36 | const int ledPin = 25; // GPIO where the LED is connected to 37 | int ledState = LOW; // the current state of the output pin 38 | 39 | // GPIO where the DS18B20 is connected to 40 | const int oneWireBus = 32; 41 | // Setup a oneWire instance to communicate with any OneWire devices 42 | OneWire oneWire(oneWireBus); 43 | // Pass our oneWire reference to Dallas Temperature sensor 44 | DallasTemperature sensors(&oneWire); 45 | 46 | void connectToWifi() { 47 | Serial.println("Connecting to Wi-Fi..."); 48 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 49 | } 50 | 51 | void connectToMqtt() { 52 | Serial.println("Connecting to MQTT..."); 53 | mqttClient.connect(); 54 | } 55 | 56 | void WiFiEvent(WiFiEvent_t event) { 57 | Serial.printf("[WiFi-event] event: %d\n", event); 58 | switch(event) { 59 | case ARDUINO_EVENT_WIFI_STA_GOT_IP: 60 | Serial.println("WiFi connected"); 61 | Serial.println("IP address: "); 62 | Serial.println(WiFi.localIP()); 63 | connectToMqtt(); 64 | break; 65 | case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: 66 | Serial.println("WiFi lost connection"); 67 | xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi 68 | xTimerStart(wifiReconnectTimer, 0); 69 | break; 70 | } 71 | } 72 | 73 | // Add more topics that want your ESP32 to be subscribed to 74 | void onMqttConnect(bool sessionPresent) { 75 | Serial.println("Connected to MQTT."); 76 | Serial.print("Session present: "); 77 | Serial.println(sessionPresent); 78 | // ESP32 subscribed to esp32/led topic 79 | uint16_t packetIdSub = mqttClient.subscribe("esp32/led", 0); 80 | Serial.print("Subscribing at QoS 0, packetId: "); 81 | Serial.println(packetIdSub); 82 | } 83 | 84 | void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { 85 | Serial.println("Disconnected from MQTT."); 86 | if (WiFi.isConnected()) { 87 | xTimerStart(mqttReconnectTimer, 0); 88 | } 89 | } 90 | 91 | void onMqttSubscribe(uint16_t packetId, uint8_t qos) { 92 | Serial.println("Subscribe acknowledged."); 93 | Serial.print(" packetId: "); 94 | Serial.println(packetId); 95 | Serial.print(" qos: "); 96 | Serial.println(qos); 97 | } 98 | 99 | void onMqttUnsubscribe(uint16_t packetId) { 100 | Serial.println("Unsubscribe acknowledged."); 101 | Serial.print(" packetId: "); 102 | Serial.println(packetId); 103 | } 104 | 105 | void onMqttPublish(uint16_t packetId) { 106 | Serial.println("Publish acknowledged."); 107 | Serial.print(" packetId: "); 108 | Serial.println(packetId); 109 | } 110 | 111 | // You can modify this function to handle what happens when you receive a certain message in a specific topic 112 | void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { 113 | String messageTemp; 114 | for (int i = 0; i < len; i++) { 115 | //Serial.print((char)payload[i]); 116 | messageTemp += (char)payload[i]; 117 | } 118 | // Check if the MQTT message was received on topic esp32/led 119 | if (strcmp(topic, "esp32/led") == 0) { 120 | // If the LED is off turn it on (and vice-versa) 121 | if (ledState == LOW) { 122 | ledState = HIGH; 123 | } else { 124 | ledState = LOW; 125 | } 126 | // Set the LED with the ledState of the variable 127 | digitalWrite(ledPin, ledState); 128 | } 129 | 130 | Serial.println("Publish received."); 131 | Serial.print(" message: "); 132 | Serial.println(messageTemp); 133 | Serial.print(" topic: "); 134 | Serial.println(topic); 135 | Serial.print(" qos: "); 136 | Serial.println(properties.qos); 137 | Serial.print(" dup: "); 138 | Serial.println(properties.dup); 139 | Serial.print(" retain: "); 140 | Serial.println(properties.retain); 141 | Serial.print(" len: "); 142 | Serial.println(len); 143 | Serial.print(" index: "); 144 | Serial.println(index); 145 | Serial.print(" total: "); 146 | Serial.println(total); 147 | } 148 | 149 | void setup() { 150 | // Start the DS18B20 sensor 151 | sensors.begin(); 152 | // Define LED as an OUTPUT and set it LOW 153 | pinMode(ledPin, OUTPUT); 154 | digitalWrite(ledPin, LOW); 155 | 156 | Serial.begin(115200); 157 | 158 | mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToMqtt)); 159 | wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToWifi)); 160 | 161 | WiFi.onEvent(WiFiEvent); 162 | 163 | mqttClient.onConnect(onMqttConnect); 164 | mqttClient.onDisconnect(onMqttDisconnect); 165 | mqttClient.onSubscribe(onMqttSubscribe); 166 | mqttClient.onUnsubscribe(onMqttUnsubscribe); 167 | mqttClient.onMessage(onMqttMessage); 168 | mqttClient.onPublish(onMqttPublish); 169 | mqttClient.setServer(MQTT_HOST, MQTT_PORT); 170 | mqttClient.setCredentials(BROKER_USER, BROKER_PASS); 171 | 172 | connectToWifi(); 173 | } 174 | 175 | void loop() { 176 | unsigned long currentMillis = millis(); 177 | // Every X number of seconds (interval = 5 seconds) 178 | // it publishes a new MQTT message on topic esp32/temperature 179 | if (currentMillis - previousMillis >= interval) { 180 | // Save the last time a new reading was published 181 | previousMillis = currentMillis; 182 | // New temperature readings 183 | sensors.requestTemperatures(); 184 | temperatureString = " " + String(sensors.getTempCByIndex(0)) + "C " + 185 | String(sensors.getTempFByIndex(0)) + "F"; 186 | Serial.println(temperatureString); 187 | // Publish an MQTT message on topic esp32/temperature with Celsius and Fahrenheit temperature readings 188 | uint16_t packetIdPub2 = mqttClient.publish("esp32/temperature", 2, true, temperatureString.c_str()); 189 | Serial.print("Publishing on topic esp32/temperature at QoS 2, packetId: "); 190 | Serial.println(packetIdPub2); 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /code/MQTT/ESP32_Client_1_LED_DS18B20/ESP32_MQTT_Client_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/MQTT/ESP32_Client_1_LED_DS18B20/ESP32_MQTT_Client_1.png -------------------------------------------------------------------------------- /code/MQTT/ESP32_Client_2_LCD_PUSHBUTTON/ESP32_Client_2_LCD_PUSHBUTTON.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | #include 7 | #include 8 | 9 | extern "C" { 10 | #include "freertos/FreeRTOS.h" 11 | #include "freertos/timers.h" 12 | } 13 | 14 | #include 15 | #include 16 | 17 | // Change the credentials below, so your ESP32 connects to your router 18 | #define WIFI_SSID "REPLACE_WITH_YOUR_SSID" 19 | #define WIFI_PASSWORD "REPLACE_WITH_YOUR_PASSWORD" 20 | 21 | // Change the MQTT_HOST variable to your Raspberry Pi IP address, 22 | // so it connects to your Mosquitto MQTT broker 23 | #define MQTT_HOST IPAddress(192, 168, 1, XXX) 24 | #define MQTT_PORT 1883 25 | 26 | #define BROKER_USER "REPLACE_WITH_BROKER_USERNAME" 27 | #define BROKER_PASS "REPLACE_WITH_BROKER_PASSWORD" 28 | 29 | // Create objects to handle MQTT client 30 | AsyncMqttClient mqttClient; 31 | TimerHandle_t mqttReconnectTimer; 32 | TimerHandle_t wifiReconnectTimer; 33 | 34 | // Set the LCD number of columns and rows 35 | const int lcdColumns = 16; 36 | const int lcdRows = 2; 37 | 38 | // Set LCD address, number of columns and rows 39 | // if you don't know your display address, run an I2C scanner sketch 40 | LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); 41 | 42 | // Thermometer icon 43 | byte thermometerIcon[8] = { 44 | B00100, 45 | B01010, 46 | B01010, 47 | B01010, 48 | B01010, 49 | B10001, 50 | B11111, 51 | B01110 52 | }; 53 | 54 | // Define GPIO where the pushbutton is connected to 55 | const int buttonPin = 32; 56 | int buttonState; // current reading from the input pin (pushbutton) 57 | int lastButtonState = LOW; // previous reading from the input pin (pushbutton) 58 | unsigned long lastDebounceTime = 0; // the last time the output pin was toggled 59 | unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers 60 | 61 | void connectToWifi() { 62 | Serial.println("Connecting to Wi-Fi..."); 63 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 64 | } 65 | 66 | void connectToMqtt() { 67 | Serial.println("Connecting to MQTT..."); 68 | mqttClient.connect(); 69 | } 70 | 71 | void WiFiEvent(WiFiEvent_t event) { 72 | Serial.printf("[WiFi-event] event: %d\n", event); 73 | switch(event) { 74 | case ARDUINO_EVENT_WIFI_STA_GOT_IP: 75 | Serial.println("WiFi connected"); 76 | Serial.println("IP address: "); 77 | Serial.println(WiFi.localIP()); 78 | connectToMqtt(); 79 | break; 80 | case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: 81 | Serial.println("WiFi lost connection"); 82 | xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi 83 | xTimerStart(wifiReconnectTimer, 0); 84 | break; 85 | } 86 | } 87 | 88 | // Add more topics that want your ESP32 to be subscribed to 89 | void onMqttConnect(bool sessionPresent) { 90 | Serial.println("Connected to MQTT."); 91 | Serial.print("Session present: "); 92 | Serial.println(sessionPresent); 93 | uint16_t packetIdSub = mqttClient.subscribe("esp32/temperature", 0); 94 | Serial.print("Subscribing at QoS 0, packetId: "); 95 | Serial.println(packetIdSub); 96 | } 97 | 98 | void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { 99 | Serial.println("Disconnected from MQTT."); 100 | if (WiFi.isConnected()) { 101 | xTimerStart(mqttReconnectTimer, 0); 102 | } 103 | } 104 | 105 | void onMqttSubscribe(uint16_t packetId, uint8_t qos) { 106 | Serial.println("Subscribe acknowledged."); 107 | Serial.print(" packetId: "); 108 | Serial.println(packetId); 109 | Serial.print(" qos: "); 110 | Serial.println(qos); 111 | } 112 | 113 | void onMqttUnsubscribe(uint16_t packetId) { 114 | Serial.println("Unsubscribe acknowledged."); 115 | Serial.print(" packetId: "); 116 | Serial.println(packetId); 117 | } 118 | 119 | void onMqttPublish(uint16_t packetId) { 120 | Serial.println("Publish acknowledged."); 121 | Serial.print(" packetId: "); 122 | Serial.println(packetId); 123 | } 124 | 125 | // You can modify this function to handle what happens when you receive a certain message in a specific topic 126 | void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { 127 | String messageTemp; 128 | for (int i = 0; i < len; i++) { 129 | //Serial.print((char)payload[i]); 130 | messageTemp += (char)payload[i]; 131 | } 132 | if (strcmp(topic, "esp32/temperature") == 0) { 133 | Serial.println("=== Updating LCD... ==="); 134 | Wire.setClock(10000); 135 | lcd.print(std::string(" ", lcdColumns).c_str()); // Clears row, better than the slow lcd.clear() 136 | lcd.setCursor(0, 1); 137 | lcd.print(messageTemp); 138 | } 139 | 140 | Serial.println("Publish received."); 141 | Serial.print(" message: "); 142 | Serial.println(messageTemp); 143 | Serial.print(" topic: "); 144 | Serial.println(topic); 145 | Serial.print(" qos: "); 146 | Serial.println(properties.qos); 147 | Serial.print(" dup: "); 148 | Serial.println(properties.dup); 149 | Serial.print(" retain: "); 150 | Serial.println(properties.retain); 151 | Serial.print(" len: "); 152 | Serial.println(len); 153 | Serial.print(" index: "); 154 | Serial.println(index); 155 | Serial.print(" total: "); 156 | Serial.println(total); 157 | } 158 | 159 | void setup() { 160 | // Initialize LCD 161 | lcd.init(); 162 | // Turn on LCD backlight 163 | lcd.backlight(); 164 | // Create thermometer icon 165 | lcd.createChar(0, thermometerIcon); 166 | lcd.setCursor(1, 0); 167 | lcd.write(0); 168 | // Print header 169 | lcd.print(" Temperature"); 170 | 171 | // Define buttonPin as an INPUT 172 | pinMode(buttonPin, INPUT); 173 | 174 | Serial.begin(115200); 175 | 176 | mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToMqtt)); 177 | wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast(connectToWifi)); 178 | 179 | WiFi.onEvent(WiFiEvent); 180 | 181 | mqttClient.onConnect(onMqttConnect); 182 | mqttClient.onDisconnect(onMqttDisconnect); 183 | mqttClient.onSubscribe(onMqttSubscribe); 184 | mqttClient.onUnsubscribe(onMqttUnsubscribe); 185 | mqttClient.onMessage(onMqttMessage); 186 | mqttClient.onPublish(onMqttPublish); 187 | mqttClient.setServer(MQTT_HOST, MQTT_PORT); 188 | mqttClient.setCredentials(BROKER_USER, BROKER_PASS); 189 | 190 | connectToWifi(); 191 | } 192 | 193 | void loop() { 194 | // Read the state of the pushbutton and save it in a local variable 195 | int reading = digitalRead(buttonPin); 196 | 197 | // If the pushbutton state changed (due to noise or pressing it), reset the timer 198 | if (reading != lastButtonState) { 199 | // Reset the debouncing timer 200 | lastDebounceTime = millis(); 201 | } 202 | 203 | // If the button state has changed, after the debounce time 204 | if ((millis() - lastDebounceTime) > debounceDelay) { 205 | // And if the current reading is different than the current buttonState 206 | if (reading != buttonState) { 207 | buttonState = reading; 208 | // Publish an MQTT message on topic esp32/led to toggle the LED (turn the LED on or off)P 209 | if (buttonState == HIGH) { 210 | mqttClient.publish("esp32/led", 0, true, "toggle"); 211 | Serial.println("Publishing on topic esp32/led topic at QoS 0"); 212 | } 213 | } 214 | } 215 | // Save the reading. Next time through the loop, it'll be the lastButtonState 216 | lastButtonState = reading; 217 | } 218 | -------------------------------------------------------------------------------- /code/MQTT/ESP32_Client_2_LCD_PUSHBUTTON/ESP32_MQTT_Client_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/MQTT/ESP32_Client_2_LCD_PUSHBUTTON/ESP32_MQTT_Client_2.png -------------------------------------------------------------------------------- /code/OTA/OTA_Web_Updater/OTA_Web_Updater.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * OTAWebUpdater.ino Example from ArduinoOTA Library 3 | * Rui Santos 4 | * Complete Project Details http://randomnerdtutorials.com 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | const char* host = "esp32"; 14 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 15 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 16 | 17 | WebServer server(80); 18 | 19 | /* 20 | * Login page 21 | */ 22 | const char* loginIndex = 23 | "
" 24 | "" 25 | "" 26 | "" 30 | "
" 31 | "
" 32 | "" 33 | "" 34 | "" 35 | "" 36 | "
" 37 | "
" 38 | "" 39 | "" 40 | "" 41 | "
" 42 | "
" 43 | "" 44 | "" 45 | "" 46 | "" 47 | "
" 27 | "
ESP32 Login Page
" 28 | "
" 29 | "
Username:
Password:
" 48 | "
" 49 | ""; 62 | 63 | /* 64 | * Server Index Page 65 | */ 66 | 67 | const char* serverIndex = 68 | "" 69 | "
" 70 | "" 71 | "" 72 | "
" 73 | "
progress: 0%
" 74 | ""; 103 | 104 | /* 105 | * setup function 106 | */ 107 | void setup(void) { 108 | Serial.begin(115200); 109 | 110 | // Connect to WiFi network 111 | WiFi.begin(ssid, password); 112 | Serial.println(""); 113 | 114 | // Wait for connection 115 | while (WiFi.status() != WL_CONNECTED) { 116 | delay(500); 117 | Serial.print("."); 118 | } 119 | Serial.println(""); 120 | Serial.print("Connected to "); 121 | Serial.println(ssid); 122 | Serial.print("IP address: "); 123 | Serial.println(WiFi.localIP()); 124 | 125 | /*use mdns for host name resolution*/ 126 | if (!MDNS.begin(host)) { //http://esp32.local 127 | Serial.println("Error setting up MDNS responder!"); 128 | while (1) { 129 | delay(1000); 130 | } 131 | } 132 | Serial.println("mDNS responder started"); 133 | /*return index page which is stored in serverIndex */ 134 | server.on("/", HTTP_GET, []() { 135 | server.sendHeader("Connection", "close"); 136 | server.send(200, "text/html", loginIndex); 137 | }); 138 | server.on("/serverIndex", HTTP_GET, []() { 139 | server.sendHeader("Connection", "close"); 140 | server.send(200, "text/html", serverIndex); 141 | }); 142 | /*handling uploading firmware file */ 143 | server.on("/update", HTTP_POST, []() { 144 | server.sendHeader("Connection", "close"); 145 | server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); 146 | ESP.restart(); 147 | }, []() { 148 | HTTPUpload& upload = server.upload(); 149 | if (upload.status == UPLOAD_FILE_START) { 150 | Serial.printf("Update: %s\n", upload.filename.c_str()); 151 | if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size 152 | Update.printError(Serial); 153 | } 154 | } else if (upload.status == UPLOAD_FILE_WRITE) { 155 | /* flashing firmware to ESP*/ 156 | if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { 157 | Update.printError(Serial); 158 | } 159 | } else if (upload.status == UPLOAD_FILE_END) { 160 | if (Update.end(true)) { //true to set the size to the current progress 161 | Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); 162 | } else { 163 | Update.printError(Serial); 164 | } 165 | } 166 | }); 167 | server.begin(); 168 | } 169 | 170 | void loop(void) { 171 | server.handleClient(); 172 | delay(1); 173 | } 174 | -------------------------------------------------------------------------------- /code/OTA/OTA_Web_Updater_LED/OTA_Web_Updater_LED.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * Rui Santos 3 | * Complete Project Details http://randomnerdtutorials.com 4 | */ 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | const char* host = "esp32"; 13 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 14 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 15 | 16 | //variabls to blink without delay: 17 | const int led = 2; 18 | unsigned long previousMillis = 0; // will store last time LED was updated 19 | const long interval = 1000; // interval at which to blink (milliseconds) 20 | int ledState = LOW; // ledState used to set the LED 21 | 22 | WebServer server(80); 23 | 24 | /* 25 | * Login page 26 | */ 27 | 28 | const char* loginIndex = 29 | "
" 30 | "" 31 | "" 32 | "" 36 | "
" 37 | "
" 38 | "" 39 | "" 40 | "" 41 | "" 42 | "
" 43 | "
" 44 | "" 45 | "" 46 | "" 47 | "
" 48 | "
" 49 | "" 50 | "" 51 | "" 52 | "" 53 | "
" 33 | "
ESP32 Login Page
" 34 | "
" 35 | "
Username:
Password:
" 54 | "
" 55 | ""; 68 | 69 | /* 70 | * Server Index Page 71 | */ 72 | 73 | const char* serverIndex = 74 | "" 75 | "
" 76 | "" 77 | "" 78 | "
" 79 | "
progress: 0%
" 80 | ""; 109 | 110 | /* 111 | * setup function 112 | */ 113 | void setup(void) { 114 | pinMode(led, OUTPUT); 115 | 116 | Serial.begin(115200); 117 | 118 | // Connect to WiFi network 119 | WiFi.begin(ssid, password); 120 | Serial.println(""); 121 | 122 | // Wait for connection 123 | while (WiFi.status() != WL_CONNECTED) { 124 | delay(500); 125 | Serial.print("."); 126 | } 127 | Serial.println(""); 128 | Serial.print("Connected to "); 129 | Serial.println(ssid); 130 | Serial.print("IP address: "); 131 | Serial.println(WiFi.localIP()); 132 | 133 | /*use mdns for host name resolution*/ 134 | if (!MDNS.begin(host)) { //http://esp32.local 135 | Serial.println("Error setting up MDNS responder!"); 136 | while (1) { 137 | delay(1000); 138 | } 139 | } 140 | Serial.println("mDNS responder started"); 141 | /*return index page which is stored in serverIndex */ 142 | server.on("/", HTTP_GET, []() { 143 | server.sendHeader("Connection", "close"); 144 | server.send(200, "text/html", loginIndex); 145 | }); 146 | server.on("/serverIndex", HTTP_GET, []() { 147 | server.sendHeader("Connection", "close"); 148 | server.send(200, "text/html", serverIndex); 149 | }); 150 | /*handling uploading firmware file */ 151 | server.on("/update", HTTP_POST, []() { 152 | server.sendHeader("Connection", "close"); 153 | server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); 154 | ESP.restart(); 155 | }, []() { 156 | HTTPUpload& upload = server.upload(); 157 | if (upload.status == UPLOAD_FILE_START) { 158 | Serial.printf("Update: %s\n", upload.filename.c_str()); 159 | if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size 160 | Update.printError(Serial); 161 | } 162 | } else if (upload.status == UPLOAD_FILE_WRITE) { 163 | /* flashing firmware to ESP*/ 164 | if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { 165 | Update.printError(Serial); 166 | } 167 | } else if (upload.status == UPLOAD_FILE_END) { 168 | if (Update.end(true)) { //true to set the size to the current progress 169 | Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); 170 | } else { 171 | Update.printError(Serial); 172 | } 173 | } 174 | }); 175 | server.begin(); 176 | } 177 | 178 | void loop(void) { 179 | server.handleClient(); 180 | delay(1); 181 | 182 | //loop to blink without delay 183 | unsigned long currentMillis = millis(); 184 | 185 | if (currentMillis - previousMillis >= interval) { 186 | // save the last time you blinked the LED 187 | previousMillis = currentMillis; 188 | 189 | // if the LED is off turn it on and vice-versa: 190 | ledState = not(ledState); 191 | 192 | // set the LED with the ledState of the variable: 193 | digitalWrite(led, ledState); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /code/PIR_Interrupts_Timers/PIR_Interrupts_Timers.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | #define timeSeconds 10 7 | 8 | // Set GPIOs for LED and PIR Motion Sensor 9 | const int led = 26; 10 | const int motionSensor = 27; 11 | 12 | // Timer: Auxiliary variables 13 | unsigned long now = millis(); 14 | unsigned long lastTrigger = 0; 15 | boolean startTimer = false; 16 | boolean motion = false; 17 | 18 | // Checks if motion was detected, sets LED HIGH and starts a timer 19 | void IRAM_ATTR detectsMovement() { 20 | digitalWrite(led, HIGH); 21 | startTimer = true; 22 | lastTrigger = millis(); 23 | } 24 | 25 | void setup() { 26 | // Serial port for debugging purposes 27 | Serial.begin(115200); 28 | 29 | // PIR Motion Sensor mode INPUT_PULLUP 30 | pinMode(motionSensor, INPUT_PULLUP); 31 | // Set motionSensor pin as interrupt, assign interrupt function and set RISING mode 32 | attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING); 33 | 34 | // Set LED to LOW 35 | pinMode(led, OUTPUT); 36 | digitalWrite(led, LOW); 37 | } 38 | 39 | void loop() { 40 | // Current time 41 | now = millis(); 42 | if((digitalRead(led) == HIGH) && (motion == false)) { 43 | Serial.println("MOTION DETECTED!!!"); 44 | motion = true; 45 | } 46 | // Turn off the LED after the number of seconds defined in the timeSeconds variable 47 | if(startTimer && (now - lastTrigger > (timeSeconds*1000))) { 48 | Serial.println("Motion stopped..."); 49 | digitalWrite(led, LOW); 50 | startTimer = false; 51 | motion = false; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /code/PIR_Interrupts_Timers/PIR_Interrupts_Timers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/PIR_Interrupts_Timers/PIR_Interrupts_Timers.png -------------------------------------------------------------------------------- /code/Print_ESP32_MAC_Address/Print_ESP32_MAC_Address.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Load Wi-Fi library 7 | #include 8 | 9 | // Replace with your network credentials 10 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 11 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 12 | 13 | // Set web server port number to 80 14 | WiFiServer server(80); 15 | 16 | void setup() { 17 | Serial.begin(115200); 18 | 19 | // Connect to Wi-Fi network with SSID and password 20 | Serial.print("Connecting to "); 21 | Serial.println(ssid); 22 | WiFi.begin(ssid, password); 23 | while (WiFi.status() != WL_CONNECTED) { 24 | delay(500); 25 | Serial.print("."); 26 | } 27 | 28 | // Print local IP address and start web server 29 | Serial.println(""); 30 | Serial.println("WiFi connected."); 31 | Serial.println("IP address: "); 32 | Serial.println(WiFi.localIP()); 33 | server.begin(); 34 | 35 | // Print ESP MAC Address 36 | Serial.println("MAC address: "); 37 | Serial.println(WiFi.macAddress()); 38 | } 39 | 40 | void loop() { 41 | // put your main code here, to run repeatedly: 42 | } 43 | -------------------------------------------------------------------------------- /code/Project_Robot/Project_Robot_Schematics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Project_Robot/Project_Robot_Schematics.png -------------------------------------------------------------------------------- /code/SPIFFS/ESP32_Async_Web_Server.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/SPIFFS/ESP32_Async_Web_Server.zip -------------------------------------------------------------------------------- /code/SPIFFS/ESP32_Async_Web_Server/ESP32_Async_Web_Server.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Import required libraries 7 | #include "WiFi.h" 8 | #include "ESPAsyncWebServer.h" 9 | #include "SPIFFS.h" 10 | 11 | // Replace with your network credentials 12 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 13 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 14 | 15 | // Set LED GPIO 16 | const int ledPin = 2; 17 | // Stores LED state 18 | String ledState; 19 | 20 | // Create AsyncWebServer object on port 80 21 | AsyncWebServer server(80); 22 | 23 | // Replaces placeholder with LED state value 24 | String processor(const String& var){ 25 | Serial.println(var); 26 | if(var == "STATE"){ 27 | if(digitalRead(ledPin)){ 28 | ledState = "ON"; 29 | } 30 | else{ 31 | ledState = "OFF"; 32 | } 33 | Serial.print(ledState); 34 | return ledState; 35 | } 36 | return String(); 37 | } 38 | 39 | void setup(){ 40 | // Serial port for debugging purposes 41 | Serial.begin(115200); 42 | pinMode(ledPin, OUTPUT); 43 | 44 | // Initialize SPIFFS 45 | if(!SPIFFS.begin(true)){ 46 | Serial.println("An Error has occurred while mounting SPIFFS"); 47 | return; 48 | } 49 | 50 | // Connect to Wi-Fi 51 | WiFi.begin(ssid, password); 52 | while (WiFi.status() != WL_CONNECTED) { 53 | delay(1000); 54 | Serial.println("Connecting to WiFi.."); 55 | } 56 | 57 | // Print ESP32 Local IP Address 58 | Serial.println(WiFi.localIP()); 59 | 60 | // Route for root / web page 61 | server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ 62 | request->send(SPIFFS, "/index.html", String(), false, processor); 63 | }); 64 | 65 | // Route to load style.css file 66 | server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){ 67 | request->send(SPIFFS, "/style.css", "text/css"); 68 | }); 69 | 70 | // Route to set GPIO to HIGH 71 | server.on("/on", HTTP_GET, [](AsyncWebServerRequest *request){ 72 | digitalWrite(ledPin, HIGH); 73 | request->send(SPIFFS, "/index.html", String(), false, processor); 74 | }); 75 | 76 | // Route to set GPIO to LOW 77 | server.on("/off", HTTP_GET, [](AsyncWebServerRequest *request){ 78 | digitalWrite(ledPin, LOW); 79 | request->send(SPIFFS, "/index.html", String(), false, processor); 80 | }); 81 | 82 | // Start server 83 | server.begin(); 84 | } 85 | 86 | void loop(){ 87 | 88 | } 89 | -------------------------------------------------------------------------------- /code/SPIFFS/ESP32_Async_Web_Server/data/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ESP32 Web Server 5 | 6 | 7 | 8 | 9 | 10 |

ESP32 Web Server

11 |

GPIO state: %STATE%

12 |

13 |

14 | 15 | 16 | -------------------------------------------------------------------------------- /code/SPIFFS/ESP32_Async_Web_Server/data/style.css: -------------------------------------------------------------------------------- 1 | html { 2 | font-family: Helvetica; 3 | display: inline-block; 4 | margin: 0px auto; 5 | text-align: center; 6 | } 7 | h1{ 8 | color: #0F3376; 9 | padding: 2vh; 10 | } 11 | p{ 12 | font-size: 1.5rem; 13 | } 14 | .button { 15 | display: inline-block; 16 | background-color: #008CBA; 17 | border: none; 18 | border-radius: 4px; 19 | color: white; 20 | padding: 16px 40px; 21 | text-decoration: none; 22 | font-size: 30px; 23 | margin: 2px; 24 | cursor: pointer; 25 | } 26 | .button2 { 27 | background-color: #f44336; 28 | } 29 | -------------------------------------------------------------------------------- /code/SPIFFS/SPIFFS_Manipulating_Files/SPIFFS_Manipulating_Files.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | #include "FS.h" 7 | #include "SPIFFS.h" 8 | 9 | // Create a File object to manipulate your file 10 | File myFile; 11 | 12 | // File path 13 | const char* myFilePath = "/new_file.txt"; 14 | 15 | void setup(){ 16 | // Serial port for debugging purposes 17 | Serial.begin(115200); 18 | 19 | // Initialize SPIFFS 20 | if(!SPIFFS.begin(true)){ 21 | Serial.println("Error while mounting SPIFFS"); 22 | return; 23 | } 24 | 25 | // Open file and write data to it 26 | myFile = SPIFFS.open(myFilePath, FILE_WRITE); 27 | if (myFile.print("Example message in write mode")){ 28 | Serial.println("Message successfully written"); 29 | } 30 | else{ 31 | Serial.print("Writting message failled!!"); 32 | } 33 | myFile.close(); 34 | 35 | // Append data to file 36 | myFile = SPIFFS.open(myFilePath, FILE_APPEND); 37 | if(myFile.print(" - Example message appended to file")){ 38 | Serial.println("Message successfully appended"); 39 | } 40 | else{ 41 | Serial.print("Appending failled!"); 42 | } 43 | myFile.close(); 44 | 45 | // Read file content 46 | myFile = SPIFFS.open(myFilePath, FILE_READ); 47 | Serial.print("File content: \""); 48 | while(myFile.available()) { 49 | Serial.write(myFile.read()); 50 | } 51 | Serial.println("\""); 52 | 53 | // Check file size 54 | Serial.print("File size: "); 55 | Serial.println(myFile.size()); 56 | 57 | myFile.close(); 58 | 59 | // Delete file 60 | if(SPIFFS.remove(myFilePath)){ 61 | Serial.println("File successfully deleted"); 62 | } 63 | else{ 64 | Serial.print("Deleting file failed!"); 65 | } 66 | } 67 | void loop(){ 68 | 69 | } 70 | -------------------------------------------------------------------------------- /code/SPIFFS/SPIFFS_Test/SPIFFS_Test.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | #include "SPIFFS.h" 7 | 8 | void setup() { 9 | Serial.begin(115200); 10 | 11 | if(!SPIFFS.begin(true)){ 12 | Serial.println("An Error has occurred while mounting SPIFFS"); 13 | return; 14 | } 15 | 16 | File file = SPIFFS.open("/test_example.txt"); 17 | if(!file){ 18 | Serial.println("Failed to open file for reading"); 19 | return; 20 | } 21 | 22 | Serial.println("File Content:"); 23 | while(file.available()){ 24 | Serial.write(file.read()); 25 | } 26 | file.close(); 27 | } 28 | 29 | void loop() { 30 | 31 | } 32 | -------------------------------------------------------------------------------- /code/Servo/ESP32_Servo_Motor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Servo/ESP32_Servo_Motor.png -------------------------------------------------------------------------------- /code/Servo/Sweep/Sweep.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://RandomNerdTutorials.com/ 4 | *********/ 5 | 6 | // Install the ESP32Servo Library: https://www.arduino.cc/reference/en/libraries/esp32servo/ 7 | // Sketch > Include Library > Manage Libraries... > ESP32Servo by Kevin Harrington 8 | #include 9 | 10 | static const int servoPin = 13; 11 | 12 | Servo servo1; 13 | 14 | void setup() { 15 | Serial.begin(115200); 16 | servo1.attach(servoPin); 17 | } 18 | 19 | void loop() { 20 | for(int posDegrees = 0; posDegrees <= 180; posDegrees++) { 21 | servo1.write(posDegrees); 22 | Serial.println(posDegrees); 23 | delay(20); 24 | } 25 | 26 | for(int posDegrees = 180; posDegrees >= 0; posDegrees--) { 27 | servo1.write(posDegrees); 28 | Serial.println(posDegrees); 29 | delay(20); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /code/Servo/WiFi_Web_Server_Servo/WiFi_Web_Server_Servo.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Install the ESP32Servo Library: https://www.arduino.cc/reference/en/libraries/esp32servo/ 7 | // Sketch > Include Library > Manage Libraries... > ESP32Servo by Kevin Harrington 8 | #include 9 | 10 | #include 11 | 12 | Servo myservo; // create servo object to control a servo 13 | // twelve servo objects can be created on most boards 14 | 15 | // GPIO the servo is attached to 16 | static const int servoPin = 13; 17 | 18 | // Replace with your network credentials 19 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 20 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 21 | 22 | // Set web server port number to 80 23 | WiFiServer server(80); 24 | 25 | // Variable to store the HTTP request 26 | String header; 27 | 28 | // Decode HTTP GET value 29 | String valueString = String(5); 30 | int pos1 = 0; 31 | int pos2 = 0; 32 | 33 | // Current time 34 | unsigned long currentTime = millis(); 35 | // Previous time 36 | unsigned long previousTime = 0; 37 | // Define timeout time in milliseconds (example: 2000ms = 2s) 38 | const long timeoutTime = 2000; 39 | 40 | void setup() { 41 | Serial.begin(115200); 42 | 43 | myservo.attach(servoPin); // attaches the servo on the servoPin to the servo object 44 | 45 | // Connect to Wi-Fi network with SSID and password 46 | Serial.print("Connecting to "); 47 | Serial.println(ssid); 48 | WiFi.begin(ssid, password); 49 | while (WiFi.status() != WL_CONNECTED) { 50 | delay(500); 51 | Serial.print("."); 52 | } 53 | // Print local IP address and start web server 54 | Serial.println(""); 55 | Serial.println("WiFi connected."); 56 | Serial.println("IP address: "); 57 | Serial.println(WiFi.localIP()); 58 | server.begin(); 59 | } 60 | 61 | void loop(){ 62 | WiFiClient client = server.available(); // Listen for incoming clients 63 | 64 | if (client) { // If a new client connects, 65 | currentTime = millis(); 66 | previousTime = currentTime; 67 | Serial.println("New Client."); // print a message out in the serial port 68 | String currentLine = ""; // make a String to hold incoming data from the client 69 | while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected 70 | currentTime = millis(); 71 | if (client.available()) { // if there's bytes to read from the client, 72 | char c = client.read(); // read a byte, then 73 | Serial.write(c); // print it out the serial monitor 74 | header += c; 75 | if (c == '\n') { // if the byte is a newline character 76 | // if the current line is blank, you got two newline characters in a row. 77 | // that's the end of the client HTTP request, so send a response: 78 | if (currentLine.length() == 0) { 79 | // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) 80 | // and a content-type so the client knows what's coming, then a blank line: 81 | client.println("HTTP/1.1 200 OK"); 82 | client.println("Content-type:text/html"); 83 | client.println("Connection: close"); 84 | client.println(); 85 | 86 | // Display the HTML web page 87 | client.println(""); 88 | client.println(""); 89 | client.println(""); 90 | // CSS to style the on/off buttons 91 | // Feel free to change the background-color and font-size attributes to fit your preferences 92 | client.println(""); 94 | client.println(""); 95 | 96 | // Web Page 97 | client.println("

ESP32 with Servo

"); 98 | client.println("

Position:

"); 99 | client.println(""); 100 | 101 | client.println(""); 106 | 107 | client.println(""); 108 | 109 | //GET /?value=180& HTTP/1.1 110 | if(header.indexOf("GET /?value=")>=0) { 111 | pos1 = header.indexOf('='); 112 | pos2 = header.indexOf('&'); 113 | valueString = header.substring(pos1+1, pos2); 114 | 115 | //Rotate the servo 116 | myservo.write(valueString.toInt()); 117 | Serial.println(valueString); 118 | } 119 | // The HTTP response ends with another blank line 120 | client.println(); 121 | // Break out of the while loop 122 | break; 123 | } else { // if you got a newline, then clear currentLine 124 | currentLine = ""; 125 | } 126 | } else if (c != '\r') { // if you got anything else but a carriage return character, 127 | currentLine += c; // add it to the end of the currentLine 128 | } 129 | } 130 | } 131 | // Clear the header variable 132 | header = ""; 133 | // Close the connection 134 | client.stop(); 135 | Serial.println("Client disconnected."); 136 | Serial.println(""); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /code/Servo/slider.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 20 |

ESP32 with Servo

21 |

Position:

22 | 23 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /code/TouchRead/TouchRead.ino: -------------------------------------------------------------------------------- 1 | // ESP32 Touch Test 2 | // Just test touch pin - Touch0 is T0 which is on GPIO 4. 3 | 4 | void setup() { 5 | Serial.begin(115200); 6 | delay(1000); // give me time to bring up serial monitor 7 | Serial.println("ESP32 Touch Test"); 8 | } 9 | 10 | void loop() { 11 | Serial.println(touchRead(4)); // get value of Touch 0 pin = GPIO 4 12 | delay(1000); 13 | } 14 | -------------------------------------------------------------------------------- /code/Touch_Sensitive_LED/Touch_Sensitive_LED.ino: -------------------------------------------------------------------------------- 1 | // set pin numbers 2 | const int touchPin = 4; 3 | const int ledPin = 16; 4 | 5 | // change with your threshold value 6 | const int threshold = 20; 7 | // variable for storing the touch pin value 8 | int touchValue; 9 | 10 | void setup(){ 11 | Serial.begin(115200); 12 | delay(1000); // give me time to bring up serial monitor 13 | // initialize the LED pin as an output: 14 | pinMode (ledPin, OUTPUT); 15 | } 16 | 17 | void loop(){ 18 | // read the state of the pushbutton value: 19 | touchValue = touchRead(touchPin); 20 | Serial.print(touchValue); 21 | // check if the touchValue is below the threshold 22 | // if it is, set ledPin to HIGH 23 | if(touchValue < threshold){ 24 | // turn LED on 25 | digitalWrite(ledPin, HIGH); 26 | Serial.println(" - LED on"); 27 | } 28 | else{ 29 | // turn LED off 30 | digitalWrite(ledPin, LOW); 31 | Serial.println(" - LED off"); 32 | } 33 | delay(500); 34 | } 35 | -------------------------------------------------------------------------------- /code/Touch_Sensitive_LED/Touch_Sensitive_LED.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/Touch_Sensitive_LED/Touch_Sensitive_LED.png -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Color_Picker/ESP32_RGB_LED_Strip.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/WiFi_Web_Server_Color_Picker/ESP32_RGB_LED_Strip.png -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Color_Picker/WiFi_Web_Server_Color_Picker.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Load Wi-Fi library 7 | #include 8 | 9 | // Replace with your network credentials 10 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 11 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 12 | 13 | // Set web server port number to 80 14 | WiFiServer server(80); 15 | 16 | // Decode HTTP GET value 17 | String redString = "0"; 18 | String greenString = "0"; 19 | String blueString = "0"; 20 | int pos1 = 0; 21 | int pos2 = 0; 22 | int pos3 = 0; 23 | int pos4 = 0; 24 | 25 | // Variable to store the HTTP req uest 26 | String header; 27 | 28 | // Red, green, and blue pins for PWM control 29 | const int redPin = 13; // 13 corresponds to GPIO13 30 | const int greenPin = 12; // 12 corresponds to GPIO12 31 | const int bluePin = 14; // 14 corresponds to GPIO14 32 | 33 | // Setting PWM frequency, channels and bit resolution 34 | const int freq = 5000; 35 | const int redChannel = 0; 36 | const int greenChannel = 1; 37 | const int blueChannel = 2; 38 | // Bit resolution 2^8 = 256 39 | const int resolution = 8; 40 | 41 | // Current time 42 | unsigned long currentTime = millis(); 43 | // Previous time 44 | unsigned long previousTime = 0; 45 | // Define timeout time in milliseconds (example: 2000ms = 2s) 46 | const long timeoutTime = 2000; 47 | 48 | void setup() { 49 | Serial.begin(115200); 50 | // configure LED PWM functionalitites 51 | ledcAttachChannel(redPin, freq, resolution, redChannel); 52 | ledcAttachChannel(greenPin, freq, resolution, greenChannel); 53 | ledcAttachChannel(bluePin, freq, resolution, blueChannel); 54 | 55 | // Connect to Wi-Fi network with SSID and password 56 | Serial.print("Connecting to "); 57 | Serial.println(ssid); 58 | WiFi.begin(ssid, password); 59 | while (WiFi.status() != WL_CONNECTED) { 60 | delay(500); 61 | Serial.print("."); 62 | } 63 | // Print local IP address and start web server 64 | Serial.println(""); 65 | Serial.println("WiFi connected."); 66 | Serial.println("IP address: "); 67 | Serial.println(WiFi.localIP()); 68 | server.begin(); 69 | } 70 | 71 | void loop(){ 72 | WiFiClient client = server.available(); // Listen for incoming clients 73 | 74 | if (client) { // If a new client connects, 75 | currentTime = millis(); 76 | previousTime = currentTime; 77 | Serial.println("New Client."); // print a message out in the serial port 78 | String currentLine = ""; // make a String to hold incoming data from the client 79 | while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected 80 | currentTime = millis(); 81 | if (client.available()) { // if there's bytes to read from the client, 82 | char c = client.read(); // read a byte, then 83 | Serial.write(c); // print it out the serial monitor 84 | header += c; 85 | if (c == '\n') { // if the byte is a newline character 86 | // if the current line is blank, you got two newline characters in a row. 87 | // that's the end of the client HTTP request, so send a response: 88 | if (currentLine.length() == 0) { 89 | // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) 90 | // and a content-type so the client knows what's coming, then a blank line: 91 | client.println("HTTP/1.1 200 OK"); 92 | client.println("Content-type:text/html"); 93 | client.println("Connection: close"); 94 | client.println(); 95 | 96 | // Display the HTML web page 97 | client.println(""); 98 | client.println(""); 99 | client.println(""); 100 | client.println(""); 101 | client.println(""); 102 | client.println("

ESP Color Picker

"); 103 | client.println("Change Color "); 104 | client.println("
"); 105 | client.println(""); 107 | // The HTTP response ends with another blank line 108 | client.println(); 109 | 110 | // Request sample: /?r201g32b255& 111 | // Red = 201 | Green = 32 | Blue = 255 112 | if(header.indexOf("GET /?r") >= 0) { 113 | pos1 = header.indexOf('r'); 114 | pos2 = header.indexOf('g'); 115 | pos3 = header.indexOf('b'); 116 | pos4 = header.indexOf('&'); 117 | redString = header.substring(pos1+1, pos2); 118 | greenString = header.substring(pos2+1, pos3); 119 | blueString = header.substring(pos3+1, pos4); 120 | /*Serial.println(redString.toInt()); 121 | Serial.println(greenString.toInt()); 122 | Serial.println(blueString.toInt());*/ 123 | ledcWrite(redPin, redString.toInt()); 124 | ledcWrite(greenPin, greenString.toInt()); 125 | ledcWrite(bluePin, blueString.toInt()); 126 | } 127 | // Break out of the while loop 128 | break; 129 | } else { // if you got a newline, then clear currentLine 130 | currentLine = ""; 131 | } 132 | } else if (c != '\r') { // if you got anything else but a carriage return character, 133 | currentLine += c; // add it to the end of the currentLine 134 | } 135 | } 136 | } 137 | // Clear the header variable 138 | header = ""; 139 | // Close the connection 140 | client.stop(); 141 | Serial.println("Client disconnected."); 142 | Serial.println(""); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /code/WiFi_Web_Server_DHT/ESP32_DHT_Sensor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/WiFi_Web_Server_DHT/ESP32_DHT_Sensor.png -------------------------------------------------------------------------------- /code/WiFi_Web_Server_DHT/WiFi_Web_Server_DHT.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at https://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Import required libraries 7 | #include "WiFi.h" 8 | #include "ESPAsyncWebServer.h" 9 | #include 10 | #include 11 | 12 | // Replace with your network credentials 13 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 14 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 15 | 16 | #define DHTPIN 27 // Digital pin connected to the DHT sensor 17 | 18 | // Uncomment the type of sensor in use: 19 | //#define DHTTYPE DHT11 // DHT 11 20 | #define DHTTYPE DHT22 // DHT 22 (AM2302) 21 | //#define DHTTYPE DHT21 // DHT 21 (AM2301) 22 | 23 | DHT dht(DHTPIN, DHTTYPE); 24 | 25 | // Create AsyncWebServer object on port 80 26 | AsyncWebServer server(80); 27 | 28 | String readDHTTemperature() { 29 | // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) 30 | // Read temperature as Celsius (the default) 31 | float t = dht.readTemperature(); 32 | // Read temperature as Fahrenheit (isFahrenheit = true) 33 | //float t = dht.readTemperature(true); 34 | // Check if any reads failed and exit early (to try again). 35 | if (isnan(t)) { 36 | Serial.println("Failed to read from DHT sensor!"); 37 | return "--"; 38 | } 39 | else { 40 | Serial.println(t); 41 | return String(t); 42 | } 43 | } 44 | 45 | String readDHTHumidity() { 46 | // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) 47 | float h = dht.readHumidity(); 48 | if (isnan(h)) { 49 | Serial.println("Failed to read from DHT sensor!"); 50 | return "--"; 51 | } 52 | else { 53 | Serial.println(h); 54 | return String(h); 55 | } 56 | } 57 | 58 | const char index_html[] PROGMEM = R"rawliteral( 59 | 60 | 61 | 62 | 63 | 79 | 80 | 81 |

ESP32 DHT Server

82 |

83 | 84 | Temperature 85 | %TEMPERATURE% 86 | °C 87 |

88 |

89 | 90 | Humidity 91 | %HUMIDITY% 92 | % 93 |

94 | 95 | 118 | )rawliteral"; 119 | 120 | // Replaces placeholder with DHT values 121 | String processor(const String& var){ 122 | //Serial.println(var); 123 | if(var == "TEMPERATURE"){ 124 | return readDHTTemperature(); 125 | } 126 | else if(var == "HUMIDITY"){ 127 | return readDHTHumidity(); 128 | } 129 | return String(); 130 | } 131 | 132 | void setup(){ 133 | // Serial port for debugging purposes 134 | Serial.begin(115200); 135 | 136 | dht.begin(); 137 | 138 | // Connect to Wi-Fi 139 | WiFi.begin(ssid, password); 140 | while (WiFi.status() != WL_CONNECTED) { 141 | delay(1000); 142 | Serial.println("Connecting to WiFi.."); 143 | } 144 | 145 | // Print ESP32 Local IP Address 146 | Serial.println(WiFi.localIP()); 147 | 148 | // Route for root / web page 149 | server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ 150 | request->send_P(200, "text/html", index_html, processor); 151 | }); 152 | server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){ 153 | request->send_P(200, "text/plain", readDHTTemperature().c_str()); 154 | }); 155 | server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request){ 156 | request->send_P(200, "text/plain", readDHTHumidity().c_str()); 157 | }); 158 | 159 | // Start server 160 | server.begin(); 161 | } 162 | 163 | void loop(){ 164 | 165 | } 166 | -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Outputs/WiFi_Web_Server_Outputs.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Load Wi-Fi library 7 | #include 8 | 9 | // Replace with your network credentials 10 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 11 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 12 | 13 | // Set web server port number to 80 14 | WiFiServer server(80); 15 | 16 | // Variable to store the HTTP request 17 | String header; 18 | 19 | // Auxiliar variables to store the current output state 20 | String output26State = "off"; 21 | String output27State = "off"; 22 | 23 | // Assign output variables to GPIO pins 24 | const int output26 = 26; 25 | const int output27 = 27; 26 | 27 | // Current time 28 | unsigned long currentTime = millis(); 29 | // Previous time 30 | unsigned long previousTime = 0; 31 | // Define timeout time in milliseconds (example: 2000ms = 2s) 32 | const long timeoutTime = 2000; 33 | 34 | void setup() { 35 | Serial.begin(115200); 36 | // Initialize the output variables as outputs 37 | pinMode(output26, OUTPUT); 38 | pinMode(output27, OUTPUT); 39 | // Set outputs to LOW 40 | digitalWrite(output26, LOW); 41 | digitalWrite(output27, LOW); 42 | 43 | // Connect to Wi-Fi network with SSID and password 44 | Serial.print("Connecting to "); 45 | Serial.println(ssid); 46 | WiFi.begin(ssid, password); 47 | while (WiFi.status() != WL_CONNECTED) { 48 | delay(500); 49 | Serial.print("."); 50 | } 51 | // Print local IP address and start web server 52 | Serial.println(""); 53 | Serial.println("WiFi connected."); 54 | Serial.println("IP address: "); 55 | Serial.println(WiFi.localIP()); 56 | server.begin(); 57 | } 58 | 59 | void loop(){ 60 | WiFiClient client = server.available(); // Listen for incoming clients 61 | 62 | if (client) { // If a new client connects, 63 | currentTime = millis(); 64 | previousTime = currentTime; 65 | Serial.println("New Client."); // print a message out in the serial port 66 | String currentLine = ""; // make a String to hold incoming data from the client 67 | while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected 68 | currentTime = millis(); 69 | if (client.available()) { // if there's bytes to read from the client, 70 | char c = client.read(); // read a byte, then 71 | Serial.write(c); // print it out the serial monitor 72 | header += c; 73 | if (c == '\n') { // if the byte is a newline character 74 | // if the current line is blank, you got two newline characters in a row. 75 | // that's the end of the client HTTP request, so send a response: 76 | if (currentLine.length() == 0) { 77 | // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) 78 | // and a content-type so the client knows what's coming, then a blank line: 79 | client.println("HTTP/1.1 200 OK"); 80 | client.println("Content-type:text/html"); 81 | client.println("Connection: close"); 82 | client.println(); 83 | 84 | // turns the GPIOs on and off 85 | if (header.indexOf("GET /26/on") >= 0) { 86 | Serial.println("GPIO 26 on"); 87 | output26State = "on"; 88 | digitalWrite(output26, HIGH); 89 | } else if (header.indexOf("GET /26/off") >= 0) { 90 | Serial.println("GPIO 26 off"); 91 | output26State = "off"; 92 | digitalWrite(output26, LOW); 93 | } else if (header.indexOf("GET /27/on") >= 0) { 94 | Serial.println("GPIO 27 on"); 95 | output27State = "on"; 96 | digitalWrite(output27, HIGH); 97 | } else if (header.indexOf("GET /27/off") >= 0) { 98 | Serial.println("GPIO 27 off"); 99 | output27State = "off"; 100 | digitalWrite(output27, LOW); 101 | } 102 | 103 | // Display the HTML web page 104 | client.println(""); 105 | client.println(""); 106 | client.println(""); 107 | // CSS to style the on/off buttons 108 | // Feel free to change the background-color and font-size attributes to fit your preferences 109 | client.println(""); 113 | 114 | // Web Page Heading 115 | client.println("

ESP32 Web Server

"); 116 | 117 | // Display current state, and ON/OFF buttons for GPIO 26 118 | client.println("

GPIO 26 - State " + output26State + "

"); 119 | // If the output26State is off, it displays the ON button 120 | if (output26State=="off") { 121 | client.println("

"); 122 | } else { 123 | client.println("

"); 124 | } 125 | 126 | // Display current state, and ON/OFF buttons for GPIO 27 127 | client.println("

GPIO 27 - State " + output27State + "

"); 128 | // If the output27State is off, it displays the ON button 129 | if (output27State=="off") { 130 | client.println("

"); 131 | } else { 132 | client.println("

"); 133 | } 134 | client.println(""); 135 | 136 | // The HTTP response ends with another blank line 137 | client.println(); 138 | // Break out of the while loop 139 | break; 140 | } else { // if you got a newline, then clear currentLine 141 | currentLine = ""; 142 | } 143 | } else if (c != '\r') { // if you got anything else but a carriage return character, 144 | currentLine += c; // add it to the end of the currentLine 145 | } 146 | } 147 | } 148 | // Clear the header variable 149 | header = ""; 150 | // Close the connection 151 | client.stop(); 152 | Serial.println("Client disconnected."); 153 | Serial.println(""); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Outputs/WiFi_Web_Server_Outputs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/WiFi_Web_Server_Outputs/WiFi_Web_Server_Outputs.png -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Outputs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ESP32 Web Server 5 | 6 | 7 | 28 | 29 | 30 |

ESP32 Web Server

31 |

GPIO 26 - State

32 |

33 |

34 |

GPIO 27 - State

35 |

36 |

37 | 38 | 39 | -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Relays/WiFi_Web_Server_Relays.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Load Wi-Fi library 7 | #include 8 | 9 | // Replace with your network credentials 10 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 11 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 12 | 13 | // Set web server port number to 80 14 | WiFiServer server(80); 15 | 16 | // Variable to store the HTTP request 17 | String header; 18 | 19 | // Auxiliar variables to store the current output state 20 | String output26State = "off"; 21 | String output27State = "off"; 22 | 23 | // Assign output variables to GPIO pins 24 | const int output26 = 26; 25 | const int output27 = 27; 26 | 27 | // Current time 28 | unsigned long currentTime = millis(); 29 | // Previous time 30 | unsigned long previousTime = 0; 31 | // Define timeout time in milliseconds (example: 2000ms = 2s) 32 | const long timeoutTime = 2000; 33 | 34 | void setup() { 35 | Serial.begin(115200); 36 | // Initialize the output variables as outputs 37 | pinMode(output26, OUTPUT); 38 | pinMode(output27, OUTPUT); 39 | // Set outputs to LOW 40 | digitalWrite(output26, HIGH); 41 | digitalWrite(output27, HIGH); 42 | 43 | // Connect to Wi-Fi network with SSID and password 44 | Serial.print("Connecting to "); 45 | Serial.println(ssid); 46 | WiFi.begin(ssid, password); 47 | while (WiFi.status() != WL_CONNECTED) { 48 | delay(500); 49 | Serial.print("."); 50 | } 51 | // Print local IP address and start web server 52 | Serial.println(""); 53 | Serial.println("WiFi connected."); 54 | Serial.println("IP address: "); 55 | Serial.println(WiFi.localIP()); 56 | server.begin(); 57 | } 58 | 59 | void loop(){ 60 | WiFiClient client = server.available(); // Listen for incoming clients 61 | 62 | if (client) { // If a new client connects, 63 | currentTime = millis(); 64 | previousTime = currentTime; 65 | Serial.println("New Client."); // print a message out in the serial port 66 | String currentLine = ""; // make a String to hold incoming data from the client 67 | while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected 68 | currentTime = millis(); 69 | if (client.available()) { // if there's bytes to read from the client, 70 | char c = client.read(); // read a byte, then 71 | Serial.write(c); // print it out the serial monitor 72 | header += c; 73 | if (c == '\n') { // if the byte is a newline character 74 | // if the current line is blank, you got two newline characters in a row. 75 | // that's the end of the client HTTP request, so send a response: 76 | if (currentLine.length() == 0) { 77 | // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) 78 | // and a content-type so the client knows what's coming, then a blank line: 79 | client.println("HTTP/1.1 200 OK"); 80 | client.println("Content-type:text/html"); 81 | client.println("Connection: close"); 82 | client.println(); 83 | 84 | // turns the GPIOs on and off 85 | if (header.indexOf("GET /26/on") >= 0) { 86 | Serial.println("GPIO 26 on"); 87 | output26State = "on"; 88 | digitalWrite(output26, LOW); 89 | } else if (header.indexOf("GET /26/off") >= 0) { 90 | Serial.println("GPIO 26 off"); 91 | output26State = "off"; 92 | digitalWrite(output26, HIGH); 93 | } else if (header.indexOf("GET /27/on") >= 0) { 94 | Serial.println("GPIO 27 on"); 95 | output27State = "on"; 96 | digitalWrite(output27, LOW); 97 | } else if (header.indexOf("GET /27/off") >= 0) { 98 | Serial.println("GPIO 27 off"); 99 | output27State = "off"; 100 | digitalWrite(output27, HIGH); 101 | } 102 | 103 | // Display the HTML web page 104 | client.println(""); 105 | client.println(""); 106 | client.println(""); 107 | // CSS to style the on/off buttons 108 | // Feel free to change the background-color and font-size attributes to fit your preferences 109 | client.println(""); 113 | 114 | // Web Page Heading 115 | client.println("

ESP32 Web Server

"); 116 | 117 | // Display current state, and ON/OFF buttons for GPIO 26 118 | client.println("

GPIO 26 - State " + output26State + "

"); 119 | // If the output26State is off, it displays the ON button 120 | if (output26State=="off") { 121 | client.println("

"); 122 | } else { 123 | client.println("

"); 124 | } 125 | 126 | // Display current state, and ON/OFF buttons for GPIO 27 127 | client.println("

GPIO 27 - State " + output27State + "

"); 128 | // If the output27State is off, it displays the ON button 129 | if (output27State=="off") { 130 | client.println("

"); 131 | } else { 132 | client.println("

"); 133 | } 134 | client.println(""); 135 | 136 | // The HTTP response ends with another blank line 137 | client.println(); 138 | // Break out of the while loop 139 | break; 140 | } else { // if you got a newline, then clear currentLine 141 | currentLine = ""; 142 | } 143 | } else if (c != '\r') { // if you got anything else but a carriage return character, 144 | currentLine += c; // add it to the end of the currentLine 145 | } 146 | } 147 | } 148 | // Clear the header variable 149 | header = ""; 150 | // Close the connection 151 | client.stop(); 152 | Serial.println("Client disconnected."); 153 | Serial.println(""); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Relays/WiFi_Web_Server_Relays.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/WiFi_Web_Server_Relays/WiFi_Web_Server_Relays.png -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Sensor_Readings/WiFi_Web_Server_Sensor_Readings.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Rui Santos 3 | Complete project details at http://randomnerdtutorials.com 4 | *********/ 5 | 6 | // Load Wi-Fi library 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | //uncomment the following lines if you're using SPI 13 | /*#include 14 | #define BME_SCK 18 15 | #define BME_MISO 19 16 | #define BME_MOSI 23 17 | #define BME_CS 5*/ 18 | 19 | #define SEALEVELPRESSURE_HPA (1013.25) 20 | 21 | Adafruit_BME280 bme; // I2C 22 | //Adafruit_BME280 bme(BME_CS); // hardware SPI 23 | //Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI 24 | 25 | // Replace with your network credentials 26 | const char* ssid = "REPLACE_WITH_YOUR_SSID"; 27 | const char* password = "REPLACE_WITH_YOUR_PASSWORD"; 28 | 29 | // Set web server port number to 80 30 | WiFiServer server(80); 31 | 32 | // Variable to store the HTTP request 33 | String header; 34 | 35 | // Current time 36 | unsigned long currentTime = millis(); 37 | // Previous time 38 | unsigned long previousTime = 0; 39 | // Define timeout time in milliseconds (example: 2000ms = 2s) 40 | const long timeoutTime = 2000; 41 | 42 | void setup() { 43 | Serial.begin(115200); 44 | bool status; 45 | 46 | // default settings 47 | // (you can also pass in a Wire library object like &Wire2) 48 | //status = bme.begin(); 49 | if (!bme.begin(0x76)) { 50 | Serial.println("Could not find a valid BME280 sensor, check wiring!"); 51 | while (1); 52 | } 53 | 54 | // Connect to Wi-Fi network with SSID and password 55 | Serial.print("Connecting to "); 56 | Serial.println(ssid); 57 | WiFi.begin(ssid, password); 58 | while (WiFi.status() != WL_CONNECTED) { 59 | delay(500); 60 | Serial.print("."); 61 | } 62 | // Print local IP address and start web server 63 | Serial.println(""); 64 | Serial.println("WiFi connected."); 65 | Serial.println("IP address: "); 66 | Serial.println(WiFi.localIP()); 67 | server.begin(); 68 | } 69 | 70 | void loop(){ 71 | WiFiClient client = server.available(); // Listen for incoming clients 72 | 73 | if (client) { // If a new client connects, 74 | currentTime = millis(); 75 | previousTime = currentTime; 76 | Serial.println("New Client."); // print a message out in the serial port 77 | String currentLine = ""; // make a String to hold incoming data from the client 78 | while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected 79 | currentTime = millis(); 80 | if (client.available()) { // if there's bytes to read from the client, 81 | char c = client.read(); // read a byte, then 82 | Serial.write(c); // print it out the serial monitor 83 | header += c; 84 | if (c == '\n') { // if the byte is a newline character 85 | // if the current line is blank, you got two newline characters in a row. 86 | // that's the end of the client HTTP request, so send a response: 87 | if (currentLine.length() == 0) { 88 | // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) 89 | // and a content-type so the client knows what's coming, then a blank line: 90 | client.println("HTTP/1.1 200 OK"); 91 | client.println("Content-type:text/html"); 92 | client.println("Connection: close"); 93 | client.println(); 94 | 95 | // Display the HTML web page 96 | client.println(""); 97 | client.println(""); 98 | client.println(""); 99 | // CSS to style the table 100 | client.println("

ESP32 with BME280

"); 110 | client.println(""); 111 | client.println(""); 114 | client.println(""); 117 | client.println(""); 120 | client.println(""); 123 | client.println(""); 126 | client.println(""); 127 | 128 | // The HTTP response ends with another blank line 129 | client.println(); 130 | // Break out of the while loop 131 | break; 132 | } else { // if you got a newline, then clear currentLine 133 | currentLine = ""; 134 | } 135 | } else if (c != '\r') { // if you got anything else but a carriage return character, 136 | currentLine += c; // add it to the end of the currentLine 137 | } 138 | } 139 | } 140 | // Clear the header variable 141 | header = ""; 142 | // Close the connection 143 | client.stop(); 144 | Serial.println("Client disconnected."); 145 | Serial.println(""); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Sensor_Readings/WiFi_Web_Server_Sensor_Readings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/WiFi_Web_Server_Sensor_Readings/WiFi_Web_Server_Sensor_Readings.png -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Sensor_Readings/table_with_css.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 39 | 40 | 41 |

ESP32 with BME280

42 |
MEASUREMENTVALUE
Temp. Celsius"); 112 | client.println(bme.readTemperature()); 113 | client.println(" *C
Temp. Fahrenheit"); 115 | client.println(1.8 * bme.readTemperature() + 32); 116 | client.println(" *F
Pressure"); 118 | client.println(bme.readPressure() / 100.0F); 119 | client.println(" hPa
Approx. Altitude"); 121 | client.println(bme.readAltitude(SEALEVELPRESSURE_HPA)); 122 | client.println(" m
Humidity"); 124 | client.println(bme.readHumidity()); 125 | client.println(" %
43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /code/WiFi_Web_Server_Sensor_Readings/table_without_css.html: -------------------------------------------------------------------------------- 1 |
MEASUREMENTVALUE
Temp. Celsius--- *C
Temp. Fahrenheit--- *F
Pressure--- hPa
Approx. Altitude--- m
Humidity--- %
2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
MEASUREMENTVALUE
Temp. Celsius--- *C
Temp. Fahrenheit--- *F
Pressure--- hPa
Approx. Altitude--- meters
Humidity--- %
27 | -------------------------------------------------------------------------------- /code/bme280test/WiFi_Web_Server_Sensor_Readings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/code/bme280test/WiFi_Web_Server_Sensor_Readings.png -------------------------------------------------------------------------------- /code/bme280test/bme280test.ino: -------------------------------------------------------------------------------- 1 | /********* 2 | Complete project details at http://randomnerdtutorials.com 3 | *********/ 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | /*#include 10 | #define BME_SCK 18 11 | #define BME_MISO 19 12 | #define BME_MOSI 23 13 | #define BME_CS 5*/ 14 | 15 | #define SEALEVELPRESSURE_HPA (1013.25) 16 | 17 | Adafruit_BME280 bme; // I2C 18 | //Adafruit_BME280 bme(BME_CS); // hardware SPI 19 | //Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI 20 | 21 | unsigned long delayTime; 22 | 23 | void setup() { 24 | Serial.begin(9600); 25 | Serial.println(F("BME280 test")); 26 | 27 | bool status; 28 | 29 | // default settings 30 | // (you can also pass in a Wire library object like &Wire2) 31 | status = bme.begin(0x76); 32 | if (!status) { 33 | Serial.println("Could not find a valid BME280 sensor, check wiring!"); 34 | while (1); 35 | } 36 | 37 | Serial.println("-- Default Test --"); 38 | delayTime = 1000; 39 | 40 | Serial.println(); 41 | } 42 | 43 | 44 | void loop() { 45 | printValues(); 46 | delay(delayTime); 47 | } 48 | 49 | void printValues() { 50 | Serial.print("Temperature = "); 51 | Serial.print(bme.readTemperature()); 52 | Serial.println(" *C"); 53 | 54 | // Convert temperature to Fahrenheit 55 | /*Serial.print("Temperature = "); 56 | Serial.print(1.8 * bme.readTemperature() + 32); 57 | Serial.println(" *F");*/ 58 | 59 | Serial.print("Pressure = "); 60 | Serial.print(bme.readPressure() / 100.0F); 61 | Serial.println(" hPa"); 62 | 63 | Serial.print("Approx. Altitude = "); 64 | Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA)); 65 | Serial.println(" m"); 66 | 67 | Serial.print("Humidity = "); 68 | Serial.print(bme.readHumidity()); 69 | Serial.println(" %"); 70 | 71 | Serial.println(); 72 | } 73 | -------------------------------------------------------------------------------- /img/ESP32-DOIT-DEVKIT-V1-Board-Pinout-30-GPIOs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/img/ESP32-DOIT-DEVKIT-V1-Board-Pinout-30-GPIOs.png -------------------------------------------------------------------------------- /img/ESP32-DOIT-DEVKIT-V1-Board-Pinout-36-GPIOs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/img/ESP32-DOIT-DEVKIT-V1-Board-Pinout-36-GPIOs.png -------------------------------------------------------------------------------- /img/ESP32-DOIT-DEVKIT-V1-Board-Pinout.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/69408933bd7ffb75fc68799465a458885e95ee11/img/ESP32-DOIT-DEVKIT-V1-Board-Pinout.pdf --------------------------------------------------------------------------------