Smart Watch for Couple using ESP32-C3, SquareLine Studio, & LVGL
Table of Contents
Smart Watch for Couple:
Smart Watch for Couple using ESP32-C3, SquareLine Studio, & LVGL- This is my 6th article in the smart watch programming series using the CrowPanel ESP32-C3 1.28-inch IPS Capacitive Touch Display. And let me tell you, this project is being made especially because of a request from someone in love.
If you have read the last 5 articles, I am sure you will have no trouble following this one. That’s because today, we will be using this smart watch with the Blynk application. It’s something totally new and hasn’t been done before. So, before reading this article, make sure you have read the previous 5 articles. The information I am sharing in this article cannot be found anywhere else.
There is a guy who wants to gift his girlfriend a smart watch, and he wants to add features of his choice. He has the same display as this one and is following my videos and articles to create the smart watch for his girlfriend. He has already covered everything I explained in the last 5 articles.
Now, let me tell you about the changes and new features he requested.
Counter Modification:
He asked me to work on improving the counter feature of the smart watch. Now, let me tell you, the counter itself works perfectly. When you press the + button, it increases the value, and when you press the Reset button, it instantly sets the value back to zero.
Simple, right? But there is one problem: the counter value gets completely wiped out if the smart watch is turned off or reset. Imagine spending all that time keeping track of a count, only to lose it when the watch powers off. That’s frustrating!
So, to fix this, he requested that I save the counter value in the EEPROM. This is a type of memory that doesn’t lose data even when the device is turned off. With this upgrade, the counter value will stay safe and sound, no matter what happens.
Now here’s the sweet part of the story: his girlfriend is a little religious, and she plans to use this counter as a digital tasbih—or prayer beads. How thoughtful is that? To make things even better, he also asked me to send the counter value to the Blynk application so he can monitor it remotely. Whether it’s for motivation or just staying connected in a unique way, this feature makes the smart watch even more personal and meaningful.
Pretty cool, right? And this is just the first feature he wanted me to work on. Let’s move on to the next one!
Adding a Keyboard:
He came up with an interesting idea: adding a keyboard Widget to the smart watch. This would allow his girlfriend to connect the smart watch to any WiFi network she wants. Imagine how handy that would be! She could just type in the WiFi name and password directly on the watch.
But that’s not all. He also asked me to make sure the WiFi details she enters are saved in the EEPROM. So that even if the watch gets turned off or restarted, the WiFi settings remain intact. This way, she won’t have to re-enter the credentials every single time.
This feature will make the smart watch much more user-friendly and practical, giving her the freedom to stay connected anytime, anywhere. And honestly, I think it’s a great idea for any smartwatch!
Vibration Motor Control:
This was the feature he emphasized the most- controlling the vibration motor through the Blynk application. He explained why this is so important: whenever he messages or calls his girlfriend, she is often unavailable. Maybe her phone is on silent, or it’s charging, or she’s spending time with her family and isn’t using her phone much.
In situations like these, he wants a discreet way to get her attention. With this feature, he can secretly turn the smart watch’s vibration motor on or off using the Blynk application. It’s like a private little signal just for the two of them!
Interestingly, this idea came to him after seeing a bracelet designed for long-distance couple. That bracelet vibrates to notify your partner, but it’s expensive and lacks additional features. So, he thought, why not include something similar in the smart watch for couple? This way, he gets the same functionality, plus a lot more, in one device and that too for a few bucks.
Feedback Feature:
He also had a unique idea for a feedback feature. He wants the smart watch to work with the Blynk application in a fun and meaningful way. Here is how it will work: whenever his girlfriend presses the screen of the smart watch, the LED widget in the Blynk application will start blinking.
It’s a simple yet thoughtful way to add a connection between the watch and the application. Imagine her pressing the screen and instantly seeing a blinking light in the application-it’s like a little signal saying, “Hey, I am here!” This adds a playful and personal touch to the smart watch, making it even more special for the two of them and obviously for the long-distance lovers.
Let’s go ahead modify the counter, and add all the features he requested for. From today’s article, you are going to learn a lot of exciting things!
So, without any further delay let’s get started!
Blynk IoT Cloud setup:
Log in to your Blynk account and create a simple dashboard like this. Add a button, LED, and gauge from the Widget Box.
Then go to Datastreams and create three datastreams: V0, V1, and V2.
Assign them to the Button, LED, and Gauge, respectively. If you have never used Blynk before, I highly recommend reading my getting-started article on Blynk and ESP32.
Next, open the program, and paste the BLYNK_TEMPLATE_ID, BLYNK_TEMPLATE_NAME, and BLYNK_AUTH_TOKEN at the top of the program.
Then open the Blynk IoT application on your smart phone and set it up exactly the same way.
We will use this button to control the vibration motor on the Smart Watch. The LED widget is for the feedback, and the Gauge is for displaying the counter value. Now, let’s open the SquareLine Studio.
SquareLine Studio:
In the last 5 videos and articles, we have covered a lot of things. In Part 2, I made a counter. In Part 3, I created a digital watch. In Part 4, I made an analog watch. And in Part 5, I added dropdown menus to set the time.
So, make sure you read those 5 articles or watch those 5 videos first. Alright, let’s continue working on the same project!
On widgets tab, scroll down and click on Screen.
You can see Screen4 has been added. Next, we need to import an image to use it as the background. For this, click the ADD FILE INTO ASSETS and select the png image.
You can see the image has been added in the Assests. While Screen4 is selected go to the Background; set the background Radius and color. Next, scroll down, click on the Background and select the image to set it as the background.
Next, scroll down and set the border color and width.
Then click on the Outline and set the color and width of the Outline.
I think it looks good, the choice of colors is totally up to you; just go ahead and try different colors. You can also spend some time on styling to make it look more attractive. Anyway, while the Screen4 is still selected; click on the ADD EVEN button.
Set the Trigger type to LONG_PRESSED.
Set action type to CALL FUNCTION.
Then click on the ADD button, check the “Do not export function”, and write the function name.
We are done with the Screen4.
Keyboard Widget:
Now, for entering the WiFi Credentials; let’s go ahead and add a 5th screen. And then;
On the Widgets tab, click on the Textarea to add a Placeholder for entering the SSID.
Enter the default text.
Activate the One line mode.
Next, name the textarea so that we can easily find it in the variables list on the Arduino side.
Now, let’s add another Textarea for entering the Password. For this, simply duplicate the existing textarea.
Set its position.
Write the name.
And then you can write the default text. Why not to write the actual SSID and password to quickly connect it to the cellphone WiFi Hotspot.
For the password, make sure to check the Password mode.
Next, let’s add a keyboard for entering the WiFi credentials.
This Keyboard really looks cool. Let’s say we enter the SSID and Password using this keyboard. Now, how to save these WiFi credentials in the EEPROM? Well for this we can add a button.
Select the button and on the inspector tab scroll down and click the ADD EVENT button.
Set the trigger type to RELEASED.
Set action type to CALL FUNCTION.
Click the ADD button, check the box, and write the function name.
Next, select the Textarea, and on the inspector tab click the ADD EVENT button.
Set the Trigger type to CLICKED.
Set the action type to KEYBOARD SET TARGET.
Then click the ADD button and select the Keyboard and textarea.
Now, follow the same setups for the other Textarea.
Now, the keyboard is ready. Now, we don’t need a Bluetooth application or a webserver for entering the WiFi Credentials. We can type-in the SSID and Password using this keyboard.
For the Screen1, 2, and 3; I have already added the Screen change events; let’s also do the same for Screen4 and Screen5. I have already explained this in the previous tutorials.
Generate UI Files:
Our setup is completed and now let’s save the project and export the UI files. Then go to the UI files folder, copy all the files, and then paste them in the Arduino project folder. After pasting all the files then go ahead and open the Arduino file. These are the steps, I have already explained in my previous tutorials.
In Part 2 and part 3, I already explained where to find the screen properties, how to enable support for large fonts, and how to locate all the variables. I recommend watching Part 2 and 3 to learn how to avoid errors.
There is just one thing you need to do every time you generate new UI files: change LV_COLOR_16_SWAP from 0 to 1.
Now, let’s go to the main Arduino file.
Complete Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 |
#define BLYNK_TEMPLATE_ID "TMPL6icEIuQgP" #define BLYNK_TEMPLATE_NAME "Blynk Led" #define BLYNK_AUTH_TOKEN "2sPO5ZiTsE3QsYswHuV1fRRj7IEByssX" #define BLYNK_PRINT Serial #define LGFX_USE_V1 #include <WiFi.h> #include "Arduino.h" #include <lvgl.h> #include <LovyanGFX.hpp> #include <Ticker.h> #include "CST816D.h" #include "do_mian.h" #include "ui.h" #include <Preferences.h> #include "I2C_BM8563.h" #include <BlynkSimpleEsp32.h> #include <esp_task_wdt.h> // Include the watchdog timer library #define WATCHDOG_TIMEOUT 3 // Time in seconds #define I2C_SDA 4 #define I2C_SCL 5 #define TP_INT 0 #define TP_RST -1 // You should get Auth Token in the Blynk App. char auth[] = BLYNK_AUTH_TOKEN; String ssid = ""; String password = ""; int wificounter = 0; // Timer for reconnect attempts unsigned long lastReconnectAttempt = 0; const unsigned long reconnectInterval = 5000; // Attempt reconnect every 5 seconds Ticker checkwificonnectivity; // Declare Preferences object Preferences preferences; int vibrationmotor = 0; int counter = 0; // For analog watch int h = 0; int m = 0; int s = 0; //encoder #define ENCODER_A_PIN 19 #define ENCODER_B_PIN 18 #define SWITCH_PIN 8 //Custom key pins #define Custom_PIN 1 long position = 0; long position_tmp = 0; bool switchPressed = false; #define PI4IO_I2C_ADDR 0x43 I2C_BM8563 rtc(I2C_BM8563_DEFAULT_ADDRESS, Wire); I2C_BM8563_DateTypeDef dateStruct; I2C_BM8563_TimeTypeDef timeStruct; #define off_pin 35 #define buf_size 120 //Alarm switch sign int fal = 0; //Indicates whether the alarm has gone off int fal1 = 0; uint32_t hourValue = 0; uint32_t minuteValue = 0; class LGFX : public lgfx::LGFX_Device { lgfx::Panel_GC9A01 _panel_instance; lgfx::Bus_SPI _bus_instance; public: LGFX(void) { { auto cfg = _bus_instance.config(); cfg.spi_host = SPI2_HOST; cfg.spi_mode = 0; cfg.freq_write = 80000000; cfg.freq_read = 20000000; cfg.spi_3wire = true; cfg.use_lock = true; cfg.dma_channel = SPI_DMA_CH_AUTO; cfg.pin_sclk = 6; cfg.pin_mosi = 7; cfg.pin_miso = -1; cfg.pin_dc = 2; _bus_instance.config(cfg); _panel_instance.setBus(&_bus_instance); } { auto cfg = _panel_instance.config(); cfg.pin_cs = 10; cfg.pin_rst = -1; cfg.pin_busy = -1; cfg.memory_width = 240; cfg.memory_height = 240; cfg.panel_width = 240; cfg.panel_height = 240; cfg.offset_x = 0; cfg.offset_y = 0; cfg.offset_rotation = 0; cfg.dummy_read_pixel = 8; cfg.dummy_read_bits = 1; cfg.readable = false; cfg.invert = true; cfg.rgb_order = false; cfg.dlen_16bit = false; cfg.bus_shared = false; _panel_instance.config(cfg); } setPanel(&_panel_instance); } }; LGFX tft; CST816D touch(I2C_SDA, I2C_SCL, TP_RST, TP_INT); /*Change to your screen resolution*/ static const uint32_t screenWidth = 240; static const uint32_t screenHeight = 240; static lv_disp_draw_buf_t draw_buf; static lv_color_t buf[2][screenWidth * buf_size]; #if LV_USE_LOG != 0 /* Serial debugging */ void my_print(lv_log_level_t level, const char *file, uint32_t line, const char *fn_name, const char *dsc) { Serial.printf("%s(%s)@%d->%s\r\n", file, fn_name, line, dsc); Serial.flush(); } #endif /* Display flushing */ void my_disp_flush(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p) { if (tft.getStartCount() == 0) { tft.endWrite(); } tft.pushImageDMA(area->x1, area->y1, area->x2 - area->x1 + 1, area->y2 - area->y1 + 1, (lgfx::swap565_t *)&color_p->full); lv_disp_flush_ready(disp); /* tell lvgl that flushing is done */ } /*Read the touchpad*/ void my_touchpad_read(lv_indev_drv_t *indev_driver, lv_indev_data_t *data) { bool touched; uint8_t gesture; uint16_t touchX, touchY; touched = touch.getTouch(&touchX, &touchY, &gesture); 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; } } Ticker ticker; //Extended IO function void init_IO_extender() { Wire.beginTransmission(PI4IO_I2C_ADDR); Wire.write(0x01); // test register Wire.endTransmission(); Wire.requestFrom(PI4IO_I2C_ADDR, 1); uint8_t rxdata = Wire.read(); Serial.print("Device ID: "); Serial.println(rxdata, HEX); Wire.beginTransmission(PI4IO_I2C_ADDR); Wire.write(0x03); // IO direction register Wire.write((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4)); // set pins 0, 1, 2 as outputs Wire.endTransmission(); Wire.beginTransmission(PI4IO_I2C_ADDR); Wire.write(0x07); // Output Hi-Z register Wire.write(~((1 << 0) | (1 << 1) | (1 << 2) | (1 << 3) | (1 << 4))); // set pins 0, 1, 2 low Wire.endTransmission(); } void set_pin_io(uint8_t pin_number, bool value) { Wire.beginTransmission(PI4IO_I2C_ADDR); Wire.write(0x05); // test register Wire.endTransmission(); Wire.requestFrom(PI4IO_I2C_ADDR, 1); uint8_t rxdata = Wire.read(); Serial.print("Before the change: "); Serial.println(rxdata, HEX); Wire.beginTransmission(PI4IO_I2C_ADDR); Wire.write(0x05); // Output register if (!value) Wire.write((~(1 << pin_number)) & rxdata); // set pin low else Wire.write((1 << pin_number) | rxdata); // set pin high Wire.endTransmission(); Wire.beginTransmission(PI4IO_I2C_ADDR); Wire.write(0x05); // test register Wire.endTransmission(); Wire.requestFrom(PI4IO_I2C_ADDR, 1); rxdata = Wire.read(); Serial.print("after the change: "); Serial.println(rxdata, HEX); } //RTC function void RTC_init() { rtc.begin(); // Set custom time // I2C_BM8563_TimeTypeDef timeStruct; // timeStruct.hours = 11; // Hour (0 - 23) // timeStruct.minutes = 59; // Minute (0 - 59) // timeStruct.seconds = 0; // Second (0 - 59) // rtc.setTime(&timeStruct); // I2C_BM8563_DateTypeDef dateStruct; // dateStruct.weekDay = 3; // Weekday (0 - 6, where 0 is Sunday) // dateStruct.month = 1; // Month (1 - 12) // dateStruct.date = 24; // Day of the month (1 - 31) // dateStruct.year = 2024; // Year // rtc.setDate(&dateStruct); } //Encoder function void updateEncoder() { static int previousState = 0; static int flag_A = 0; static int flag_C = 0; int currentState = (digitalRead(ENCODER_A_PIN) << 1) | digitalRead(ENCODER_B_PIN); if ((currentState == 0b00 && previousState == 0b01) || (currentState == 0b01 && previousState == 0b11) || (currentState == 0b11 && previousState == 0b10) || (currentState == 0b10 && previousState == 0b00)) { // foreward // if (switchPressed) { flag_A++; if (flag_A == 50) { flag_A = 0; flag_C = 0; // position++; // position_tmp=position; position_tmp = 1; } // flag_C=0; // } } else if ((currentState == 0b01 && previousState == 0b00) || (currentState == 0b11 && previousState == 0b01) || (currentState == 0b10 && previousState == 0b11) || (currentState == 0b00 && previousState == 0b10)) { // reversal // if (switchPressed) { flag_C++; if (flag_C == 50) { // position--; flag_C = 0; flag_A = 0; // position_tmp=position; position_tmp = 0; } // flag_A=0; // } } previousState = currentState; } void switchPressedInterrupt() { switchPressed = !switchPressed; } void setup() { Serial.begin(115200); /* prepare for possible serial debug */ // Initialize Preferences preferences.begin("wifi-creds", false); /*first we read the ssid and password from the eeprom */ String myssid = preferences.getString("ssid", "No SSID"); String mypassword = preferences.getString("password", "No SSID"); counter = preferences.getInt("counter", 0); // Default to 0 if no value exists //if new ssid and password are saved, then we store default ssid and password in the eeprom // so when first connecting it to the wifi router; set its ssid to Engr Fahad and password to electroniclinic if ( myssid == "" && mypassword == "") { preferences.putString("ssid", "Engr Fahad"); preferences.putString("password", "electroniclinic"); } else // else if ssid and password are already stored in the eeprom then simply retieve them and save them in ssid and password { ssid = preferences.getString("ssid", "No SSID"); password = preferences.getString("password", "No password"); } preferences.end(); // close the namespace // Initialize WiFi, simple code without the eeprom // if by mistake wrong ssid or password is entered then the ssid and password will set to its default values // then again you will have to change your wifi hotspot or wifi router ssid and password to the default values to set the new ssid and password from the smart watch //otherwise the smartwatch screen will show nothing, it will keep looking for the wifi // that's why there is a wificounter, if it doesn't connect to the newly set rounter then its ssid and password will change to Engr Fahad and electroniclinic WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); wificounter++; if(wificounter >= 10) { preferences.begin("wifi-creds", false); preferences.putString("ssid", "Engr Fahad"); preferences.putString("password", "electroniclinic"); ssid = preferences.getString("ssid", "No SSID"); password = preferences.getString("password", "No password"); wificounter = 0; preferences.end(); // close the namespace } } Serial.println("\nWiFi connected!"); // Configure Blynk Blynk.config(auth); Blynk.connect(); // Initial connection attempt Wire.begin(4, 5); init_IO_extender(); delay(100); set_pin_io(3, true); set_pin_io(4, true); pinMode(ENCODER_A_PIN, INPUT_PULLUP); pinMode(ENCODER_B_PIN, INPUT_PULLUP); pinMode(SWITCH_PIN, INPUT_PULLUP); pinMode(Custom_PIN, INPUT); attachInterrupt(digitalPinToInterrupt(ENCODER_A_PIN), updateEncoder, CHANGE); attachInterrupt(digitalPinToInterrupt(ENCODER_B_PIN), updateEncoder, CHANGE); attachInterrupt(digitalPinToInterrupt(SWITCH_PIN), switchPressedInterrupt, FALLING); // ticker.attach(1, tcr1s); tft.init(); tft.initDMA(); tft.startWrite(); tft.setColor(0, 0, 0); tft.fillScreen(TFT_BLACK); delay(200); if (is_touch == 1) { touch.begin(); } lv_init(); #if LV_USE_LOG != 0 //lv_log_register_print_cb(my_print); /* register print function for debugging */ #endif lv_disp_draw_buf_init(&draw_buf, buf[0], buf[1], screenWidth * buf_size); /*Initialize the display*/ static lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); /*Change the following line to your display resolution*/ disp_drv.hor_res = screenWidth; disp_drv.ver_res = screenHeight; disp_drv.flush_cb = my_disp_flush; disp_drv.draw_buf = &draw_buf; lv_disp_drv_register(&disp_drv); /*Initialize the (dummy) input device driver*/ if (is_touch == 1) { 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); } #if 0 /* Create simple label */ lv_obj_t *label = lv_label_create( lv_scr_act() ); lv_label_set_text( label, "Hello Arduino! (V8.0.X)" ); lv_obj_align( label, LV_ALIGN_CENTER, 0, 0 ); #else /* Try an example from the lv_examples Arduino library make sure to include it as written above. lv_example_btn_1(); */ // uncomment one of these demos // lv_demo_widgets(); // OK // lv_demo_benchmark(); // OK // lv_demo_keypad_encoder(); // works, but I haven't an encoder // lv_demo_music(); // NOK // lv_demo_printer(); // lv_demo_stress(); // seems to be OK ui_mian(); // watch #endif Serial.println("Setup done"); // delay(200); set_pin_io(2, true); pinMode(3, OUTPUT); digitalWrite(3, LOW); // pinMode(0, INPUT); // Get RTC RTC_init(); rtc.getDate(&dateStruct); rtc.getTime(&timeStruct); // Configuration structure for the watchdog timer esp_task_wdt_config_t wdtConfig = { .timeout_ms = WATCHDOG_TIMEOUT * 1000, // Timeout in milliseconds .idle_core_mask = 0, // Monitor core 0 .trigger_panic = true // Trigger panic on timeout }; // Initialize the Task Watchdog Timer esp_task_wdt_init(&wdtConfig); esp_task_wdt_add(NULL); // Add the current task to the watchdog } //void Watch_Function(void *param) void loop() { esp_task_wdt_reset(); // Reset the watchdog timer lv_timer_handler(); /* let the GUI do its work */ delay(5); // Small delay for smoother operation // Check Blynk connection if (Blynk.connected()) { Blynk.run(); // Run Blynk tasks if connected lv_timer_handler(); /* let the GUI do its work */ } else { // Attempt reconnection at intervals unsigned long currentMillis = millis(); if (currentMillis - lastReconnectAttempt >= reconnectInterval) { lastReconnectAttempt = currentMillis; Serial.println("Attempting to reconnect to Blynk..."); Blynk.connect(); // Attempt to reconnect non-blockingly lv_timer_handler(); /* let the GUI do its work */ } } lv_label_set_text(ui_lblCounter, String(counter).c_str()); rtc.getTime(&timeStruct); // Get the current time from the RTC lv_label_set_text(ui_lblHours, String(timeStruct.hours).c_str()); lv_label_set_text(ui_lblminutes, String(timeStruct.minutes).c_str()); lv_label_set_text(ui_lblseconds, String(timeStruct.seconds).c_str()); /****************** For Analog Watch ****************/ h = timeStruct.hours; m = timeStruct.minutes; // s = timeStruct.seconds * 60 % 3600; //Initializing the alarm page from the RTC // lv_img_set_angle(ui_shand, s); // lv_img_set_angle(ui_shand2, s); lv_img_set_angle(ui_imageMinuteHand, m * 60); lv_img_set_angle(ui_imageHourHand, h * 300 + m / 12 * 60); lv_img_set_angle(ui_imageMinuteHand, m * 60); lv_img_set_angle(ui_imageHourHand, h * 300 + m / 12 * 60); handleToggling(); } void ResetCounter(lv_event_t * e) { counter = 0; preferences.begin("wifi-creds", false); preferences.putInt("counter", counter); // Save counter immediately preferences.end(); Blynk.virtualWrite(V2, counter); } void incrementCounter(lv_event_t * e) { counter++; preferences.begin("wifi-creds", false); preferences.putInt("counter", counter); // Save counter immediately preferences.end(); Blynk.virtualWrite(V2, counter); } // Vibration Motor control from Blynk BLYNK_WRITE(V0) // virtual pin V0 from the Blynk, asssigned to the button { vibrationmotor = param.asInt(); if (vibrationmotor == 0) { set_pin_io(0, false); // Set pin 0 to low lv_scr_load(ui_Screen4); // This switches to ui_Screen4 startToggling(); } if (vibrationmotor == 1) { set_pin_io(0, true); // Set pin 0 to low } } void setthehours(lv_event_t * e) { // Buffer to store the selected option text char myHour[25]; // Adjust size based on the longest dropdown option ui_Dropdown3 = lv_event_get_target(e); lv_dropdown_get_selected_str(ui_Dropdown3, myHour, sizeof(myHour)); timeStruct.hours = atoi(myHour); rtc.setTime(&timeStruct); } void Settheminutes(lv_event_t * e) { char myMinutes[61]; // Adjust size based on the longest dropdown option ui_Dropdown1 = lv_event_get_target(e); lv_dropdown_get_selected_str(ui_Dropdown1, myMinutes, sizeof(myMinutes)); timeStruct.minutes = atoi(myMinutes); rtc.setTime(&timeStruct); } void applyssidpassword(lv_event_t * e) { // Get text from the text holders ssid = lv_textarea_get_text(ui_txtssid); password = lv_textarea_get_text(ui_txtpassword); preferences.begin("wifi-creds", false); // Save to Preferences preferences.putString("ssid", ssid); preferences.putString("password", password); ssid = preferences.getString("ssid", "No SSID"); password = preferences.getString("password", "No password"); preferences.end(); } unsigned long previousMillis = 0; // Tracks the last recorded time const unsigned long interval = 500; // 500 milliseconds delay int toggleCount = 0; // Counter for toggles const int maxToggles = 10; // Total toggles (5 times for each color) bool toggle = false; // Tracks which color to show bool isToggling = false; // Indicates whether toggling is active void startToggling() { toggleCount = 0; // Reset the toggle count isToggling = true; // Activate toggling } void handleToggling() { if (!isToggling) return; // Exit if toggling is not active unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; // Update the last recorded time // Toggle the background color if (toggle) { lv_obj_set_style_bg_color(ui_Screen4, lv_color_hex(0xFF0000), LV_PART_MAIN | LV_STATE_DEFAULT); Blynk.virtualWrite(V1, 0); set_pin_io(0, false); // Set pin 0 to high } else { lv_obj_set_style_bg_color(ui_Screen4, lv_color_hex(0x00FF17), LV_PART_MAIN | LV_STATE_DEFAULT); Blynk.virtualWrite(V1, 1); set_pin_io(0, true); // Set pin 0 to high } toggle = !toggle; // Alternate the toggle state toggleCount++; // Increment the toggle count if (toggleCount >= maxToggles) { isToggling = false; // Stop toggling after max toggles } } } void notification(lv_event_t * e) // when you long press on the screen 4 { startToggling(); } |
Code Explanation:
1 |
#include <esp_task_wdt.h> |
This library allows you to manage and monitor the watchdog timer for tasks running on the ESP32, helping to prevent the system from hanging due to stuck or unresponsive tasks.
1 |
#define WATCHDOG_TIMEOUT 3 // Time in seconds |
This line sets the timeout period for a Watchdog Timer in seconds.
1 |
char auth[] = BLYNK_AUTH_TOKEN; |
This line stores the Blynk authentication token (BLYNK_AUTH_TOKEN) as a character array.
The BLYNK_AUTH_TOKEN is a unique identifier provided by the Blynk platform for your project, allowing your device to connect to the Blynk server.
1 |
String ssid = ""; |
This variable is intended to store the SSID (network name) of the Wi-Fi you want the Smartwatch to connect to.
1 |
String password = ""; |
This variable holds the password for the Wi-Fi network.
1 2 3 4 5 6 7 |
int wificounter = 0; // Timer for reconnect attempts unsigned long lastReconnectAttempt = 0; const unsigned long reconnectInterval = 5000; // Attempt reconnect every 5 seconds |
This line initializes a wificounter to track Wi-Fi connection attempts and sets up a timer (lastReconnectAttempt) for managing reconnect attempts every 5 seconds (reconnectInterval).
1 |
Ticker checkwificonnectivity; |
The Ticker checkwificonnectivity is used to periodically check the Wi-Fi status and execute actions if disconnected. This setup helps ensure reliable Wi-Fi connectivity by attempting reconnections when needed.
1 |
Preferences preferences; |
The line; creates an instance of the Preferences class, which is part of the ESP32’s Preferences.h library. Including #include <Preferences.h> allows you to use the Preferences library, which provides a simpler and more robust way to store and retrieve key-value pairs in the ESP32’s non-volatile storage (NVS). Unlike EEPROM, Preferences handles wear leveling automatically, is optimized for frequent writes, and supports namespacing for organizing data. It is preferred over EEPROM because it is less prone to memory corruption, easier to use with string-based keys, and more reliable for modern applications. Now, let’s go to the setup() function.
1 2 3 4 5 6 7 8 9 10 11 |
// Initialize Preferences preferences.begin("wifi-creds", false); /*first we read the ssid and password from the eeprom */ String myssid = preferences.getString("ssid", "No SSID"); String mypassword = preferences.getString("password", "No SSID"); counter = preferences.getInt("counter", 0); // Default to 0 if no value exists |
This part of the code initializes the Preferences library with the namespace “wifi-creds” in read-write mode (false). It then retrieves stored Wi-Fi credentials and a counter from non-volatile storage using the keys “ssid”, “password”, and “counter”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
if ( myssid == "" && mypassword == "") { preferences.putString("ssid", "Engr Fahad"); preferences.putString("password", " electroniclinic"); } else // else if ssid and password are already stored in the eeprom then simply retieve them and save them in ssid and password { ssid = preferences.getString("ssid", "No SSID"); password = preferences.getString("password", "No password"); } preferences.end(); // close the namespace |
This part of the code checks if myssid and mypassword are empty. If they are, it stores default Wi-Fi credentials (“Engr Fahad” and ” electroniclinic”) in Preferences. Otherwise, it retrieves the stored SSID and password and assigns them to ssid and password. Finally, preferences.end() closes the namespace to free resources.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); wificounter++; if(wificounter >= 10) { preferences.begin("wifi-creds", false); preferences.putString("ssid", "Engr Fahad"); preferences.putString("password", "electroniclinic"); ssid = preferences.getString("ssid", "No SSID"); password = preferences.getString("password", "No password"); wificounter = 0; preferences.end(); // close the namespace } } Serial.println("\nWiFi connected!"); |
This part of the code attempts to connect the ESP32 to a Wi-Fi network using the provided ssid and password via WiFi.begin(ssid, password). It enters a loop, checking the connection status (WiFi.status() != WL_CONNECTED) and printing a dot every 500ms until it is connected. If the connection fails after 10 attempts (wificounter >= 10), it stores default Wi-Fi credentials (“Engr Fahad” and “electroniclinic”) in Preferences and retrieves them for use. The wificounter is reset, and the Preferences namespace is closed with preferences.end() to release resources. Once connected, it prints “WiFi connected!”.
If you need the full source code of the project, you can download it from my Patreon page. Anyway, I have already uploaded the code, so let’s go ahead and watch this in action.
Practical Demonstration:
Right now, both the smart watch and my phone are connected to my home’s main Wi-Fi router, and everything is set up perfectly. Let’s dive into the counter functionality and see how it works!
Using the plus button on the smart watch, I can easily increase the counter value step by step. What’s even cooler is that this value updates in real time, not only on the smart watch’s display but also on the Blynk application. Whether you are in another room or halfway across the globe, as long as there’s a Wi-Fi network, you can monitor the counter in real time. Pretty awesome, right?
Now, imagine this; when his girlfriend uses the counter for tasbih, he can feel connected to her, no matter where he is in the world. That’s a unique way to stay close to someone, isn’t it? And here’s the best part: he specifically requested that this counter value should be saved even if the smart watch restarts or turns off. I tested it by turning the display OFF and I then restarted it, and the value didn’t lost. You can practically see it in action in the video given at the end of this article.
For demonstration purposes, I have set the counter’s maximum range to 100, but don’t worry-you can easily customize it to any range you prefer.
Now, let’s talk about the reset button. She can use this button anytime to reset the counter back to zero. But here’s the smart part: I have configured the reset button’s trigger type to LONG_PRESSED. This means that even if she accidentally touches the reset button, the counter value won’t reset to 0 unless she presses and holds the button for a longer duration. This feature is a great way to prevent accidental resets.
Now, if I swipe my finger to the left, Screen2 will appear, showing a digital watch with a custom watch face designed in Figma.
There are also two dropdown menus for setting the minutes and hours in just a few seconds. If you are curious about how these dropdown menus work or want to create something similar, be sure to check out Part 5, where I go into all the details. Trust me, it’s worth it!
If I swipe my finger to the left again, Screen3 will appear, featuring our stunning analog watch.
The animations and details really bring it to life! If you’re interested in learning how to animate PNG images, you should definitely check out Part 4. Not only will it help you create amazing analog watches, but it will also give you insights into designing custom gauges for your projects.
Now, if I swipe my finger to the left one more time, Screen4 appears, and this one is really special!
I put a lot of effort into it because it’s designed to connect long-distance couples in a meaningful way. This screen allows two-way communication through the Blynk application, and it’s honestly one of my favorite features.
Here’s how it works: when the boy presses a button in the Blynk application, the smartwatch’s vibration motor starts to turn on and off, instantly letting the girl know that her boyfriend or husband is thinking about her.
And to make it even more exciting, I have added a background color toggle for a visual effect. Instead of just changing the background color, you could even add cool animations to surprise your partner. Just imagine—one button press, and your loved one feels connected to you no matter the distance!
But wait—it gets even better. This communication works both ways.
When the girl touches the screen on the smart watch, an LED in the Blynk application starts blinking, sending a feedback notification that she is also thinking about him or is available to chat. You can even create your own secret codes for some playful and fun interaction!
What’s even better is that the notification works no matter which screen the girl is on. When the boy presses the button in the application, the smartwatch will automatically switch to Screen4, ensuring she doesn’t miss the love signal.
Compared to smart bracelets, this idea is on another level. Smart bracelets are expensive, lack customization, and don’t let you add fun features like these. With this smart watch, you have full control; change the design, check the time, and add anything you can imagine!
Lastly, let’s connect this smart watch to another WiFi network. If you remember, in SquareLine Studio, I already entered the credentials for a mobile hotspot.
Currently, the smart watch is not connected to the phone’s hotspot. So, let’s click the Apply button to save these new Wi-Fi credentials to the ESP32’s non-volatile memory.
Amazing! It worked perfectly; the smart watch connected to my phone’s hotspot without any issues.
Let me know in the comments what you think of this idea, and share your thoughts on what features I should add next. I would love to hear your suggestions!
So, that’s all for now!
Watch Video Tutorial: