├── Chapter 1 └── hello_world │ └── hello_world.ino ├── Chapter 2 ├── ESP32_PWM │ └── ESP32_PWM.ino ├── ESP32_button_and_LED │ └── ESP32_button_and_LED.ino ├── I2C Communication │ └── ESP32_RTC │ │ └── ESP32_RTC.ino ├── SPI Communication │ └── ESP32_NFC │ │ └── ESP32_NFC.ino └── UART Communication │ ├── Receiver │ └── Receiver.ino │ └── Sender │ └── Sender.ino ├── Chapter 5 ├── ESP32_MQTT │ └── ESP32_MQTT.ino ├── ESP32_WiFiManager │ └── ESP32_WiFiManager.ino ├── ESP32_as_HTTP_client │ └── ESP32_as_HTTP_client.ino ├── ESP32_webhook │ └── ESP32_webhook.ino └── ESP32_webserver │ └── ESP32_webserver.ino ├── Chapter 6 ├── Final_code │ └── Final_code.ino ├── Read_sensors │ └── Read_sensors.ino ├── Send_Email │ └── Send_Email.ino ├── Whatsapp_Telegram │ └── Whatsapp_Telegram.ino └── twitter │ └── twitter.ino ├── Chapter3 ├── 16x2 LCD │ └── 16x2_LCD.ino ├── E-paper │ └── E_paper.ino ├── PIR motion Sensor and camera │ └── PIR_Camera.ino ├── SSD1306 OLED │ └── SSD1306_OLED.ino └── TFT Touchscreen │ └── TFT_touchscreen.ino ├── Chapter4 ├── BLE │ ├── ble-as-beacon-advertiser │ │ └── ble-as-beacon-advertiser.ino │ ├── ble-client │ │ └── ble-client.ino │ └── ble-server │ │ └── ble-server.ino ├── Cellular │ └── AT-commands-basic-code │ │ └── AT-commands-basic-code.ino ├── LICENSE ├── README.md └── WiFi │ ├── ESP32-as-WiFiClient │ └── ESP32-as-WiFiClient.ino │ ├── ESP32-as-accesspoint │ └── ESP32-as-accesspoint.ino │ └── WiFi direct │ ├── wifi-Server │ └── wifi-Server.ino │ └── wifi-client │ └── wifi-client.ino ├── LICENSE ├── README.md ├── chapter 7 ├── QRCode_OLED │ └── QRCode_OLED.ino ├── Reading_Pushbutton_controlling_servo │ └── Reading_pushbutton_controlling_servo.ino ├── Reading_distance │ └── Reading_distance.ino ├── Reading_webhook_paypal │ └── Reading_webhook_paypal.ino └── Rent_out_Parking_Complete │ └── Rent_out_Parking_complete.ino └── chapter 8 ├── bathroom_data └── bathroom_data.ino ├── bedroom_data └── bedroom_data.ino ├── kitchen_data └── kitchen_data.ino ├── livingroom └── livingroom.ino └── read_sensors └── read_sensors.ino /Chapter 1/hello_world/hello_world.ino: -------------------------------------------------------------------------------- 1 | void setup() { 2 | 3 | pinMode(LED_BUILTIN, OUTPUT); 4 | 5 | } 6 | 7 | void loop() { 8 | 9 | digitalWrite(LED_BUILTIN, HIGH); 10 | 11 | delay(1000); 12 | 13 | digitalWrite(LED_BUILTIN, LOW); 14 | 15 | delay(1000); 16 | 17 | } -------------------------------------------------------------------------------- /Chapter 2/ESP32_PWM/ESP32_PWM.ino: -------------------------------------------------------------------------------- 1 | #define PWM_PIN 13 2 | 3 | void setup() { 4 | 5 | pinMode(PWM_PIN, OUTPUT); 6 | 7 | } 8 | 9 | void loop() { 10 | 11 | for (int dutyCycle = 0; dutyCycle <= 255; dutyCycle++) { 12 | 13 | analogWrite(PWM_PIN, dutyCycle); 14 | 15 | delay(10); 16 | 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /Chapter 2/ESP32_button_and_LED/ESP32_button_and_LED.ino: -------------------------------------------------------------------------------- 1 | // Digital input and output pin definitions 2 | 3 | #define BUTTON_PIN 12 4 | 5 | #define LED_PIN 13 6 | 7 | void setup() { 8 | 9 | // Set the button pin as input 10 | 11 | pinMode(BUTTON_PIN, INPUT_PULLUP); 12 | 13 | // Set the LED pin as output 14 | 15 | pinMode(LED_PIN, OUTPUT); 16 | 17 | } 18 | 19 | void loop() { 20 | 21 | // Read the state of the button 22 | 23 | int buttonState = digitalRead(BUTTON_PIN); 24 | 25 | // If the button is pressed (LOW state), turn on the LED 26 | 27 | if (buttonState == LOW) { 28 | 29 | digitalWrite(LED_PIN, HIGH); 30 | 31 | } else { 32 | 33 | // Otherwise, turn off the LED 34 | 35 | digitalWrite(LED_PIN, LOW); 36 | 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /Chapter 2/I2C Communication/ESP32_RTC/ESP32_RTC.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | RTC_DS1307 rtc; 6 | 7 | void setup() { 8 | 9 | Serial.begin(9600); 10 | 11 | Wire.begin(); 12 | 13 | // Uncomment the following line if the RTC has not been initialized 14 | 15 | // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); 16 | 17 | if (!rtc.begin()) { 18 | 19 | Serial.println("Couldn't find RTC"); 20 | 21 | while (1); 22 | 23 | } 24 | 25 | if (!rtc.isrunning()) { 26 | 27 | Serial.println("RTC is not running!"); 28 | 29 | // Uncomment the following line to set the RTC to the date and time at the moment of uploading the code 30 | 31 | // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); 32 | 33 | } 34 | 35 | } 36 | 37 | void loop() { 38 | 39 | DateTime now = rtc.now(); 40 | 41 | Serial.print("Current Date and Time: "); 42 | 43 | Serial.print(now.year(), DEC); 44 | 45 | Serial.print('/'); 46 | 47 | Serial.print(now.month(), DEC); 48 | 49 | Serial.print('/'); 50 | 51 | Serial.print(now.day(), DEC); 52 | 53 | Serial.print(' '); 54 | 55 | Serial.print(now.hour(), DEC); 56 | 57 | Serial.print(':'); 58 | 59 | Serial.print(now.minute(), DEC); 60 | 61 | Serial.print(':'); 62 | 63 | Serial.print(now.second(), DEC); 64 | 65 | Serial.println(); 66 | 67 | delay(1000); 68 | 69 | } -------------------------------------------------------------------------------- /Chapter 2/SPI Communication/ESP32_NFC/ESP32_NFC.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | #define PN532_SCK (14) 6 | 7 | #define PN532_MOSI (13) 8 | 9 | #define PN532_SS (15) 10 | 11 | #define PN532_MISO (12) 12 | 13 | Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS); 14 | 15 | void setup(void) { 16 | 17 | Serial.begin(115200); 18 | 19 | nfc.begin(); 20 | 21 | uint32_t versiondata = nfc.getFirmwareVersion(); 22 | 23 | if (! versiondata) { 24 | 25 | Serial.print("Didn't find PN53x board"); 26 | 27 | while (1); // halt 28 | 29 | } 30 | 31 | // Got ok data, print it out! 32 | 33 | Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 34 | 35 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 36 | 37 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 38 | 39 | Serial.println("Waiting for a Card ..."); 40 | 41 | } 42 | 43 | void loop(void) { 44 | 45 | uint8_t success; 46 | 47 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; 48 | 49 | uint8_t uidLength; 50 | 51 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 52 | 53 | 54 | 55 | if (success) { 56 | 57 | Serial.println("Found a card"); 58 | 59 | Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); 60 | 61 | Serial.print(" UID Value: "); 62 | 63 | nfc.PrintHex(uid, uidLength); 64 | 65 | if (uidLength == 4) 66 | 67 | { 68 | 69 | // We probably have a Mifare Classic card ... 70 | 71 | uint32_t cardid = uid[0]; 72 | 73 | cardid <<= 8; 74 | 75 | cardid |= uid[1]; 76 | 77 | cardid <<= 8; 78 | 79 | cardid |= uid[2]; 80 | 81 | cardid <<= 8; 82 | 83 | cardid |= uid[3]; 84 | 85 | Serial.print("Seems to be a Mifare Classic card #"); 86 | 87 | Serial.println(cardid); 88 | 89 | } 90 | 91 | Serial.println(""); 92 | 93 | } 94 | 95 | } -------------------------------------------------------------------------------- /Chapter 2/UART Communication/Receiver/Receiver.ino: -------------------------------------------------------------------------------- 1 | void setup() { 2 | 3 | // Set UART baud rate to 9600 4 | 5 | Serial.begin(9600); 6 | 7 | } 8 | 9 | 10 | 11 | void loop() { 12 | 13 | if (Serial.available() > 0) { 14 | 15 | // If data is available to read 16 | 17 | String receivedData = Serial.readString(); 18 | 19 | // Process or use the received data 20 | 21 | // Example: Print the received data 22 | 23 | Serial.print("Received Data: "); 24 | 25 | Serial.println(receivedData); 26 | 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /Chapter 2/UART Communication/Sender/Sender.ino: -------------------------------------------------------------------------------- 1 | void setup() { 2 | 3 | // Set UART baud rate to 9600 4 | 5 | Serial.begin(9600); 6 | 7 | } 8 | 9 | 10 | 11 | void loop() { 12 | 13 | // Send the string "IoT" over UART 14 | 15 | Serial.println("IoT"); 16 | 17 | 18 | 19 | // Wait for a moment before sending again 20 | 21 | delay(1000); 22 | 23 | } -------------------------------------------------------------------------------- /Chapter 5/ESP32_MQTT/ESP32_MQTT.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define DHTPIN 12 8 | #define LED 26 9 | #define SERVO_PIN 2 10 | #define DHTTYPE DHT22 11 | 12 | DHT_Unified dht(DHTPIN, DHTTYPE); 13 | 14 | uint32_t delayMS; 15 | 16 | Servo servo; 17 | 18 | const char* ssid = "WiFi_SSID"; 19 | const char* password = "WiFi_Password"; 20 | 21 | const char* mqttServer = "broker.hivemq.com"; 22 | const char* clientID = "client_ID"; 23 | const char* topic = "Tempdata"; 24 | 25 | unsigned long previousMillis = 0; 26 | 27 | const long interval = 1000; 28 | 29 | String msgStr = ""; 30 | 31 | float temp, hum; 32 | 33 | WiFiClient espClient; 34 | 35 | PubSubClient client(espClient); 36 | 37 | void setup_wifi() { 38 | 39 | delay(10); 40 | WiFi.begin(ssid, password); 41 | 42 | while (WiFi.status() != WL_CONNECTED) { 43 | delay(500); 44 | } 45 | 46 | } 47 | 48 | 49 | 50 | void reconnect() { 51 | 52 | while (!client.connected()) { 53 | 54 | if (client.connect(clientID)) { 55 | Serial.println("MQTT connected"); 56 | client.subscribe("lights"); 57 | client.subscribe("servo"); 58 | } 59 | 60 | else { 61 | delay(5000); 62 | } 63 | 64 | } 65 | 66 | } 67 | 68 | 69 | 70 | void callback(char* topic, byte* payload, unsigned int length) { 71 | 72 | String data = ""; 73 | 74 | for (int i = 0; i < length; i++) { 75 | data += (char)payload[i]; 76 | } 77 | 78 | if (String(topic) == "lights") { 79 | if (data == "ON") { 80 | digitalWrite(LED, HIGH); 81 | } 82 | 83 | else { 84 | digitalWrite(LED, LOW); 85 | } 86 | 87 | } 88 | 89 | else if (String(topic) == "servo") { 90 | int degree = data.toInt(); 91 | servo.write(degree); 92 | } 93 | 94 | } 95 | 96 | 97 | 98 | void setup() { 99 | Serial.begin(115200); 100 | dht.begin(); 101 | sensor_t sensor; 102 | 103 | dht.temperature().getSensor(&sensor); 104 | dht.humidity().getSensor(&sensor); 105 | 106 | pinMode(LED, OUTPUT); 107 | digitalWrite(LED, LOW); 108 | servo.attach(SERVO_PIN); 109 | servo.write(0); 110 | setup_wifi(); 111 | client.setServer(mqttServer, 1883); 112 | client.setCallback(callback); 113 | 114 | } 115 | 116 | 117 | 118 | void loop() { 119 | 120 | if (!client.connected()) { 121 | reconnect(); 122 | } 123 | 124 | client.loop(); 125 | 126 | unsigned long currentMillis = millis(); 127 | 128 | if (currentMillis - previousMillis >= interval) { 129 | previousMillis = currentMillis; 130 | sensors_event_t event; 131 | 132 | dht.temperature().getEvent(&event); 133 | 134 | if (isnan(event.temperature)) { 135 | 136 | Serial.println(F("Error reading temperature!")); 137 | 138 | } 139 | 140 | else { 141 | 142 | temp = event.temperature; 143 | 144 | } 145 | 146 | dht.humidity().getEvent(&event); 147 | 148 | if (isnan(event.relative_humidity)) { 149 | 150 | Serial.println(F("Error reading humidity!")); 151 | 152 | } 153 | 154 | else { 155 | 156 | hum = event.relative_humidity; 157 | 158 | } 159 | 160 | msgStr = String(temp) + "," + String(hum) + ","; 161 | 162 | byte arrSize = msgStr.length() + 1; 163 | 164 | char msg[arrSize]; 165 | 166 | msgStr.toCharArray(msg, arrSize); 167 | 168 | client.publish(topic, msg); 169 | 170 | msgStr = ""; 171 | 172 | delay(1); 173 | 174 | } 175 | 176 | } -------------------------------------------------------------------------------- /Chapter 5/ESP32_WiFiManager/ESP32_WiFiManager.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | 6 | 7 | void setup() { 8 | 9 | Serial.begin(115200); 10 | 11 | WiFiManager wifiManager; 12 | 13 | // Uncomment the following line to reset Wi-Fi settings and enter configuration mode 14 | 15 | //wifiManager.resetSettings(); 16 | 17 | wifiManager.autoConnect("ESP32-Config"); // Access point name 18 | 19 | Serial.println("Connected to Wi-Fi!"); 20 | 21 | Serial.print("IP Address: "); 22 | 23 | Serial.println(WiFi.localIP()); 24 | 25 | } 26 | 27 | void loop() { 28 | 29 | // Your code goes here 30 | 31 | } -------------------------------------------------------------------------------- /Chapter 5/ESP32_as_HTTP_client/ESP32_as_HTTP_client.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define SCREEN_WIDTH 128 9 | #define SCREEN_HEIGHT 64 10 | #define OLED_RESET -1 11 | 12 | Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); 13 | 14 | const char* wifiSSID = "WIFI SSID"; 15 | const char* wifiPassword = "WIFI PASSWORD"; 16 | 17 | String openWeatherMapApiKey = "Your API Key"; 18 | String city = "London"; //change city name 19 | 20 | String jsonBuffer; 21 | 22 | void setup() { 23 | 24 | Serial.begin(115200); 25 | WiFi.begin(wifiSSID, wifiPassword); 26 | Serial.println("Connecting to WiFi..."); 27 | 28 | while (WiFi.status() != WL_CONNECTED) { 29 | delay(500); 30 | Serial.print("."); 31 | 32 | } 33 | 34 | Serial.println("\nConnected to WiFi network. IP Address: " + WiFi.localIP().toString()); 35 | 36 | if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { 37 | Serial.println(F("SSD1306 allocation failed")); 38 | for (;;); 39 | } 40 | 41 | display.clearDisplay(); 42 | 43 | } 44 | 45 | void loop() { 46 | 47 | if (WiFi.status() == WL_CONNECTED) { 48 | String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey + "&units=metric"; 49 | jsonBuffer = httpGETRequest(serverPath.c_str()); 50 | Serial.println(jsonBuffer); 51 | JSONVar weatherData = JSON.parse(jsonBuffer); 52 | 53 | if (JSON.typeof(weatherData) == "undefined") { 54 | Serial.println("Parsing input failed!"); 55 | return; 56 | } 57 | 58 | Serial.print("JSON object = "); 59 | Serial.println(weatherData); 60 | Serial.print("Temperature: "); 61 | Serial.println(weatherData["main"]["temp"]); 62 | Serial.print("Pressure: "); 63 | Serial.println(weatherData["main"]["pressure"]); 64 | Serial.print("Humidity: "); 65 | Serial.println(weatherData["main"]["humidity"]); 66 | Serial.print("Wind Speed: "); 67 | Serial.println(weatherData["wind"]["speed"]); 68 | 69 | display.clearDisplay(); 70 | display.setTextSize(1); 71 | display.setTextColor(SSD1306_WHITE); 72 | display.setCursor(0, 0); 73 | display.println("City: " + city); 74 | display.print("\nTemperature: "); 75 | display.println(weatherData["main"]["temp"]); 76 | display.print("\nPressure: "); 77 | display.println(weatherData["main"]["pressure"]); 78 | display.print("\nHumidity: "); 79 | display.println(weatherData["main"]["humidity"]); 80 | display.print("\nWind Speed: "); 81 | display.println(weatherData["wind"]["speed"]); 82 | display.display(); 83 | 84 | } else { 85 | 86 | Serial.println("WiFi Disconnected"); 87 | } 88 | 89 | delay(1000); 90 | 91 | } 92 | 93 | String httpGETRequest(const char* serverName) { 94 | 95 | WiFiClient client; 96 | HTTPClient http; 97 | 98 | http.begin(client, serverName); 99 | 100 | int httpResponseCode = http.GET(); 101 | 102 | String payload = "{}"; 103 | 104 | if (httpResponseCode > 0) { 105 | Serial.print("HTTP Response code: "); 106 | Serial.println(httpResponseCode); 107 | 108 | payload = http.getString(); 109 | 110 | } else { 111 | 112 | Serial.print("HTTP Request failed. Error code: "); 113 | 114 | Serial.println(httpResponseCode); 115 | 116 | } 117 | 118 | http.end(); 119 | 120 | return payload; 121 | 122 | } -------------------------------------------------------------------------------- /Chapter 5/ESP32_webhook/ESP32_webhook.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | const char* ssid = "WiFi_SSID"; 6 | 7 | const char* password = "WiFi_Password"; 8 | 9 | const char* webhookURL = "Your_Unique_URL"; 10 | 11 | const int buttonPin = 35; 12 | 13 | int buttonState = HIGH; 14 | 15 | int lastButtonState = HIGH; 16 | 17 | unsigned long lastDebounceTime = 0; 18 | 19 | unsigned long debounceDelay = 50; 20 | 21 | 22 | 23 | void setup() { 24 | 25 | Serial.begin(115200); 26 | 27 | pinMode(buttonPin, INPUT_PULLUP); 28 | 29 | digitalWrite(buttonPin, HIGH); 30 | 31 | WiFi.begin(ssid, password); 32 | 33 | while (WiFi.status() != WL_CONNECTED) { 34 | 35 | delay(1000); 36 | 37 | } 38 | 39 | } 40 | 41 | 42 | 43 | void loop() { 44 | 45 | int reading = digitalRead(buttonPin); 46 | 47 | if (reading != lastButtonState) { 48 | 49 | lastDebounceTime = millis(); 50 | 51 | } 52 | 53 | if ((millis() - lastDebounceTime) > debounceDelay) { 54 | 55 | if (reading != buttonState) { 56 | 57 | buttonState = reading; 58 | 59 | if (buttonState == LOW) { 60 | 61 | sendWebhookRequest(buttonState); 62 | 63 | } 64 | 65 | } 66 | 67 | } 68 | 69 | lastButtonState = reading; 70 | 71 | } 72 | 73 | 74 | 75 | void sendWebhookRequest(int switchStatus) { 76 | 77 | HTTPClient http; 78 | 79 | String url = String(webhookURL) + "?random=" + String(random(30)); 80 | 81 | http.begin(url); 82 | 83 | int httpResponseCode = http.GET(); 84 | 85 | if (httpResponseCode > 0) { 86 | 87 | Serial.print("Webhook request sent. Response code: "); 88 | 89 | Serial.println(httpResponseCode); 90 | 91 | } else { 92 | 93 | Serial.print("Error sending webhook request. HTTP response code: "); 94 | 95 | Serial.println(httpResponseCode); 96 | 97 | } 98 | 99 | http.end(); 100 | 101 | } -------------------------------------------------------------------------------- /Chapter 5/ESP32_webserver/ESP32_webserver.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | const char* ssid = "YourWiFiSSID"; 6 | 7 | const char* password = "WIFIPASSWORD"; 8 | 9 | WebServer server(80); 10 | 11 | const int ledPin = 13; 12 | 13 | const int buttonPin = 12; 14 | 15 | bool ledState = false; 16 | 17 | void setup() { 18 | 19 | Serial.begin(115200); 20 | 21 | pinMode(ledPin, OUTPUT); 22 | 23 | pinMode(buttonPin, INPUT_PULLUP); 24 | 25 | digitalWrite(ledPin, ledState); 26 | 27 | WiFi.begin(ssid, password); 28 | 29 | while (WiFi.status() != WL_CONNECTED) { 30 | 31 | delay(1000); 32 | 33 | Serial.println("Connecting to WiFi..."); 34 | 35 | } 36 | 37 | Serial.println("WiFi connected"); 38 | 39 | Serial.println("IP address: "); 40 | 41 | Serial.println(WiFi.localIP()); 42 | 43 | server.on("/", HTTP_GET, handleRoot); 44 | 45 | server.on("/toggle", HTTP_GET, handleToggle); 46 | 47 | server.begin(); 48 | 49 | } 50 | 51 | void loop() { 52 | 53 | server.handleClient(); 54 | 55 | int buttonState = digitalRead(buttonPin); 56 | 57 | if (buttonState == LOW) { 58 | 59 | ledState = !ledState; 60 | 61 | digitalWrite(ledPin, ledState); 62 | 63 | } 64 | 65 | } 66 | 67 | void handleRoot() { 68 | 69 | String html = ""; 70 | 71 | html += "

ESP32 LED Control

"; 72 | 73 | html += "

LED Status: " + String(ledState) + "

"; 74 | 75 | html += "
"; 76 | 77 | html += ""; 78 | 79 | html += "
"; 80 | 81 | html += ""; 82 | 83 | server.send(200, "text/html", html); 84 | 85 | } 86 | 87 | void handleToggle() { 88 | 89 | ledState = !ledState; 90 | 91 | digitalWrite(ledPin, ledState); 92 | 93 | server.send(200, "text/plain", "LED toggled"); 94 | 95 | } -------------------------------------------------------------------------------- /Chapter 6/Final_code/Final_code.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "time.h" 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | 14 | //Sensors interfacing & parameters 15 | #define DHTPIN 13 // DHT22 data pin 16 | #define DHTTYPE DHT22 // DHT22 sensor model 17 | #define MoistureSensor 34 // Moisture pin 18 | DHT dht(DHTPIN, DHTTYPE); 19 | int moisturePin = MoistureSensor; 20 | int moistureThresholds[] = {300, 700}; // Adjust these thresholds for your setup 21 | int tempThreshold = 30; 22 | int humidityThreshold = 40; 23 | 24 | //WiFi Credentitals 25 | #define WIFI_SSID "WiFi SSID" 26 | #define WIFI_PASSWORD "WIFI Password" 27 | 28 | //Email Credentials 29 | #define SMTP_server "smtp.gmail.com" 30 | #define SMTP_Port 465 31 | #define sender_email "your email@gmail.com" 32 | #define sender_password "password" 33 | #define Recipient_email "receiver@gmail.com" 34 | #define Recipient_name "Name" 35 | SMTPSession smtp; 36 | 37 | //twitter credentials, update them with your credentials 38 | const char *consumerKey = "j4jpQJNKyxZHFUac"; 39 | const char *consumerSecret = "9DnlbfcmRMvruXZEm3pbpHKUF"; 40 | const char *accessToken = "1697183233648013312-iRzF"; 41 | const char *accessTokenSecret = "yb13u10BqsQ2unYBHR"; 42 | 43 | WiFiClientSecure client; 44 | TweESP32 twitter(client, consumerKey, consumerSecret, accessToken, accessTokenSecret); 45 | //connectWiFi() Function 46 | void connectWiFi() { 47 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 48 | while (WiFi.status() != WL_CONNECTED) { 49 | delay(1000); 50 | Serial.println("Connecting to WiFi..."); 51 | } 52 | Serial.println("Connected to WiFi"); 53 | } 54 | 55 | //SendEmail(const String& messageText) function 56 | void sendEmail(const String& messageText) { 57 | ESP_Mail_Session session; 58 | session.server.host_name = SMTP_server ; 59 | session.server.port = SMTP_Port; 60 | session.login.email = sender_email; 61 | session.login.password = sender_password; 62 | session.login.user_domain = ""; 63 | SMTP_Message message; 64 | message.sender.name = "ESP32"; 65 | message.sender.email = sender_email; 66 | message.subject = "ESP32 Plant Updates"; 67 | message.addRecipient(Recipient_name, Recipient_email); 68 | // Send simple text message 69 | message.text.content = messageText.c_str(); 70 | message.text.charSet = "us-ascii"; 71 | message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit; 72 | if (!smtp.connect(&session)){ 73 | Serial.println("Email Sent"); 74 | return; 75 | } 76 | if (!MailClient.sendMail(&smtp, &message)){ 77 | Serial.println("Error sending Email, " + smtp.errorReason()); 78 | } 79 | } 80 | 81 | void setup() { 82 | Serial.begin(115200); 83 | connectWiFi(); 84 | dht.begin(); 85 | } 86 | 87 | void loop() { 88 | float temperature = readTemperature(); 89 | float humidity = readHumidity(); 90 | int moistureValue = readMoisture(); 91 | String moistureStatus = getMoistureStatus(moistureValue); 92 | String msg = PlantMessages(temperature, humidity, moistureValue, moistureStatus); 93 | Serial.println(msg); 94 | sendEmail(msg); 95 | sendTweet(msg.c_str()); 96 | sendWhatsAppMessage(msg); 97 | sendTelegramMessage(msg); 98 | delay(20000); 99 | } 100 | float readTemperature() { 101 | return dht.readTemperature(); 102 | } 103 | float readHumidity() { 104 | return dht.readHumidity(); 105 | } 106 | int readMoisture() { 107 | return analogRead(moisturePin); 108 | } 109 | //PlantMessages function 110 | String PlantMessages(float temperature, float humidity, int moistureValue, String moistureStatus) { 111 | String Message = ""; 112 | bool NeedWater = false; 113 | Message = "Moisture Status is "+ moistureStatus+"."; 114 | if(moistureStatus == "Dry"){ 115 | Message += " I need Water Now."; 116 | } 117 | if (temperature > tempThreshold){ 118 | Message += "The weather is hot, which causes the soil to dry out more quickly. I will need water more frequently."; 119 | } 120 | if (humidity < humidityThreshold){ 121 | Message += "Low Moisture Level, Water evaporates quickly. I will need water Frequently."; 122 | } 123 | Message += "Summary of Data: Moisture Status : " + moistureStatus +" Moisture Value : "+ String(moistureValue) + " Temperature : "+ String(temperature) +" Humidity : "+ String(humidity); 124 | return Message; 125 | } 126 | 127 | //getMoistureStatus function 128 | String getMoistureStatus(int value) { 129 | if (value < moistureThresholds[0]) { 130 | return "Dry"; 131 | } else if (value >= moistureThresholds[0] && value <= moistureThresholds[1]) { 132 | return "Ok"; 133 | } else { 134 | return "Wet"; 135 | } 136 | } 137 | void sendWhatsAppMessage(const String& message) { 138 | String apiUrl = "https://api.callmebot.com/whatsapp.php"; 139 | String phoneNumber = "Your number"; // Replace with the desired phone number 140 | String apiKey = "API key"; // Replace with your API key 141 | String url = apiUrl + "?phone=" + phoneNumber + "&text=" + urlEncode(message) + "&apikey=" + apiKey; 142 | HTTPClient http; 143 | http.begin(url); 144 | 145 | int httpResponseCode = http.GET(); 146 | if (httpResponseCode == 200) { 147 | Serial.println("WhatsApp message sent successfully!"); 148 | } else { 149 | Serial.print("Error sending WhatsApp message. HTTP code: "); 150 | Serial.println(httpResponseCode); 151 | } 152 | 153 | http.end(); 154 | } 155 | 156 | void sendTelegramMessage(const String& message) { 157 | String apiUrl = "http://api.callmebot.com/text.php"; 158 | String user = "Photon67000"; // Replace with your user ID 159 | String url = apiUrl + "?user=" + user + "&text=" + urlEncode(message); 160 | 161 | HTTPClient http; 162 | http.begin(url); 163 | 164 | int httpResponseCode = http.GET(); 165 | 166 | if (httpResponseCode == 200) { 167 | Serial.println("Telegram message sent successfully!"); 168 | } else { 169 | Serial.print("Error sending Telegram message. HTTP code: "); 170 | Serial.println(httpResponseCode); 171 | } 172 | http.end(); 173 | } 174 | //send Tweet 175 | void sendTweet(const char* tweetText) { 176 | twitter.timeConfig(); 177 | client.setCACert(twitter_server_cert); 178 | bool success = twitter.sendTweet(const_cast(tweetText)); 179 | if (success) { 180 | Serial.println("Tweet Sent"); 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /Chapter 6/Read_sensors/Read_sensors.ino: -------------------------------------------------------------------------------- 1 | #include 2 | //Sensors interfacing & parameters 3 | #define DHTPIN 13 // DHT22 data pin 4 | #define DHTTYPE DHT22 // DHT22 sensor model 5 | #define MoistureSensor 34 // Moisture pin 6 | DHT dht(DHTPIN, DHTTYPE); 7 | int moisturePin = MoistureSensor; 8 | int moistureThresholds[] = {300, 700}; // Adjust these thresholds for your setup 9 | int tempThreshold = 30; 10 | int humidityThreshold = 40; 11 | 12 | void setup() { 13 | Serial.begin(115200); 14 | dht.begin(); 15 | } 16 | void loop() { 17 | float temperature = readTemperature(); 18 | float humidity = readHumidity(); 19 | int moistureValue = readMoisture(); 20 | String moistureStatus = getMoistureStatus(moistureValue); 21 | Serial.println(PlantMessages(temperature, humidity, moistureValue, moistureStatus)); 22 | delay(20000); 23 | } 24 | float readTemperature() { 25 | return dht.readTemperature(); 26 | } 27 | float readHumidity() { 28 | return dht.readHumidity(); 29 | } 30 | int readMoisture() { 31 | return analogRead(moisturePin); 32 | } 33 | String PlantMessages(float temperature, float humidity, int moistureValue, String moistureStatus) { 34 | String Message = ""; 35 | Message = "Moisture Status is "+moistureStatus+"."; 36 | if(moistureStatus == "Dry"){ 37 | Message += " I need Water Now."; 38 | } 39 | if (temperature > tempThreshold){ 40 | Message += "\nThe weather is hot, which causes the soil to dry out more quickly. I will need water more frequently."; 41 | } 42 | if (humidity < humidityThreshold){ 43 | Message += "\nLow Moisture Level, Water evaporates quickly. I will need water Frequently."; 44 | } 45 | Message += "\nSummary of Data: \n Moisture Status : " + moistureStatus +"\n Moisture Value : "+ String(moistureValue) + "\n Temperature : "+ String(temperature) +"\n Humidity : "+ String(humidity); 46 | return Message; 47 | } 48 | String getMoistureStatus(int value) { 49 | if (value < moistureThresholds[0]) { 50 | return "Dry"; 51 | } else if (value >= moistureThresholds[0] && value <= moistureThresholds[1]) { 52 | return "Ok"; 53 | } else { 54 | return "Wet"; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Chapter 6/Send_Email/Send_Email.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | //Sensors interfacing & parameters 6 | 7 | //WiFi Credentitals 8 | #define WIFI_SSID "Your WIFI SSID" 9 | #define WIFI_PASSWORD "WIFI PASSWORD" 10 | 11 | //Email Credentials 12 | #define SMTP_server "smtp.gmail.com" 13 | #define SMTP_Port 465 14 | #define sender_email "youremail@gmail.com" 15 | #define sender_password "password that we generated" 16 | #define Recipient_email "receiver_email@gmail.com" 17 | #define Recipient_name "Recipient name" 18 | SMTPSession smtp; 19 | //connectWiFi() Function 20 | void connectWiFi() { 21 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 22 | while (WiFi.status() != WL_CONNECTED) { 23 | delay(1000); 24 | Serial.println("Connecting to WiFi..."); 25 | } 26 | Serial.println("Connected to WiFi"); 27 | } 28 | //SendEmail(const String& messageText) function 29 | void sendEmail(const String& messageText) { 30 | ESP_Mail_Session session; 31 | session.server.host_name = SMTP_server ; 32 | session.server.port = SMTP_Port; 33 | session.login.email = sender_email; 34 | session.login.password = sender_password; 35 | session.login.user_domain = ""; 36 | SMTP_Message message; 37 | message.sender.name = "ESP32"; 38 | message.sender.email = sender_email; 39 | message.subject = "ESP32 Plant Updates"; 40 | message.addRecipient(Recipient_name, Recipient_email); 41 | // Send simple text message 42 | message.text.content = messageText.c_str(); 43 | message.text.charSet = "us-ascii"; 44 | message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit; 45 | if (!smtp.connect(&session)){ 46 | Serial.println("Email Sent"); 47 | return; 48 | } 49 | if (!MailClient.sendMail(&smtp, &message)){ 50 | Serial.println("Error sending Email, " + smtp.errorReason()); 51 | } 52 | } 53 | void setup() { 54 | Serial.begin(115200); 55 | connectWiFi(); 56 | dht.begin(); 57 | } 58 | void loop() { 59 | float temperature = readTemperature(); 60 | float humidity = readHumidity(); 61 | int moistureValue = readMoisture(); 62 | String moistureStatus = getMoistureStatus(moistureValue); 63 | String msg = PlantMessages(temperature, humidity, moistureValue, moistureStatus); 64 | Serial.println(msg); 65 | sendEmail(msg); 66 | delay(10000); 67 | } 68 | float readTemperature() { 69 | return dht.readTemperature(); 70 | } 71 | float readHumidity() { 72 | return dht.readHumidity(); 73 | } 74 | int readMoisture() { 75 | return analogRead(moisturePin); 76 | } 77 | String PlantMessages(float temperature, float humidity, int moistureValue, String moistureStatus) { 78 | String Message = ""; 79 | Message = "Moisture Status is "+moistureStatus+"."; 80 | if(moistureStatus == "Dry"){ 81 | Message += " I need Water Now."; 82 | } 83 | if (temperature > tempThreshold){ 84 | Message += "\nThe weather is hot, which causes the soil to dry out more quickly. I will need water more frequently."; 85 | } 86 | if (humidity < humidityThreshold){ 87 | Message += "\nLow Moisture Level, Water evaporates quickly. I will need water Frequently."; 88 | } 89 | Message += "\nSummary of Data: \n Moisture Status : " + moistureStatus +"\n Moisture Value : "+ String(moistureValue) + "\n Temperature : "+ String(temperature) +"\n Humidity : "+ String(humidity); 90 | return Message; 91 | } 92 | String getMoistureStatus(int value) { 93 | if (value < moistureThresholds[0]) { 94 | return "Dry"; 95 | } else if (value >= moistureThresholds[0] && value <= moistureThresholds[1]) { 96 | return "Ok"; 97 | } else { 98 | return "Wet"; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Chapter 6/Whatsapp_Telegram/Whatsapp_Telegram.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | //Sensors interfacing & parameters 8 | #define DHTPIN 13 // DHT22 data pin 9 | #define DHTTYPE DHT22 // DHT22 sensor model 10 | #define MoistureSensor 34 // Moisture pin 11 | DHT dht(DHTPIN, DHTTYPE); 12 | int moisturePin = MoistureSensor; 13 | int moistureThresholds[] = {300, 700}; // Adjust these thresholds for your setup 14 | int tempThreshold = 30; 15 | int humidityThreshold = 40; 16 | 17 | //WiFi Credentitals 18 | #define WIFI_SSID "Your WIFI SSID" 19 | #define WIFI_PASSWORD "WIFI PASSWORD" 20 | 21 | //Email Credentials 22 | #define SMTP_server "smtp.gmail.com" 23 | #define SMTP_Port 465 24 | #define sender_email "youremail@gmail.com" 25 | #define sender_password "password that we generated" 26 | #define Recipient_email "receiver_email@gmail.com" 27 | #define Recipient_name "Recipient name" 28 | SMTPSession smtp; 29 | 30 | //connectWiFi() Function 31 | void connectWiFi() { 32 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 33 | while (WiFi.status() != WL_CONNECTED) { 34 | delay(1000); 35 | Serial.println("Connecting to WiFi..."); 36 | } 37 | Serial.println("Connected to WiFi"); 38 | } 39 | 40 | //SendEmail(const String& messageText) function 41 | void sendEmail(const String& messageText) { 42 | ESP_Mail_Session session; 43 | session.server.host_name = SMTP_server ; 44 | session.server.port = SMTP_Port; 45 | session.login.email = sender_email; 46 | session.login.password = sender_password; 47 | session.login.user_domain = ""; 48 | SMTP_Message message; 49 | message.sender.name = "ESP32"; 50 | message.sender.email = sender_email; 51 | message.subject = "ESP32 Plant Updates"; 52 | message.addRecipient(Recipient_name, Recipient_email); 53 | // Send simple text message 54 | message.text.content = messageText.c_str(); 55 | message.text.charSet = "us-ascii"; 56 | message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit; 57 | if (!smtp.connect(&session)){ 58 | Serial.println("Email Sent"); 59 | return; 60 | } 61 | if (!MailClient.sendMail(&smtp, &message)){ 62 | Serial.println("Error sending Email, " + smtp.errorReason()); 63 | } 64 | } 65 | 66 | void setup() { 67 | Serial.begin(115200); 68 | connectWiFi(); 69 | dht.begin(); 70 | } 71 | 72 | void loop() { 73 | float temperature = readTemperature(); 74 | float humidity = readHumidity(); 75 | 76 | int moistureValue = readMoisture(); 77 | String moistureStatus = getMoistureStatus(moistureValue); 78 | String msg = PlantMessages(temperature, humidity, moistureValue, moistureStatus); 79 | Serial.println(msg); 80 | sendEmail(msg); 81 | sendWhatsAppMessage(msg); 82 | sendTelegramMessage(msg); 83 | delay(20000); 84 | } 85 | 86 | float readTemperature() { 87 | return dht.readTemperature(); 88 | } 89 | float readHumidity() { 90 | return dht.readHumidity(); 91 | } 92 | int readMoisture() { 93 | return analogRead(moisturePin); 94 | } 95 | String PlantMessages(float temperature, float humidity, int moistureValue, String moistureStatus) { 96 | String Message = ""; 97 | Message = "Moisture Status is "+moistureStatus+"."; 98 | if(moistureStatus == "Dry"){ 99 | Message += " I need Water Now."; 100 | } 101 | if (temperature > tempThreshold){ 102 | Message += "\nThe weather is hot, which causes the soil to dry out more quickly. I will need water more frequently."; 103 | } 104 | if (humidity < humidityThreshold){ 105 | Message += "\nLow Moisture Level, Water evaporates quickly. I will need water Frequently."; 106 | } 107 | Message += "\nSummary of Data: \n Moisture Status : " + moistureStatus +"\n Moisture Value : "+ String(moistureValue) + "\n Temperature : "+ String(temperature) +"\n Humidity : "+ String(humidity); 108 | return Message; 109 | } 110 | String getMoistureStatus(int value) { 111 | if (value < moistureThresholds[0]) { 112 | return "Dry"; 113 | } else if (value >= moistureThresholds[0] && value <= moistureThresholds[1]) { 114 | return "Ok"; 115 | } else { 116 | return "Wet"; 117 | } 118 | } 119 | 120 | void sendWhatsAppMessage(const String& message) { 121 | String apiUrl = "https://api.callmebot.com/whatsapp.php"; 122 | String phoneNumber = "Phone Number"; // Replace with the desired phone number 123 | String apiKey = "API Key"; // Replace with your API key 124 | String url = apiUrl + "?phone=" + phoneNumber + "&text=" + urlEncode(message) + "&apikey=" + apiKey; 125 | HTTPClient http; 126 | http.begin(url); 127 | int httpResponseCode = http.GET(); 128 | if (httpResponseCode == 200) { 129 | Serial.println("WhatsApp message sent successfully!"); 130 | } else { 131 | Serial.print("Error sending WhatsApp message. HTTP code: "); 132 | Serial.println(httpResponseCode); 133 | } 134 | http.end(); 135 | } 136 | 137 | void sendTelegramMessage(const String& message) { 138 | String apiUrl = "http://api.callmebot.com/text.php"; 139 | String user = "Photon67000"; // Replace with your user ID 140 | String url = apiUrl + "?user=" + user + "&text=" + urlEncode(message); 141 | HTTPClient http; 142 | http.begin(url); 143 | int httpResponseCode = http.GET(); 144 | 145 | if (httpResponseCode == 200) { 146 | Serial.println("Telegram message sent successfully!"); 147 | } else { 148 | Serial.print("Error sending Telegram message. HTTP code: "); 149 | Serial.println(httpResponseCode); 150 | } 151 | http.end(); 152 | } 153 | -------------------------------------------------------------------------------- /Chapter 6/twitter/twitter.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "time.h" 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | // Sensors interfacing & parameters 14 | #define DHTPIN 13 // DHT22 data pin 15 | #define DHTTYPE DHT22 // DHT22 sensor model 16 | #define MoistureSensor 34 // Moisture pin 17 | DHT dht(DHTPIN, DHTTYPE); 18 | int moisturePin = MoistureSensor; 19 | int moistureThresholds[] = {300, 700}; // Adjust these thresholds for your setup 20 | int tempThreshold = 30; 21 | int humidityThreshold = 40; 22 | 23 | // WiFi Credentitals 24 | #define WIFI_SSID "WiFi SSID" 25 | #define WIFI_PASSWORD "WIFI Password" 26 | 27 | // twitter credentials, update them with your credentials 28 | const char *consumerKey = "j4jpQJNKyxZHFUac"; 29 | const char *consumerSecret = "9DnlbfcmRMvruXZEm3pbpHKUF"; 30 | const char *accessToken = "1697183233648013312-iRzF"; 31 | const char *accessTokenSecret = "yb13u10BqsQ2unYBHR"; 32 | 33 | WiFiClientSecure client; 34 | TweESP32 twitter(client, consumerKey, consumerSecret, accessToken, accessTokenSecret); 35 | // connectWiFi() Function 36 | void connectWiFi() 37 | { 38 | WiFi.begin(WIFI_SSID, WIFI_PASSWORD); 39 | while (WiFi.status() != WL_CONNECTED) 40 | { 41 | delay(1000); 42 | Serial.println("Connecting to WiFi..."); 43 | } 44 | Serial.println("Connected to WiFi"); 45 | } 46 | 47 | void setup() 48 | { 49 | Serial.begin(115200); 50 | connectWiFi(); 51 | dht.begin(); 52 | } 53 | 54 | void loop() 55 | { 56 | float temperature = readTemperature(); 57 | float humidity = readHumidity(); 58 | int moistureValue = readMoisture(); 59 | String moistureStatus = getMoistureStatus(moistureValue); 60 | String msg = PlantMessages(temperature, humidity, moistureValue, moistureStatus); 61 | Serial.println(msg); 62 | sendTelegramMessage(msg); 63 | delay(20000); 64 | } 65 | 66 | float readTemperature() 67 | { 68 | return dht.readTemperature(); 69 | } 70 | float readHumidity() 71 | { 72 | return dht.readHumidity(); 73 | } 74 | int readMoisture() 75 | { 76 | return analogRead(moisturePin); 77 | } 78 | 79 | // PlantMessages function 80 | String PlantMessages(float temperature, float humidity, int moistureValue, String moistureStatus) 81 | { 82 | String Message = ""; 83 | bool NeedWater = false; 84 | Message = "Moisture Status is " + moistureStatus + "."; 85 | if (moistureStatus == "Dry") 86 | { 87 | Message += " I need Water Now."; 88 | } 89 | if (temperature > tempThreshold) 90 | { 91 | Message += "The weather is hot, which causes the soil to dry out more quickly. I will need water more frequently."; 92 | } 93 | if (humidity < humidityThreshold) 94 | { 95 | Message += "Low Moisture Level, Water evaporates quickly. I will need water Frequently."; 96 | } 97 | Message += "Summary of Data: Moisture Status : " + moistureStatus + " Moisture Value : " + String(moistureValue) + " Temperature : " + String(temperature) + " Humidity : " + String(humidity); 98 | return Message; 99 | } 100 | 101 | // getMoistureStatus function 102 | String getMoistureStatus(int value) 103 | { 104 | if (value < moistureThresholds[0]) 105 | { 106 | return "Dry"; 107 | } 108 | else if (value >= moistureThresholds[0] && value <= moistureThresholds[1]) 109 | { 110 | return "Ok"; 111 | } 112 | else 113 | { 114 | return "Wet"; 115 | } 116 | } 117 | 118 | // send Tweet 119 | void sendTweet(const char *tweetText) 120 | { 121 | twitter.timeConfig(); 122 | client.setCACert(twitter_server_cert); 123 | bool success = twitter.sendTweet(const_cast(tweetText)); 124 | if (success) 125 | { 126 | Serial.println("Tweet Sent"); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /Chapter3/16x2 LCD/16x2_LCD.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | const int LCD_ADDRESS = 0x27; 6 | 7 | const int LCD_COLS = 16; 8 | 9 | const int LCD_ROWS = 2; 10 | 11 | LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLS, LCD_ROWS); 12 | 13 | void setup() { 14 | 15 | lcd.init(); 16 | 17 | lcd.backlight(); 18 | 19 | lcd.setCursor(0, 0); 20 | 21 | lcd.print("Hello, ESP32!"); 22 | 23 | lcd.setCursor(0, 1); 24 | 25 | lcd.print("LCD Example"); 26 | 27 | delay(3000); 28 | 29 | lcd.clear(); 30 | 31 | lcd.print("Scrolling Text:"); 32 | 33 | lcd.autoscroll(); 34 | 35 | for (int i = 0; i < 16; i++) { 36 | 37 | lcd.scrollDisplayLeft(); 38 | 39 | delay(500); 40 | 41 | } 42 | 43 | lcd.noAutoscroll(); 44 | 45 | lcd.clear(); 46 | 47 | byte heart[8] = { 48 | 49 | B00000, 50 | 51 | B01010, 52 | 53 | B11111, 54 | 55 | B11111, 56 | 57 | B01110, 58 | 59 | B00100, 60 | 61 | B00000, 62 | 63 | }; 64 | 65 | lcd.createChar(0, heart); 66 | 67 | lcd.setCursor(0, 0); 68 | 69 | lcd.print("I "); 70 | 71 | lcd.write(byte(0)); 72 | 73 | lcd.print(" ESP32!"); 74 | 75 | } 76 | 77 | void loop() { 78 | 79 | // Do nothing in the loop 80 | 81 | } 82 | -------------------------------------------------------------------------------- /Chapter3/E-paper/E_paper.ino: -------------------------------------------------------------------------------- 1 | include 2 | 3 | #include   4 | 5 | #include 6 | 7 | #include 8 | 9 | 10 | 11 | GxEPD2_BW display(GxEPD2_290(/*CS=*/ 5, /*DC=*/ 17, /*RST=*/ 16, /*BUSY=*/ 4)); 12 | 13 | 14 | 15 | void setup() { 16 | 17 |   Serial.begin(115200); 18 | 19 |   display.init(); 20 | 21 |   display.setRotation(1); 22 | 23 | } 24 | 25 | void loop() { 26 | 27 |   display.fillScreen(GxEPD_WHITE); 28 | 29 |   display.setFont(&FreeMonoBold12pt7b); 30 | 31 |   display.setTextColor(GxEPD_BLACK); 32 | 33 |   display.setCursor((display.width() - 11) / 2, display.height() / 2); 34 | 35 |   display.println("Hello World"); 36 | 37 |   display.display(); 38 | 39 |   delay(10000); 40 | 41 | } 42 | -------------------------------------------------------------------------------- /Chapter3/PIR motion Sensor and camera/PIR_Camera.ino: -------------------------------------------------------------------------------- 1 | #include "esp_camera.h" 2 | 3 | #include 4 | 5 | 6 | #define CAMERA_MODEL_AI_THINKER 7 | 8 | #define PWDN_GPIO_NUM -1 9 | 10 | #define RESET_GPIO_NUM -1 11 | 12 | #define XCLK_GPIO_NUM 4 13 | 14 | #define SIOD_GPIO_NUM 18 15 | 16 | #define SIOC_GPIO_NUM 23 17 | 18 | #define Y9_GPIO_NUM 36 19 | 20 | #define Y8_GPIO_NUM 37 21 | 22 | #define Y7_GPIO_NUM 38 23 | 24 | #define Y6_GPIO_NUM 39 25 | 26 | #define Y5_GPIO_NUM 35 27 | 28 | #define Y4_GPIO_NUM 14 29 | 30 | #define Y3_GPIO_NUM 13 31 | 32 | #define Y2_GPIO_NUM 34 33 | 34 | #define VSYNC_GPIO_NUM 5 35 | 36 | #define HREF_GPIO_NUM 27 37 | 38 | #define PCLK_GPIO_NUM 25 39 | 40 | // Motion sensor configuration 41 | 42 | #define MOTION_SENSOR_PIN 2 43 | 44 | 45 | 46 | void setup() { 47 | 48 | Serial.begin(115200); 49 | 50 | // Initialize SD card 51 | 52 | if (!SD_MMC.begin()) { 53 | 54 | Serial.println("SD card initialization failed"); 55 | 56 | return; 57 | 58 | } 59 | 60 | Serial.println("SD card initialized"); 61 | 62 | // Initialize the camera 63 | 64 | camera_config_t config; 65 | 66 | config.ledc_channel = LEDC_CHANNEL_0; 67 | 68 | config.ledc_timer = LEDC_TIMER_0; 69 | 70 | config.pin_d0 = Y2_GPIO_NUM; 71 | 72 | config.pin_d1 = Y3_GPIO_NUM; 73 | 74 | config.pin_d2 = Y4_GPIO_NUM; 75 | 76 | config.pin_d3 = Y5_GPIO_NUM; 77 | 78 | config.pin_d4 = Y6_GPIO_NUM; 79 | 80 | config.pin_d5 = Y7_GPIO_NUM; 81 | 82 | config.pin_d6 = Y8_GPIO_NUM; 83 | 84 | config.pin_d7 = Y9_GPIO_NUM; 85 | 86 | config.pin_xclk = XCLK_GPIO_NUM; 87 | 88 | config.pin_pclk = PCLK_GPIO_NUM; 89 | 90 | config.pin_vsync = VSYNC_GPIO_NUM; 91 | 92 | config.pin_href = HREF_GPIO_NUM; 93 | 94 | config.pin_sscb_sda = SIOD_GPIO_NUM; 95 | 96 | config.pin_sscb_scl = SIOC_GPIO_NUM; 97 | 98 | config.pin_pwdn = PWDN_GPIO_NUM; 99 | 100 | config.pin_reset = RESET_GPIO_NUM; 101 | 102 | config.xclk_freq_hz = 20000000; 103 | 104 | config.pixel_format = PIXFORMAT_JPEG; 105 | 106 | // Initialize camera module 107 | 108 | if (esp_camera_init(&config) != ESP_OK) { 109 | 110 | Serial.println("Camera initialization failed"); 111 | 112 | return; 113 | 114 | } 115 | 116 | Serial.println("Camera initialized"); 117 | 118 | 119 | // Configure motion sensor pin as input 120 | pinMode(MOTION_SENSOR_PIN, INPUT); 121 | 122 | } 123 | 124 | 125 | void loop() { 126 | 127 | if (digitalRead(MOTION_SENSOR_PIN) == HIGH) { 128 | 129 | // Motion detected, capture image 130 | 131 | // Capture image 132 | 133 | camera_fb_t* fb = NULL; 134 | 135 | fb = esp_camera_fb_get(); 136 | 137 | if (!fb) { 138 | 139 | Serial.println("Camera capture failed"); 140 | 141 | return; 142 | 143 | } 144 | 145 | // Create a file on the SD card 146 | 147 | File file = SD_MMC.open("/image.jpg", FILE_WRITE); 148 | 149 | if (!file) { 150 | 151 | Serial.println("Failed to create file"); 152 | 153 | return; 154 | 155 | } 156 | // Write the image data to the file 157 | 158 | file.write(fb->buf, fb->len); 159 | 160 | file.close(); 161 | 162 | esp_camera_fb_return(fb); 163 | 164 | Serial.println("Image captured and saved"); 165 | 166 | } 167 | 168 | // Delay for a short time before checking for motion again 169 | 170 | delay(100); 171 | 172 | } 173 | -------------------------------------------------------------------------------- /Chapter3/SSD1306 OLED/SSD1306_OLED.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | #include 6 | 7 | #define SCREEN_WIDTH 128 8 | 9 | #define SCREEN_HEIGHT 64 10 | 11 | 12 | 13 | Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); 14 | 15 | const unsigned char logo [] PROGMEM = { 16 | 17 | // Paste the generated logo bitmap here 18 | // you could convert your BMP image to c array by using this online tool: https://javl.github.io/image2cpp/ 19 | 20 | }; 21 | 22 | 23 | 24 | void setup() { 25 | 26 |   if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { 27 | 28 |     Serial.println(F("SSD1306 allocation failed")); 29 | 30 |     for (;;); 31 | 32 |   } 33 | 34 | 35 | 36 |   display.clearDisplay(); 37 | 38 |   display.setTextSize(1); 39 | 40 |   display.setTextColor(SSD1306_WHITE); 41 | 42 |   display.setCursor(0, 0); 43 | 44 |   display.println("Hello, ESP32!"); 45 | 46 |   display.println("OLED Example"); 47 | 48 |   display.display(); 49 | 50 |   delay(2000); 51 | 52 | 53 | 54 |   display.clearDisplay(); 55 | 56 |   display.display(); 57 | 58 | } 59 | 60 | 61 | 62 | void loop() { 63 | 64 |   display.clearDisplay(); 65 | 66 |   display.setTextSize(2); 67 | 68 |   display.setTextColor(SSD1306_WHITE); 69 | 70 |   display.setCursor(0, 10); 71 | 72 |   display.println("ESP32"); 73 | 74 |   display.setTextSize(1); 75 | 76 |   display.setCursor(0, 30); 77 | 78 |   display.println("OLED Display"); 79 | 80 |   display.display(); 81 | 82 |   delay(2000); 83 | 84 | 85 | 86 |   display.clearDisplay(); 87 | 88 |   display.drawRect(10, 10, 50, 30, SSD1306_WHITE); 89 | 90 |   display.display(); 91 | 92 |   delay(2000); 93 | 94 | 95 | 96 |   display.clearDisplay(); 97 | 98 |   display.fillCircle(30, 20, 15, SSD1306_WHITE); 99 | 100 |   display.display(); 101 | 102 |   delay(2000); 103 | display.clearDisplay(); 104 | 105 |   display.drawLine(10, 10, 50, 30, SSD1306_WHITE); 106 | 107 |   display.display(); 108 | 109 |   delay(2000); 110 | 111 | 112 | 113 |   display.clearDisplay(); 114 | 115 |   display.drawBitmap(0, 0, logo, 128, 64, SSD1306_WHITE); 116 | 117 |   display.display(); 118 | 119 |   delay(2000); 120 | 121 | } 122 | -------------------------------------------------------------------------------- /Chapter3/TFT Touchscreen/TFT_touchscreen.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | #include 6 | 7 | #define TFT_CS 15 8 | 9 | #define TFT_DC 2 10 | 11 | #define SCREEN_WIDTH 320 12 | 13 | #define SCREEN_HEIGHT 240 14 | 15 | 16 | 17 | #define BACKGROUND_COLOR ILI9341_BLACK 18 | 19 | #define TEXT_COLOR ILI9341_WHITE 20 | 21 | #define HIGHLIGHT_COLOR ILI9341_YELLOW 22 | 23 | 24 | 25 | #define TS_MINX 0    // Replace with the minimum X touch value 26 | 27 | #define TS_MAXX 240  // Replace with the maximum X touch value 28 | 29 | #define TS_MINY 0    // Replace with the minimum Y touch value 30 | 31 | #define TS_MAXY 320  // Replace with the maximum Y touch value 32 | 33 | 34 | 35 | Adafruit_FT6206 ts = Adafruit_FT6206(); 36 | 37 | Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC); 38 | 39 | 40 | 41 | const char* menuOptions[] = { 42 | 43 |   "Toggle LED", 44 | 45 |   "Show Temp", 46 | 47 |   "Change Background", 48 | 49 |   "Rotate Screen", 50 | 51 |   "Restart ESP32" 52 | 53 | }; 54 | 55 | int currentOption = 0; 56 | 57 | int numOptions = sizeof(menuOptions) / sizeof(menuOptions[0]); 58 | 59 | 60 | 61 | #define LED 5 62 | 63 | int LED_state = 0; 64 | 65 | 66 | 67 | void setup() { 68 | 69 |   tft.begin(); 70 | 71 |   tft.setRotation(0); 72 | 73 |   tft.fillScreen(BACKGROUND_COLOR); 74 | 75 |   tft.setTextSize(2); 76 | 77 |   tft.setTextColor(TEXT_COLOR); 78 | 79 |   pinMode(LED, OUTPUT); 80 | 81 | 82 | 83 |   if (!ts.begin(40)) { 84 | 85 |     while (1); 86 | 87 |   } 88 | 89 |   drawMenu(); 90 | 91 | } 92 | 93 | 94 | 95 | void loop() { 96 | 97 |   if (ts.touched()) { 98 | 99 |     TS_Point touchPoint = ts.getPoint(); 100 | 101 |     int16_t screenX = map(touchPoint.x, TS_MINX, TS_MAXX, SCREEN_WIDTH - 1, 0); 102 | 103 |     int16_t screenY = map(touchPoint.y, TS_MINY, TS_MAXY, SCREEN_HEIGHT - 1, 0); 104 | 105 | 106 | 107 |     if (screenY >= 0 && screenY < numOptions * 30) { 108 | 109 |       int selectedOption = screenY / 30; 110 | 111 |       drawMenu(); 112 | 113 |       tft.setTextColor(HIGHLIGHT_COLOR); 114 | 115 |       tft.setCursor(10, selectedOption * 30); 116 | 117 |       tft.println(menuOptions[selectedOption]); 118 | 119 |       tft.setTextColor(TEXT_COLOR); 120 | 121 |       switch (selectedOption) { 122 | 123 |         case 0: 124 | 125 |           Toggle_LED(); 126 | 127 |           break; 128 | 129 |         case 1: 130 | 131 |           showTemp(); 132 | 133 |           break; 134 | 135 |         case 2: 136 | 137 |           tft.fillScreen(random(0xFFFF)); 138 | 139 |           break; 140 | 141 |         case 3: 142 | 143 |           tft.setRotation((tft.getRotation() + 1) % 4); 144 | 145 |           break; 146 | 147 |         case 4: 148 | 149 |           ESP.restart(); 150 | 151 |           break; 152 | 153 |         default: 154 | 155 |           drawMenu(); 156 | 157 |           break; 158 | 159 |       } 160 | 161 |     } 162 | 163 |   } 164 | 165 | } 166 | 167 | void drawMenu() { 168 | 169 |   tft.fillScreen(BACKGROUND_COLOR); 170 | 171 |   for (int i = 0; i < numOptions; i++) { 172 | 173 |     tft.setCursor(10, i * 30); 174 | 175 |     if (i == currentOption) { 176 | 177 |       tft.setTextColor(HIGHLIGHT_COLOR); 178 | 179 |     } else { 180 | 181 |       tft.setTextColor(TEXT_COLOR); 182 | 183 |     } 184 | 185 |     tft.println(menuOptions[i]); 186 | 187 |   } 188 | 189 | } 190 | 191 | void Toggle_LED() { 192 | 193 |   LED_state = !LED_state; 194 | 195 |   digitalWrite(LED, LED_state); 196 | 197 | } 198 | 199 | void showTemp() { 200 | 201 |   float temperature = 25.5; 202 | 203 |   tft.fillScreen(BACKGROUND_COLOR); 204 | 205 |   tft.setTextSize(3); 206 | 207 |   tft.setCursor(0, 30); 208 | 209 |   tft.setTextColor(ILI9341_GREEN); 210 | 211 |   tft.print("Temperature"); 212 | 213 |   tft.setTextSize(5); 214 | 215 |   tft.setCursor(30, 100); 216 | 217 |   tft.setTextColor(TEXT_COLOR); 218 | 219 |   tft.print(temperature, 1); 220 | 221 |   tft.setTextSize(3); 222 | 223 |   tft.setCursor(200, 105); 224 | 225 |   tft.print("C"); 226 | 227 |   tft.setTextSize(2); 228 | 229 | } 230 | -------------------------------------------------------------------------------- /Chapter4/BLE/ble-as-beacon-advertiser/ble-as-beacon-advertiser.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | #include 6 | 7 | #include 8 | 9 | #include 10 | 11 | #define DEVICE_NAME "ESP32" 12 | 13 | #define SERVICE_UUID "7A0247E7-8E88-409B-A959-AB5092DDB03E" 14 | 15 | #define BEACON_UUID "2D7A9F0C-E0E8-4CC9-A71B-A21DB2D034A1" 16 | 17 | #define BEACON_UUID_REV "A134D0B2-1DA2-1BA7-C94C-E8E00C9F7A2D" 18 | 19 | #define CHARACTERISTIC_UUID "82258BAA-DF72-47E8-99BC-B73D7ECD08A5" 20 | 21 | BLEServer *pServer; 22 | 23 | BLECharacteristic *pCharacteristic; 24 | 25 | bool deviceConnected = false; 26 | 27 | uint8_t value = 0; 28 | 29 | class MyServerCallbacks: public BLEServerCallbacks { 30 | 31 | void onConnect(BLEServer* pServer) { 32 | 33 | deviceConnected = true; 34 | 35 | Serial.println("deviceConnected = true"); 36 | 37 | }; 38 | 39 | void onDisconnect(BLEServer* pServer) { 40 | 41 | deviceConnected = false; 42 | 43 | Serial.println("deviceConnected = false"); 44 | 45 | BLEAdvertising* pAdvertising; 46 | 47 | pAdvertising = pServer->getAdvertising(); 48 | 49 | pAdvertising->start(); 50 | 51 | Serial.println("iBeacon advertising restarted"); 52 | 53 | } 54 | 55 | }; 56 | 57 | class MyCallbacks: public BLECharacteristicCallbacks { 58 | 59 | void onWrite(BLECharacteristic *pCharacteristic) { 60 | 61 | std::string rxValue = pCharacteristic->getValue(); 62 | 63 | if (rxValue.length() > 0) { 64 | 65 | Serial.println("*********"); 66 | 67 | Serial.print("Received Value: "); 68 | 69 | for (int i = 0; i < rxValue.length(); i++) { 70 | 71 | Serial.print(rxValue[i]); 72 | 73 | } 74 | 75 | Serial.println(); 76 | 77 | Serial.println("*********"); 78 | 79 | } 80 | 81 | } 82 | 83 | }; 84 | 85 | void init_service() { 86 | 87 | BLEAdvertising* pAdvertising; 88 | 89 | pAdvertising = pServer->getAdvertising(); 90 | 91 | pAdvertising->stop(); 92 | 93 | BLEService *pService = pServer->createService(BLEUUID(SERVICE_UUID)); 94 | 95 | pCharacteristic = pService->createCharacteristic( 96 | 97 | CHARACTERISTIC_UUID, 98 | 99 | BLECharacteristic::PROPERTY_READ | 100 | 101 | BLECharacteristic::PROPERTY_WRITE | 102 | 103 | BLECharacteristic::PROPERTY_NOTIFY 104 | 105 | ); 106 | 107 | pCharacteristic->setCallbacks(new MyCallbacks()); 108 | 109 | pCharacteristic->addDescriptor(new BLE2902()); 110 | 111 | pAdvertising->addServiceUUID(BLEUUID(SERVICE_UUID)); 112 | 113 | pService->start(); 114 | 115 | pAdvertising->start(); 116 | 117 | } 118 | 119 | void init_beacon() { 120 | 121 | BLEAdvertising* pAdvertising; 122 | 123 | pAdvertising = pServer->getAdvertising(); 124 | 125 | pAdvertising->stop(); 126 | 127 | BLEBeacon myBeacon; 128 | 129 | myBeacon.setManufacturerId(0x4c00); 130 | 131 | myBeacon.setMajor(5); 132 | 133 | myBeacon.setMinor(88); 134 | 135 | myBeacon.setSignalPower(0xc5); 136 | 137 | myBeacon.setProximityUUID(BLEUUID(BEACON_UUID_REV)); 138 | 139 | BLEAdvertisementData advertisementData; 140 | 141 | advertisementData.setFlags(0x1A); 142 | 143 | advertisementData.setManufacturerData(myBeacon.getData()); 144 | 145 | pAdvertising->setAdvertisementData(advertisementData); 146 | 147 | pAdvertising->start(); 148 | 149 | } 150 | 151 | void setup() { 152 | 153 | Serial.begin(115200); 154 | 155 | Serial.println(); 156 | 157 | Serial.println("Initializing..."); 158 | 159 | Serial.flush(); 160 | 161 | BLEDevice::init(DEVICE_NAME); 162 | 163 | pServer = BLEDevice::createServer(); 164 | 165 | pServer->setCallbacks(new MyServerCallbacks()); 166 | 167 | init_service(); 168 | 169 | init_beacon(); 170 | 171 | Serial.println("iBeacon + service defined and advertising!"); 172 | 173 | } 174 | 175 | void loop() { 176 | 177 | if (deviceConnected) { 178 | 179 | Serial.printf("*** NOTIFY: %d ***\n", value); 180 | 181 | pCharacteristic->setValue(&value, 1); 182 | 183 | pCharacteristic->notify(); 184 | 185 | value++; 186 | 187 | } 188 | 189 | delay(2000); 190 | 191 | } -------------------------------------------------------------------------------- /Chapter4/BLE/ble-client/ble-client.ino: -------------------------------------------------------------------------------- 1 | #include "BLEDevice.h" 2 | 3 | static BLEUUID serviceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b"); 4 | 5 | static BLEUUID charUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8"); 6 | 7 | 8 | 9 | static boolean doConnect = false; 10 | 11 | static boolean connected = false; 12 | 13 | static boolean doScan = false; 14 | 15 | static BLERemoteCharacteristic* pRemoteCharacteristic; 16 | 17 | static BLEAdvertisedDevice* myDevice; 18 | 19 | 20 | 21 | static void notifyCallback( 22 | 23 | BLERemoteCharacteristic* pBLERemoteCharacteristic, 24 | 25 | uint8_t* pData, 26 | 27 | size_t length, 28 | 29 | bool isNotify) { 30 | 31 | Serial.print("Notify callback for characteristic "); 32 | 33 | Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str()); 34 | 35 | Serial.print(" of data length "); 36 | 37 | Serial.println(length); 38 | 39 | Serial.print("data: "); 40 | 41 | Serial.write(pData, length); 42 | 43 | Serial.println(); 44 | 45 | } 46 | 47 | 48 | 49 | class MyClientCallback : public BLEClientCallbacks { 50 | 51 | void onConnect(BLEClient* pclient) { 52 | 53 | } 54 | 55 | 56 | 57 | void onDisconnect(BLEClient* pclient) { 58 | 59 | connected = false; 60 | 61 | Serial.println("onDisconnect"); 62 | 63 | } 64 | 65 | }; 66 | 67 | 68 | 69 | bool connectToServer() { 70 | 71 | Serial.print("Forming a connection to "); 72 | 73 | Serial.println(myDevice->getAddress().toString().c_str()); 74 | 75 | 76 | 77 | BLEClient* pClient = BLEDevice::createClient(); 78 | 79 | Serial.println(" - Created client"); 80 | 81 | 82 | 83 | pClient->setClientCallbacks(new MyClientCallback()); 84 | 85 | pClient->connect(myDevice); 86 | 87 | Serial.println(" - Connected to server"); 88 | 89 | pClient->setMTU(517); 90 | 91 | 92 | 93 | BLERemoteService* pRemoteService = pClient->getService(serviceUUID); 94 | 95 | if (pRemoteService == nullptr) { 96 | 97 | Serial.print("Failed to find our service UUID: "); 98 | 99 | Serial.println(serviceUUID.toString().c_str()); 100 | 101 | pClient->disconnect(); 102 | 103 | return false; 104 | 105 | } 106 | 107 | Serial.println(" - Found our service"); 108 | 109 | 110 | 111 | pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID); 112 | 113 | if (pRemoteCharacteristic == nullptr) { 114 | 115 | Serial.print("Failed to find our characteristic UUID: "); 116 | 117 | Serial.println(charUUID.toString().c_str()); 118 | 119 | pClient->disconnect(); 120 | 121 | return false; 122 | 123 | } 124 | 125 | Serial.println(" - Found our characteristic"); 126 | 127 | 128 | 129 | 130 | 131 | if(pRemoteCharacteristic->canRead()) { 132 | 133 | std::string value = pRemoteCharacteristic->readValue(); 134 | 135 | Serial.print("The characteristic value was: "); 136 | 137 | Serial.println(value.c_str()); 138 | 139 | } 140 | 141 | 142 | 143 | if(pRemoteCharacteristic->canNotify()) 144 | 145 | pRemoteCharacteristic->registerForNotify(notifyCallback); 146 | 147 | 148 | 149 | connected = true; 150 | 151 | return true; 152 | 153 | } 154 | 155 | 156 | 157 | class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { 158 | 159 | /** 160 | 161 | * Called for each advertising BLE server. 162 | 163 | */ 164 | 165 | void onResult(BLEAdvertisedDevice advertisedDevice) { 166 | 167 | Serial.print("BLE Advertised Device found: "); 168 | 169 | Serial.println(advertisedDevice.toString().c_str()); 170 | 171 | 172 | 173 | // We have found a device, let us now see if it contains the service we are looking for. 174 | 175 | if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) { 176 | 177 | 178 | 179 | BLEDevice::getScan()->stop(); 180 | 181 | myDevice = new BLEAdvertisedDevice(advertisedDevice); 182 | 183 | doConnect = true; 184 | 185 | doScan = true; 186 | 187 | 188 | 189 | } // Found our server 190 | 191 | } // onResult 192 | 193 | }; // MyAdvertisedDeviceCallbacks 194 | 195 | 196 | 197 | void setup() { 198 | 199 | Serial.begin(115200); 200 | 201 | Serial.println("Starting Arduino BLE Client application..."); 202 | 203 | BLEDevice::init(""); 204 | 205 | BLEScan* pBLEScan = BLEDevice::getScan(); 206 | 207 | pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); 208 | 209 | pBLEScan->setInterval(1349); 210 | 211 | pBLEScan->setWindow(449); 212 | 213 | pBLEScan->setActiveScan(true); 214 | 215 | pBLEScan->start(5, false); 216 | 217 | } // End of setup. 218 | 219 | void loop() { 220 | 221 | 222 | 223 | if (doConnect == true) { 224 | 225 | if (connectToServer()) { 226 | 227 | Serial.println("We are now connected to the BLE Server."); 228 | 229 | } else { 230 | 231 | Serial.println("We have failed to connect to the server; there is nothin more we will do."); 232 | 233 | } 234 | 235 | doConnect = false; 236 | 237 | } 238 | 239 | if (connected) { 240 | 241 | String newValue = "Time since boot: " + String(millis()/1000); 242 | 243 | Serial.println("Setting new characteristic value to \"" + newValue + "\""); 244 | 245 | pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length()); 246 | 247 | }else if(doScan){ 248 | 249 | BLEDevice::getScan()->start(0); // this is just example to start scan after disconnect, most likely there is better way to do it in arduino 250 | 251 | } 252 | 253 | 254 | 255 | delay(1000); // Delay a second between loops. 256 | 257 | } // End of loop -------------------------------------------------------------------------------- /Chapter4/BLE/ble-server/ble-server.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | 7 | #define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" 8 | 9 | #define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" 10 | 11 | 12 | 13 | void setup() { 14 | 15 | Serial.begin(115200); 16 | 17 | Serial.println("Starting BLE work!"); 18 | 19 | BLEDevice::init("Long name works now"); 20 | 21 | BLEServer *pServer = BLEDevice::createServer(); 22 | 23 | BLEService *pService = pServer->createService(SERVICE_UUID); 24 | 25 | BLECharacteristic *pCharacteristic = pService->createCharacteristic( 26 | 27 | CHARACTERISTIC_UUID, 28 | 29 | BLECharacteristic::PROPERTY_READ | 30 | 31 | BLECharacteristic::PROPERTY_WRITE); 32 | 33 | pCharacteristic->setValue("Hello World"); 34 | 35 | pService->start(); 36 | 37 | BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); 38 | 39 | pAdvertising->addServiceUUID(SERVICE_UUID); 40 | 41 | pAdvertising->setScanResponse(true); 42 | 43 | pAdvertising->setMinPreferred(0x06); // functions that help with iPhone connections issue 44 | 45 | pAdvertising->setMinPreferred(0x12); 46 | 47 | BLEDevice::startAdvertising(); 48 | 49 | Serial.println("Characteristic defined! Now you can read it in your phone!"); 50 | 51 | } 52 | 53 | 54 | 55 | void loop() { 56 | 57 | // put your main code here, to run repeatedly: 58 | 59 | delay(2000); 60 | 61 | } -------------------------------------------------------------------------------- /Chapter4/Cellular/AT-commands-basic-code/AT-commands-basic-code.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | SoftwareSerial BG95Serial(2, 3); // RX, TX pins for BG95 Shield 4 | 5 | const int baudRate = 9600; 6 | 7 | void setup() { 8 | 9 | Serial.begin(115200); 10 | 11 | BG95Serial.begin(baudRate); 12 | 13 | 14 | 15 | // Wait for the BG95 module to initialize 16 | 17 | delay(1000); 18 | 19 | 20 | 21 | Serial.println("Initializing BG95..."); 22 | 23 | sendATCommand("AT"); 24 | 25 | sendATCommand("AT+CPIN?"); 26 | } 27 | 28 | void loop() { 29 | 30 | // Your code goes here 31 | } 32 | 33 | void sendATCommand(String command) { 34 | 35 | BG95Serial.println(command); 36 | 37 | delay(500); 38 | 39 | while (BG95Serial.available()) { 40 | 41 | Serial.write(BG95Serial.read()); 42 | } 43 | } -------------------------------------------------------------------------------- /Chapter4/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Chapter4/README.md: -------------------------------------------------------------------------------- 1 | # Programming-ESP32-with-Arduino-IDE 2 | GitHub repository for the Programming ESP32 with Arduino IDE book 3 | -------------------------------------------------------------------------------- /Chapter4/WiFi/ESP32-as-WiFiClient/ESP32-as-WiFiClient.ino: -------------------------------------------------------------------------------- 1 | #include 2 | const char* ssid = "MyESP32AP"; 3 | const char* password = "Password123"; 4 | 5 | void setup() { 6 | Serial.begin(115200); 7 | WiFi.begin(ssid, password); 8 | 9 | Serial.print("Connecting to WiFi..."); 10 | 11 | while (WiFi.status() != WL_CONNECTED) { 12 | 13 | delay(500); 14 | Serial.print("."); 15 | } 16 | 17 | Serial.println(); 18 | Serial.print("Connected to WiFi network with IP address: "); 19 | Serial.println(WiFi.localIP()); 20 | } 21 | 22 | 23 | 24 | void loop() { 25 | // Your code goes here 26 | } -------------------------------------------------------------------------------- /Chapter4/WiFi/ESP32-as-accesspoint/ESP32-as-accesspoint.ino: -------------------------------------------------------------------------------- 1 | #include 2 | const char* ssid = "MyESP32AP"; 3 | const char* password = "password123"; 4 | 5 | void setup() { 6 | Serial.begin(115200); 7 | WiFi.softAP(ssid, password); 8 | IPAddress apIP(192, 168, 4, 1); 9 | IPAddress subnet(255, 255, 255, 0); 10 | WiFi.softAPConfig(apIP, apIP, subnet); 11 | Serial.print("Access Point IP Address: "); 12 | Serial.println(WiFi.softAPIP()); 13 | } 14 | 15 | void loop() { 16 | // Your code goes here 17 | } -------------------------------------------------------------------------------- /Chapter4/WiFi/WiFi direct/wifi-Server/wifi-Server.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | WiFiServer server(80); 4 | const char* ssid = "MyESP32Direct"; 5 | const char* password = "password123"; 6 | 7 | void setup() { 8 | Serial.begin(115200); 9 | WiFi.softAP(ssid, password); 10 | 11 | IPAddress apIP(192, 168, 4, 1); 12 | 13 | IPAddress subnet(255, 255, 255, 0); 14 | 15 | WiFi.softAPConfig(apIP, apIP, subnet); 16 | 17 | server.begin(); 18 | 19 | Serial.print("WiFi Direct Group Owner IP Address: "); 20 | 21 | Serial.println(WiFi.softAPIP()); 22 | } 23 | 24 | void loop() { 25 | WiFiClient client = server.available(); 26 | 27 | if (client) { 28 | Serial.println("Client connected."); 29 | client.println("Hello from Group Owner!"); 30 | while (client.connected()) { 31 | 32 | if (client.available()) { 33 | 34 | String message = client.readStringUntil('\n'); 35 | 36 | Serial.print("Received message: "); 37 | 38 | Serial.println(message); 39 | } 40 | } 41 | 42 | client.stop(); 43 | 44 | Serial.println("Client disconnected."); 45 | } 46 | } -------------------------------------------------------------------------------- /Chapter4/WiFi/WiFi direct/wifi-client/wifi-client.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const char* ssid = "MyESP32Direct"; 4 | const char* password = "password123"; 5 | 6 | void setup() { 7 | 8 | Serial.begin(115200); 9 | 10 | WiFi.begin(ssid, password); 11 | 12 | 13 | 14 | Serial.print("Connecting to WiFi Direct Group Owner..."); 15 | 16 | while (WiFi.status() != WL_CONNECTED) { 17 | 18 | delay(500); 19 | 20 | Serial.print("."); 21 | } 22 | 23 | 24 | 25 | Serial.println(); 26 | 27 | Serial.print("Connected to WiFi Direct Group Owner with IP address: "); 28 | 29 | Serial.println(WiFi.localIP()); 30 | } 31 | 32 | 33 | 34 | void loop() { 35 | 36 | // Check if there is a connection to the server 37 | 38 | if (WiFi.status() == WL_CONNECTED) { 39 | 40 | WiFiClient client; 41 | 42 | 43 | 44 | // Connect to the server on the Group Owner's IP address and port 80 45 | 46 | if (client.connect("192.168.4.1", 80)) { 47 | 48 | // Read and print the message from the Group Owner 49 | 50 | while (client.connected()) { 51 | 52 | if (client.available()) { 53 | 54 | String message = client.readStringUntil('\n'); 55 | 56 | Serial.print("Received message: "); 57 | 58 | Serial.println(message); 59 | 60 | 61 | 62 | // Send a response message to the Group Owner 63 | 64 | client.println("Hello from Client!"); 65 | } 66 | } 67 | 68 | client.stop(); 69 | 70 | } else { 71 | 72 | Serial.println("Connection to server failed."); 73 | } 74 | 75 | } else { 76 | 77 | Serial.println("WiFi connection failed."); 78 | } 79 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hands-on ESP32 with Arduino IDE 2 | 3 | 4 | 5 | This is the code repository for [Hands-on ESP32 with Arduino IDE](https://www.packtpub.com/product/hands-on-esp32-with-arduino-ide/9781837638031?utm_source=github&utm_medium=repository&utm_campaign=9781786461629), published by Packt. 6 | 7 | **Unleash the power of IoT with ESP32 and build exciting projects with this practical guide** 8 | 9 | ## What is this book about? 10 | This book will help you gain valuable knowledge and practical skills needed to develop innovative IoT projects by learning how to use ESP32 using Arduino IDE 2.0. 11 | 12 | This book covers the following exciting features: 13 | * Understand the architecture of ESP32 including all its ins and outs 14 | * Get to grips with writing code for ESP32 using Arduino IDE 2.0 15 | * Interface sensors with ESP32, focusing on the science behind it 16 | * Familiarize yourself with the architecture of various IoT network protocols in-depth 17 | * Gain an understanding of the network protocols involved in IoT device communication 18 | * Evaluate and select the ideal data-based IoT protocol for your project or application 19 | * Apply IoT principles to real-world projects using Arduino IDE 2.0 20 | 21 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1837638039) today! 22 | 23 | https://www.packtpub.com/ 25 | 26 | **Following is what you need for this book:** 27 | This book is for electronics enthusiasts, hobbyists, and other professionals looking to design IoT applications utilizing ESP32. While it’s designed to be accessible for beginners, a basic understanding of electronics and some experience with programming concepts is a prerequisite. 28 | 29 | With the following software and hardware list you can run all code files present in the book (Chapter 1-9). 30 | ### Software and Hardware List 31 | | Chapter | Software required | OS required | 32 | | -------- | ------------------------------------ | ----------------------------------- | 33 | | 1-9 | An ESP32 development board | Windows, Mac OS X, and Linux (Any) | 34 | | 1-9 | An ESP32-CAM board | | 35 | | 1-9 | Display modules | | 36 | | 1-9 | Sensors and actuators | | 37 | | 1-9 | Free API services (OpenWeatherMap, Twitter, | | 38 | | 1-9 | InfluxDB Cloud and Grafana Cloud | | 39 | 40 | ### Related products 41 | * Practical Arduino Robotics [[Packt]](https://www.packtpub.com/product/practical-arduino-robotics/9781804613177?utm_source=github&utm_medium=repository&utm_campaign=9781804613177) [[Amazon]](https://www.amazon.com/dp/1804613177) 42 | 43 | * Arduino Data Communications [[Packt]](https://www.packtpub.com/product/arduino-data-communications/9781837632619?utm_source=github&utm_medium=repository&utm_campaign=9781837632619) [[Amazon]](https://www.amazon.com/dp/1837632618) 44 | 45 | ## Get to Know the Author 46 | **Asim Zulfiqar** 47 | is a blogger and tech content creator who has been writing tutorials on embedded systems and IoT on his blog and YouTube channel, High Voltages. Currently, he is working as a scientific programmer for IoT research projects. He completed his bachelor's degree in electronic engineering at Sir Syed University of Engineering and Technology, Pakistan. After that, he completed his Erasmus Mundus joint master's degree program in Photonics Integrated Circuits, Sensors, and Networks at Scuola Superiore Sant'Anna (Italy), Aston University (U.K), and Osaka University (Japan). 48 | 49 | ### Download a free PDF 50 | 51 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
52 |

https://packt.link/free-ebook/9781837638031

53 | -------------------------------------------------------------------------------- /chapter 7/QRCode_OLED/QRCode_OLED.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "qrcode.h" //https://github.com/ricmoo/QRCode.git 5 | 6 | #define SCREEN_WIDTH 128 7 | #define SCREEN_HEIGHT 64 8 | #define OLED_RESET -1 9 | 10 | Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); 11 | QRCode qrcode; 12 | String paypalLink = "https://paypal.me/username"; //insert your paypal link from here 13 | 14 | void setup() 15 | { 16 | Serial.begin(115200); 17 | if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { 18 | Serial.println(F("SSD1306 allocation failed")); 19 | for (;;); 20 | } 21 | showScantoPay(); 22 | } 23 | 24 | void loop() 25 | { 26 | } 27 | 28 | void showScantoPay(void) { 29 | display.clearDisplay(); 30 | display.setTextSize(2); // Change the font size to 2 31 | display.setTextColor(WHITE); 32 | uint8_t qrcodeData[qrcode_getBufferSize(3)]; 33 | qrcode_initText(&qrcode, qrcodeData, 3, 0, paypalLink.c_str() ); 34 | int scale = 2; // Change this for different sizes 35 | for (uint8_t y = 0; y < qrcode.size; y++) 36 | { 37 | for (uint8_t x = 0; x < qrcode.size; x++) 38 | { 39 | if (qrcode_getModule(&qrcode, x, y)) 40 | { 41 | display.fillRect(x * scale, y * scale, scale, scale, WHITE); 42 | } 43 | } 44 | } 45 | display.setCursor(65, 5); // Adjust the position as needed 46 | display.println("Scan"); 47 | display.setCursor(65, 25); // Adjust the position as needed 48 | display.println("to"); 49 | display.setCursor(65, 45); // Adjust the position as needed 50 | display.println("Open."); 51 | 52 | display.display(); 53 | } 54 | -------------------------------------------------------------------------------- /chapter 7/Reading_Pushbutton_controlling_servo/Reading_pushbutton_controlling_servo.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #define BUTTON 5 3 | Servo myservo; // Create a Servo object 4 | const int servoPin = 14; 5 | bool barrier = false; 6 | void setup() { 7 | Serial.begin(115200); 8 | pinMode(BUTTON, INPUT_PULLUP); 9 | myservo.attach(servoPin); // Attaches the servo on the specified pin 10 | } 11 | void loop() { 12 | if (!barrier) { 13 | if (!digitalRead(BUTTON)) { 14 | openServo(); 15 | barrier = true; 16 | delay(1000); 17 | } 18 | } 19 | if (barrier) { 20 | if (!digitalRead(BUTTON)) { 21 | closeServo(); 22 | barrier = false; 23 | } 24 | } 25 | } 26 | 27 | void openServo() { 28 | Serial.println("Servo open"); 29 | myservo.write(0); 30 | } 31 | void closeServo() { 32 | delay(1000); 33 | Serial.println("Servo closed"); 34 | myservo.write(180); 35 | } 36 | -------------------------------------------------------------------------------- /chapter 7/Reading_distance/Reading_distance.ino: -------------------------------------------------------------------------------- 1 | const int trigPin = 13; 2 | const int echoPin = 12; 3 | const int redPin = 4; 4 | const int greenPin = 2; 5 | const int bluePin = 15; 6 | int distanceRange = 50; 7 | void setup() { 8 | Serial.begin(115200); 9 | pinMode(trigPin, OUTPUT); 10 | pinMode(echoPin, INPUT); 11 | pinMode(redPin, OUTPUT); 12 | pinMode(greenPin, OUTPUT); 13 | pinMode(bluePin, OUTPUT); 14 | } 15 | void loop() { 16 | int distance = getdistance(); 17 | delay(1000); 18 | } 19 | int getdistance() { 20 | long duration; 21 | int distance; 22 | digitalWrite(trigPin, LOW); 23 | delayMicroseconds(2); 24 | digitalWrite(trigPin, HIGH); 25 | delayMicroseconds(10); 26 | digitalWrite(trigPin, LOW); 27 | duration = pulseIn(echoPin, HIGH); 28 | distance = (duration / 2) / 29.1; 29 | Serial.println("Distance: " + String(distance)); 30 | if (distance > distanceRange) { 31 | digitalWrite(redPin, LOW); 32 | digitalWrite(greenPin, HIGH); 33 | } else { 34 | digitalWrite(greenPin, LOW); 35 | digitalWrite(redPin, HIGH); 36 | } 37 | return distance; 38 | } 39 | -------------------------------------------------------------------------------- /chapter 7/Reading_webhook_paypal/Reading_webhook_paypal.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | WiFiUDP ntpUDP; 9 | NTPClient timeClient(ntpUDP, "pool.ntp.org"); 10 | 11 | const char* ssid = "Your SSID"; 12 | const char* password = "Your Password"; 13 | const char* apiKey = "Your API key"; //insert your webhook.site api key 14 | const char* url = "https://webhook.site/token/df23f2ff-1b38-452c-8c4b-928e1c437ce4/request/latest/"; //replace with your webhook.site api key 15 | String lastModifiedHeader = ""; 16 | 17 | void setup() { 18 | Serial.begin(115200); 19 | WiFi.begin(ssid, password); 20 | while (WiFi.status() != WL_CONNECTED) { 21 | delay(1000); 22 | Serial.println("Connecting to WiFi..."); 23 | } 24 | Serial.println("Connected to WiFi"); 25 | } 26 | 27 | void loop() { 28 | int payment = checkPayment(); 29 | delay(6000); 30 | } 31 | 32 | int checkPayment() { 33 | String amountPaid; 34 | int timeLimitMinutes = 2; 35 | timeClient.update(); 36 | time_t now = timeClient.getEpochTime(); 37 | 38 | if (WiFi.status() == WL_CONNECTED) { 39 | HTTPClient http; 40 | http.begin(url); 41 | http.addHeader("accept", "application/json"); 42 | http.addHeader("api-key", apiKey); 43 | 44 | if (!lastModifiedHeader.isEmpty()) { 45 | http.addHeader("If-Modified-Since", lastModifiedHeader); 46 | } 47 | 48 | int httpCode = http.GET(); 49 | 50 | if (httpCode > 0) { 51 | if (httpCode == HTTP_CODE_OK) { 52 | lastModifiedHeader = http.header("Last-Modified"); 53 | String payload = http.getString(); 54 | 55 | if (parseJsonData(payload, amountPaid, now, timeLimitMinutes)) { 56 | return amountPaid.toInt(); 57 | } 58 | } else if (httpCode == HTTP_CODE_NOT_MODIFIED) { 59 | Serial.println("No new data available."); 60 | } else { 61 | Serial.printf("HTTP error code: %d\n", httpCode); 62 | } 63 | } else { 64 | Serial.println("Failed to connect to the server."); 65 | } 66 | http.end(); 67 | } 68 | return amountPaid.toInt(); 69 | } 70 | 71 | bool parseJsonData(String payload, String &amountPaid, time_t now, int timeLimitMinutes) { 72 | StaticJsonDocument<4096> jsonDocument; 73 | DeserializationError error = deserializeJson(jsonDocument, payload); 74 | 75 | if (error) { 76 | Serial.println("JSON parsing error: " + String(error.c_str())); 77 | return false; 78 | } 79 | 80 | String timestampStr = jsonDocument["created_at"].as(); 81 | struct tm createdTime; 82 | if (!parseTimestamp(timestampStr, createdTime)) { 83 | return false; 84 | } 85 | 86 | int minutesSinceData = (now - mktime(&createdTime)) / 60; 87 | 88 | if (minutesSinceData <= timeLimitMinutes) { 89 | String name = jsonDocument["request"]["first_name"].as() + " " + jsonDocument["request"]["last_name"].as(); 90 | String email = jsonDocument["request"]["payer_email"].as(); 91 | amountPaid = jsonDocument["request"]["mc_gross"].as(); 92 | Serial.println("Name: " + name); 93 | Serial.println("Email: " + email); 94 | Serial.println("Amount Paid: " + amountPaid); 95 | } else { 96 | Serial.println("Data is too old to process."); 97 | return false; 98 | } 99 | 100 | return true; 101 | } 102 | 103 | bool parseTimestamp(String timestampStr, struct tm &createdTime) { 104 | if (strptime(timestampStr.c_str(), "%Y-%m-%d %H:%M:%S", &createdTime)) { 105 | return true; 106 | } else { 107 | Serial.println("Failed to parse timestamp."); 108 | return false; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /chapter 7/Rent_out_Parking_Complete/Rent_out_Parking_complete.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "qrcode.h" //https://github.com/ricmoo/QRCode.git 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | enum ScreenStatus 14 | { 15 | SCREEN_PARKING, 16 | SCREEN_PAYMENT, 17 | SCREEN_OPEN, 18 | SCREEN_PAYMENTSUCCESS, 19 | SCREEN_CLOSE, 20 | SCREEN_OTHER 21 | }; 22 | 23 | ScreenStatus currentScreen = SCREEN_PARKING; 24 | ScreenStatus lastScreen = SCREEN_OTHER; 25 | const int servoPin = 14; 26 | Servo myservo; // Create a Servo object 27 | #define BUTTON 5 28 | #define SCREEN_WIDTH 128 29 | #define SCREEN_HEIGHT 64 30 | #define OLED_RESET -1 31 | WiFiUDP ntpUDP; 32 | NTPClient timeClient(ntpUDP, "pool.ntp.org"); 33 | Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); 34 | QRCode qrcode; 35 | 36 | String paypalLink = "https://paypal.me/username"; // insert your 37 | 38 | const int trigPin = 13; 39 | const int echoPin = 12; 40 | const int redPin = 4; 41 | const int greenPin = 2; 42 | const int bluePin = 15; 43 | bool parked = false; 44 | bool barrier = false; 45 | int sensorRange = 15; 46 | const char *ssid = "Wokwi-GUEST"; 47 | const char *password = ""; 48 | const char* apiKey = "Your API key"; //insert your webhook.site api key 49 | const char* url = "https://webhook.site/token/df23f2ff-1b38-452c-8c4b-928e1c437ce4/request/latest/"; //replace with your webhook.site api key 50 | String lastModifiedHeader = ""; 51 | 52 | void setup() 53 | { 54 | Serial.begin(115200); 55 | WiFi.begin(ssid, password); 56 | while (WiFi.status() != WL_CONNECTED) 57 | { 58 | delay(1000); 59 | Serial.println("Connecting to WiFi..."); 60 | } 61 | Serial.println("Connected to WiFi"); 62 | 63 | if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) 64 | { 65 | Serial.println(F("SSD1306 allocation failed")); 66 | for (;;) 67 | ; 68 | } 69 | myservo.attach(servoPin); // Attaches the servo on the specified pin 70 | pinMode(trigPin, OUTPUT); 71 | pinMode(echoPin, INPUT); 72 | pinMode(redPin, OUTPUT); 73 | pinMode(greenPin, OUTPUT); 74 | pinMode(bluePin, OUTPUT); 75 | pinMode(BUTTON, INPUT_PULLUP); 76 | 77 | updateDisplay(); 78 | } 79 | 80 | void loop() 81 | { 82 | if (!parked) 83 | { 84 | while (!barrier) 85 | { 86 | currentScreen = SCREEN_PARKING; 87 | updateDisplay(); 88 | lastScreen = currentScreen; 89 | 90 | if (!digitalRead(BUTTON)) 91 | { 92 | openServo(); 93 | currentScreen = SCREEN_OPEN; 94 | updateDisplay(); 95 | lastScreen = currentScreen; 96 | barrier = true; 97 | delay(1000); 98 | } 99 | } 100 | while (barrier) 101 | { 102 | if (!digitalRead(BUTTON)) 103 | { 104 | currentScreen = SCREEN_CLOSE; 105 | updateDisplay(); 106 | lastScreen = currentScreen; 107 | closeServo(); 108 | barrier = false; 109 | parked = true; 110 | } 111 | } 112 | } 113 | 114 | while (parked) 115 | { 116 | currentScreen = SCREEN_PAYMENT; 117 | updateDisplay(); 118 | lastScreen = currentScreen; 119 | int payment = checkPayment(); 120 | if (payment >= 1) 121 | { 122 | openServo(); 123 | currentScreen = SCREEN_PAYMENTSUCCESS; 124 | updateDisplay(); 125 | lastScreen = currentScreen; 126 | while (getdistance() < sensorRange) 127 | ; 128 | currentScreen = SCREEN_CLOSE; 129 | updateDisplay(); 130 | lastScreen = currentScreen; 131 | closeServo(); 132 | parked = false; 133 | barrier = false; 134 | payment = 0; 135 | } 136 | delay(6000); 137 | } 138 | } 139 | 140 | void openServo() 141 | { 142 | Serial.println("Servo open"); 143 | myservo.write(0); 144 | } 145 | void closeServo() 146 | { 147 | delay(1000); 148 | Serial.println("Servo closed"); 149 | myservo.write(180); 150 | } 151 | 152 | int getdistance() 153 | { 154 | long duration; 155 | int distance; 156 | digitalWrite(trigPin, LOW); 157 | delayMicroseconds(2); 158 | digitalWrite(trigPin, HIGH); 159 | delayMicroseconds(10); 160 | digitalWrite(trigPin, LOW); 161 | duration = pulseIn(echoPin, HIGH); 162 | distance = (duration / 2) / 29.1; 163 | Serial.println("Distance: " + String(distance)); 164 | 165 | if (distance > 100) 166 | { 167 | digitalWrite(redPin, LOW); 168 | digitalWrite(greenPin, HIGH); 169 | } 170 | else 171 | { 172 | digitalWrite(greenPin, LOW); 173 | digitalWrite(redPin, HIGH); 174 | } 175 | return distance; 176 | } 177 | 178 | int checkPayment() 179 | { 180 | String amountPaid; 181 | int timeLimitMinutes = 2; 182 | timeClient.update(); 183 | time_t now = timeClient.getEpochTime(); 184 | 185 | if (WiFi.status() == WL_CONNECTED) 186 | { 187 | HTTPClient http; 188 | http.begin(url); 189 | http.addHeader("accept", "application/json"); 190 | http.addHeader("api-key", apiKey); 191 | 192 | if (!lastModifiedHeader.isEmpty()) 193 | { 194 | http.addHeader("If-Modified-Since", lastModifiedHeader); 195 | } 196 | 197 | int httpCode = http.GET(); 198 | 199 | if (httpCode > 0) 200 | { 201 | if (httpCode == HTTP_CODE_OK) 202 | { 203 | lastModifiedHeader = http.header("Last-Modified"); 204 | String payload = http.getString(); 205 | 206 | if (parseJsonData(payload, amountPaid, now, timeLimitMinutes)) 207 | { 208 | return amountPaid.toInt(); 209 | } 210 | } 211 | else if (httpCode == HTTP_CODE_NOT_MODIFIED) 212 | { 213 | Serial.println("No new data available."); 214 | } 215 | else 216 | { 217 | Serial.printf("HTTP error code: %d\n", httpCode); 218 | } 219 | } 220 | else 221 | { 222 | Serial.println("Failed to connect to the server."); 223 | } 224 | http.end(); 225 | } 226 | return amountPaid.toInt(); 227 | } 228 | 229 | bool parseJsonData(String payload, String &amountPaid, time_t now, int timeLimitMinutes) 230 | { 231 | StaticJsonDocument<4096> jsonDocument; 232 | DeserializationError error = deserializeJson(jsonDocument, payload); 233 | 234 | if (error) 235 | { 236 | Serial.println("JSON parsing error: " + String(error.c_str())); 237 | return false; 238 | } 239 | 240 | String timestampStr = jsonDocument["created_at"].as(); 241 | struct tm createdTime; 242 | if (!parseTimestamp(timestampStr, createdTime)) 243 | { 244 | return false; 245 | } 246 | 247 | int minutesSinceData = (now - mktime(&createdTime)) / 60; 248 | 249 | if (minutesSinceData <= timeLimitMinutes) 250 | { 251 | String name = jsonDocument["request"]["first_name"].as() + " " + jsonDocument["request"]["last_name"].as(); 252 | String email = jsonDocument["request"]["payer_email"].as(); 253 | amountPaid = jsonDocument["request"]["mc_gross"].as(); 254 | Serial.println("Name: " + name); 255 | Serial.println("Email: " + email); 256 | Serial.println("Amount Paid: " + amountPaid); 257 | } 258 | else 259 | { 260 | Serial.println("Data is too old to process."); 261 | return false; 262 | } 263 | 264 | return true; 265 | } 266 | 267 | bool parseTimestamp(String timestampStr, struct tm &createdTime) 268 | { 269 | if (strptime(timestampStr.c_str(), "%Y-%m-%d %H:%M:%S", &createdTime)) 270 | { 271 | return true; 272 | } 273 | else 274 | { 275 | Serial.println("Failed to parse timestamp."); 276 | return false; 277 | } 278 | } 279 | 280 | void updateDisplay() 281 | { 282 | if (currentScreen != lastScreen) 283 | { 284 | uint8_t qrcodeData[qrcode_getBufferSize(3)]; 285 | int scale = 2; 286 | display.clearDisplay(); 287 | display.setTextSize(1); 288 | display.setTextColor(SSD1306_WHITE); 289 | display.setCursor(0, 0); 290 | 291 | switch (currentScreen) 292 | { 293 | case SCREEN_PARKING: 294 | display.setTextSize(1); 295 | display.setCursor(0, 0); 296 | display.println("Paid parking!\n"); 297 | display.println("Press button to open.\n"); 298 | display.println("Pay while leaving.\n"); 299 | display.println("Using Paypal."); 300 | break; 301 | 302 | case SCREEN_PAYMENT: 303 | qrcode_initText(&qrcode, qrcodeData, 3, 0, paypalLink.c_str()); 304 | 305 | for (uint8_t y = 0; y < qrcode.size; y++) 306 | { 307 | for (uint8_t x = 0; x < qrcode.size; x++) 308 | { 309 | if (qrcode_getModule(&qrcode, x, y)) 310 | { 311 | display.fillRect(x * scale, y * scale, scale, scale, WHITE); 312 | } 313 | } 314 | } 315 | display.setTextSize(2); 316 | display.setCursor(65, 5); 317 | display.println("Scan"); 318 | display.setCursor(65, 25); 319 | display.println("to"); 320 | display.setCursor(65, 45); 321 | display.println("Open."); 322 | break; 323 | 324 | case SCREEN_OPEN: 325 | display.setTextSize(1); 326 | display.setCursor(0, 0); 327 | display.println("Door Opened.\n"); 328 | display.println("Park Car.\n"); 329 | display.println("Press button to Close.\n"); 330 | break; 331 | 332 | case SCREEN_CLOSE: 333 | display.setTextSize(1); 334 | display.setCursor(0, 0); 335 | display.println("Door is Closing\n"); 336 | display.println("Stay away.\n"); 337 | delay(2000); 338 | break; 339 | 340 | case SCREEN_PAYMENTSUCCESS: 341 | display.setTextSize(1); 342 | display.setCursor(0, 0); 343 | display.println("Payment Successful.\n"); 344 | display.println("Opening door.\n"); 345 | display.println("Take Out car.\n"); 346 | break; 347 | 348 | case SCREEN_OTHER: 349 | display.setTextSize(1); 350 | display.println("Some other screen"); 351 | break; 352 | } 353 | display.display(); 354 | } 355 | } 356 | -------------------------------------------------------------------------------- /chapter 8/bathroom_data/bathroom_data.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include //https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino.git 5 | #include 6 | 7 | // WiFi configuration 8 | WiFiMulti wifiMulti; 9 | 10 | #define DEVICE "bathroom" //change device name 11 | 12 | const char* WIFI_SSID = "SSID"; // SSID 13 | const char* WIFI_PASSWORD = "Password"; //PASSWORD 14 | 15 | // InfluxDB configuration 16 | const char* INFLUXDB_URL = "ClusterURL"; // cluster URL 17 | const char* INFLUXDB_TOKEN = "API Token” //api token 18 | const char* INFLUXDB_ORG = "org ID"; //organization ID 19 | const char* INFLUXDB_BUCKET = "Home data"; //bucket name 20 | 21 | // Define pins 22 | const int DHTPIN = 12; 23 | const int LDR = 13; 24 | const int motionsensor = 14; 25 | 26 | // DHT sensor parameters 27 | #define DHTTYPE DHT22 // DHT 11 28 | DHT_Unified dht(DHTPIN, DHTTYPE); 29 | uint32_t delayMS; 30 | 31 | // Time zone information 32 | const char* TZ_INFO = "UTC1"; 33 | 34 | // InfluxDB client instance 35 | InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); 36 | 37 | // Data point 38 | Point dbdata("House_data"); 39 | 40 | void setupWifi() { 41 | WiFi.mode(WIFI_STA); 42 | wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); 43 | 44 | Serial.print("Connecting to Wi-Fi"); 45 | while (wifiMulti.run() != WL_CONNECTED) { 46 | Serial.print("."); 47 | delay(100); 48 | } 49 | Serial.println(); 50 | } 51 | 52 | void setupSensors() { 53 | dht.begin(); 54 | sensor_t sensor; 55 | dht.temperature().getSensor(&sensor); 56 | dht.humidity().getSensor(&sensor); 57 | 58 | pinMode(LDR, INPUT); 59 | pinMode(motionsensor, INPUT); 60 | 61 | // Sync time 62 | timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov"); 63 | 64 | if (client.validateConnection()) { 65 | Serial.print("Connected to InfluxDB: "); 66 | Serial.println(client.getServerUrl()); 67 | } else { 68 | Serial.print("InfluxDB connection failed: "); 69 | Serial.println(client.getLastErrorMessage()); 70 | } 71 | dbdata.addTag("device", DEVICE); 72 | dbdata.addTag("SSID", WiFi.SSID()); 73 | } 74 | 75 | void readSensors() { 76 | dbdata.clearFields(); 77 | 78 | sensors_event_t event; 79 | dht.temperature().getEvent(&event); 80 | dbdata.addField("temperature", event.temperature); 81 | dht.humidity().getEvent(&event); 82 | dbdata.addField("humidity", event.relative_humidity); 83 | dbdata.addField("rssi", WiFi.RSSI()); 84 | dbdata.addField("motion_sensor", digitalRead(motionsensor)); 85 | dbdata.addField("light", digitalRead(LDR)); 86 | } 87 | 88 | void writeToInfluxDB() { 89 | Serial.print("Writing: "); 90 | Serial.println(dbdata.toLineProtocol()); 91 | 92 | if (!client.writePoint(dbdata)) { 93 | Serial.print("InfluxDB write failed: "); 94 | Serial.println(client.getLastErrorMessage()); 95 | } 96 | 97 | Serial.println("Waiting 1 second"); 98 | delay(5000); 99 | } 100 | 101 | void setup() { 102 | Serial.begin(115200); 103 | setupWifi(); 104 | setupSensors(); 105 | } 106 | 107 | void loop() { 108 | readSensors(); 109 | writeToInfluxDB(); 110 | delay(1000); 111 | } 112 | 113 | -------------------------------------------------------------------------------- /chapter 8/bedroom_data/bedroom_data.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include //https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino.git 5 | #include 6 | 7 | // WiFi configuration 8 | WiFiMulti wifiMulti; 9 | 10 | #define DEVICE "bedroom" //change device name 11 | 12 | const char* WIFI_SSID = "SSID"; // SSID 13 | const char* WIFI_PASSWORD = "Password"; //PASSWORD 14 | 15 | // InfluxDB configuration 16 | const char* INFLUXDB_URL = "ClusterURL"; // cluster URL 17 | const char* INFLUXDB_TOKEN = "API Token” //api token 18 | const char* INFLUXDB_ORG = "org ID"; //organization ID 19 | const char* INFLUXDB_BUCKET = "Home data"; //bucket name 20 | 21 | // Define pins 22 | const int DHTPIN = 12; 23 | const int LDR = 13; 24 | const int motionsensor = 14; 25 | 26 | // DHT sensor parameters 27 | #define DHTTYPE DHT22 // DHT 11 28 | DHT_Unified dht(DHTPIN, DHTTYPE); 29 | uint32_t delayMS; 30 | 31 | // Time zone information 32 | const char* TZ_INFO = "UTC1"; 33 | 34 | // InfluxDB client instance 35 | InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); 36 | 37 | // Data point 38 | Point dbdata("House_data"); 39 | 40 | void setupWifi() { 41 | WiFi.mode(WIFI_STA); 42 | wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); 43 | 44 | Serial.print("Connecting to Wi-Fi"); 45 | while (wifiMulti.run() != WL_CONNECTED) { 46 | Serial.print("."); 47 | delay(100); 48 | } 49 | Serial.println(); 50 | } 51 | 52 | void setupSensors() { 53 | dht.begin(); 54 | sensor_t sensor; 55 | dht.temperature().getSensor(&sensor); 56 | dht.humidity().getSensor(&sensor); 57 | 58 | pinMode(LDR, INPUT); 59 | pinMode(motionsensor, INPUT); 60 | 61 | // Sync time 62 | timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov"); 63 | 64 | if (client.validateConnection()) { 65 | Serial.print("Connected to InfluxDB: "); 66 | Serial.println(client.getServerUrl()); 67 | } else { 68 | Serial.print("InfluxDB connection failed: "); 69 | Serial.println(client.getLastErrorMessage()); 70 | } 71 | dbdata.addTag("device", DEVICE); 72 | dbdata.addTag("SSID", WiFi.SSID()); 73 | } 74 | 75 | void readSensors() { 76 | dbdata.clearFields(); 77 | 78 | sensors_event_t event; 79 | dht.temperature().getEvent(&event); 80 | dbdata.addField("temperature", event.temperature); 81 | dht.humidity().getEvent(&event); 82 | dbdata.addField("humidity", event.relative_humidity); 83 | dbdata.addField("rssi", WiFi.RSSI()); 84 | dbdata.addField("motion_sensor", digitalRead(motionsensor)); 85 | dbdata.addField("light", digitalRead(LDR)); 86 | } 87 | 88 | void writeToInfluxDB() { 89 | Serial.print("Writing: "); 90 | Serial.println(dbdata.toLineProtocol()); 91 | 92 | if (!client.writePoint(dbdata)) { 93 | Serial.print("InfluxDB write failed: "); 94 | Serial.println(client.getLastErrorMessage()); 95 | } 96 | 97 | Serial.println("Waiting 1 second"); 98 | delay(5000); 99 | } 100 | 101 | void setup() { 102 | Serial.begin(115200); 103 | setupWifi(); 104 | setupSensors(); 105 | } 106 | 107 | void loop() { 108 | readSensors(); 109 | writeToInfluxDB(); 110 | delay(1000); 111 | } 112 | 113 | -------------------------------------------------------------------------------- /chapter 8/kitchen_data/kitchen_data.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include //https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino.git 5 | #include 6 | 7 | // WiFi configuration 8 | WiFiMulti wifiMulti; 9 | 10 | #define DEVICE "kitchen" //change device name 11 | 12 | const char* WIFI_SSID = "SSID"; // SSID 13 | const char* WIFI_PASSWORD = "Password"; //PASSWORD 14 | 15 | // InfluxDB configuration 16 | const char* INFLUXDB_URL = "ClusterURL"; // cluster URL 17 | const char* INFLUXDB_TOKEN = "API Token” //api token 18 | const char* INFLUXDB_ORG = "org ID"; //organization ID 19 | const char* INFLUXDB_BUCKET = "Home data"; //bucket name 20 | 21 | // Define pins 22 | const int DHTPIN = 12; 23 | const int LDR = 13; 24 | const int motionsensor = 14; 25 | 26 | // DHT sensor parameters 27 | #define DHTTYPE DHT22 // DHT 11 28 | DHT_Unified dht(DHTPIN, DHTTYPE); 29 | uint32_t delayMS; 30 | 31 | // Time zone information 32 | const char* TZ_INFO = "UTC1"; 33 | 34 | // InfluxDB client instance 35 | InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); 36 | 37 | // Data point 38 | Point dbdata("House_data"); 39 | 40 | void setupWifi() { 41 | WiFi.mode(WIFI_STA); 42 | wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); 43 | 44 | Serial.print("Connecting to Wi-Fi"); 45 | while (wifiMulti.run() != WL_CONNECTED) { 46 | Serial.print("."); 47 | delay(100); 48 | } 49 | Serial.println(); 50 | } 51 | 52 | void setupSensors() { 53 | dht.begin(); 54 | sensor_t sensor; 55 | dht.temperature().getSensor(&sensor); 56 | dht.humidity().getSensor(&sensor); 57 | 58 | pinMode(LDR, INPUT); 59 | pinMode(motionsensor, INPUT); 60 | 61 | // Sync time 62 | timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov"); 63 | 64 | if (client.validateConnection()) { 65 | Serial.print("Connected to InfluxDB: "); 66 | Serial.println(client.getServerUrl()); 67 | } else { 68 | Serial.print("InfluxDB connection failed: "); 69 | Serial.println(client.getLastErrorMessage()); 70 | } 71 | dbdata.addTag("device", DEVICE); 72 | dbdata.addTag("SSID", WiFi.SSID()); 73 | } 74 | 75 | void readSensors() { 76 | dbdata.clearFields(); 77 | 78 | sensors_event_t event; 79 | dht.temperature().getEvent(&event); 80 | dbdata.addField("temperature", event.temperature); 81 | dht.humidity().getEvent(&event); 82 | dbdata.addField("humidity", event.relative_humidity); 83 | dbdata.addField("rssi", WiFi.RSSI()); 84 | dbdata.addField("motion_sensor", digitalRead(motionsensor)); 85 | dbdata.addField("light", digitalRead(LDR)); 86 | } 87 | 88 | void writeToInfluxDB() { 89 | Serial.print("Writing: "); 90 | Serial.println(dbdata.toLineProtocol()); 91 | 92 | if (!client.writePoint(dbdata)) { 93 | Serial.print("InfluxDB write failed: "); 94 | Serial.println(client.getLastErrorMessage()); 95 | } 96 | 97 | Serial.println("Waiting 1 second"); 98 | delay(5000); 99 | } 100 | 101 | void setup() { 102 | Serial.begin(115200); 103 | setupWifi(); 104 | setupSensors(); 105 | } 106 | 107 | void loop() { 108 | readSensors(); 109 | writeToInfluxDB(); 110 | delay(1000); 111 | } 112 | 113 | -------------------------------------------------------------------------------- /chapter 8/livingroom/livingroom.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include //https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino.git 5 | #include 6 | #include 7 | #include 8 | 9 | // WiFi configuration 10 | WiFiMulti wifiMulti; 11 | 12 | #define DEVICE "livingroom" //change device name 13 | 14 | const char* WIFI_SSID = "SSID"; // SSID 15 | const char* WIFI_PASSWORD = "Password"; //PASSWORD 16 | 17 | // InfluxDB configuration 18 | const char* INFLUXDB_URL = "ClusterURL"; // cluster URL 19 | const char* INFLUXDB_TOKEN = "API Token” //api token 20 | const char* INFLUXDB_ORG = "org ID"; //organization ID 21 | const char* INFLUXDB_BUCKET = "Home data"; //bucket name 22 | 23 | // Define pins 24 | const int DHTPIN = 12; 25 | const int LDR = 13; 26 | const int motionsensor = 14; 27 | 28 | // DHT sensor parameters 29 | #define DHTTYPE DHT22 // DHT 11 30 | DHT_Unified dht(DHTPIN, DHTTYPE); 31 | uint32_t delayMS; 32 | 33 | // Servo setup 34 | Servo doorLock; 35 | int servoPosition = 90; // Initial position 36 | 37 | // MQTT settings 38 | const char *mqttServer = "broker.hivemq.com"; 39 | const char *clientID = "client_ID"; 40 | const char *topic = "/door/lock"; 41 | 42 | WiFiClient espClient; 43 | PubSubClient mqttclient(espClient); 44 | 45 | // Time zone information 46 | const char *TZ_INFO = "UTC1"; 47 | 48 | // InfluxDB client instance 49 | InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); 50 | 51 | // Data point 52 | Point dbdata("House_data"); 53 | 54 | void setupWifi() 55 | { 56 | WiFi.mode(WIFI_STA); 57 | wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); 58 | 59 | Serial.print("Connecting to Wi-Fi"); 60 | while (wifiMulti.run() != WL_CONNECTED) 61 | { 62 | Serial.print("."); 63 | delay(100); 64 | } 65 | Serial.println(); 66 | } 67 | 68 | void setupSensors() 69 | { 70 | dht.begin(); 71 | sensor_t sensor; 72 | dht.temperature().getSensor(&sensor); 73 | dht.humidity().getSensor(&sensor); 74 | 75 | pinMode(LDR, INPUT); 76 | pinMode(motionsensor, INPUT); 77 | 78 | // Sync time 79 | timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov"); 80 | 81 | if (client.validateConnection()) 82 | { 83 | Serial.print("Connected to InfluxDB: "); 84 | Serial.println(client.getServerUrl()); 85 | } 86 | else 87 | { 88 | Serial.print("InfluxDB connection failed: "); 89 | Serial.println(client.getLastErrorMessage()); 90 | } 91 | dbdata.addTag("device", DEVICE); 92 | dbdata.addTag("SSID", WiFi.SSID()); 93 | 94 | // Servo setup 95 | doorLock.attach(15); // Attach the servo to pin D15 96 | doorLock.write(servoPosition); // Set initial position 97 | } 98 | 99 | void readSensors() 100 | { 101 | dbdata.clearFields(); 102 | 103 | sensors_event_t event; 104 | dht.temperature().getEvent(&event); 105 | dbdata.addField("temperature", event.temperature); 106 | dht.humidity().getEvent(&event); 107 | dbdata.addField("humidity", event.relative_humidity); 108 | dbdata.addField("rssi", WiFi.RSSI()); 109 | dbdata.addField("motion_sensor", digitalRead(motionsensor)); 110 | dbdata.addField("light", digitalRead(LDR)); 111 | } 112 | 113 | void writeToInfluxDB() 114 | { 115 | Serial.print("Writing: "); 116 | Serial.println(dbdata.toLineProtocol()); 117 | 118 | if (!client.writePoint(dbdata)) 119 | { 120 | Serial.print("InfluxDB write failed: "); 121 | Serial.println(client.getLastErrorMessage()); 122 | } 123 | 124 | Serial.println("Waiting 1 second"); 125 | 126 | } 127 | 128 | void callback(char *topic, byte *payload, unsigned int length) 129 | { 130 | Serial.print("Received message on topic: "); 131 | Serial.println(topic); 132 | 133 | Serial.print("Message payload: "); 134 | for (int i = 0; i < length; i++) { 135 | Serial.print((char)payload[i]); 136 | } 137 | Serial.println(); 138 | if (strcmp(topic, "/door/lock") == 0) 139 | { 140 | if (payload[0] == '1') 141 | { 142 | // Open the door lock 143 | doorLock.write(0); // Adjust the servo position for the open state 144 | Serial.println("door opened"); 145 | delay(500); // Keep it open for 5 seconds 146 | // Close the door lock 147 | doorLock.write(servoPosition); // Return to the initial position 148 | } 149 | } 150 | } 151 | 152 | void reconnect() 153 | { 154 | while (!mqttclient.connected()) 155 | { 156 | if (mqttclient.connect(clientID)) 157 | { 158 | mqttclient.subscribe(topic); 159 | } 160 | else 161 | { 162 | delay(5000); 163 | } 164 | } 165 | } 166 | 167 | void mqttsetup() 168 | { 169 | // MQTT setup 170 | mqttclient.setServer(mqttServer, 1883); 171 | mqttclient.setCallback(callback); 172 | mqttclient.setKeepAlive(15); 173 | 174 | if (mqttclient.connect(clientID)) 175 | { 176 | mqttclient.subscribe(topic); 177 | } 178 | } 179 | 180 | void mqttTask(void *pvParameters) { 181 | // MQTT setup code here 182 | 183 | while (1) { 184 | // MQTT loop code here 185 | if (!mqttclient.connected()) { 186 | // Reconnect to MQTT broker 187 | reconnect(); 188 | } 189 | mqttclient.loop(); 190 | // Add any other MQTT-related logic here 191 | } 192 | } 193 | 194 | void setup() 195 | { 196 | Serial.begin(115200); 197 | setupWifi(); 198 | setupSensors(); 199 | mqttsetup(); 200 | xTaskCreatePinnedToCore(mqttTask, "MQTT Task", 8192, NULL, 1, NULL, 0); 201 | 202 | } 203 | 204 | void loop() 205 | { 206 | readSensors(); 207 | writeToInfluxDB(); 208 | } 209 | -------------------------------------------------------------------------------- /chapter 8/read_sensors/read_sensors.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Define pins 5 | const int DHTPIN = 12; 6 | const int LDR = 13; 7 | const int motionsensor = 14; 8 | 9 | // DHT sensor parameters 10 | #define DHTTYPE DHT22 // DHT 11 11 | DHT_Unified dht(DHTPIN, DHTTYPE); 12 | uint32_t delayMS; 13 | 14 | void setupSensors() 15 | { 16 | dht.begin(); 17 | sensor_t sensor; 18 | dht.temperature().getSensor(&sensor); 19 | dht.humidity().getSensor(&sensor); 20 | 21 | pinMode(LDR, INPUT); 22 | pinMode(motionsensor, INPUT); 23 | } 24 | void readSensors() 25 | { 26 | sensors_event_t event; 27 | dht.temperature().getEvent(&event); 28 | float temperature = event.temperature; 29 | Serial.println("Temperature : " + String(temperature)); 30 | dht.humidity().getEvent(&event); 31 | float humidity = event.relative_humidity; 32 | Serial.println("Humidity : " + String(humidity)); 33 | Serial.println("Motion : " + String(digitalRead(motionsensor))); 34 | Serial.println("Light : " + String(digitalRead(LDR))); 35 | } 36 | void setup() 37 | { 38 | Serial.begin(115200); 39 | setupSensors(); 40 | } 41 | void loop() 42 | { 43 | readSensors(); 44 | delay(1000); 45 | } 46 | --------------------------------------------------------------------------------