### setup() Function Implementation Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-wifiserver The complete setup function that initializes hardware, connects to WiFi, and starts the web server. ```cpp void setup() { Serial.begin(115200); pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); digitalWrite(RED_PIN, LED_OFF); digitalWrite(GREEN_PIN, LED_OFF); digitalWrite(BLUE_PIN, LED_OFF); my_lcd.begin(); my_lcd.setRotation(0); my_lcd.fillScreen(TFT_WHITE); my_lcd.setTextColor(TFT_RED); WiFi.mode(WIFI_STA); WiFi.setSleep(false); my_lcd.drawString("Start connecting to WiFi...", 10,55,2); WiFi.begin(ssid, password); while(WiFi.status()!= WL_CONNECTED) { delay(500); Serial.print("."); } my_lcd.fillRect(10, 55, my_lcd.width()-1, 25,TFT_WHITE); my_lcd.setTextColor(TFT_GREEN); my_lcd.drawString("Connection WIFI successful!!!", 10,55,2); my_lcd.setTextColor(TFT_BLUE); sprintf(t_buf, "SSID : %s", ssid); my_lcd.drawString(t_buf, 10,75,2); sprintf(t_buf, " IP : %s", WiFi.localIP().toString().c_str()); my_lcd.drawString(t_buf, 10,95,2); sprintf(t_buf, " MAC : %s", WiFi.macAddress().c_str()); my_lcd.drawString(t_buf, 10,115,2); server.begin(); my_lcd.drawString("Waiting for client connection", 10,135,2); } ``` -------------------------------- ### setup() Function Implementation Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-tcpserver Initializes the serial interface, display, and WiFi connection, then starts the TCP server. ```cpp void setup() { Serial.begin(115200); my_lcd.begin(); my_lcd.setRotation(0); my_lcd.fillScreen(TFT_WHITE); my_lcd.setTextColor(TFT_RED); WiFi.mode(WIFI_STA); WiFi.setSleep(false); my_lcd.drawString("Start connecting to WiFi ...", 10,55,2); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } my_lcd.fillRect(10, 55, my_lcd.width()-1, 25,TFT_WHITE); my_lcd.setTextColor(TFT_GREEN); my_lcd.drawString("Connection WIFI successful!!!", 10,55,2); my_lcd.setTextColor(TFT_BLUE); sprintf(t_buf, "SSID : %s", ssid); my_lcd.drawString(t_buf, 10,75,2); sprintf(t_buf, " IP : %s", WiFi.localIP().toString().c_str()); my_lcd.drawString(t_buf, 10,95,2); sprintf(t_buf, " MAC : %s", WiFi.macAddress().c_str()); my_lcd.drawString(t_buf, 10,115,2); sprintf(t_buf, " PORT : %d", port); my_lcd.drawString(t_buf, 10,135,2); my_lcd.setTextColor(TFT_RED); server.begin(); //Start server my_lcd.drawString("Waiting for client connection", 10,155,2); } ``` -------------------------------- ### Switch LVGL Demo in setup() Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-lvgl Uncomment the desired demo function and comment out others in setup(). The example shows lv_demo_benchmark() enabled while lv_demo_widgets() is commented out. Available demos include lv_demo_widgets(), lv_demo_benchmark(), lv_demo_keypad_encoder(), lv_demo_music(), and lv_demo_stress(). ```cpp // lv_demo_widgets(); lv_demo_benchmark(); // switch to benchmark ``` -------------------------------- ### setup() Function - Initialization Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/wifintp Initializes serial, connects to WiFi with a double-check loop to work around a UNO R4 firmware bug, and starts UDP listening. ```cpp void setup() { Serial.begin(9600); while (!Serial); // Connect to WiFi Serial.print("Connecting to WiFi: "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED || WiFi.localIP() == IPAddress(0,0,0,0)) { delay(500); Serial.print("."); } Serial.println("\nWiFi connected successfully!"); Serial.print("IP Address: "); Serial.println(WiFi.localIP()); Udp.begin(localPort); Serial.println("Waiting for NTP time sync...\n"); } ``` -------------------------------- ### Initialize System in setup() Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/wifistable Configures serial communication and performs the initial WiFi connection and UDP setup. ```cpp void setup() { Serial.begin(9600); while (!Serial); Serial.println("=== Arduino UNO R4 WiFi Stability Optimization ==="); Serial.println("System starting, initializing WiFi..."); connectWiFi(); // First WiFi connection on boot (encapsulated as function) Udp.begin(localPort); Serial.println("UDP Initialized (For NTP Example)\n"); } ``` -------------------------------- ### ESP32 setup() Initialization Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/dualboard-esp32 The setup function initializes the serial port, configures the LED, creates a WiFi access point, and starts the TCP server. It runs once upon power-on. ```cpp void setup() { Serial.begin(115200); delay(1000); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); Serial.println(); Serial.println("========================================"); Serial.println(" ESP32 TCP Server — Starting up..."); Serial.println("========================================"); // Step 1: Create WiFi hotspot Serial.print("[SERVER] Creating AP hotspot: "); Serial.println(ap_ssid); WiFi.mode(WIFI_AP); WiFi.softAP(ap_ssid, ap_password); delay(1000); Serial.print("[SERVER] AP IP Address: "); Serial.println(WiFi.softAPIP()); // Step 2: Start TCP server server.begin(); Serial.print("[SERVER] TCP Server started on port: "); Serial.println(serverPort); Serial.println("[SERVER] Waiting for client connection..."); Serial.println(); Serial.println("[SERVER] Type a message and press Enter to send."); Serial.println(); } ``` -------------------------------- ### IR Transmitter setup() Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/receiver-transmitter setup() function for the infrared transmitter example. Initializes serial communication at 9600 baud, initializes the infrared transmitter on the configured pin, and prints a startup message to the Serial Monitor. ```cpp void setup() { Serial.begin(9600); IrSender.begin(IR_SEND_PIN); Serial.println("Infrared Transmitter Started, Sending 0x00 and 0x01 in Loop"); } ``` -------------------------------- ### Initialize setup() function Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-backlight The setup function initializes the serial port, LCD, touch screen, draws the UI, and configures the PWM backlight control. ```cpp void setup() { Serial.begin(115200); my_lcd.begin(); my_lcd.setRotation(1); my_touch.setCal(495, 3398, 721, 3448, 320, 240, 1); my_lcd.fillScreen(TFT_WHITE); my_lcd.setTextColor(TFT_BLACK, TFT_WHITE); my_lcd.setTextSize(2); my_lcd.setCursor(my_lcd.width()/2-150, 160); my_lcd.println("0"); my_lcd.setCursor(my_lcd.width()/2+110, 160); my_lcd.println("255"); my_lcd.fillRoundRect(my_lcd.width()/2-138, 130, 276, 21,10,0x07FF); my_lcd.fillCircle(my_lcd.width()/2+128, 140,10,TFT_MAGENTA); my_lcd.setTextColor(TFT_RED); my_lcd.drawNumber(255, my_lcd.width()/2-15, 65,2); ledcAttachChannel(BACKLIGHT_PIN, freq, resolution, channel); ledcWrite(BACKLIGHT_PIN, 255); } ``` -------------------------------- ### Start AP fallback and web server Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/wifistable-esp32 Switches to AP mode, starts a softAP with credentials from Module 1, sets up the web server via setupWebServer(), and starts the HTTP server. If AP start fails, enters FAIL state. ```cpp void startAPFallback() { Serial.println("[ACTION] Starting AP fallback: " + String(AP_SSID)); WiFi.mode(WIFI_AP); bool ok = WiFi.softAP(AP_SSID, AP_PASSWORD, 6, 0, 4); if (ok) { Serial.print(" AP IP: "); Serial.println(WiFi.softAPIP()); Serial.println(" Open http://192.168.4.1 in a browser to configure WiFi"); setupWebServer(); // Module 8: register web routes server.begin(); // Start HTTP server Serial.println(" Web server started on port 80"); } else { Serial.println(" AP start failed, entering FAIL state"); switchState(STATE_FAIL); } } ``` -------------------------------- ### ESP32 setup() Initialization Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/iot-esp32 Configures pin modes, initializes serial communication, I2C, and starts the boot-up sequence including WiFi, AP mode, and the web server. ```cpp void setup() { Serial.begin(115200); // Initialize serial at 115200 baud delay(1000); pinMode(LED_PIN, OUTPUT); // Set LED pin as output pinMode(MOTOR_PIN, OUTPUT); // Set motor pin as output digitalWrite(LED_PIN, LOW); // Initial state: LED OFF digitalWrite(MOTOR_PIN, LOW); // Initial state: motor OFF // Buzzer stop button (active low with internal pull-up) pinMode(BUZZER_BTN_PIN, INPUT_PULLUP); // Wait for DHT11 sensor to stabilize Serial.print("[DHT] Sensor type: DHT11, Pin: GPIO"); Serial.println(DHT_SENSOR_PIN); Serial.println("[DHT] Waiting for sensor stabilization..."); delay(2000); Wire.begin(21, 22); // I2C init: SDA=GPIO21, SCL=GPIO22 oledInit(); // Initialize OLED display // ===== Boot-up Sequence ===== getNetTime(currentUnixTime); // Step 1: Connect WiFi, get NTP time startAPMode(); // Step 2: Switch to AP mode, create hotspot server.begin(); // Step 3: Start Web server lastUpdateTime = millis(); // Step 4: Record timekeeping reference point } ``` -------------------------------- ### setup() Function Initialization Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-bleserver The setup function initializes the serial port, TFT screen, and BLE server, and displays initial text on the screen. ```cpp void setup() { Serial.begin(115200); my_lcd.begin(); my_lcd.setRotation(0); my_lcd.fillScreen(TFT_WHITE); my_lcd.setTextFont(2); my_lcd.setTextColor(TFT_RED); setupBLE(); my_lcd.drawString("BLE server start.", 10, 0); my_lcd.drawString("receive data :",10,16,2); } ``` -------------------------------- ### Implement HTTP Basic Auth in Web Server Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/wifistable-esp32 Example of wrapping the root handler with authentication in the web server setup. ```cpp void setupWebServer() { server.on("/", HTTP_GET, []() { if (!server.authenticate("admin", "esp32pass")) { return server.requestAuthentication(); } handleRoot(); }); // ... add protection to other routes too } ``` -------------------------------- ### setup() function attaching servos and homing Source: https://wiki.elegoo.com/Robots%26Kits/Penguin-move Initializes the four servos by attaching them to their pins and calls homes(100) to set the initial position. This is part of the Forward_Back.ino example. ```arduino void setup() { servo[0].attach(RR_PIN); servo[1].attach(RL_PIN); servo[2].attach(YR_PIN); servo[3].attach(YL_PIN); homes(100); } ``` -------------------------------- ### setup() Function for STA/AP WiFi Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/twomode Initializes serial communication at 115200 baud, configures the LED as output and low, prints a boot message, then calls getNetTime() to sync NTP time via STA mode, startAPMode() to create a hotspot, server.begin() to start the web server, and records the millis() timestamp as the software timekeeping starting point. ```cpp void setup() { Serial.begin(115200); while (!Serial); delay(1000); pinMode(led, OUTPUT); digitalWrite(led, LOW); Serial.println("=== Boot: Get Time → Switch to AP ==="); getNetTime(); startAPMode(); server.begin(); lastUpdateTime = millis(); } ``` -------------------------------- ### Complete setup() function Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-stamode The setup function initializes the screen, configures WiFi, and attempts to connect to a network, handling both success and failure states. ```cpp void setup() { Serial.begin(115200); my_lcd.begin(); my_lcd.setRotation(0); my_lcd.fillScreen(TFT_WHITE); my_lcd.setTextColor(TFT_RED); WiFi.mode(WIFI_STA); WiFi.setSleep(false); my_lcd.drawString("Start connecting to WiFi...", 22,85,2); WiFi.begin(ssid, password); while(WiFi.status()!= WL_CONNECTED) { i++; delay(500); Serial.print("."); if(i>360) { break; } } if(i>360) { while(1) { my_lcd.fillRect(22, 85, my_lcd.width()-1, 25,TFT_WHITE); delay(500); my_lcd.drawString("connection failed!!!", 22,85,2); delay(500); } } else { my_lcd.fillRect(22, 85, my_lcd.width()-1, 25,TFT_WHITE); my_lcd.setTextColor(TFT_GREEN); my_lcd.drawString("Connection successful!!!", 22,85,2); my_lcd.setTextColor(TFT_BLUE); sprintf(t_buf, "SSID : %s", ssid); my_lcd.drawString(t_buf, 22,105,2); sprintf(t_buf, " IP : %s", WiFi.localIP().toString().c_str()); my_lcd.drawString(t_buf, 22,125,2); sprintf(t_buf, " MAC : %s", WiFi.macAddress().c_str()); my_lcd.drawString(t_buf, 22,145,2); } } ``` -------------------------------- ### ESP32 Simple Serial Program Example Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/serial-2 A basic setup function that initializes the serial port and sends a welcome message to the terminal. ```cpp void setup() { // 1. Initialize serial port with baud rate 115200 Serial.begin(115200); // Wait for serial port to connect (required for some boards) while (!Serial); // 2. Send welcome message Serial.println(" ESP32 Simple Serial Program "); Serial.println("Commands:"); Serial.println(" on - Turn on LED"); Serial.println(" off - Turn off LED"); Serial.println(" status - Check LED status"); Serial.println("===================================="); } void loop() { } ``` -------------------------------- ### Complete setup() function Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-blescan The full setup function used to initialize the serial port, screen, and BLE scanning parameters. ```cpp void setup() { Serial.begin(115200); my_lcd.begin(); my_lcd.setRotation(1); my_lcd.fillScreen(TFT_WHITE); my_lcd.setTextColor(TFT_RED); my_lcd.setFreeFont(&FreeSans18pt7b); my_lcd.drawString("BLE Scan Start", 34, 110); BLEDevice::init("ESP BLEDevice"); pBLEScan = BLEDevice::getScan(); pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); pBLEScan->setActiveScan(true); pBLEScan->setInterval(100); pBLEScan->setWindow(99); my_lcd.fillScreen(TFT_WHITE); my_lcd.setTextFont(1); } ``` -------------------------------- ### setup() Function Implementation Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-ap The setup function initializes the serial port, LCD screen, WiFi AP mode, and displays initial network information. It runs once upon power-up or reset. ```cpp void setup() { Serial.begin(115200); my_lcd.begin(); my_lcd.setRotation(0); my_lcd.fillScreen(TFT_WHITE); my_lcd.setTextColor(TFT_RED); my_lcd.drawString("Enable ESP32 WIFI AP mode...", 22,85,2); WiFi.softAP(ssid, password); my_lcd.setTextColor(TFT_BLUE); sprintf(t_buf, "SSID : %s", ssid); my_lcd.drawString(t_buf, 22,105,2); sprintf(t_buf, "PASSWORD : %s", password); my_lcd.drawString(t_buf, 22,125,2); sprintf(t_buf, "HOST IP : %s", WiFi.softAPIP().toString().c_str()); my_lcd.drawString(t_buf, 22,145,2); sprintf(t_buf, "HOST MAC : %s", WiFi.softAPmacAddress().c_str()); my_lcd.drawString(t_buf, 22,165,2); my_lcd.drawString("CONNECTED NUMBER : ", 22,195,2); } ``` -------------------------------- ### Full setup() Initialization Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/blueteeth The complete setup function for initializing BLE, configuring services, and setting event handlers. ```cpp void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); if (!BLE.begin()) { Serial.println("BLE initialization failed!"); Serial2.begin(115200); Serial2.write("AT+RESET\n"); delay(2000); NVIC_SystemReset(); } BLE.setLocalName("UNO-R4-BLE"); BLE.setDeviceName("UNO-R4-Controller"); BLE.setAdvertisedService(controlService); controlService.addCharacteristic(ledChar); controlService.addCharacteristic(cmdChar); BLE.addService(controlService); ledChar.writeValue(0); BLE.setEventHandler(BLEConnected, onConnect); BLE.setEventHandler(BLEDisconnected, onDisconnect); ledChar.setEventHandler(BLEWritten, onLedWritten); cmdChar.setEventHandler(BLEWritten, onCmdWritten); BLE.advertise(); Serial.println("BLE started, waiting for connection..."); } ``` -------------------------------- ### Initialize setup() function Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-voltage The setup function initializes the serial port, TFT screen, and draws the initial battery icon. It runs once upon power-up or reset. ```cpp void setup() { Serial.begin(115200); tft.begin(); tft.setRotation(0); tft.setTextSize(3); tft.fillScreen(TFT_BLACK); tft.setTextColor(TFT_GREEN, TFT_BLACK); tft.drawRoundRect(tft.width()/2-51, tft.height()/2, 102, 22, 3, TFT_WHITE); tft.fillRect(tft.width()/2+51, tft.height()/2+6, 5, 10, TFT_WHITE); } ``` -------------------------------- ### Main Program Setup Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/ntp-esp32 The main setup function that orchestrates WiFi connection, NTP synchronization, and the periodic time display loop. ```cpp void setup() { Serial.begin(115200); delay(1000); Serial.println("\n========================================"); Serial.println(" ESP32 NTP Time Sync Example"); Serial.println("========================================\n"); pinMode(LED_BUILTIN, OUTPUT); // Step 1: Connect to WiFi (Module 2) if (!connectWiFi()) { Serial.println("[ERROR] Cannot continue without WiFi."); while (true) { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); delay(200); } } // Step 2: Sync NTP time (Module 3) if (!syncNTP()) { Serial.println("[WARN] Time sync may have failed. Check NTP server."); } // Step 3: Display time every second (Module 4) Serial.println("\n[Time] Starting periodic time display...\n"); digitalWrite(LED_BUILTIN, HIGH); unsigned long lastDisplay = 0; while (true) { unsigned long now = millis(); if (now - lastDisplay >= DISPLAY_INTERVAL) { lastDisplay = now; printTime(); } delay(10); } } void loop() { // Never reached } ``` -------------------------------- ### Complete Serial Example Code Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/2560-serial A full Arduino sketch using Serial.begin(115200), waiting for the serial port, and printing a welcome message with command hints in the setup. The loop is empty in the shown source. ```arduino void setup() { // 1. Initialize serial port with baud rate 115200 Serial.begin(115200); // Wait for serial port to connect (required for some boards) while (!Serial); // 2. Send welcome message Serial.println(" ESP32 Simple Serial Program "); Serial.println("Commands:"); Serial.println(" on - Turn on LED"); Serial.println(" off - Turn off LED"); Serial.println(" status - Check LED status"); Serial.println("===================================="); } void loop() { } ``` -------------------------------- ### Servo library include and setup() with attach(9) and write(90) Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/servo-uno The first block includes the Servo library and creates a Servo object named myservo. The second block defines the setup() function, attaching the servo to pin 9 and moving it to the center position (90°). Requires the Servo library installed; otherwise the code won't work. ```arduino #include /* After including the corresponding libraries, we can use the "class" like "Servo" created by the developer for us. We can use the functions and variables created in the libraries by creating objects like the following "myservo" to refer to the members in ".".*/ Servo myservo; //it created an object called myservo. /* you can see Servo as a complex date type(Including functions and various data types) and see myservo as variables. */ ``` ```arduino void setup(){ /*"attach" and "write" are both functions, and they are members contained in the complex structure of "Servo". We can only use them if we create the object "myservo" for the complex structure of "Servo". */ myservo.attach(9);//connect pin 9 with the control line(the middle line of Servo) myservo.write(90);// move servos to center position -> 90° } ``` -------------------------------- ### setup() function for capacitive touch initialization Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/capactive_touch Initializes serial communication at 9600 baud, starts the touch sensor, prints initialization status, and sets the touch threshold to 2000. If initialization fails, it prints an error and enters an infinite loop. ```arduino void setup() { Serial.begin(9600); if(touchButton.begin()){ Serial.println("Capacitive touch sensor initialized."); } else { Serial.println("Failed to initialize capacitive touch sensor. Please use a supported pin."); while(true); } touchButton.setThreshold(2000); } ``` -------------------------------- ### setup() Function Implementation Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/screen-phonecall The setup function initializes the serial port, identifies the LCD driver, sets screen orientation, and draws the initial button grid and text field. ```cpp void setup(void) { Serial.begin(9600); Serial.println(F("TFT LCD test")); Serial.println(F("Elegoo 2.8\" TFT Screen")); Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height()); tft.reset(); uint16_t identifier = tft.readID(); if(identifier == 0x9325) { Serial.println(F("Found ILI9325 LCD driver")); } else if(identifier == 0x9328) { Serial.println(F("Found ILI9328 LCD driver")); } else if(identifier == 0x4535) { Serial.println(F("Found LGDP4535 LCD driver")); }else if(identifier == 0x7575) { Serial.println(F("Found HX8347G LCD driver")); } else if(identifier == 0x9341) { Serial.println(F("Found ILI9341 LCD driver")); } else if(identifier == 0x8357) { Serial.println(F("Found HX8357D LCD driver")); } else if(identifier==0x0101) { identifier=0x9341; Serial.println(F("Found 0x9341 LCD driver")); }else { Serial.print(F("Unknown LCD driver chip: ")); Serial.println(identifier, HEX); identifier=0x9341; } tft.begin(identifier); tft.setRotation(2); tft.fillScreen(BLACK); // create buttons for (uint8_t row=0; row<5; row++) { for (uint8_t col=0; col<3; col++) { buttons[col + row*3].initButton(&tft, BUTTON_X+col*(BUTTON_W+BUTTON_SPACING_X), BUTTON_Y+row*(BUTTON_H+BUTTON_SPACING_Y), // x, y, w, h, outline, fill, text BUTTON_W, BUTTON_H, ILI9341_WHITE, buttoncolors[col+row*3], ILI9341_WHITE, buttonlabels[col + row*3], BUTTON_TEXTSIZE); buttons[col + row*3].drawButton(); } } // create 'text field' tft.drawRect(TEXT_X, TEXT_Y, TEXT_W, TEXT_H, ILI9341_WHITE); } ``` -------------------------------- ### Setup Function for RGB Pins Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/37-rgb The setup function initializes the RGB pins as outputs and sets their initial state. ```cpp void setup() { pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); digitalWrite(RED, HIGH); digitalWrite(GREEN, LOW); digitalWrite(BLUE, LOW); } ``` -------------------------------- ### Starting the TCP Server Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-tcpserver Starts the server listener and updates the display to indicate it is waiting for a client. ```cpp server.begin(); my_lcd.drawString("Waiting for client connection", 10,155,2); ``` -------------------------------- ### Bitwise Operation Examples Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/74h595-2560 Examples of using bitSet and binary literals to control individual LEDs. ```cpp bitSet(leds, 0) ``` ```cpp bitSet(leds, 7) ``` ```cpp leds = 0b00000001 ``` ```cpp leds = 0b10000001 ``` ```cpp leds = 0b01010101 ``` -------------------------------- ### Serial Command Workflow Example Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-desktopdisplay Example interaction sequence for adjusting screen brightness and changing the weather city via the Serial Monitor. ```text In Serial Monitor enter: 0x01 Serial returns: Enter brightness value (0-100) Enter: 80 Serial returns: Brightness set to: 80 Screen brightness adjusts immediately Enter: 0x02 Serial returns: Enter city name in English (e.g. London), or 0 to reset Enter: Beijing Serial returns: City set to: Beijing Screen updates to show Beijing weather Enter: 0x02 Serial returns: Enter city name in English (e.g. London), or 0 to reset Enter: 0 Serial returns: City reset to default: London …… ``` -------------------------------- ### setup() Function for GraphicsTest Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/screen-graphicstest The setup function initializes the serial port, detects the LCD driver chip, and executes a series of benchmark tests for various graphics functions. ```cpp void setup(void) { Serial.begin(9600); Serial.println(F("TFT LCD test")); Serial.println(F("Elegoo 2.8\" TFT Screen")); Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height()); tft.reset(); uint16_t identifier = tft.readID(); if(identifier == 0x9325) { Serial.println(F("Found ILI9325 LCD driver")); } else if(identifier == 0x9328) { Serial.println(F("Found ILI9328 LCD driver")); } else if(identifier == 0x4535) { Serial.println(F("Found LGDP4535 LCD driver")); }else if(identifier == 0x7575) { Serial.println(F("Found HX8347G LCD driver")); } else if(identifier == 0x9341) { Serial.println(F("Found ILI9341 LCD driver")); } else if(identifier == 0x8357) { Serial.println(F("Found HX8357D LCD driver")); } else if(identifier==0x0101) { identifier=0x9341; Serial.println(F("Found 0x9341 LCD driver")); }else { Serial.print(F("Unknown LCD driver chip: ")); Serial.println(identifier, HEX); identifier=0x9341; } tft.begin(identifier); Serial.println(F("Benchmark Time (microseconds)")); Serial.print(F("Screen fill ")); Serial.println(testFillScreen()); delay(500); Serial.print(F("Text ")); Serial.println(testText()); delay(3000); Serial.print(F("Lines ")); Serial.println(testLines(CYAN)); delay(500); Serial.print(F("Horiz/Vert Lines ")); Serial.println(testFastLines(RED, BLUE)); delay(500); Serial.print(F("Rectangles (outline) ")); Serial.println(testRects(GREEN)); delay(500); Serial.print(F("Rectangles (filled) ")); Serial.println(testFilledRects(YELLOW, MAGENTA)); delay(500); Serial.print(F("Circles (filled) ")); Serial.println(testFilledCircles(10, MAGENTA)); Serial.print(F("Circles (outline) ")); Serial.println(testCircles(10, WHITE)); delay(500); Serial.print(F("Triangles (outline) ")); Serial.println(testTriangles()); delay(500); Serial.print(F("Triangles (filled) ")); Serial.println(testFilledTriangles()); delay(500); Serial.print(F("Rounded rects (outline) ")); Serial.println(testRoundRects()); delay(500); Serial.print(F("Rounded rects (filled) ")); Serial.println(testFilledRoundRects()); delay(500); Serial.println(F("Done!")); } ``` -------------------------------- ### IR Receiver Setup Function (IR_Receiver.ino) Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/receiver-transmitter Initializes the LED pin as output, starts serial communication at 9600 baud, and initializes the IR receiver on RECV_PIN with DISABLE_LED_FEEDBACK to disable hardware LED feedback. This is part of the IR_Receiver.ino example. ```Arduino void setup() { pinMode(LED, OUTPUT); Serial.begin(9600); IrReceiver.begin(RECV_PIN, DISABLE_LED_FEEDBACK); } ``` -------------------------------- ### Install Cheese webcam app with apt Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/boot-with-unoq Run this command in the terminal to install Cheese, a graphical application for taking snapshots and recording with a USB camera. ```bash sudo apt install cheese ``` -------------------------------- ### Setup Function for Stepper Motor IR Control Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/stepmotor Initializes motor pins as OUTPUT, sets motor speed, configures IR pin as INPUT, and starts serial communication at 9600 baud. Prints a welcome message and operation guide. ```Arduino void setup() { // Initialize motor pins (explicitly set to OUTPUT for initial operation) (new) pinMode(MOTOR_PIN1, OUTPUT); pinMode(MOTOR_PIN2, OUTPUT); pinMode(MOTOR_PIN3, OUTPUT); pinMode(MOTOR_PIN4, OUTPUT); // Initialize motor myStepper.setSpeed(motorSpeed); // Initialize IR pin pinMode(IR_PIN, INPUT); // Initialize serial communication (baud rate 9600) Serial.begin(9600); Serial.println("=== System Started Successfully ==="); Serial.println("Operation Guide:"); Serial.println("VOL+ → Motor Clockwise"); Serial.println("VOL- → Motor Counterclockwise"); Serial.println("Auto-stop after 3 seconds of inactivity, auto-sleep after 5 seconds"); Serial.println("-------------------"); } ``` -------------------------------- ### Install VLC media player with apt Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/boot-with-unoq Run this command in the terminal to install VLC media player on the UNO Q Debian-based system. ```bash sudo apt install vlc ``` -------------------------------- ### Start Advertising Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-bleserver Gets the advertising object and starts advertising so the device can be discovered by scans. ```cpp BLEAdvertising *pAdvertising = pServer->getAdvertising(); pAdvertising->start(); ``` -------------------------------- ### IR receiver setup and includes Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/irreceive-uno Includes the IRremote and IR libraries, creates the IRrecv instance and decode_results structure, and initializes serial communication and IR reception in setup(). ```cpp #include "IRremote.h" #include "IR.h" IRrecv irrecv(RECEIVER); // create instance of 'irrecv' decode_results results; // create instance of 'decode_results' void setup() { Serial.begin(9600); Serial.println("IR Receiver Button Decode"); irrecv.enableIRIn(); } ``` -------------------------------- ### Stepper motor IR remote control - Setup Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/stepmotor-2560 The setup function starts the IR receiver to begin listening for IR signals. ```arduino void setup() { irrecv.enableIRIn(); // Start the receiver } ``` -------------------------------- ### setup Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/74h595-2560 Initializes the system by configuring the GPIO pins as outputs. ```cpp void setup() { pinMode(latchPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); } ``` -------------------------------- ### Complete setup() function for TFT LCD initialization Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/screen-displaystring The full setup() function that initializes the serial port, resets the LCD, identifies the driver chip, and begins the display. It runs once on power-up or reset. ```cpp void setup(void) { Serial.begin(9600); Serial.println(F("TFT LCD test")); Serial.println(F("Elegoo 2.8\" TFT Screen")); Serial.print("TFT size is "); Serial.print(tft.width()); Serial.print("x"); Serial.println(tft.height()); tft.reset(); uint16_t identifier = tft.readID(); if(identifier == 0x9325) { Serial.println(F("Found ILI9325 LCD driver")); } else if(identifier == 0x9328) { Serial.println(F("Found ILI9328 LCD driver")); } else if(identifier == 0x4535) { Serial.println(F("Found LGDP4535 LCD driver")); }else if(identifier == 0x7575) { Serial.println(F("Found HX8347G LCD driver")); } else if(identifier == 0x9341) { Serial.println(F("Found ILI9341 LCD driver")); } else if(identifier == 0x8357) { Serial.println(F("Found HX8357D LCD driver")); } else if(identifier==0x0101) { identifier=0x9341; Serial.println(F("Found 0x9341 LCD driver")); } else if(identifier==0x1111) { identifier=0x9328; Serial.println(F("Found 0x9328 LCD driver")); } else { Serial.print(F("Unknown LCD driver chip: ")); Serial.println(identifier, HEX); identifier=0x9341; } tft.begin(identifier); } ``` -------------------------------- ### Servo setup function with attach and write Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/servo-r4 Initializes the servo by attaching it to pin 9 and moving it to the center position (90 degrees). This setup ensures the servo starts at a known position and prevents unexpected movement. ```Arduino void setup(){ /*"attach" and "write" are both functions, and they are members contained in the complex structure of "Servo". We can only use them if we create the object "myservo" for the complex structure of "Servo". */ myservo.attach(9);//connect pin 9 with the control line(the middle line of Servo) myservo.write(90);// move servos to center position -> 90° } ``` -------------------------------- ### setup() Function Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-desktopdisplay The main initialization function that configures hardware, network, and display components. ```cpp void setup() { Serial.begin(115200); EEPROM.begin(1024); if (EEPROM.read(BL_addr) > 0 && EEPROM.read(BL_addr) < 100) LCD_BL_PWM = EEPROM.read(BL_addr); pinMode(LCD_BL_PIN, OUTPUT); analogWrite(LCD_BL_PIN, map(LCD_BL_PWM, 0, 100, 0, 255)); tft.begin(); tft.fillScreen(TFT_WHITE); tft.setTextColor(TFT_BLACK, bgColor); targetTime = millis() + 1000; TJpgDec.setJpgScale(1); TJpgDec.setSwapBytes(true); TJpgDec.setCallback(tft_output); connect_wifi(); Udp.begin(localPort); setSyncProvider(getNtpTime); setSyncInterval(300); preferences.begin("weather", false); String savedCity = preferences.getString("city", DEFAULT_CITY); preferences.end(); cityName = savedCity; tft.fillScreen(TFT_WHITE); TJpgDec.drawJpg(10, 193, temperature, sizeof(temperature)); TJpgDec.drawJpg(10, 223, humidity, sizeof(humidity)); getCityWeather(); } ``` -------------------------------- ### setup() Function Initialization Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-key Configures GPIO modes and initial states for the LEDs and the button during startup. ```cpp void setup() { //Initialize LED GPIO, turn off tricolor light pinMode(RED_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(BLUE_PIN, OUTPUT); digitalWrite(RED_PIN, LED_OFF); //RED digitalWrite(GREEN_PIN, LED_OFF); //GREEN digitalWrite(BLUE_PIN, LED_OFF); //GREEN //Initialize KEY GPIO pinMode(KEY_PIN,INPUT_PULLUP); } ``` -------------------------------- ### Initialize Encoder State in Setup Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/rotary-encodemodule Reads the initial logic levels of the CLK and DT pins to establish the starting state. ```cpp lastState = (digitalRead(CLK) << 1) | digitalRead(DT); ``` -------------------------------- ### setup() Function: Initialize Hardware and Draw UI Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-phonecall Initializes the touch IRQ pin, LCD, and touch screen, then draws the keypad UI by calling show_menu(). Sets LCD rotation to 0 (portrait mode) and fills the screen with blue. ```cpp void setup(void) { pinMode(RTP_IRQ, INPUT); my_lcd.init(); my_lcd.setRotation(0); my_touch.setCal(495, 3398, 721, 3448, 320, 240, 1); my_touch.setRotation(0); my_lcd.fillScreen(BLUE); show_menu(); } ``` -------------------------------- ### Joystick Setup Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/joystick-r4 Initializes the system by configuring the switch pin as an input with an internal pull-up resistor and starting serial communication. ```cpp void setup() { pinMode(SW_pin, INPUT); digitalWrite(SW_pin, HIGH); Serial.begin(9600); } ``` -------------------------------- ### setup() Function Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-setup Configures the CS, DC, and backlight pins, and initializes SPI and the LCD display. ```cpp void setup() { pinMode(LCD_CS, OUTPUT); digitalWrite(LCD_CS, HIGH); pinMode(LCD_DC, OUTPUT); digitalWrite(LCD_DC, HIGH); pinMode(LCD_BL, OUTPUT); digitalWrite(LCD_BL, HIGH); SPI_Init(); Lcd_Init(); } ``` -------------------------------- ### MPU-6500 setup() Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/gyro-2560 Initializes I2C, wakes up the sensor by writing to the PWR_MGMT_1 register, and starts serial communication at 9600 baud. ```arduino void setup(){ Wire.begin(); Wire.beginTransmission(MPU_addr); Wire.write(0x6B); // PWR_MGMT_1 register Wire.write(0); // set to zero (wakes up the MPU-6500) Wire.endTransmission(true); Serial.begin(9600); } ``` -------------------------------- ### setup() Function Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-wifiscan Initializes the TFT display, sets landscape orientation, configures WiFi to Station mode (required for scanning), disconnects any previous connections, and waits 100 ms for stabilization. ```cpp void setup() { my_lcd.begin(); my_lcd.setRotation(1); WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100); } ``` -------------------------------- ### setup() Initialization Function Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/dualboard-esp32 Initializes the serial interface, configures the LED pin, and triggers the initial server connection attempt. ```cpp void setup() { Serial.begin(115200); delay(1000); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); Serial.println(); Serial.println("========================================"); Serial.println(" ESP32 TCP Client — Starting up..."); Serial.println("========================================"); connectToServer(); lastReconnectAttempt = millis(); } ``` -------------------------------- ### Step 3: Get network time Source: https://wiki.elegoo.com/oshw-getting-started-%26-kits/twomode Starts the NTP client, requests time, and retrieves the Unix timestamp. Retries up to 3 times with 2-second intervals. ```cpp timeClient.begin(); // Start NTP client timeClient.update(); // Request time from NTP server currentUnixTime = timeClient.getEpochTime(); // Get timestamp ``` -------------------------------- ### ESP32 setup() function for audio player initialization Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-playmusic Complete setup() function that initializes serial, GPIO, TFT, touch, SD card, audio, and UI. Runs once on power-on or reset. Includes error handling for missing SD card and MP3 files, and displays a song list. ```C++ void setup() { Serial.begin(115200); pinMode(AUDIO_EN, OUTPUT); digitalWrite(AUDIO_EN, LOW); pinMode(SD_CS, OUTPUT); digitalWrite(SD_CS, HIGH); pinMode(RTP_IRQ, INPUT); tft.begin(); tft.setRotation(1); my_touch.setCal(495, 3398, 721, 3448, 320, 240, 1); tft.fillScreen(TFT_WHITE); clk.setColorDepth(8); clk.loadFont(simsun16); TJpgDec.setJpgScale(1); TJpgDec.setSwapBytes(true); TJpgDec.setCallback(tft_output); MySPI.begin(SD_SCK, SD_MISO, SD_MOSI); while(!SD.begin(SD_CS,MySPI)) { Serial.println("SD card does not exist"); clk.createSprite(320, 60); clk.fillSprite(TFT_WHITE); clk.setTextDatum(CC_DATUM); clk.setTextColor(TFT_RED, TFT_WHITE); clk.drawString("SD card does not exist",160,16); clk.drawString("Please insert SD card",160,46); clk.pushSprite(0,tft.height()/2-30); clk.deleteSprite(); delay(100); } tft.fillScreen(TFT_WHITE); delay(200); audioInit(); audio.setVolume(21); ticker.attach(1, tcr1s); if(!demo_music()) { clk.createSprite(320, 30); clk.fillSprite(TFT_WHITE); clk.setTextDatum(CC_DATUM); clk.setTextColor(TFT_RED, TFT_WHITE); clk.drawString("Not find MP3 file",160,16); clk.pushSprite(0,tft.height()/2-15); clk.deleteSprite(); while(1); } if(song_num>8) { song_num = 8; } for(int i=0; i< song_num; i++) { clk.createSprite(310, 20); clk.fillSprite(TFT_WHITE); clk.setTextDatum(CC_DATUM); clk.setTextColor(TFT_BLACK, TFT_WHITE); sprintf(tbuf, "%d.%s",i+1,demo_music_get_title(i)); clk.drawString(tbuf,155,10); clk.pushSprite(5,5+i*20); clk.deleteSprite(); } Serial.println("Setup done"); delay(500); clk.createSprite(310, 20); clk.fillSprite(TFT_WHITE); clk.setTextDatum(CC_DATUM); clk.setTextColor(TFT_RED, TFT_WHITE); sprintf(tbuf, "%d.%s",1,demo_music_get_title(0)); clk.drawString(tbuf,155,10); clk.pushSprite(5,5); clk.deleteSprite(); tft.drawFastHLine(0, 165, tft.width(), TFT_BLACK); tft.setTextColor(TFT_BLUE); tft.fillRect(0, 166, tft.width(),28,TFT_WHITE); tft.drawString("Audio time : ",10,167,2); tft.drawString("Total time : ",180,167,2); tft.drawString("00:00",266,167,2); tft.drawFastHLine(0, 185, tft.width(), TFT_BLACK); TJpgDec.drawJpg(40,tft.height()-52,music_play, sizeof(music_play)); TJpgDec.drawJpg(200,tft.height()-52,music_sound, sizeof(music_sound)); } ``` -------------------------------- ### setup() Function for LVGL Initialization Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-lvgl Initializes serial communication, LCD display, touch calibration, LVGL core, display buffers, and drivers. It concludes by launching a demo widget. ```cpp void setup() { Serial.begin(115200); String LVGL_Arduino = "Hello Arduino! "; LVGL_Arduino += String('V') + lv_version_major() + "." + lv_version_minor() + "." + lv_version_patch(); my_lcd.init(); my_lcd.fillScreen(0xFFFF); my_lcd.setRotation(1); my_touch.setCal(495, 3398, 721, 3448, 320, 240, 1); lv_init(); delay(10); #if USE_LV_LOG != 0 lv_log_register_print_cb(my_print); #endif lv_disp_draw_buf_init(&disp_buf, buf, NULL, screenWidth*30); /* Initialize display driver */ static lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.hor_res = my_lcd.width(); disp_drv.ver_res = my_lcd.height(); disp_drv.flush_cb = my_disp_flush; disp_drv.draw_buf = &disp_buf; lv_disp_drv_register(&disp_drv); /* Initialize input device driver */ static lv_indev_drv_t indev_drv; lv_indev_drv_init(&indev_drv); indev_drv.type = LV_INDEV_TYPE_POINTER; indev_drv.read_cb = my_touchpad_read; lv_indev_drv_register(&indev_drv); // Uncomment one demo lv_demo_widgets(); // lv_demo_benchmark(); // lv_demo_keypad_encoder(); // lv_demo_music(); // lv_demo_stress(); } ``` -------------------------------- ### Performance Timing Start Source: https://wiki.elegoo.com/oshw-parts-%26-accessories/esp32-dispaly-flashjpg Records the start time (in milliseconds) to calculate the JPEG decoding and display duration. ```C++ uint32_t dt = millis(); ```