Search Results
163 results found with an empty search
- ESP32 3.5inch TFT Touch display ILI9488 with LVGL UI Part2
Here to learn how to make a ESP32 board based 3.5inch touch display ILI9488 using the LVGL (Light and Versatile Graphics Library) and Bodmer's TFT_eSPI arduino Library. The LVGL is a popular free and open-source embedded graphics library to create UIs for arduino. In this Setting up LVGL (Light and Versatile Graphics Library) on an ESP32 with a TFT LCD touchscreen display ILI9488 is a great way to create interactive user interfaces for your projects. Here’s a step-by-step guide to help you get started. Demo: Components Required ESP-32 Module (38Pin) 3.5 inch TFT LCD Display Module SPI Interface 320x480 with Touch Screen Jumper Wires Circuit Diagram TFT refer blog: https://www.dofbot.com/post/esp32-dht-weather-monitor-with-3-5inch-tft-touch-display In the VCC pin, you can either use 5V or 3.3V depending upon if your J1 connection is open or closed, J1 = open=5V; J1=close=3.3V. LVGL refer: https://docs.lvgl.io/master/overview/index.html Hardware Requirements ESP32 Board : Any variant should work, but make sure it has enough GPIO pins. TFT LCD Touchscreen : Common models include ILI9488 Connecting Wires : Jumper wires for connections. Breadboard (optional): For easier connections. Software Requirements Arduino IDE : Make sure you have the latest version. Select “File>Preferences>settings>Additional Boards Manager URLs” to fill the link. Here are the steps to install the ESP32 board in Arduino IDE: Open the Arduino IDE Select File and then Preferences Find the Additional Board Manager URLs field and activate the text box Add the URL to the field Click OK to save the changes https:// raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json , https://arduino.esp8266.com/stable/package_esp8266com_index.json , https://espressif.github.io/arduino-esp32/package_esp32_index.json LVGL Library : Available through the Library Manager in the Arduino IDE. Touch Driver Library : Depending on your touchscreen (e.g., TFT_eSPI) Configuring LVGL LVGL Configuration : You may need to configure LVGL for your specific display and touch screen. Create a lv_conf.h file or modify the existing one in the LVGL library folder: Set LVGL_DISPLAY_HOR_RES and LVGL_DISPLAY_VER_RES to match your display's resolution. Configure the display and touch input settings based on your library (e.g., TFT_eSPI settings). TFT_eSPI Configuration : A feature rich Arduino IDE compatible graphics and fonts library for 32-bit processors. The library is targeted at 32-bit processors, it has been performance optimised for RP2040, STM32, ESP8266 and ESP32 types, other 32-bit processors may be used but will use the slower generic Arduino interface calls. The library can be loaded using the Arduino IDE's Library Manager. Direct Memory Access (DMA) can be used with the ESP32, RP2040 and STM32 processors with SPI interface displays to improve rendering performance. DMA with a parallel interface (8 and 16-bit) is only supported with the RP2040. Go to the TFT_eSPI library folder and open the User_Setup.h file to configure the pins according to your wiring. Wiring the TFT Display TFT Pin ESP32 Pin VCC 3.3V GND GND CS GPIO 5 RESET GPIO 2 DC/RS GPIO 17 SDI(MOSI) GPIO 23 SCK GPIO 18 LED 3.3V (or PWM pin for brightness) Wiring the Touchscreen (e.g., TFT_espi) Touch Pin ESP32 Pin T_CS GPIO 16 T_IRQ GPIO 21 T_DOUT GPIO 19 T_DIN GPIO 23 T_CLK GPIO 18 Sample Code Here’s a basic example to initialize the display and create a simple button using LVGL: Example 2. ########################################################################### //Arduino-TFT_eSPI board-template main routine. There's a TFT_eSPI create+flush driver already in LVGL-9.1 but we create our own here for more control (like e.g. 16-bit color swap). #include "FS.h" #include #include #include #include /*Don't forget to set Sketchbook location in File/Preferences to the path of your UI project (the parent foder of this INO file)*/ /*Change to your screen resolution*/ static const uint16_t screenWidth = 480 ; static const uint16_t screenHeight = 320 ; enum { SCREENBUFFER_SIZE_PIXELS = screenWidth * screenHeight / 10 } ; static lv_color_t buf [SCREENBUFFER_SIZE_PIXELS]; TFT_eSPI tft = TFT_eSPI ( screenWidth, screenHeight ) ; /* TFT instance */ #define CALIBRATION_FILE "/calibrationData" #if LV_USE_LOG != 0 /* Serial debugging */ void my_print ( const char * buf) { Serial . printf ( buf ) ; Serial . flush () ; } #endif /* Display flushing */ void my_disp_flush ( lv_display_t disp , const lv_area_t area , uint8_t * pixelmap) { uint32_t w = ( area -> x2 - area -> x1 + 1 ) ; uint32_t h = ( area -> y2 - area -> y1 + 1 ) ; if ( LV_COLOR_16_SWAP ) { size_t len = lv_area_get_size ( area ) ; lv_draw_sw_rgb565_swap ( pixelmap, len ) ; } tft . startWrite () ; tft . setAddrWindow ( area -> x1 , area -> y1 , w, h ) ; tft . pushColors ( ( uint16_t * ) pixelmap, w * h, true ) ; tft . endWrite () ; lv_disp_flush_ready ( disp ) ; } /*Read the touchpad*/ void my_touchpad_read ( lv_indev_t indev_driver , lv_indev_data_t data) { uint16_t touchX = 0 , touchY = 0 ; bool touched = tft . getTouch ( &touchX, &touchY, 600 ) ; if ( !touched ) { data -> state = LV_INDEV_STATE_REL; } else { data -> state = LV_INDEV_STATE_PR; /*Set the coordinates*/ data -> point . x = touchX; data -> point . y = touchY; Serial . print ( "Data x " ) ; Serial . println ( touchX ) ; Serial . print ( "Data y " ) ; Serial . println ( touchY ) ; } } /*Set tick routine needed for LVGL internal timings*/ static uint32_t my_tick_get_cb ( void ) { return millis () ; } void setup () { uint16_t calibrationData [ 5 ]; uint8_t calDataOK = 0 ; Serial . begin ( 115200 ) ; /* prepare for possible serial debug */ String LVGL_Arduino = "Hello Arduino! " ; LVGL_Arduino += String ( 'V' ) + lv_version_major () + "." + lv_version_minor () + "." + lv_version_patch () ; Serial . println ( LVGL_Arduino ) ; Serial . println ( "I am LVGL_Arduino" ) ; lv_init () ; #if LV_USE_LOG != 0 lv_log_register_print_cb ( my_print ) ; /* register print function for debugging */ #endif tft . begin () ; /* TFT init */ tft . setRotation ( 3 ) ; /* Landscape orientation, flipped */ static lv_disp_t * disp; disp = lv_display_create ( screenWidth, screenHeight ) ; lv_display_set_buffers ( disp, buf, NULL , SCREENBUFFER_SIZE_PIXELS * sizeof ( lv_color_t ) , LV_DISPLAY_RENDER_MODE_PARTIAL ) ; lv_display_set_flush_cb ( disp, my_disp_flush ) ; static lv_indev_t * indev; indev = lv_indev_create () ; lv_indev_set_type ( indev, LV_INDEV_TYPE_POINTER ) ; lv_indev_set_read_cb ( indev, my_touchpad_read ) ; lv_tick_set_cb ( my_tick_get_cb ) ; ui_init () ; Serial . println ( "Setup done" ) ; // check file system if ( ! SPIFFS . begin ()) { Serial . println ( "formatting file system" ) ; SPIFFS . format () ; SPIFFS . begin () ; } // check if calibration file exists if ( SPIFFS . exists ( CALIBRATION_FILE )) { File f = SPIFFS . open ( CALIBRATION_FILE, "r" ) ; if ( f ) { if ( f . readBytes (( char * ) calibrationData, 14 ) == 14 ) calDataOK = 1 ; f . close () ; } } if ( calDataOK ) { // calibration data valid tft . setTouch ( calibrationData ) ; } else { // data not valid. recalibrate tft . calibrateTouch ( calibrationData, TFT_WHITE, TFT_RED, 15 ) ; // store data File f = SPIFFS . open ( CALIBRATION_FILE, "w" ) ; if ( f ) { f . write (( const unsigned char * ) calibrationData, 14 ) ; f . close () ; } } } void loop () { lv_timer_handler () ; /* let the GUI do its work */ delay ( 5 ) ; } ########################################################################### Next Example: https://www.dofbot.com/post/esp32-3-5inch-tft-touch-display-ili9488-with-lvgl-ui-part3 Final Steps Upload the code to your ESP32 using the Arduino IDE. Open the Serial Monitor to check for any debug messages. Interact with the touchscreen to see your UI in action! Tips Adjust the pin assignments based on your wiring. Explore LVGL's extensive documentation for more UI elements and functionalities. Use LVGL's built-in tools to design and customize your interfaces. This should give you a solid start on using LVGL with an ESP32 and a TFT LCD touchscreen. Happy coding!
- ESP32 3.5inch TFT Touch display ILI9488 with LVGL UI Part1
Here to learn how to make a ESP32 board based 3.5inch touch display ILI9488 using the LVGL (Light and Versatile Graphics Library) and Bodmer's TFT_eSPI arduino Library. The LVGL is a popular free and open-source embedded graphics library to create UIs for arduino. In this Setting up LVGL (Light and Versatile Graphics Library) on an ESP32 with a TFT LCD touchscreen display ILI9488 is a great way to create interactive user interfaces for your projects. Here’s a step-by-step guide to help you get started. Demo: Components Required ESP-32 Module (38Pin) 3.5 inch TFT LCD Display Module SPI Interface 320x480 with Touch Screen Jumper Wires Circuit Diagram TFT refer blog: https://www.dofbot.com/post/esp32-dht-weather-monitor-with-3-5inch-tft-touch-display In the VCC pin, you can either use 5V or 3.3V depending upon if your J1 connection is open or closed, J1 = open=5V; J1=close=3.3V. LVGL refer: https://docs.lvgl.io/master/overview/index.html Hardware Requirements ESP32 Board : Any variant should work, but make sure it has enough GPIO pins. TFT LCD Touchscreen : Common models include ILI9488 Connecting Wires : Jumper wires for connections. Breadboard (optional): For easier connections. Software Requirements Arduino IDE : Make sure you have the latest version. Select “File>Preferences>settings>Additional Boards Manager URLs” to fill the link. Here are the steps to install the ESP32 board in Arduino IDE: Open the Arduino IDE Select File and then Preferences Find the Additional Board Manager URLs field and activate the text box Add the URL to the field Click OK to save the changes https:// raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json , https://arduino.esp8266.com/stable/package_esp8266com_index.json , https://espressif.github.io/arduino-esp32/package_esp32_index.json LVGL Library : Available through the Library Manager in the Arduino IDE. Touch Driver Library : Depending on your touchscreen (e.g., TFT_eSPI) Configuring LVGL LVGL Configuration : You may need to configure LVGL for your specific display and touch screen. Create a lv_conf.h file or modify the existing one in the LVGL library folder: Set LVGL_DISPLAY_HOR_RES and LVGL_DISPLAY_VER_RES to match your display's resolution. Configure the display and touch input settings based on your library (e.g., TFT_eSPI settings). TFT_eSPI Configuration : A feature rich Arduino IDE compatible graphics and fonts library for 32-bit processors. The library is targeted at 32-bit processors, it has been performance optimised for RP2040, STM32, ESP8266 and ESP32 types, other 32-bit processors may be used but will use the slower generic Arduino interface calls. The library can be loaded using the Arduino IDE's Library Manager. Direct Memory Access (DMA) can be used with the ESP32, RP2040 and STM32 processors with SPI interface displays to improve rendering performance. DMA with a parallel interface (8 and 16-bit) is only supported with the RP2040. Go to the TFT_eSPI library folder and open the User_Setup.h file to configure the pins according to your wiring. Wiring the TFT Display TFT Pin ESP32 Pin VCC 3.3V GND GND CS GPIO 5 RESET GPIO 2 DC/RS GPIO 17 SDI(MOSI) GPIO 23 SCK GPIO 18 LED 3.3V (or PWM pin for brightness) Wiring the Touchscreen (e.g., TFT_espi) Touch Pin ESP32 Pin T_CS GPIO 16 T_IRQ GPIO 21 T_DOUT GPIO 19 T_DIN GPIO 23 T_CLK GPIO 18 Sample Code Here’s a basic example to initialize the display and create a simple button using LVGL: Example 1. ######################################################################### //Arduino-TFT_eSPI board-template main routine. There's a TFT_eSPI create+flush driver already in LVGL-9.1 but we create our own here for more control (like e.g. 16-bit color swap). #include "FS.h" #include #include #include #include /*Don't forget to set Sketchbook location in File/Preferences to the path of your UI project (the parent foder of this INO file)*/ /*Change to your screen resolution*/ static const uint16_t screenWidth = 480 ; static const uint16_t screenHeight = 320 ; enum { SCREENBUFFER_SIZE_PIXELS = screenWidth * screenHeight / 10 } ; static lv_color_t buf [SCREENBUFFER_SIZE_PIXELS]; TFT_eSPI tft = TFT_eSPI ( screenWidth, screenHeight ) ; /* TFT instance */ #define CALIBRATION_FILE "/calibrationData" #if LV_USE_LOG != 0 /* Serial debugging */ void my_print ( const char * buf) { Serial . printf ( buf ) ; Serial . flush () ; } #endif /* Display flushing */ void my_disp_flush ( lv_display_t disp , const lv_area_t area , uint8_t * pixelmap) { uint32_t w = ( area -> x2 - area -> x1 + 1 ) ; uint32_t h = ( area -> y2 - area -> y1 + 1 ) ; if ( LV_COLOR_16_SWAP ) { size_t len = lv_area_get_size ( area ) ; lv_draw_sw_rgb565_swap ( pixelmap, len ) ; } tft . startWrite () ; tft . setAddrWindow ( area -> x1 , area -> y1 , w, h ) ; tft . pushColors ( ( uint16_t * ) pixelmap, w * h, true ) ; tft . endWrite () ; lv_disp_flush_ready ( disp ) ; } /*Read the touchpad*/ void my_touchpad_read ( lv_indev_t indev_driver , lv_indev_data_t data) { uint16_t touchX = 0 , touchY = 0 ; bool touched = tft . getTouch ( &touchX, &touchY, 600 ) ; if ( !touched ) { data -> state = LV_INDEV_STATE_REL; } else { data -> state = LV_INDEV_STATE_PR; /*Set the coordinates*/ data -> point . x = touchX; data -> point . y = touchY; Serial . print ( "Data x " ) ; Serial . println ( touchX ) ; Serial . print ( "Data y " ) ; Serial . println ( touchY ) ; } } /*Set tick routine needed for LVGL internal timings*/ static uint32_t my_tick_get_cb ( void ) { return millis () ; } void setup () { uint16_t calibrationData [ 5 ]; uint8_t calDataOK = 0 ; Serial . begin ( 115200 ) ; /* prepare for possible serial debug */ String LVGL_Arduino = "Hello Arduino! " ; LVGL_Arduino += String ( 'V' ) + lv_version_major () + "." + lv_version_minor () + "." + lv_version_patch () ; Serial . println ( LVGL_Arduino ) ; Serial . println ( "I am LVGL_Arduino" ) ; lv_init () ; #if LV_USE_LOG != 0 lv_log_register_print_cb ( my_print ) ; /* register print function for debugging */ #endif tft . begin () ; /* TFT init */ tft . setRotation ( 3 ) ; /* Landscape orientation, flipped */ static lv_disp_t * disp; disp = lv_display_create ( screenWidth, screenHeight ) ; lv_display_set_buffers ( disp, buf, NULL , SCREENBUFFER_SIZE_PIXELS * sizeof ( lv_color_t ) , LV_DISPLAY_RENDER_MODE_PARTIAL ) ; lv_display_set_flush_cb ( disp, my_disp_flush ) ; static lv_indev_t * indev; indev = lv_indev_create () ; lv_indev_set_type ( indev, LV_INDEV_TYPE_POINTER ) ; lv_indev_set_read_cb ( indev, my_touchpad_read ) ; lv_tick_set_cb ( my_tick_get_cb ) ; ui_init () ; Serial . println ( "Setup done" ) ; // check file system if ( ! SPIFFS . begin ()) { Serial . println ( "formatting file system" ) ; SPIFFS . format () ; SPIFFS . begin () ; } // check if calibration file exists if ( SPIFFS . exists ( CALIBRATION_FILE )) { File f = SPIFFS . open ( CALIBRATION_FILE, "r" ) ; if ( f ) { if ( f . readBytes (( char * ) calibrationData, 14 ) == 14 ) calDataOK = 1 ; f . close () ; } } if ( calDataOK ) { // calibration data valid tft . setTouch ( calibrationData ) ; } else { // data not valid. recalibrate tft . calibrateTouch ( calibrationData, TFT_WHITE, TFT_RED, 15 ) ; // store data File f = SPIFFS . open ( CALIBRATION_FILE, "w" ) ; if ( f ) { f . write (( const unsigned char * ) calibrationData, 14 ) ; f . close () ; } } } void loop () { lv_timer_handler () ; /* let the GUI do its work */ delay ( 5 ) ; } ########################################################################### Next Example: https://www.dofbot.com/post/esp32-3-5inch-tft-touch-display-ili9488-with-lvgl-ui-part2 Final Steps Upload the code to your ESP32 using the Arduino IDE. Open the Serial Monitor to check for any debug messages. Interact with the touchscreen to see your UI in action! Tips Adjust the pin assignments based on your wiring. Explore LVGL's extensive documentation for more UI elements and functionalities. Use LVGL's built-in tools to design and customize your interfaces. This should give you a solid start on using LVGL with an ESP32 and a TFT LCD touchscreen. Happy coding!
- ESP32 Web Image Controlled Servo Motor
In this tutorial to create a project where you control a servo motor angle from 0 to 180 degrees using a web interface with an image that rotates based on mouse clicks, you’ll use WebSocket communication to send angle coordinates to the ESP32, which will then adjust the servo motor accordingly. Below is a detailed guide to help you build this project. Components Required ESP32 Development Board Servo Motor SG90 Power Supply (e.g., 5V battery or external power adapter) Breadboard and Jumper Wires Circuit Diagram Setup Arduino IDE for ESP32 Install the ESP32 Board Package: Open Arduino IDE. Go to File > Preferences . Add the following URL to the "Additional Board Manager URLs" field: https://dl.espressif.com/dl/package_esp32_index.json . Go to Tools > Board > Boards Manager , search for ESP32 , and install it. 2. Connect the Servo Motor Wiring : Connect the servo’s power (red) and ground (black/brown) wires to the 5V and GND pins on the ESP32. Connect the signal (yellow/orange) wire to a PWM-capable GPIO pin on the ESP32 (e.g., GPIO 19). Power Consideration : Ensure the servo is adequately powered. Use an external power supply if the servo requires more current than the ESP32 can provide. 3. Install Required Libraries Install Servo Library : Open Arduino IDE, go to Sketch -> Include Library -> Manage Libraries, search for Servo, and install it. Install WebSocket Library : Search for and install the WebSockets library. Download Similarly, search for and install the ESP32 Servo library. Download Search for and install the TCP library. Download After installed the libraries, restart your Arduino IDE. 4. Write the ESP32 Code Here’s the code to handle WebSocket communication and control the servo: #include #ifdef ESP32 #include #include #elif defined(ESP8266) #include #include #endif #include AsyncWebServer server(80); #include #include #include #include "index.h" #define SERVO_PIN 19 Servo servo; const char* ssid = "TPLink"; const char* password = "95001121379884265554"; WebSocketsServer webSocket = WebSocketsServer(81); void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) { switch (type) { case WStype_DISCONNECTED: Serial.printf("[%u] Disconnected!\n", num); break; case WStype_CONNECTED: { IPAddress ip = webSocket.remoteIP(num); Serial.printf("[%u] Connected from %d.%d.%d.%d\n", num, ip[0], ip[1], ip[2], ip[3]); } break; case WStype_TEXT: //Serial.printf("[%u] Received text: %s\n", num, payload); String angle = String((char*)payload); int angle_value = angle.toInt(); Serial.println(angle_value); servo.write(angle_value); break; } } void setup() { Serial.begin(9600); servo.attach(SERVO_PIN); // attaches the servo on ESP32 pin WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.printf("WiFi Failed!\n"); return; } Serial.println("Connecting to WiFi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); // Initialize WebSocket server webSocket.begin(); webSocket.onEvent(webSocketEvent); // Serve a basic HTML page with JavaScript to create the WebSocket connection server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { Serial.println("Web Server: received a web page request"); String html = HTML_CONTENT; // Use the HTML content from the index.h file request->send(200, "text/html", html); }); server.begin(); } void loop() { webSocket.loop(); } 5. Create the Web Interface Here’s the HTML for the web interface and Base64 for image data url. This will send the angle coordinates to the ESP32 when you click on the image: Base 64 https://www.base64-image.de/ to convert the Image to Base64 online and use the result string as data URI, img src, CSS background-url, and others. Sometimes you have to send or output an image within a text document (for example, HTML, CSS, JSON, XML), but you cannot do this because binary characters will damage the syntax of the text document. To prevent this, for example, you can encode image to Base64 and embed it using the data URI. The Allowed image types are JPG, PNG, GIF, WebP, BMP and SVG and allowed image 1mb size. To embed a Base64-encoded image in HTML, use the data URI scheme in the src attribute of the tag. Here's an example: . Here the index.h file const char *HTML_CONTENT = R"=====( ESP32 Web Image Controlled Servo Motor WebSocket : null Angle : 90 )====="; 6. Upload and Test Upload the Code : Connect your ESP32 to your computer, select the correct board and port in the Arduino IDE, and upload the code. Access the Web Interface : Open the Serial Monitor to get the ESP32's IP address. Enter this IP address into your web browser to access the web interface. Test and Debug : Click on the image on your web interface. The servo should move according to the horizontal position of the click, translating it into an angle between 0 and 180 degrees. If the servo does not respond as expected, check your wiring, ensure the web interface is properly sending the angle, and verify WebSocket communication in the browser’s developer tools. Demo: Conclusion With this setup, you can control a servo motor's angle using mouse clicks on an image rotate in a web interface. The ESP32 receives angle data via WebSocket and adjusts the servo position accordingly. Customize the image and refine the code as needed to suit your project’s requirements!
- Home Automation ESP32 and TFT Touch Display
In this tutorial to learn the home automation project using ESP32, TFT 3.5 inch touch screen Display. Using this project is replacement for the manual switch and you can easily on/off the home appliances like Lights, Fans, AC, TV, etc. Here we used the 4 channel relay board for controlling the 4 devices. Components: ESP-32 Dev Module (38Pin) - 1 n0 3.5 inch TFT LCD Display Module SPI Interface 320x480 with Touch Screen- 1No 4 channel Relay Module- 1 no Jumper Wires Circuit Diagram 3.5 inch TFT LCD Display Module SPI Interface 320x480 with Touch Screen This TFT display is big bright and colorful! 480×320 pixels with individual RGB pixel control, this has way more resolution than a black and white 128×64 display. As a bonus, this display has a resistive touch screen attached to it already, so you can detect finger presses anywhere on the screen. This display has a controller built into it with RAM buffering so that almost no work is done by the microcontroller. This 3.5-inch SPI Touch Screen Module is wrapped up into an easy-to-use breakout board, with SPI connections on one end. If you’re going with SPI mode, you can also take advantage of the onboard MicroSD card socket to display images. The 3.5-inch display doesn't have a built-in level shifter, so it's advised to use only 3.3v. Using a node MCU would be more suitable cause it provides only 3.3v. if you are using a 5v microcontroller like the Arduino UNO, MEGA, Using a level shifter would give you the appropriate voltage needed to operate the LCD without damaging it. DATA SHEET Download 3.5 inch TFT LCD SPI Module Manual Download Refer the blog for more deatils in TFT configuration. https://www.dofbot.com/post/esp32-dht-weather-monitor-with-3-5inch-tft-touch-display ESP32 Development Board WiFi+Bluetooth 38 Pin ESP32 Development board is based on the ESP WROOM32 WIFI + BLE Module.It’s a low-footprint, minimal system development board powered by the latest ESP-WROOM-32 module and can be easily inserted into a solderless breadboard. It contains the entire basic support circuitry for the ESP-WROOM-32, including the USB-UART bridge, reset- and boot-mode buttons, LDO regulator and a micro-USB connector. Every important GPIO is available to the developer. ESP32 Development Board Feature: ESP32 is already integrated antenna and RF balun,power amplifier,low-noise amplifiers,filters,and power management module. This board is used with 2.4 GHz dual-mode Wi-Fi and Bluetooth chips by TSMC 40nm low power technology,power and RF properties best,which is safe,reliable,and scalable to a variety of applications. Strong function with support LWIP protocol,Freertos. Supporting three modes:AP,STA,and AP+STA. Supporting Lua program,easily to develop. Installing the library To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. Download TFT Library , we need to use this library for TFT touch display In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After Arduino IDE installed, there is no package to support ESP32-S2, we need to install the ESP32 package in Arduino IDE to continue. Select “File>Preferences>settings>Additional Boards Manager URLs” to fill the link: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json arduino code #include #include "Free_Fonts.h" // Include the header file attached to this sketch #include "dofbot.h" #include #include // Hardware-specific library #include // Widget library TFT_eSPI tft = TFT_eSPI(); // Invoke custom library #define CALIBRATION_FILE "/TouchCalData1" #define REPEAT_CAL false ButtonWidget btn1SW = ButtonWidget(&tft); ButtonWidget btn2SW = ButtonWidget(&tft); ButtonWidget btn3SW = ButtonWidget(&tft); ButtonWidget btn4SW = ButtonWidget(&tft); #define BUTTON_W 100 #define BUTTON_H 50 // Create an array of button instances to use in for() loops // This is more useful where large numbers of buttons are employed ButtonWidget* btn[] = {&btn1SW , &btn2SW , &btn3SW , &btn4SW}; uint8_t buttonCount = sizeof(btn) / sizeof(btn[0]); // define the GPIO connected with Relays and switches #define RelayPin1 33 //D33 #define RelayPin2 32 //D32 #define RelayPin3 25 //D25 #define RelayPin4 26 //D26 // Relay State bool toggleState_1 = HIGH; //Define integer to remember the toggle state for relay 1 bool toggleState_2 = HIGH; //Define integer to remember the toggle state for relay 2 bool toggleState_3 = HIGH; //Define integer to remember the toggle state for relay 3 bool toggleState_4 = HIGH; //Define integer to remember the toggle state for relay 4 void btn1SW_pressAction(void) { if (btn1SW.justPressed()) { btn1SW.drawSmoothButton(!btn1SW.getState(), 3, TFT_BLACK, btn1SW.getState() ? "OFF" : "ON"); Serial.print("Button toggled: "); if (btn1SW.getState()) {Serial.println("ON"); digitalWrite(RelayPin1, HIGH);} else { Serial.println("OFF"); digitalWrite(RelayPin1, LOW); btn1SW.setPressTime(millis());} } // if button pressed for more than 1 sec... if (millis() - btn1SW.getPressTime() >= 1000) { Serial.println("Stop pressing my buttton......."); } else Serial.println("Right button is being pressed"); } void btn1SW_releaseAction(void) { // Not action } void btn2SW_pressAction(void) { if (btn2SW.justPressed()) { btn2SW.drawSmoothButton(!btn2SW.getState(), 3, TFT_BLACK, btn2SW.getState() ? "OFF" : "ON"); Serial.print("Button toggled: "); if (btn2SW.getState()) {Serial.println("ON"); digitalWrite(RelayPin2, HIGH);} else { Serial.println("OFF"); digitalWrite(RelayPin2, LOW); btn2SW.setPressTime(millis());} } // if button pressed for more than 1 sec... if (millis() - btn2SW.getPressTime() >= 1000) { Serial.println("Stop pressing my buttton......."); } else Serial.println("Right button is being pressed"); } void btn2SW_releaseAction(void) { // Not action } void btn3SW_pressAction(void) { if (btn3SW.justPressed()) { btn3SW.drawSmoothButton(!btn3SW.getState(), 3, TFT_BLACK, btn3SW.getState() ? "OFF" : "ON"); Serial.print("Button toggled: "); if (btn3SW.getState()) {Serial.println("ON"); digitalWrite(RelayPin3, HIGH);} else { Serial.println("OFF"); digitalWrite(RelayPin3, LOW); btn3SW.setPressTime(millis());} } // if button pressed for more than 1 sec... if (millis() - btn3SW.getPressTime() >= 1000) { Serial.println("Stop pressing my buttton......."); } else Serial.println("Right button is being pressed"); } void btn3SW_releaseAction(void) { // Not action } void btn4SW_pressAction(void) { if (btn4SW.justPressed()) { btn4SW.drawSmoothButton(!btn4SW.getState(), 3, TFT_BLACK, btn4SW.getState() ? "OFF" : "ON"); Serial.print("Button toggled: "); if (btn4SW.getState()) {Serial.println("ON"); digitalWrite(RelayPin4, HIGH);} else { Serial.println("OFF"); digitalWrite(RelayPin4, LOW); btn4SW.setPressTime(millis());} } // if button pressed for more than 1 sec... if (millis() - btn4SW.getPressTime() >= 1000) { Serial.println("Stop pressing my buttton......."); } else Serial.println("Right button is being pressed"); } void btn4SW_releaseAction(void) { // Not action } void initButtons() { uint16_t x = 150; uint16_t y = 85; btn1SW.initButtonUL(x, y, BUTTON_W, BUTTON_H, TFT_BLACK, TFT_RED, TFT_GREEN, "OFF", 1); btn1SW.setPressAction(btn1SW_pressAction); btn1SW.setReleaseAction(btn1SW_releaseAction); btn1SW.drawSmoothButton(false, 3, TFT_BLACK); // 3 is outline width, TFT_BLACK is the surrounding background colour for anti-aliasing y = 160; btn2SW.initButtonUL(x, y, BUTTON_W, BUTTON_H, TFT_BLACK, TFT_RED, TFT_GREEN, "OFF", 1); btn2SW.setPressAction(btn2SW_pressAction); //btn2SW.setReleaseAction(btn2SW_releaseAction); btn2SW.drawSmoothButton(false, 3, TFT_BLACK); // 3 is outline width, TFT_BLACK is the surrounding background colour for anti-aliasing y = 235; btn3SW.initButtonUL(x, y, BUTTON_W, BUTTON_H, TFT_BLACK, TFT_RED, TFT_GREEN, "OFF", 1); btn3SW.setPressAction(btn3SW_pressAction); btn3SW.setReleaseAction(btn3SW_releaseAction); btn3SW.drawSmoothButton(false, 3, TFT_BLACK); // 3 is outline width, TFT_BLACK is the surrounding background colour for anti-aliasing y = 310; btn4SW.initButtonUL(x, y, BUTTON_W, BUTTON_H, TFT_BLACK, TFT_RED, TFT_GREEN, "OFF", 1); btn4SW.setPressAction(btn4SW_pressAction); btn4SW.setReleaseAction(btn4SW_releaseAction); btn4SW.drawSmoothButton(false, 3, TFT_BLACK); // 3 is outline width, TFT_BLACK is the surrounding background colour for anti-aliasing } void setup() { Serial.begin(115200); pinMode(RelayPin1, OUTPUT); pinMode(RelayPin2, OUTPUT); pinMode(RelayPin3, OUTPUT); pinMode(RelayPin4, OUTPUT); //During Starting all Relays should TURN OFF digitalWrite(RelayPin1, !toggleState_1); digitalWrite(RelayPin2, !toggleState_2); digitalWrite(RelayPin3, !toggleState_3); digitalWrite(RelayPin4, !toggleState_4); tft.init(); tft.begin(); tft.setRotation(0); tft.setSwapBytes(true); tft.fillScreen(TFT_WHITE); // tft.fillScreen(TFT_BLACK); tft.setFreeFont(FF18); // Calibrate the touch screen and retrieve the scaling factors touch_calibrate(); initButtons(); tft.setTextColor(TFT_BLACK, TFT_WHITE); //tft.setTextSize(1); // tft.fillScreen(TFT_BLACK); // tft.setSwapBytes(true); tft.setCursor(1,30); tft.println("HOME AUTOMATION ESP32"); tft.setCursor(15,55); tft.println("& TFT TOUCH DISPLAY"); tft.setCursor(50,115); tft.println("Relay1"); tft.setCursor(50,195); tft.println("Relay2"); tft.setCursor(50,270); tft.println("Relay3"); tft.setCursor(50,345); tft.println("Relay4"); tft.setCursor(120,410); tft.setTextSize(0.5); tft.println("PROJECT BY "); tft.setCursor(120,435); tft.println("RAMESH G"); tft.setCursor(120,460); tft.println("DOFBOT.COM"); } void loop() { static uint32_t scanTime = millis(); uint16_t t_x = 9999, t_y = 9999; // To store the touch coordinates // Scan keys every 50ms at most if (millis() - scanTime >= 50) { // Pressed will be set true if there is a valid touch on the screen bool pressed = tft.getTouch(&t_x, &t_y); scanTime = millis(); for (uint8_t b = 0; b < buttonCount; b++) { if (pressed) { if (btn[b]->contains(t_x, t_y)) { btn[b]->press(true); btn[b]->pressAction(); } } else { btn[b]->press(false); btn[b]->releaseAction(); } } } for(int i=0;i
- ESP32 Internet Weather with 3.5inch TFT Display
Here to learn how to make an IOT based internet weather station with TFT Display. The ESP32 can access the internet and gets weather data from www.openweathermap.org that provide Free/Paid weather information for many cities over the world. In this project to show how to get weather data from the internet and print TFT display. Components Required ESP-32 Module (38Pin) 3.5 inch TFT LCD Display Module SPI Interface 320x480 with Touch Screen Jumper Wires Circuit Diagram 3.5 inch TFT LCD Display Module SPI Interface 320x480 with Touch Screen This TFT display is big bright and colorful! 480×320 pixels with individual RGB pixel control, this has way more resolution than a black and white 128×64 display. As a bonus, this display has a resistive touch screen attached to it already, so you can detect finger presses anywhere on the screen. This display has a controller built into it with RAM buffering so that almost no work is done by the microcontroller. This 3.5-inch SPI Touch Screen Module is wrapped up into an easy-to-use breakout board, with SPI connections on one end. If you’re going with SPI mode, you can also take advantage of the onboard MicroSD card socket to display images. The 3.5-inch display doesn't have a built-in level shifter, so it's advised to use only 3.3v. Using a node MCU would be more suitable cause it provides only 3.3v. if you are using a 5v microcontroller like the Arduino UNO, MEGA, Using a level shifter would give you the appropriate voltage needed to operate the LCD without damaging it. DATA SHEET Download 3.5 inch TFT LCD SPI Module Manual Download Open weather map Internet weather station To get weather data, first we’ve to sign up for a free account in order to get an API key which is important in this project. Refer blog: https://www.dofbot.com/post/internet-weather-station Feature Access current weather data for any location including over 200,000 cities Current weather is frequently updated based on global models and data from more than 40,000 weather stations Data is available in JSON, XML, or HTML format Available for Free and all other paid accounts Once you sign in to your account (of course after the free registration), you’ll be directed to member area, go to API keys and you’ll find your API key as shown in the following image: Replace CITY by with the city you want weather data for, COUNTRY_CODE with the country code for that city (for example uk for the United Kingdom, us for the USA …) and YOUR_API_KEY with your API key which is shown above and replace API key in the arduino code. Installing the library To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. Download TFT Library , we need to use this library for TFT touch display Download Jpeg decoder Library , we need to use this library for image display Download Json Library , we need to use this library for arduino Download NTPClient Library , we need to use this library for server. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After Arduino IDE installed, there is no package to support ESP32-S2, we need to install the ESP32 package in Arduino IDE to continue. Select “File>Preferences>settings>Additional Boards Manager URLs” to fill the link: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json arduino code Subscribe and Download c ode #include "earth.h" #include #include // Hardware-specific library #include //https://github.com/bblanchon/ArduinoJson.git #include //https://github.com/taranais/NTPClient TFT_eSPI tft = TFT_eSPI(); // JPEG decoder library #include // Return the minimum of two values a and b #define minimum(a,b) (((a) < (b)) ? (a) : (b)) // Include the sketch header file that contains the image stored as an array of bytes // More than one image array could be stored in each header file. #include "jpeg1.h" // Count how many times the image is drawn for test purposes uint32_t icount = 0; #define TFT_GREY 0x5AEB #define lightblue 0x01E9 #define darkred 0xA041 #define blue 0x5D9B #include "Orbitron_Medium_20.h" #include #include #include const int pwmFreq = 5000; const int pwmResolution = 8; const int pwmLedChannelTFT = 0; const char* ssid = "TP-Link_3200"; // your SSID const char* password = "95001121379884265554"; //Your Password String town="Chennai"; String Country="IN"; const String endpoint = "http://api.openweathermap.org/data/2.5/weather?q="+town+","+Country+"&units=metric&APPID="; const String key = "add82e4e24d449f3a522f06621a3aaeb"; //paste your API key here String payload=""; //whole json String tmp="" ; //temperatur String hum="" ; //humidity StaticJsonDocument<1000> doc; // Define NTP Client to get time WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); // Variables to save date and time String formattedDate; String dayStamp; String timeStamp; int backlight[5] = {10,30,60,120,220}; byte b=1; void setup(void) { Serial.begin(115200); tft.begin(); tft.init(); tft.setRotation(0); tft.setSwapBytes(true);/// tft.fillScreen(TFT_BLACK); tft.setTextColor(TFT_WHITE,TFT_BLACK); tft.setTextSize(1); ledcSetup(pwmLedChannelTFT, pwmFreq, pwmResolution); ledcAttachPin(TFT_BLACK, pwmLedChannelTFT); ledcWrite(pwmLedChannelTFT, backlight[b]); tft.print("Connecting to "); tft.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(300); tft.print("."); } tft.println(""); tft.println("WiFi connected."); tft.println("IP address: "); tft.println(WiFi.localIP()); delay(3000); tft.setTextColor(TFT_WHITE,TFT_BLACK); tft.setTextSize(1); tft.fillScreen(TFT_BLACK); tft.setSwapBytes(true); tft.setCursor(2, 392, 1); tft.println(WiFi.localIP()); // tft.setCursor(80, 282, 2); // tft.println("SEC:"); tft.setTextColor(TFT_WHITE,lightblue); tft.setFreeFont(&Orbitron_Medium_20); tft.setCursor(4, 300, 2); tft.println("TEMP:"); tft.setCursor(4, 352, 2); tft.println("HUM: "); tft.setFreeFont(&Orbitron_Medium_20); tft.setTextColor(TFT_WHITE,TFT_BLACK); tft.setFreeFont(&Orbitron_Medium_20); tft.setCursor(6, 82); tft.println(town); tft.setCursor(4, 420, 2); // tft.setFreeFont(&Orbitron_Light_18); tft.setTextColor(TFT_CYAN,TFT_BLACK); tft.println("IOT BASED INTERNET"); tft.println("WEATHER DATA OUTSIDE"); tft.println("OPEN WEATHER"); // Initialize a NTPClient to get time timeClient.begin(); // Set offset time in seconds to adjust for your timezone, for example: // GMT +1 = 3600 // GMT +8 = 28800 // GMT -1 = -3600 // GMT 0 = 0 timeClient.setTimeOffset(19800); /*EDDITTTTTTTTTTTTTTTTTTTTTTTT */ getData(); drawArrayJpeg(Earth, sizeof(Earth), 160, 290); delay(500); } int i=0; String tt=""; int count=0; void animation(){ // The image is 300 x 300 pixels so we do some sums to position image in the middle of the screen! // Doing this by reading the image width and height from the jpeg info is left as an exercise! int x = (tft.width() - 300) / 2 - 1; int y = (tft.height() - 300) / 2 - 1; drawArrayJpeg(Frames00, sizeof(Frames00), 0, 88); drawArrayJpeg(Frames04, sizeof(Frames04), 0, 88); drawArrayJpeg(Frames08, sizeof(Frames08), 0, 88); drawArrayJpeg(Frames12, sizeof(Frames12), 0, 88); drawArrayJpeg(Frames16, sizeof(Frames16), 0, 88); drawArrayJpeg(Frames20, sizeof(Frames20), 0, 88); drawArrayJpeg(Frames24, sizeof(Frames24), 0, 88); drawArrayJpeg(Frames28, sizeof(Frames28), 0, 88); drawArrayJpeg(Frames32, sizeof(Frames32), 0, 88); drawArrayJpeg(Frames36, sizeof(Frames36), 0, 88); drawArrayJpeg(Frames40, sizeof(Frames40), 0, 88); drawArrayJpeg(Frames44, sizeof(Frames44), 0, 88); } void loop() { if(count==0) getData(); count++; if(count>200) count=0; tft.fillRect(1,302,62,30,darkred); tft.setFreeFont(&Orbitron_Light_32); tft.setCursor(2, 329); tft.println(tmp.substring(0,3)); tft.fillRect(1,356,88,30,darkred); tft.setFreeFont(&Orbitron_Light_32); tft.setCursor(2, 383); tft.println(hum+"%"); tft.setTextColor(TFT_ORANGE,TFT_BLACK); tft.setTextFont(2); tft.setCursor(6, 44); tft.println(dayStamp); tft.setTextColor(TFT_WHITE,TFT_BLACK); while(!timeClient.update()) { timeClient.forceUpdate(); } // The formattedDate comes with the following format: // 2018-05-28T16:00:13Z // We need to extract date and time formattedDate = timeClient.getFormattedDate(); Serial.println(formattedDate); int splitT = formattedDate.indexOf("T"); dayStamp = formattedDate.substring(0, splitT); timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1); tft.setFreeFont(&Orbitron_Light_32); String current=timeStamp.substring(0,5); if(current!=tt) { tft.fillRect(3,8,120,30,TFT_BLACK); tft.setCursor(5, 34); tft.println(timeStamp.substring(0,5)); tt=timeStamp.substring(0,5); } delay(80); animation(); } void getData() { tft.fillRect(1,170,64,20,TFT_BLACK); tft.fillRect(1,210,64,20,TFT_BLACK); if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status HTTPClient http; http.begin(endpoint + key); //Specify the URL int httpCode = http.GET(); //Make the request if (httpCode > 0) { //Check for the returning code payload = http.getString(); // Serial.println(httpCode); Serial.println(payload); } else { Serial.println("Error on HTTP request"); } http.end(); //Free the resources } char inp[1000]; payload.toCharArray(inp,1000); deserializeJson(doc,inp); String tmp2 = doc["main"]["temp"]; String hum2 = doc["main"]["humidity"]; String town2 = doc["name"]; tmp=tmp2; hum=hum2; Serial.println("Temperature"+String(tmp)); Serial.println("Humidity"+hum); Serial.println(town); } //#################################################################################################### // Draw a JPEG on the TFT pulled from a program memory array //#################################################################################################### void drawArrayJpeg(const uint8_t arrayname[], uint32_t array_size, int xpos, int ypos) { int x = xpos; int y = ypos; JpegDec.decodeArray(arrayname, array_size); renderJPEG(x, y); Serial.println("#########################"); } //#################################################################################################### // Draw a JPEG on the TFT, images will be cropped on the right/bottom sides if they do not fit //#################################################################################################### // This function assumes xpos,ypos is a valid screen coordinate. For convenience images that do not // fit totally on the screen are cropped to the nearest MCU size and may leave right/bottom borders. void renderJPEG(int xpos, int ypos) { // retrieve infomration about the image uint16_t *pImg; uint16_t mcu_w = JpegDec.MCUWidth; uint16_t mcu_h = JpegDec.MCUHeight; uint32_t max_x = JpegDec.width; uint32_t max_y = JpegDec.height; // Jpeg images are draw as a set of image block (tiles) called Minimum Coding Units (MCUs) // Typically these MCUs are 16x16 pixel blocks // Determine the width and height of the right and bottom edge image blocks uint32_t min_w = minimum(mcu_w, max_x % mcu_w); uint32_t min_h = minimum(mcu_h, max_y % mcu_h); // save the current image block size uint32_t win_w = mcu_w; uint32_t win_h = mcu_h; // record the current time so we can measure how long it takes to draw an image uint32_t drawTime = millis(); // save the coordinate of the right and bottom edges to assist image cropping // to the screen size max_x += xpos; max_y += ypos; // read each MCU block until there are no more while (JpegDec.read()) { // save a pointer to the image block pImg = JpegDec.pImage ; // calculate where the image block should be drawn on the screen int mcu_x = JpegDec.MCUx * mcu_w + xpos; // Calculate coordinates of top left corner of current MCU int mcu_y = JpegDec.MCUy * mcu_h + ypos; // check if the image block size needs to be changed for the right edge if (mcu_x + mcu_w <= max_x) win_w = mcu_w; else win_w = min_w; // check if the image block size needs to be changed for the bottom edge if (mcu_y + mcu_h <= max_y) win_h = mcu_h; else win_h = min_h; // copy pixels into a contiguous block if (win_w != mcu_w) { uint16_t *cImg; int p = 0; cImg = pImg + win_w; for (int h = 1; h < win_h; h++) { p += mcu_w; for (int w = 0; w < win_w; w++) { *cImg = *(pImg + w + p); cImg++; } } } // calculate how many pixels must be drawn uint32_t mcu_pixels = win_w * win_h; tft.startWrite(); // draw image MCU block only if it will fit on the screen if (( mcu_x + win_w ) <= tft.width() && ( mcu_y + win_h ) <= tft.height()) { // Now set a MCU bounding window on the TFT to push pixels into (x, y, x + width - 1, y + height - 1) tft.setAddrWindow(mcu_x, mcu_y, win_w, win_h); // Write all MCU pixels to the TFT window while (mcu_pixels--) { // Push each pixel to the TFT MCU area tft.pushColor(*pImg++); } } else if ( (mcu_y + win_h) >= tft.height()) JpegDec.abort(); // Image has run off bottom of screen so abort decoding tft.endWrite(); } // calculate how long it took to draw the image drawTime = millis() - drawTime; // print the results to the serial port Serial.print(F( "Total render time was : ")); Serial.print(drawTime); Serial.println(F(" ms")); Serial.println(F("")); } Subscribe and Download c ode After a successful upload, open the Serial Monitor at a baud rate of 115200. Press the “ EN/RST ” button on the ESP32 board. Demo: Subscribe and Download c ode
- ESP32 DHT Weather Monitor with 3.5inch TFT touch Display
In this tutorial, I 'll Published an ESP32 based webserver to display the temperature and humidity values from the DHT11 sensor. ESP32 board will read the temperature and humidity data from the DHT11 sensor and display it on the Webpage and 3.5inch TFT Display. The 3.5″ TFT Touch Screen Display uses an ILI9488 TFT LCD Driver. The screen resolution is 320×480. Components Required ESP-32 Module (38Pin) DHT11 Sensor Module 3.5 inch TFT LCD Display Module SPI Interface 320x480 with Touch Screen Jumper Wires Circuit Diagram ESP32 Development Board WiFi+Bluetooth 38 Pin ESP32 Development board is based on the ESP WROOM32 WIFI + BLE Module.It’s a low-footprint, minimal system development board powered by the latest ESP-WROOM-32 module and can be easily inserted into a solderless breadboard. It contains the entire basic support circuitry for the ESP-WROOM-32, including the USB-UART bridge, reset- and boot-mode buttons, LDO regulator and a micro-USB connector. Every important GPIO is available to the developer. ESP32 Development Board Feature: ESP32 is already integrated antenna and RF balun,power amplifier,low-noise amplifiers,filters,and power management module. This board is used with 2.4 GHz dual-mode Wi-Fi and Bluetooth chips by TSMC 40nm low power technology,power and RF properties best,which is safe,reliable,and scalable to a variety of applications. Strong function with support LWIP protocol,Freertos. Supporting three modes:AP,STA,and AP+STA. Supporting Lua program,easily to develop. 3.5 inch TFT LCD Display Module SPI Interface 320x480 with Touch Screen This TFT display is big bright and colorful! 480×320 pixels with individual RGB pixel control, this has way more resolution than a black and white 128×64 display. As a bonus, this display has a resistive touch screen attached to it already, so you can detect finger presses anywhere on the screen. This display has a controller built into it with RAM buffering so that almost no work is done by the microcontroller. This 3.5-inch SPI Touch Screen Module is wrapped up into an easy-to-use breakout board, with SPI connections on one end. If you’re going with SPI mode, you can also take advantage of the onboard MicroSD card socket to display images. The 3.5-inch display doesn't have a built-in level shifter, so it's advised to use only 3.3v. Using a node MCU would be more suitable cause it provides only 3.3v. if you are using a 5v microcontroller like the Arduino UNO, MEGA, Using a level shifter would give you the appropriate voltage needed to operate the LCD without damaging it. Specifications: 3.5-inch color screen,support 65K color display,display rich colors Touch: Resistive Display Size: 3.5 inch Operating Voltage (V): 3.3 to 5V SPI Signal Voltage (V): 3.3 to 5V Display Driver IC: ILI9488 Touch Driver IC: Color Depth: 262K/65K Resolution (pixels): 320 x 480 Using the SPI serial bus, it only takes a few IOs to illuminate the display Easy to expand the experiment with SD card slot DATA SHEET Download 3.5 inch TFT LCD SPI Module Manual Download Installing the library To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. Download TFT Library , we need to use this library for TFT touch display Download DHT Library , we need to use this library for Temperature sensor. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After Arduino IDE installed, there is no package to support ESP32-S2, we need to install the ESP32 package in Arduino IDE to continue. Select “File>Preferences>settings>Additional Boards Manager URLs” to fill the link: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json arduino code Subscribe and Download code #define RED2RED 0 #define GREEN2GREEN 1 #define BLUE2BLUE 2 #define BLUE2RED 3 #define GREEN2RED 4 #define RED2GREEN 5 #define TFT_GREY 0x2104 // Dark grey 16 bit colour #include // Hardware-specific library #include TFT_eSPI tft = TFT_eSPI(); // Invoke custom library with default width and height uint32_t runTime = -99999; // time for next update int reading = 0; // Value to be displayed int reading2 = 0; // Value to be displayed int d = 0; // Variable used for the sinewave test waveform bool range_error = 0; int8_t ramp = 1; #include const char* ssid = "TP-Link_3200"; // Your ssid const char* password = "95001121379884265554"; // Your Password char status; WiFiServer server(80); #include #define DHT_SENSOR_PIN 12 // ESP32 pin connected to DHT11 sensor #define DHT_SENSOR_TYPE DHT11 DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE); void setup(void) { tft.begin(); Serial.begin(9600); dht_sensor.begin(); // initialize the DHT sensor tft.setRotation(1); tft.fillScreen(TFT_WHITE); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi is connected"); server.begin(); Serial.println("Server started"); Serial.println(WiFi.localIP()); delay(5000); } void loop() { if (millis() - runTime >= 0L) { // Execute every TBD ms runTime = millis(); // Test with a slowly changing value from a Sine function //d += 4; if (d >= 360) d = 0; // Set the the position, gap between meters, and inner radius of the meters int xpos = 0, ypos = 5, gap = 4, radius = 52; // Draw meter and get back x position of next meter // Test with Sine wave function, normally reading will be from a sensor //reading = 250 + 250 * sineWave(d+0); //xpos = gap + ringMeter(reading, 0, 500, xpos, ypos, radius, "mA", GREEN2RED); // Draw analogue meter //reading = 20 + 30 * sineWave(d+60); //xpos = gap + ringMeter(reading, -10, 50, xpos, ypos, radius, "degC", BLUE2RED); // Draw analogue meter //reading = 50 + 50 * sineWave(d + 120); //ringMeter(reading, 0, 100, xpos, ypos, radius, "%RH", BLUE2BLUE); // Draw analogue meter // Draw two more larger meters //xpos = 20, ypos = 115, gap = 24, radius = 64; //reading = 1000 + 150 * sineWave(d + 90); //xpos = gap + ringMeter(reading, 850, 1150, xpos, ypos, radius, "mb", BLUE2RED); // Draw analogue meter //reading = 15 + 15 * sineWave(d + 150); //xpos = gap + ringMeter(reading, 0, 30, xpos, ypos, radius, "Volts", GREEN2GREEN); // Draw analogue meter // read humidity float humi = dht_sensor.readHumidity(); // read temperature in Celsius float tempC = dht_sensor.readTemperature(); // read temperature in Fahrenheit float tempF = dht_sensor.readTemperature(true); // check whether the reading is successful or not if ( isnan(tempC) || isnan(tempF) || isnan(humi)) { Serial.println("Failed to read from DHT sensor!"); } else { Serial.print("Humidity: "); Serial.print(humi); Serial.print("%"); Serial.print(" | "); Serial.print("Temperature: "); Serial.print(tempC); Serial.print("°C ~ "); Serial.print(tempF); Serial.println("°F"); } // Draw a large meter xpos = 20, ypos = 30, gap = 2, radius = 100; // reading +=(ramp); // if (reading>98) ramp = -1; // if (reading<0) ramp = 1; reading = tempC; // Comment out above meters, then uncomment the next line to show large meter ringMeter(reading,0,100, xpos,ypos,radius,"°C",GREEN2GREEN); // Draw analogue meter if (reading<0) delay(500); tft.setCursor(10, 250, 4); // Set the font colour to be white with a black background, set text size multiplier to 1 tft.setTextColor(TFT_BLACK,TFT_WHITE); tft.setTextSize(1); // We can now plot text on screen using the "print" class tft.drawString("`", 101, 186, 4); // prints ° tft.print("Temperature:"); tft.print(tempC); tft.print(" "); // Draw a large meter xpos = 245, ypos = 30, gap = 2, radius = 100; // reading +=(ramp); // if (reading>98) ramp = -1; // if (reading<0) ramp = 1; reading2 = humi; // Comment out above meters, then uncomment the next line to show large meter ringMeter2(reading2,0,100, xpos,ypos,radius," %h",RED2RED); // Draw analogue meter if (reading2<0) delay(500); tft.setCursor(265, 250, 4); // Set the font colour to be white with a black background, set text size multiplier to 1 tft.setTextColor(TFT_BLACK,TFT_WHITE); tft.setTextSize(1); // We can now plot text on screen using the "print" class // tft.drawString("`", 101, 186, 4); // prints ° tft.print("Humidity:"); tft.print(humi); tft.print(" "); } // read humidity float humi = dht_sensor.readHumidity(); // read temperature in Celsius float tempC = dht_sensor.readTemperature(); WiFiClient client = server.available(); client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response client.println("Refresh: 10"); // update the page after 10 sec client.println(); client.println(""); client.println(""); client.println(""); client.println(""); client.println(""); client.println(""); client.println(""); client.println("ESP32 Based Temperature & Humidity Data"); client.println(""); client.println("Temperature:"); client.println(""); client.print(tempC); client.println("°C"); client.println(""); client.println(""); client.println("Humidity:"); client.println(""); client.print(humi); client.println("%"); client.println(""); client.println(""); client.println(""); client.println(""); } // ######################################################################### // Draw the meter on the screen, returns x coord of righthand side // ######################################################################### int ringMeter(int value, int vmin, int vmax, int x, int y, int r, const char *units, byte scheme) { // Minimum value of r is about 52 before value text intrudes on ring // drawing the text first is an option x += r; y += r; // Calculate coords of centre of ring int w = r / 3; // Width of outer ring is 1/4 of radius int angle = 150; // Half the sweep angle of meter (300 degrees) int v = map(value, vmin, vmax, -angle, angle); // Map the value to an angle v //int v = map(value, vmin, vmax, -angle, angle); // Map the value to an angle v byte seg = 3; // Segments are 3 degrees wide = 100 segments for 300 degrees byte inc = 3; // Draw segments every 3 degrees, increase to 6 for segmented ring // Variable to save "value" text colour from scheme and set default int colour = TFT_BLACK; // Draw colour blocks every inc degrees for (int i = -angle+inc/2; i < angle-inc/2; i += inc) { // Calculate pair of coordinates for segment start float sx = cos((i - 90) * 0.0174532925); float sy = sin((i - 90) * 0.0174532925); uint16_t x0 = sx * (r - w) + x; uint16_t y0 = sy * (r - w) + y; uint16_t x1 = sx * r + x; uint16_t y1 = sy * r + y; // Calculate pair of coordinates for segment end float sx2 = cos((i + seg - 90) * 0.0174532925); float sy2 = sin((i + seg - 90) * 0.0174532925); int x2 = sx2 * (r - w) + x; int y2 = sy2 * (r - w) + y; int x3 = sx2 * r + x; int y3 = sy2 * r + y; if (i < v) { // Fill in coloured segments with 2 triangles switch (scheme) { case 0: colour = TFT_RED; break; // Fixed colour case 1: colour = TFT_GREEN; break; // Fixed colour case 2: colour = TFT_BLUE; break; // Fixed colour default: colour = TFT_YELLOW; break; // Fixed colour } tft.fillTriangle(x0, y0, x1, y1, x2, y2, colour); tft.fillTriangle(x1, y1, x2, y2, x3, y3, colour); //text_colour = colour; // Save the last colour drawn } else // Fill in blank segments { tft.fillTriangle(x0, y0, x1, y1, x2, y2, TFT_GREY); tft.fillTriangle(x1, y1, x2, y2, x3, y3, TFT_GREY); } } // Convert value to a string char buf[10]; byte len = 3; if (value > 999) len = 5; dtostrf(value, len, 0, buf); buf[len] = ' '; buf[len+1] = 0; // Add blanking space and terminator, helps to centre text too! // Set the text colour to default tft.setTextSize(1); tft.setTextColor(TFT_WHITE, TFT_BLACK); // Uncomment next line to set the text colour to the last segment value! tft.setTextColor(colour, TFT_WHITE); tft.setTextDatum(MC_DATUM); // Print value, if the meter is large then use big font 8, othewise use 4 if (r > 84) { tft.setTextPadding(25*3); // Allow for 3 digits each 55 pixels wide tft.drawString(buf, x, y, 6); // Value in middle } else { tft.setTextPadding(3 * 7); // Allow for 3 digits each 14 pixels wide tft.drawString(buf, x, y, 6); // Value in middle } tft.setTextSize(1); tft.setTextPadding(0); // Print units, if the meter is large then use big font 4, othewise use 2 tft.setTextColor(TFT_BLACK,TFT_WHITE); if (r > 84) tft.drawString(units, x, y + 60, 4); // Units display else tft.drawString(units, x, y + 15, 2); // Units display // Calculate and return right hand side x coordinate return x + r; } // ######################################################################### // Draw the meter on the screen, returns x coord of righthand side // ######################################################################### int ringMeter2(int value, int vmin, int vmax, int x, int y, int r, const char *units, byte scheme) { // Minimum value of r is about 52 before value text intrudes on ring // drawing the text first is an option x += r; y += r; // Calculate coords of centre of ring int w = r / 3; // Width of outer ring is 1/4 of radius int angle = 150; // Half the sweep angle of meter (300 degrees) int v = map(value, vmin, vmax, -angle, angle); // Map the value to an angle v //int v = map(value, vmin, vmax, -angle, angle); // Map the value to an angle v byte seg = 3; // Segments are 3 degrees wide = 100 segments for 300 degrees byte inc = 3; // Draw segments every 3 degrees, increase to 6 for segmented ring // Variable to save "value" text colour from scheme and set default int colour = TFT_BLACK; // Draw colour blocks every inc degrees for (int i = -angle+inc/2; i < angle-inc/2; i += inc) { // Calculate pair of coordinates for segment start float sx = cos((i - 90) * 0.0174532925); float sy = sin((i - 90) * 0.0174532925); uint16_t x0 = sx * (r - w) + x; uint16_t y0 = sy * (r - w) + y; uint16_t x1 = sx * r + x; uint16_t y1 = sy * r + y; // Calculate pair of coordinates for segment end float sx2 = cos((i + seg - 90) * 0.0174532925); float sy2 = sin((i + seg - 90) * 0.0174532925); int x2 = sx2 * (r - w) + x; int y2 = sy2 * (r - w) + y; int x3 = sx2 * r + x; int y3 = sy2 * r + y; if (i < v) { // Fill in coloured segments with 2 triangles switch (scheme) { case 0: colour = TFT_RED; break; // Fixed colour case 1: colour = TFT_GREEN; break; // Fixed colour case 2: colour = TFT_BLUE; break; // Fixed colour default: colour = TFT_YELLOW; break; // Fixed colour } tft.fillTriangle(x0, y0, x1, y1, x2, y2, colour); tft.fillTriangle(x1, y1, x2, y2, x3, y3, colour); //text_colour = colour; // Save the last colour drawn } else // Fill in blank segments { tft.fillTriangle(x0, y0, x1, y1, x2, y2, TFT_GREY); tft.fillTriangle(x1, y1, x2, y2, x3, y3, TFT_GREY); } } // Convert value to a string char buf[10]; byte len = 3; if (value > 999) len = 5; dtostrf(value, len, 0, buf); buf[len] = ' '; buf[len+1] = 0; // Add blanking space and terminator, helps to centre text too! // Set the text colour to default tft.setTextSize(1); tft.setTextColor(TFT_BLACK,TFT_WHITE); // Uncomment next line to set the text colour to the last segment value! tft.setTextColor(colour, TFT_WHITE); tft.setTextDatum(MC_DATUM); // Print value, if the meter is large then use big font 8, othewise use 4 if (r > 84) { tft.setTextPadding(25*3); // Allow for 3 digits each 55 pixels wide tft.drawString(buf, x, y, 6); // Value in middle } else { tft.setTextPadding(3 * 7); // Allow for 3 digits each 14 pixels wide tft.drawString(buf, x, y, 6); // Value in middle } tft.setTextSize(1); tft.setTextPadding(0); // Print units, if the meter is large then use big font 4, othewise use 2 tft.setTextColor(TFT_BLACK,TFT_WHITE); if (r > 84) tft.drawString(units, x, y + 60, 4); // Units display else tft.drawString(units, x, y + 15, 2); // Units display // Calculate and return right hand side x coordinate return x + r; } // ######################################################################### // Return a value in range -1 to +1 for a given phase angle in degrees // ######################################################################### float sineWave(int phase) { return sin(phase * 0.0174532925); } //==================================================================================== // This is the function to draw the icon stored as an array in program memory (FLASH) //==================================================================================== // To speed up rendering we use a 64 pixel buffer #define BUFF_SIZE 64 // Draw array "icon" of defined width and height at coordinate x,y // Maximum icon size is 255x255 pixels to avoid integer overflow void drawIcon(const unsigned short* icon, int16_t x, int16_t y, int8_t width, int8_t height) { uint16_t pix_buffer[BUFF_SIZE]; // Pixel buffer (16 bits per pixel) tft.startWrite(); // Set up a window the right size to stream pixels into tft.setAddrWindow(x, y, width, height); // Work out the number whole buffers to send uint16_t nb = ((uint16_t)height * width) / BUFF_SIZE; // Fill and send "nb" buffers to TFT for (int i = 0; i < nb; i++) { for (int j = 0; j < BUFF_SIZE; j++) { pix_buffer[j] = pgm_read_word(&icon[i * BUFF_SIZE + j]); } tft.pushColors(pix_buffer, BUFF_SIZE); } // Work out number of pixels not yet sent uint16_t np = ((uint16_t)height * width) % BUFF_SIZE; // Send any partial buffer left over if (np) { for (int i = 0; i < np; i++) pix_buffer[i] = pgm_read_word(&icon[nb * BUFF_SIZE + i]); tft.pushColors(pix_buffer, np); } tft.endWrite(); } Subscribe and Download code After a successful upload, open the Serial Monitor at a baud rate of 9600. Press the “ EN/RST ” button on the ESP32 board and see the IP address in serial monitor. After that Open the web browser and enter the IP address path for DHT11 Weather data. Demo: Subscribe and Download code
- ESP32 Interface Simcom A7670C 4G LTE AT Command, Call, Read SMS and Send SMS
In this tutorial, you'll learn how to use Simcom 7670C 4G LTE Module, An Integrating the SIM7670C 4G LTE module with an ESP32 and using AT commands to make calls and send / receive SMS is a powerful way to leverage cellular connectivity in your projects. Here’s a step-by-step guide to get you started with this:. Circuit Diagram: Components Required: ESP32 Development Board SIM7670C 4G LTE Module SIM Card with Data Plan Connecting Wires Power Supply (if needed) SIMCom7670C The SIM A7670C is a compact and robust development board that integrates the SIMCom A7670C module, a high-performance 4G LTE Cat-1 module with fallback to 2G networks. This board is designed to provide reliable and efficient communication solutions for a wide range of IoT applications, including smart meters, asset tracking, and remote monitoring systems. The module support GSM, LTE-TDD and LTE-FDD. Users can choose the module according to the wireless network configuration. The supported radio frequency bands are described in the data sheet. Datasheet : https://nostris.ee/pdf/A7670%20Series%20Hardware%20Design_V1.00.pdf Pin Assignment overview All functions of the module will be provided through 88 pads that will be connected to the customers’ platform. The following Figure is a high-level view of the pin assignment of the module. Wiring the SIM7670C with ESP32 Connect the SIM7670C to ESP32: SIM7670C TX -> ESP32 RX (e.g., GPIO 27) SIM7670C RX -> ESP32 TX (e.g., GPIO 24) SIM7670C PowerKey -> ESP32 TX (e.g., GPIO 4) SIM7670C GND -> ESP32 GND SIM7670C VCC -> ESP32 3.3V or External 4G Power Supply (Check the module’s voltage requirements. Some modules need 4V to 5V, so use an appropriate power supply if needed.) Ensure proper power supply to avoid potential damage to the module or unstable operation. To start developing with the SIM A7670C, you’ll need a few essential components and tools: SIM A7670C Development Board: The main development board with the SIMCom A7670C module. Microcontroller or Development Platform: Such as Arduino, Raspberry Pi, or any other platform with UART or USB interface. SIM Card: A SIM card with an active data plan to enable network connectivity. Setup Arduino IDE for ESP32 Install the ESP32 Board Package: Open Arduino IDE. Go to File > Preferences. Add the following URL to the "Additional Board Manager URLs" field: https://dl.espressif.com/dl/package_esp32_index.json. Go to Tools > Board > Boards Manager, search for ESP32, and install it. Install the Required Libraries: Generally, no additional libraries are required for basic AT command communication. However, if you need specific libraries for advanced features, you can install them via the Library Manager. Tiny GSM Arduino library for GSM modules, After installed the libraries, restart your Arduino IDE. AT COMMAND Arduino Code #define TINY_GSM_MODEM_SIM7600 // SIM7600 AT instruction is compatible with A7670 #define SerialAT Serial1 #define SerialMon Serial #define TINY_GSM_USE_GPRS true #include #define RXD2 27 #define TXD2 26 #define powerPin 4 char a, b; const char apn[] = ""; //APN automatically detects for 4G SIM, NO NEED TO ENTER, KEEP IT BLANK #ifdef DUMP_AT_COMMANDS #include StreamDebugger debugger(SerialAT, SerialMon); TinyGsm modem(debugger); #else TinyGsm modem(SerialAT); #endif TinyGsmClient client(modem); void setup() { Serial.begin(115200); pinMode(powerPin, OUTPUT); digitalWrite(powerPin, LOW); delay(100); digitalWrite(powerPin, HIGH); delay(1000); digitalWrite(powerPin, LOW); Serial.println("\nconfiguring A7670C Module. Kindly wait"); delay(10000); SerialAT.begin(115200, SERIAL_8N1, RXD2, TXD2); // Restart takes quite some time // To skip it, call init() instead of restart() DBG("Initializing modem..."); if (!modem.init()) { DBG("Failed to restart modem, delaying 10s and retrying"); return; } // Restart takes quite some time // To skip it, call init() instead of restart() DBG("Initializing modem..."); if (!modem.restart()) { DBG("Failed to restart modem, delaying 10s and retrying"); return; } String name = modem.getModemName(); DBG("Modem Name:", name); String modemInfo = modem.getModemInfo(); DBG("Modem Info:", modemInfo); Serial.println("Waiting for network..."); if (!modem.waitForNetwork()) { Serial.println(" fail"); delay(10000); return; } Serial.println(" success"); if (modem.isNetworkConnected()) { Serial.println("Network connected"); } // GPRS connection parameters are usually set after network registration Serial.print(F("Connecting to ")); Serial.print(apn); if (!modem.gprsConnect(apn)) { Serial.println(" fail"); delay(10000); return; } Serial.println(" success"); if (modem.isGprsConnected()) { Serial.println("LTE module connected"); } Serial.println("Enter Standard AT commands like AT, AT+CPIN?, AT+CCLK?, etc."); Serial.println("SELECT SERIAL PORT MONITOR AS \"BOTH NL & CR\" TO VIEW COMMAND RESPONSE CORRECTLY IF YOU ARE USING ARDUINO IDE"); Serial.println("Refer A7600 series datasheet for entire list of commands"); Serial.println("Understand the AT Commands properly"); Serial.println("Incorrect AT commands can corrupt the 4G module memory!!!"); // MQTT Broker setup //mqtt.setServer(broker, 1883); //mqtt.setCallback(callback); } void loop() { if (Serial.available() > 0) // read AT commands from user Serial port and send to the Module { a = Serial.read(); SerialAT.write(a); } if (SerialAT.available() > 0) //read Response commands from module and send to user Serial Port { b = SerialAT.read(); Serial.write(b); } } After a successful upload, open the Serial Monitor at a baud rate of 115200. Press the “EN/RST” button on the ESP32 board. Subscribe and Download code. Basic AT Command Testing Upload Basic Code to ESP32: Open the Arduino IDE and load the following sketch to test AT commands via the Serial Monitor. Upload this code to the ESP32. Open the Serial Monitor (set to 115200 baud rate) to interact with the SIM7670C module. Test Basic AT Commands: In the Serial Monitor, type AT and press Enter. You should receive an OK response if the module is correctly connected. A7670 Module Connect AT Command Manual : https://www.ktron.in/wp-content/uploads/2023/03/A76XX-Series_AT_Command_Manual_V1.06-4.pdf AT COMMAND Call/ Send SMS Arduino Code #define RXD2 27 #define TXD2 26 #define powerPin 4 int rx = -1; #define SerialAT Serial1 String rxString; int _timeout; String _buffer; String number = "+919500950137"; // send/call replace mobile number enter here void setup() { pinMode(powerPin, OUTPUT); digitalWrite(powerPin, LOW); Serial.begin(115200); delay(100); SerialAT.begin(115200, SERIAL_8N1, RXD2, TXD2); delay(10000); Serial.println("Modem Reset, please wait"); SerialAT.println("AT+CRESET"); delay(1000); SerialAT.println("AT+CRESET"); delay(20000); // WAITING FOR SOME TIME TO CONFIGURE MODEM SerialAT.flush(); Serial.println("Echo Off"); SerialAT.println("ATE0"); //120s delay(1000); SerialAT.println("ATE0"); //120s rxString = SerialAT.readString(); Serial.print("Got: "); Serial.println(rxString); rx = rxString.indexOf("OK"); if (rx != -1) Serial.println("Modem Ready"); delay(1000); Serial.println("SIM card check"); SerialAT.println("AT+CPIN?"); //9s rxString = SerialAT.readString(); Serial.print("Got: "); Serial.println(rxString); rx = rxString.indexOf("+CPIN: READY"); if (rx != -1) Serial.println("SIM Card Ready"); delay(1000); Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call"); } void loop() { if (Serial.available() > 0) switch (Serial.read()) { case 's': SendMessage(); //YOU CAN SEND MESSAGE FROM SIM TO THE MENTIONED PHONE NUMBER break; case 'r': RecieveMessage(); // RECEIVE MESSAGE FROM THE MENTIONED PHONE NUMBER TO SIM break; case 'c': callNumber(); // CALL break; } if (SerialAT.available() > 0) Serial.write(SerialAT.read()); } void SendMessage() { //Serial.println ("Sending Message"); SerialAT.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode delay(1000); //Serial.println ("Set SMS Number"); SerialAT.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message delay(1000); String SMS = "MESSAGE FROM ESP32 4G LTE MODULE"; //replace message here SerialAT.println(SMS); delay(100); SerialAT.println((char)26);// ASCII code of CTRL+Z delay(1000); _buffer = _readSerial(); } void RecieveMessage() { Serial.println ("AT7670C Read an SMS"); delay (1000); SerialAT.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS delay(1000); Serial.write ("Unread Message done"); } String _readSerial() { _timeout = 0; while (!SerialAT.available() && _timeout < 12000 ) { delay(13); _timeout++; } if (SerialAT.available()) { return SerialAT.readString(); } } void callNumber() { SerialAT.print (F("ATD")); SerialAT.print (number); SerialAT.print (F(";\r\n")); _buffer = _readSerial(); Serial.println(_buffer); } After a successful upload, open the Serial Monitor at a baud rate of 115200. Press the “EN/RST” button on the ESP32 board. Subscribe and Download code. Making Calls and Sending / Receive SMS Here’s how you can extend the functionality to make calls and send SMS. Code to Make Calls and Send / Receive SMS: Replace "+1234567890" with the phone number you want to call or send SMS Upload the Code and Test: Upload the sketch to the ESP32. Open the Serial Monitor to observe the AT commands being sent and the responses from the module. Command "s" - send SMS Command "r" - read SMS Command "c" - call Refer below for serial monitor output: A7670 Modem Check: A7670 Modem Ready AT Command : Read/Send SMS AT Command : To Call AT Command : Receive Call Mobile Log: Network Timeout: Demo: Subscribe and Download code. Subscribe and Download code. Troubleshooting No Response: Check wiring connections and ensure the module is powered correctly. Command Errors: Make sure AT commands are formatted correctly and the module supports them. Module Not Found: Verify the baud rate and serial port settings match those of the SIM7670C. This guide should give you a good starting point for using the SIM7670C with the ESP32 and testing various AT commands. Let me know if you have any specific questions or run into issues!
- ESP32 Rotary Encoder LED Control with 7segment Display
In this tutorial, you'll learn how to control an LED using a rotary encoder and display the status on a Max7912 8-digit 7-segment display with an ESP32. We’ll go through the steps to connect the hardware, write the code, and control the LED based on rotary encoder input. Let's break it down. Circuit Diagram: Components Required: ESP32 Development Board Rotary Encoder Max7912 8-Digit 7-Segment Display LED 220 Ohm Resistor (for LED) Breadboard and Jumper Wires Power Supply (5V or 3.3V depending on your setup) Rotary Encoder The KY-040 rotary encoder is a rotary input device (as in knob) that provides an indication of how much the knob has been rotated AND what direction it is rotating in. It’s a great device for stepper and servo motor control. You could also use it to control devices like digital potentiometers. A rotary encoder has a fixed number of positions per revolution. These positions are easily felt as small “clicks” you turn the encoder. The KY-040 module has thirty of these positions. On one side of the switch there are three pins. They are normally referred to as A, B and C. In the case of the KY-040, they are oriented as shown. Inside the encoder there are two switches. Once switch connects pin A to pin C and the other switch connects pin B to C. In each encoder position, both switches are either opened or closed. Each click causes these switches to change states as follows: If both switches are closed, turning the encoder either clockwise or counterclockwise one position will cause both switches to open. If both switches are open, turning the encoder either clockwise or counterclockwise one position will cause both switches to close. The illustration below is representative of how the switch is constructed. A rotary encoder has a fixed number of positions per revolution. These positions are easily felt as small “clicks” you turn the encoder. The KY-040 module has thirty of these positions. On one side of the switch there are three pins. They are normally referred to as A, B and C. In the case of the KY-040, they are oriented as shown. Inside the encoder there are two switches. Once switch connects pin A to pin C and the other switch connects pin B to C. In each encoder position, both switches are either opened or closed. Each click causes these switches to change states as follows: If both switches are closed, turning the encoder either clockwise or counterclockwise one position will cause both switches to open If both switches are open, turning the encoder either clockwise or counterclockwise one position will cause both switches to close. The illustration below is representative of how the switch is constructed. As you can see, the angular position of the A terminal and the B terminal is such that: Rotating the switch clockwise will cause the switch connecting A and C to change states first. Rotating the switch counterclockwise will cause the switch connecting B and C to change states first. If we were to represent the opening and closing of the switches as wave forms, it would look something like this. Essentially, determining which switch changed states first is how the direction of rotation is determined. If A changed states first, the switch is rotating in a clockwise direction. If B changed states first, the switch is rotating in a counter clockwise direction. . Wiring the Rotary Encoder VCC of the rotary encoder to 3.3V (or 5V if the encoder supports it). GND of the rotary encoder to GND on ESP32. DT (Data) pin of rotary encoder to GPIO 34 on ESP32. CLK (Clock) pin of rotary encoder to GPIO 35 on ESP32. SW (Switch) pin of rotary encoder (optional for additional functionality) to GPIO 32 on ESP32. Max7912 Serially Interfaced, 8-Digit LED Display Driver Refer : https://www.dofbot.com/post/esp32-web-server-with-ds18b20-and-max7912-7segment-display-interface .Wiring the Max7912 Module Max7912 Pinout: VCC (Red) – Connect to 3.3V on the ESP32. GND (Black) – Connect to GND on the ESP32. DIN (Green) – Connect to a GPIO pin on the ESP32 GPIO 25. CS (Blue) – Connect to a GPIO pin on the ESP32 GPIO 26. CLK (Orange) – Connect to a GPIO pin on the ESP32 GPIO 27. LED to ESP32: Anode (long leg) of the LED to GPIO 27 on ESP32. Cathode (short leg) of the LED through a 220 Ohm resistor to GND. Install Required Libraries: Make sure you have the following libraries installed in the Arduino IDE: Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. MAX7219_7Seg_Display for 7egment display driver. After installed the libraries, restart your Arduino IDE. Subscribe and Download code. Arduino Code #include /*DIN CS CLK*/ MAX7219_7Seg_Disp disp(25, 26, 27); // Rotary Encoder Inputs #define CLK 13 #define DT 14 #define SW 12 int currentStateCLK; int lastStateCLK; unsigned long lastButtonPress = 0; int leds [] = {4, 0, 2, 15}; unsigned int menu = 0; int ledStatus[5] = {0}; int timer = 1000; void setup() { Serial.begin(9600); disp.Initialize(15); /*initialize MAX7219 & set brightness level-max 15*/ disp.Clear(); /*clear all 8 digits of display*/ // Set encoder pins as input pinMode(CLK, INPUT); pinMode(DT, INPUT); pinMode(SW, INPUT_PULLUP); for (int i = 0; i < 4; i++) { pinMode(leds[i], OUTPUT); } menu = 0; updateMenu(); } void loop() { currentStateCLK = digitalRead(CLK); if (currentStateCLK != lastStateCLK && currentStateCLK == 1) { if (digitalRead(DT) != currentStateCLK) { menu --; updateMenu(); } else { menu ++; updateMenu(); } } lastStateCLK = currentStateCLK; int btnState = digitalRead(SW); if (btnState == LOW) { if (millis() - lastButtonPress > 50) { executeAction(); updateMenu(); } lastButtonPress = millis(); } delay(1); } void MatrixSegment(){ disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Char (5, ' '); disp.Char (4, 'C'); disp.Char (3, 'N'); disp.Char (2, 'T'); disp.Char (1, 'L'); } void updateMenu() { switch (menu) { case 0: menu = 1; break; case 1: MatrixSegment(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '1'); break; case 2: MatrixSegment(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '2'); break; case 3: MatrixSegment(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '3'); break; case 4: MatrixSegment(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '4'); break; case 5: menu = 4; break; } } void executeAction() { switch (menu) { case 1: action1(); break; case 2: action2(); break; case 3: action3(); break; case 4: action4(); break; } } void action1() { if (ledStatus[menu] != 0) { ledStatus[menu] = 0; disp.Clear(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '1'); disp.Char (4, ' '); disp.Char (3, 'O'); disp.Char (2, 'F'); disp.Char (1, 'F'); digitalWrite(leds[menu - 1], ledStatus[menu]); delay(timer); } else { ledStatus[menu] = 1; disp.Clear(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '2'); disp.Char (4, ' '); disp.Char (3, 'O'); disp.Char (2, 'N'); disp.Char (1, ' '); digitalWrite(leds[menu - 1], ledStatus[menu]); delay(timer); } } void action2() { if (ledStatus[menu] != 0) { ledStatus[menu] = 0; disp.Clear(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '2'); disp.Char (4, ' '); disp.Char (3, 'O'); disp.Char (2, 'F'); disp.Char (1, 'F'); digitalWrite(leds[menu - 1], ledStatus[menu]); delay(timer); } else { ledStatus[menu] = 1; disp.Clear(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '2'); disp.Char (4, ' '); disp.Char (3, 'O'); disp.Char (2, 'N'); disp.Char (1, ' '); digitalWrite(leds[menu - 1], ledStatus[menu]); delay(timer); } } void action3() { if (ledStatus[menu] != 0) { ledStatus[menu] = 0; disp.Clear(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '3'); disp.Char (4, ' '); disp.Char (3, 'O'); disp.Char (2, 'F'); disp.Char (1, 'F'); digitalWrite(leds[menu - 1], ledStatus[menu]); delay(timer); } else { ledStatus[menu] = 1; disp.Clear(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '3'); disp.Char (4, ' '); disp.Char (3, 'O'); disp.Char (2, 'N'); disp.Char (1, ' '); digitalWrite(leds[menu - 1], ledStatus[menu]); delay(timer); } } void action4() { if (ledStatus[menu] != 0) { ledStatus[menu] = 0; disp.Clear(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '4'); disp.Char (4, ' '); disp.Char (3, 'O'); disp.Char (2, 'F'); disp.Char (1, 'F'); digitalWrite(leds[menu - 1], ledStatus[menu]); delay(timer); } else { ledStatus[menu] = 1; disp.Clear(); disp.Char (8, 'L'); disp.Char (7, 'E'); disp.Char (6, 'D'); disp.Number (5, '4'); disp.Char (4, ' '); disp.Char (3, 'O'); disp.Char (2, 'N'); disp.Char (1, ' '); digitalWrite(leds[menu - 1], ledStatus[menu]); delay(timer); } } After a successful upload, open the Serial Monitor at a baud rate of 115200. Press the “EN/RST” button on the ESP32 board. Explanation of the Code Libraries: The Encoder library reads rotary encoder values, and the MAx7912 library communicates with the Max7912 display. Pin Definitions: The pins for the rotary encoder and Max7912 are defined. Setup: Initializes the display and sets initial values. Loop: Reads the rotary encoder value and updates the LED and display based on changes. Update Display: Shows the current value on the 7-segment display. Testing Upload the code to the ESP32. Rotate the rotary encoder and observe the LED toggling on/off and the 7-segment display updating accordingly. Troubleshooting Ensure all connections are secure and correct. Check if the libraries are correctly installed and included in the sketch. Use Serial Monitor to debug and check encoder values if needed. With this setup, you should be able to control an LED using a rotary encoder and display the state on a Max7912 8-digit 7-segment display using your ESP32. Demo: Subscribe and Download code.
- ESP32 Web Server with DS18B20 and Max7912 7segment display Interface
In this tutorial, we will learn how to create a temperature monitor using the DS18B20 digital temperature sensor, an ESP32 web server, and a MAX7912 8-digit 7-segment display. The ESP32 will be used to host a web server that presents temperature readings directly on a webpage, which can be accessed through any standard web browser. The DS18B20 sensor will provide temperature data, and the MAX7912 will drive an 8-digit 7-segment display. The display will be divided into two 4-digit sections: one for Celsius readings and the other for Fahrenheit readings. Circuit Diagram: Components Required: DS18B20 with Probe - 1 no Resistor 4k7 ohms- 1 no ESP32S Development Board - 1 no Max7912 8digit 7segment module - 1no DS18B20 Refer Project : https://www.dofbot.com/post/temperature-controlled-fan-using-ds18b20-and-arduino The DS18S20 digital thermometer provides 9-bit Celsius temperature measurements and has an alarm function with nonvolatile user-programmable upper and lower trigger points. The DS18S20 communicates over a 1-Wire bus that by definition requires only one data line (and ground) for communication with a central microprocessor. In addition, the DS18S20 can derive power directly from the data line (“parasite power”), eliminating the need for an external power supply. Each DS18S20 has a unique 64-bit serial code, which allows multiple DS18S20s to function on the same 1-Wire bus. Thus, it is simple to use one microprocessor to control many DS18S20s distributed over a large area. Applications that can benefit from this feature include HVAC environmental controls, temperature monitoring systems inside buildings, equipment, or machinery, and process monitoring and control systems. Feature: • Unique 1–Wire TM interface requires only one port pin for communication • Multidrop capability simplifies distributed temperature sensing applications • Requires no external components • Can be powered from data line • Zero standby power required • Measures temperatures from –55°C to +125°C in 0.5°C increments. Fahrenheit equivalent is –67°F to +257°F in 0.9°F increments • Temperature is read as a 9–bit digital value. • Converts temperature to digital word in 200ms (typ.) • User–definable, nonvolatile temperature alarm settings • Alarm search command identifies and addresses devices whose temperature is outside of programmed limits (temperature alarm condition) • Applications include thermostatic controls, industrial systems, consumer products, thermometers, or any thermally sensitive system. Datasheet : https://www.analog.com/media/en/technical-documentation/data-sheets/DS18S20.pdf How to use the DS18B20 Sensor The sensor works with the method of 1-Wire communication. It requires only the data pin connected to the microcontroller with a pull up resistor and the other two pins are used for power as shown below. The pull-up resistor is used to keep the line in high state when the bus is not in use. The temperature value measured by the sensor will be stored in a 2-byte register inside the sensor. This data can be read by the using the 1- wire method by sending in a sequence of data. Wiring the DS18B20 Sensor DS18B20 Pinout: VCC (Red) – Connect to 3.3V on the ESP32. GND (Black) – Connect to GND on the ESP32. DQ (Yellow) – Connect to a GPIO pin on the ESP32 GPIO 13. Pull-up Resistor: Place a 4.7kΩ resistor between the VCC and DQ pins of the DS18B20 . Max7912 Serially Interfaced, 8-Digit LED Display Driver The MAX7219/MAX7221 are compact, serial input/ output common-cathode display drivers that interface microprocessors (μPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays, or 64 individual LEDs. Included on-chip are a BCD code-B decoder, multiplex scan circuitry, segment and digit drivers, and an 8x8 static RAM that stores each digit. Only one external resistor is required to set the segment current for all LEDs. Pin Configuration The MAX7221 is compatible with SPI™, QSPI™, and MICROWIRE™, and has slew-rate-limited segment drivers to reduce EMI. A convenient 4-wire serial interface connects to all common μPs. Individual digits may be addressed and updated without rewriting the entire display. The MAX7219/MAX7221 also allow the user to select code-B decoding or no-decode for each digit. The devices include a 150μA low-power shutdown mode, analog and digital brightness control, a scan-limit register that allows the user to display from 1 to 8 digits, and a test mode that forces all LEDs on. For applications requiring 3V operation or segment blinking, refer to the MAX6951 data sheet. Datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/MAX7219-MAX7221.pdf Features: ● 10MHz Serial Interface ● Individual LED Segment Control ● Decode/No-Decode Digit Selection ● 150μA Low-Power Shutdown (Data Retained) ● Digital and Analog Brightness Control ● Display Blanked on Power-Up ● Drive Common-Cathode LED Display ● Slew-Rate Limited Segment Drivers for Lower EMI (MAX7221) ● SPI, QSPI, MICROWIRE Serial Interface (MAX7221) ● 24-Pin DIP and SO Packages. Application: ● Bar-Graph Displays ● Industrial Controllers ● Panel Meters ● LED Matrix Displays Typical Application Circuit Wiring the Max7912 Module Max7912 Pinout: VCC (Red) – Connect to 3.3V on the ESP32. GND (Black) – Connect to GND on the ESP32. DIN (Green) – Connect to a GPIO pin on the ESP32 GPIO 25. CS (Blue) – Connect to a GPIO pin on the ESP32 GPIO 26. CLK (Orange) – Connect to a GPIO pin on the ESP32 GPIO 27. Install Required Libraries: Make sure you have the following libraries installed in the Arduino IDE: Open your Arduino IDE and go to Sketch > Include Library > Manage Libraries. The Library Manager should open. 1. Type “onewire” in the search box and install the OneWire library by Paul Stoffregen. 2. Then, search for “Dallas” and install the Dallas Temperature library by Miles Burton. 3. ESPAsyncWebServer: For hosting the web server. 4.MAX7219_7Seg_Display for 7egment display driver. After installed the libraries, restart your Arduino IDE. Subscribe and Download code. Arduino Code #ifdef ESP32 #include #include #else #include #include #include #include #include #endif // Replace with your network credentials const char* ssid = "TPLink"; // your Wifi SSID const char* password = "95001121379884265554"; // your wifi password // Create AsyncWebServer object on port 80 AsyncWebServer server(80); #include #include // GPIO where the DS18B20 is connected to const int oneWireBus = 13; //gpio 13 of ESP32 // Setup a oneWire instance to communicate with any OneWire devices OneWire oneWire(oneWireBus); // Pass our oneWire reference to Dallas Temperature sensor DallasTemperature sensors(&oneWire); float tempC, tempF; int tempC_LSD, tempC_MSD, tempC_fraction, tempF_LSD, tempF_MSD, tempF_MSD2, tempF_fraction; String temperatureF = ""; String temperatureC = ""; #include /*DIN CS CLK*/ MAX7219_7Seg_Disp disp(25, 26, 27); //gpio 25,26,27 of ESP32 // Timer variables unsigned long lastTime = 0; unsigned long timerDelay = 1000; String readDSTemperatureC() { // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus sensors.requestTemperatures(); float tempC = sensors.getTempCByIndex(0); if(tempC == -127.00) { Serial.println("Failed to read from DS18B20 sensor"); return "--"; } else { Serial.print("Temperature Celsius: "); Serial.println(tempC); } return String(tempC); } String readDSTemperatureF() { // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus sensors.requestTemperatures(); float tempF = sensors.getTempFByIndex(0); if(int(tempF) == -196){ Serial.println("Failed to read from DS18B20 sensor"); return "--"; } else { Serial.print("Temperature Fahrenheit: "); Serial.println(tempF); } return String(tempF); } const char index_html[] PROGMEM = R"rawliteral( ESP32 Web Server DS18B20 Digital Therometer Temperature: %TEMPERATUREC% °C Temperature: %TEMPERATUREF% °F )rawliteral"; // Replaces placeholder with DS18B20 values String processor(const String& var){ //Serial.println(var); if(var == "TEMPERATUREC"){ return temperatureC; } else if(var == "TEMPERATUREF"){ return temperatureF; } return String(); } void setup() { // Start the Serial Monitor Serial.begin(115200); // Start the DS18B20 sensor sensors.begin(); disp.Initialize(15); /*initialize MAX7219 & set brightness level 0 to 15*/ disp.Clear(); /*clear all 8 digits of display*/ delay(1000); temperatureC = readDSTemperatureC(); temperatureF = readDSTemperatureF(); // Connect to Wi-Fi WiFi.begin(ssid, password); Serial.println("Connecting to WiFi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); // Print ESP Local IP Address Serial.println(WiFi.localIP()); // Route for root / web page server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/html", index_html, processor); }); server.on("/temperaturec", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/plain", temperatureC.c_str()); }); server.on("/temperaturef", HTTP_GET, [](AsyncWebServerRequest *request){ request->send_P(200, "text/plain", temperatureF.c_str()); }); // Start server server.begin(); } void loop() { if ((millis() - lastTime) > timerDelay) { temperatureC = readDSTemperatureC(); temperatureF = readDSTemperatureF(); lastTime = millis(); } sensors.requestTemperatures(); float tempC = sensors.getTempCByIndex(0); float tempF = sensors.getTempFByIndex(0); tempC_MSD = int(tempC)/10; tempC_LSD = int(tempC)%10; tempC_fraction = (tempC - int(tempC))*10; disp.Number (8, tempC_MSD); disp.Numberdp(7, tempC_LSD); disp.Number (6, tempC_fraction); disp.Char (5, 'C'); tempF_MSD2 = int(tempF)/100; tempF_MSD = int(tempF/10)%10; tempF_LSD = int(tempF)%10; tempF_fraction = (tempF - int(tempF))*10; disp.Number (4, tempF_MSD2); disp.Number (3, tempF_MSD); disp.Numberdp(2, tempF_LSD); // disp.Number (1, tempF_fraction); //or disp.Char (1, 'F'); } Subscribe and Download code. After a successful upload, open the Serial Monitor at a baud rate of 115200. Press the “EN/RST” button on the ESP32 board. Make sure you have selected the right board and COM port. Also, make sure you’ve inserted your WiFi Credentials in the code. Explanation: This code sets up the ESP32 to connect to a Wi-Fi network, reads the temperature from the DS18B20, and serves a simple webpage displaying the temperature in Celsius and Fahrenheit. Testing and Calibration Power the ESP32 and ensure it connects to Wi-Fi. Open a web browser and enter the ESP32’s IP address to access the temperature monitor webpage. Verify the temperature readings on both the webpage and the 7-segment displays. Demo: Subscribe and Download code. Conclusion You’ve set up a temperature monitoring system with live temperature readings displayed on both a webpage and an 8-digit 7-segment display. Fine-tune your code and hardware connections as needed for optimal performance.
- ESP32 WiFi Controlled Home Automation and Android
In this tutorial, I 'll Publish how to controlling LED On/Off using web server over WiFi using ESP32 and android application. An Android application using the MIT app inventor that allows you to control the ESP32 GPIO pins and digital read the GPIO pins status. Components Required ESP32S Development Board - 1 no LED - 4 nos 330ohms Resistor - 4nos Jumper wires Circuit Diagram Installing the library To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. Download WiFi manger Library , we need to use this library for WiFi function. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After Arduino IDE installed, there is no package to support ESP32-S2, we need to install the ESP32 package in Arduino IDE to continue. Select “File>Preferences>settings>Additional Boards Manager URLs” to fill the link: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json arduino code ************************************** #include #define LED1 13 #define LED2 12 #define LED3 27 #define LED4 32 String State = ""; WiFiServer server(80); #include "soc/soc.h" #include "soc/rtc_cntl_reg.h" void setup() { Serial.begin(115200); pinMode(LED1, OUTPUT); pinMode(LED2, OUTPUT); pinMode(LED3, OUTPUT); pinMode(LED4, OUTPUT); WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector // WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP // it is a good practice to make sure your code sets wifi mode how you want it. //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around WiFiManager wm; // reset settings - wipe stored credentials for testing // these are stored by the esp library // wm.resetSettings(); // Automatically connect using saved credentials, // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) // then goes into a blocking loop awaiting configuration and will return success result bool res; // res = wm.autoConnect(); // auto generated AP name from chipid // res = wm.autoConnect("AutoConnectAP"); // anonymous ap res = wm.autoConnect("ConnectAP","1234567890"); // your choice AP & password protected ap if(!res) { Serial.println("Failed to connect"); // ESP.restart(); } else { //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); } Serial.println("Connected with WiFi"); server.begin(); Serial.print("http://"); Serial.println(WiFi.localIP()); } void loop() { WiFiClient client = server.available(); if (!client) { return; } String req = client.readStringUntil('\r'); Serial.println(req); req.replace("+", " "); req.replace(" HTTP/1.1", ""); req.replace("GET /", ""); if (req.indexOf("1on") != -1) {digitalWrite(LED1, HIGH); State = "11,,,";} if (req.indexOf("1off") != -1) {digitalWrite(LED1, LOW); State = "10,,,";} if (req.indexOf("2on") != -1) {digitalWrite(LED2, HIGH); State = "21,,,";} if (req.indexOf("2off") != -1) {digitalWrite(LED2, LOW); State = "20,,,";} if (req.indexOf("3on") != -1) {digitalWrite(LED3, HIGH); State = "31,,,";} if (req.indexOf("3off") != -1) {digitalWrite(LED3, LOW); State = "30,,,";} if (req.indexOf("4on") != -1) {digitalWrite(LED4, HIGH); State = "41,,,";} if (req.indexOf("4off") != -1) {digitalWrite(LED4, LOW); State = "40,,,";} if (req.indexOf("Status") != -1){ State =""; if (digitalRead(LED1) == HIGH) {State = "11,";} else {State = "10,";} if (digitalRead(LED2) == HIGH) {State = State + "21,";} else {State = State + "20,";} if (digitalRead(LED3) == HIGH) {State = State + "31,";} else {State = State + "30,";} if (digitalRead(LED4) == HIGH) {State = State + "41,";} else {State = State + "40,";} } client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); client.println(State); client.flush(); client.stop(); Serial.println("Client disconnected."); } ************************************** Subscribe and Download code After a successful upload, open the Serial Monitor at a baud rate of 115200. Press the “EN/RST” button on the ESP32 board. ANDROID APPLICATION The Android app developers generally use JAVA language, but this Android app can also build without knowing the Java language. This app inventor is specially designed for Block programmers those who don’t know the JAVA language. MIT main page Subscribe and Download .apk Demo: Subscribe: arduino Download code Subscribe and Download .apk
- ESP32 Web Server Based Real time ADC with MIT App Inventor2
In this tutorial, I 'll Published how to read the analog value using web server and MIT app inventor over WiFi using ESP32 development board. In this project an angular gauge display using canvas method and real time graph using the Chart 2D are applied. The ADC value is printed in local webpage and web string input to android application for display and graph purpose. A pot is connected power 3.3V, ground and analog pin of ESP32 for voltage measurement. Finally the variable voltage from pot 0 to 3300mv is displayed in Webpage and android application. Components Required To make this project you need the following components: ESP32S Development Board - 1 no Potentiometer 10K - 1 no Jumper wires Circuit Diagram Installing the library To install the library navigate to the Sketch > Include Library > Manage Libraries… Wait for Library Manager to download libraries index and update list of installed libraries. Download WiFi manger Library , we need to use this library for WiFi function. In your Arduino IDE, to install the libraries go to Sketch > Include Library > Add .ZIP library… and select the library you’ve just downloaded. After Arduino IDE installed, there is no package to support ESP32-S2, we need to install the ESP32 package in Arduino IDE to continue. Select “File>Preferences>settings>Additional Boards Manager URLs” to fill the link: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json arduino code ************************************** #include //#include #include #include "index.h" WebServer server(80); void handleRoot() { String s = MAIN_page; server.send(200, "text/html", s); } void handleADC() { int a = 0; a = analogRead(A0); // pot center pin to A0 a = map (a,0,4095,0,3300); //mapping the 3.3 v (3300mv) String adcValue = String(a); server.send(200, "text/plane", adcValue); } void setup() { // WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP // it is a good practice to make sure your code sets wifi mode how you want it. // put your setup code here, to run once: Serial.begin(115200); //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around WiFiManager wm; // reset settings - wipe stored credentials for testing // these are stored by the esp library // wm.resetSettings(); // Automatically connect using saved credentials, // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) // then goes into a blocking loop awaiting configuration and will return success result bool res; // res = wm.autoConnect(); // auto generated AP name from chipid // res = wm.autoConnect("AutoConnectAP"); // anonymous ap res = wm.autoConnect("ConnectAP","1234567890"); // password protected ap - Your choice SSID,PW if(!res) { Serial.println("Failed to connect"); // ESP.restart(); } else { //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); } Serial.println(""); Serial.print("Connected to "); Serial.print("IP address: "); Serial.println(WiFi.localIP()); server.on("/", handleRoot); server.on("/readADC", handleADC); server.begin(); Serial.println("HTTP server started"); } void loop(void){ server.handleClient(); } ****************************************** The HTML file index.h in below: const char MAIN_page[] PROGMEM = R"=====( ESP32 ADC Web Server Value: mv )====="; Subscribe and Download code After a successful upload, open the Serial Monitor at a baud rate of 115200. Press the “EN/RST” button on the ESP32 board. ANDROID APPLICATION The Android app developers generally use JAVA language, but this Android app can also build without knowing the Java language. This app inventor is specially designed for Block programmers those who don’t know the JAVA language. MIT main page MIT Block Subscribe and Download .apk Demo: Subscribe: arduino Download code Subscribe and Download .apk
- Bluetooth Visitor Counter and automatic light control
Here to learn, we will make a Arduino and Bluetooth based Visitor Counter and an Automatic Light Control System using Infrared sensor. In this project, a pair of IR sensors can detect the visitor IN/OUT directions, and arduino send these data to android application using Bluetooth. Android screen displayed in Visitor Walk In count, Visitor Walk Out count and Visitor inside count using android application. This device also have a Bar chart and pie chart for comparison of Visitor In, Out and Inside count for visual and data analysis. In addition to that Visitor counter control an automatic light control system for ON/OFF for the light. If people presence inside the building the light automatically ON and If no people are inside the building the light automatically OFF. Components required Arduino Nano - 1 no Bluetooth module HC-05 - 1no IR sensor module -2nos 1-Channel 5V Relay Module - 1no Circuit diagram What is an IR Sensor? IR sensor is an electronic device, that emits the light in order to sense some object of the surroundings. An IR sensor can measure the heat of an object as well as detects the motion. Usually, in the infrared spectrum, all the objects radiate some form of thermal radiation. These types of radiations are invisible to our eyes, but infrared sensor can detect these radiations. The emitter is simply an IR LED (Light Emitting Diode) and the detector is simply an IR photodiode . Photodiode is sensitive to IR light of the same wavelength which is emitted by the IR LED. When IR light falls on the photodiode, the resistances and the output voltages will change in proportion to the magnitude of the IR light received. IR Sensor Working Principle There are different types of infrared transmitters depending on their wavelengths, output power and response time. An IR sensor consists of an IR LED and an IR Photodiode, together they are called as PhotoCoupler or OptoCoupler. IR Transmitter or IR LED Infrared Transmitter is a light emitting diode (LED) which emits infrared radiations called as IR LED’s. Even though an IR LED looks like a normal LED, the radiation emitted by it is invisible to the human eye. IR Receiver or Photodiode Infrared receivers or infrared sensors detect the radiation from an IR transmitter. IR receivers come in the form of photodiodes and phototransistors. Infrared Photodiodes are different from normal photo diodes as they detect only infrared radiation. Different types of IR receivers exist based on the wavelength, voltage, package, etc. When used in an infrared transmitter – receiver combination, the wavelength of the receiver should match with that of the transmitter. The emitter is an IR LED and the detector is an IR photodiode. The IR photodiode is sensitive to the IR light emitted by an IR LED. The photo-diode’s resistance and output voltage change in proportion to the IR light received. This is the underlying working principle of the IR sensor. When the IR transmitter emits radiation, it reaches the object and some of the radiation reflects back to the IR receiver. Based on the intensity of the reception by the IR receiver, the output of the sensor defines. Bluetooth HC-05 Module HC-05 is a Bluetooth module which is designed for wireless communication. This module can be used in a master or slave configuration. Bluetooth serial modules allow all serial enabled devices to communicate with each other using Bluetooth. It has 6 pins, Key/EN- NC VCC to Connect 5 V power GND to power Ground TXD to Arduino Nano Rx (D0) RXD to Arduino Nano Tx (D1) State- NC HC-05 module Information HC-05 has red LED which indicates connection status, whether the Bluetooth is connected or not. Before connecting to HC-05 module this red LED blinks continuously in a periodic manner. When it gets connected to any other Bluetooth device, its blinking slows down to two seconds. This module works on 3.3 V. We can connect 5V supply voltage as well since the module has on board 5 to 3.3 V regulator. As HC-05 Bluetooth module has 3.3 V level for RX/TX and microcontroller can detect 3.3 V level, so, no need to shift transmit level of HC-05 module. But we need to shift the transmit voltage level from microcontroller to RX of HC-05 module. HC-05 Default Settings Default Bluetooth Name: “HC-05” Default Password: 1234 or 0000 Download Datasheet Subscribe and Download code. Arduino Code #define DELAY_TIMEOUT 1500 int IR_Right_Pin = 8; // <<<---->>> ** IN DIRECTION ** SENSOR int IR_Left_Pin = 9; // **<<<---->>> OUT DIRECTION ** SENSOR #define Relay 2 //Remove Bluetooth RX, Tx wiring when program upload int IR_Right_state = 0; int IR_Left_state = 0; int IR_Right_state_last = -1; int IR_Left_state_last = -1; int IN_counter = 0; int OUT_counter = 0; int Inside_counter = 0; bool Walk_IN = false; bool Walk_Out = false; unsigned long tm; void setup(void) { Serial.begin(9600); pinMode(IR_Right_Pin, INPUT); pinMode( IR_Left_Pin , INPUT); pinMode(Relay, OUTPUT); } void loop(void) { IR_Right_state = digitalRead(IR_Right_Pin ); IR_Left_state = digitalRead( IR_Left_Pin ); checkWalkIn(); checkWalkOUT(); checkInside(); } void checkWalkIn(){ if( IR_Right_state != IR_Right_state_last ){ IR_Right_state_last = IR_Right_state; if( (Walk_IN == false) && ( IR_Right_state == LOW ) ){ Walk_IN = true; tm = millis(); } } if( (millis() - tm) > DELAY_TIMEOUT ){ Walk_IN = false; } if( Walk_IN && (IR_Left_state == LOW) && (IR_Right_state == HIGH) ){ Walk_IN = false; IN_counter++; // Serial.print("in:"); // Serial.print(IN_counter); } } void checkWalkOUT(){ if( IR_Left_state != IR_Left_state_last ){ IR_Left_state_last = IR_Left_state; if( (Walk_Out == false) && ( IR_Left_state == LOW ) ){ Walk_Out = true; tm = millis(); } } if( (millis() - tm) > DELAY_TIMEOUT ){ Walk_Out = false; } if( Walk_Out && (IR_Right_state == LOW) && (IR_Left_state == HIGH) ){ Walk_Out = false; OUT_counter++; // Serial.print("out:"); // Serial.print(OUT_counter); } } void checkInside(){ Inside_counter = (IN_counter-OUT_counter); if(Inside_counter<=0) { digitalWrite(Relay, LOW); delay(200); } else digitalWrite(Relay, HIGH); Serial.print(IN_counter); Serial.print("|"); Serial.print(OUT_counter); Serial.print("|"); Serial.print(Inside_counter); Serial.print("|"); Serial.print(digitalRead(Relay)); Serial.print("\n"); delay(700); } Serial monitor After a successful upload, open the Serial Monitor at a baud rate of 9600. see the result on Serial monitor. Android application First open Mobile application and select Bluetooth image button, after that select Bluetooth HC-05 device to connect and enter Password as mentioned above (0000 or 1234). In this Mobile output Visitors In, Out,Inside head counts and Light control ON/OFF status displayed in screen. And also update chart button for Bar chart and Pie chart view and you can click to In,out,inside count data to add/remove in pie chart for desired output result. Subscribe and Download code. Android App Download