Islamic Prayer Times - ESP32 TTGO T-Display

by AKN in Circuits > Arduino

483 Views, 6 Favorites, 0 Comments

Islamic Prayer Times - ESP32 TTGO T-Display

Prayer Screen-02.jpg
Deep-Sleep.jpg
Portal.jpg
IMG-20241224-WA0003.jpg
Prayer Time Display - TTGO T-Display - 25 Dec 2024

This is an Arduino IDE project that uses a readily-available development board that includes a small TFT screen - LilyGo TTGO T-Display - to retrieve and display Islamic prayer time data according to the geolocation of the user.


ESP32 Dev. Board

The LilyGo TTGO T-Display is an ESP32 device and is available from all the usual outlets. The standard 'shell' available through the same stores makes a glaringly obvious omission - space for a battery! A 402030 or 402035 lithium battery is ideal and can be stuck to the back of this case/shell.

There are a number of freely-available .stl files for this board that incorporate space for a lithium battery. A search will reveal many to suit your needs. Here is one example.

There is almost no soldering required except for wiring the supplied JST connector to a battery. You can be up and running in a very short time once the Arduino IDE and necessary libraries are installed. Please refer to the ReadMe.md file in the GitHub repository.


APIs & Keys

Prayer data is retrieved from https://muwaqqit.com in JSON format via the site's JSON endpoint. This API requires the user's latitude and longitude coordinates along with other basic information to provide a full month's prayer data.

Geolocation information is retrieved from Google using the Google Maps API. This requires a personal API key. There are many resources to guide you through how to obtain the API key. You are responsible for managing API call frequency and any costs should you rack-up API calls over the free monthly allowance. This API is accurate enough for the purpose of the project.

A GPS module could have been implemented, but this adds unnecessary bulk to the device. The WiFiLocation library fully manages the retrieval of lat/long and accuracy data. Other 'free' services and libraries are available, like the GeoIP library. However, accuracy is hit-and-miss when connected to the internet via a mobile 'phone. Hard-wired internet connections return reasonably accurate geolocation data.

Google's Timezone API is used to determine the Timezone string to pass to Muwaqqit. DST and UTC offsets are passed to the NTP/Time library to correct DST and UTC offsets.

Be aware that in sparsely populated areas where WiFi access points are limited, geolocation accuracy may be compromised, leading to inaccurate prayer times.

Muwaqqit

There are a number of prayer-time APIs available. This is one of the most configurable, accurate and reliable sources for prayer data. The developer has thoroughly researched this science, gaining the approval of scholars of the subject. Please consider supporting Muwaqqit.

Arduino Sketch

I'm not the most accomplished or elegant coder. You may find that some parts/functions resemble example code from the installed libraries. I'm a great believer of not reinventing the wheel! I'm sure you'll find ways to streamline the code.

ArduinoJSON

This library is used to extract the required data to display on the TFT screen and serial port. The WiFiLocation library also uses ArduinoJSON. Please also consider supporting Benoit.

This project was started over four years ago, and stalled due to my lack of understanding how to extract JSON elements or how to use ArduinoJSON. Having purchased Benoit's book, and access to more examples, I was able to complete what I'd planned on achieving in a few days! My coding skills are rudimentary at best, so please go easy on me. :-)

WiFiManager

This library is incorporated to eliminate the need to hard-code one's WiFi credentials.

Supplies

Screenshot 2024-12-09 195101.png
Screenshot 2024-12-09 195345.png
IMG-20241224-WA0005.jpg
IMG-20241224-WA0008.jpg
TTGO-CH9102.jpg

Hardware

LilyGo TTGO T-Display Module (16M)

T-Display Shell

402030 Lithium Battery

402035 Lithium Battery


Software

Muwaqqit API Documentation

Arduino IDE

Google Maps API

GitHub Project Sketch


Serial Driver

If you haven't already done so, you'll need to install the correct serial driver. Without this driver, the Arduino IDE won't "see" the device. All the T-Display boards I have seen use the WCH CH9102F.

Adafruit has a decent tutorial on how to install the driver.

Windows CHxxx driver

Mac CHxxx driver

Arduino IDE

Screenshot 2024-12-09 193721.png

ESP32 Board Install - V2.0.17

If not already, install the Arduino IDE. You'll need to install ESP32 Board files. Instructions are available at a number of sites. Random Nerd Tutorials is a reliable source.

There have been some issues with the V3 release of Espressif's ESP32 Board library, which caused some compilation problems. Downgrading to V2.0.17 resolved the problems experienced. It may also be prudent to downgrade the Arduino ESP32 Board to V2.0.13

Libraries

Search for the following Libraries and install the versions shown:

ArduinoJSON - V7.2.1

ArduinoJSON provides an elegant and powerful solution to extracting JSON data.

TFT_eSPI - V2.5.43

TFT_eSPI library's setup file will need to be modified. Locate where TFT_eSPI is installed. Ensure the User_Setup_Select.h file is correctly configured for the TTGO T-Display ST7789 driver:

Comment out the line as below:
//#include <User_Setup.h> // Default setup is root library folder

Uncomment line as below:
#include <User_Setups/Setup25_TTGO_T_Display.h> // Setup file for ESP32 and TTGO T-Display ST7789V SPI bus TFT


WiFiLocation - V1.2.9

WiFiLocation leverages Google's Maps API to retrieve longitude and latitude coordinates without the need use a GPS receiver. The returned coordinates are extremely accurate!

WiFiManager - V2.0.17

This library is incorporated to eliminate the need to hard-code one's WiFi credentials. If no WiFi credentials are stored or the stored SSID is not present, an Access Point is enabled for you to launch the WiFi Configuration Portal.

Battery18650Stats - V1.0.0 ***

This library provides an easy method of obtaining battery charge level and voltage.

*** Newly added functionality since this instructable was published

Arduino Sketch

Screenshot 2024-12-09 200908.png
Screenshot 2024-12-09 201056.png

Download the latest version of the Sketch from GitHub and save it to your Sketch directory and open for editing.

Board Type & COM Port

Set the Board type to ESP32 Dev Module.

Plug in your TTGO board into an unused USB port. Select the correct COM Port linked to the Board.

Google API Key

Insert your Google Maps API Key in the line indicated:

const char* googleApiKey = "Paste Your Google API Key Here";

This Key will be used to access Google's Timezone, Geolocation and Geocode APIs

Upload Sketch

You're now ready to compile and upload the code to the TTGO device. There shouldn't be any compilation errors and your device is ready for use. If you encounter any errors, review the reported errors, correct any issues and re-upload.

Sketch Function Descriptions

fetchJSON() // Fetch JSON data from Muwaqqit.

timeToSeconds(const char* timeStr) // Function to convert time string HH:MM:SS to total seconds since midnight. Reason is to help determine which is the current prayer.

getTZ() // Function to determine Timezone, DST and UTC Offset via Google Maps Timezone API.

getAddress() // Function to determine location Address from Lat/Long and send to TFT.

drawflag() // Draw Palestinian Flag as a show of solidarity to all those being harmed and oppressed.

batteryV() // Determine the charge state of the battery.

This function now uses the more reliable Battery18650Stats library. ***

printLocalTime() // Function to print current local time and date.

checkButton() // Function to test if button pressed and held for 3 seconds to reset WiFi credentials.

print_wakeup_reason() // Send to serial device, the wake-up reason. For debug purposes.

setup() // Configuration and setup of screen, button, WiFi, Splash screen, and first retrieval & display of prayer data.

loop() // Update time and battery status on TFT. Repeat until Deep-Sleep entered after 60 seconds.

*** Newly added functionality since this instructable was published

Programme Flow

Here is a detailed description of the main points of the sketch.

  1. Definition of all libraries used, initialisation of:
  2. WiFiManager
  3. WiFiLocation
  4. TFT_eSPI
  5. NTP Service
  6. GPIO Pin definitions
  7. definition of global variables
  8. Setup() function
  9. Configure TFT display
  10. Initialise GPIO pins used
  11. Configure Deep-Sleep wake-up button
  12. Initialize Serial Port
  13. Send to serial port the reason wake-up forced after Deep-Sleep
  14. Draw flag
  15. Display Config Portal details
  16. Initialise WiFi config portal
  17. If previously configured WiFi not available or WiFi not configured within 60 seconds, enter deep-sleep
  18. Determine Latitude & Longitude
  19. Get time & date from NTP server
  20. Pass date to Google Timezone API ***
  21. Determine Timezone, DST & UTC offset ***
  22. Get time & date from NTP server and apply correct offsets ***
  23. Send local time and date to serial port
  24. Pass fully-formed URL endpoint to Muwaqqit API
  25. Get and display prayer time data
  26. Get location address via Google Geocode API ***
  27. Display prayer times
  28. Highlight current prayer time
  29. Loop() function
  30. Send local time to serial port
  31. Update local time and date on TFT screen
  32. Update battery status on TFT screen - % or "Charging" ***
  33. Check if button on GPIO 35 pressed and held for 3 seconds
  34. If button pressed and held, clear WiFi credentials from memory and restart device
  35. If 60 seconds have elapsed after running Loop function, enter deep-sleep
  36. Otherwise, repeat Loop().

*** Newly added functionality since this instructable was published

Functionality

WiFi-AP.jpg
Portal-02.jpg
Portal-01.jpg
Screenshot 2024-12-09 201541.png

WiFi Configuration Portal

If no connection or no SSID defined, the WiFi Configuration Portal is enabled.

On a mobile device, connect to SSID "Muwaqqit-AP" - You may have to browse to 192.168.4.1

Select "Configure WiFi"

Choose WiFi network, enter password and select "Save"

Configuration portal will close and the device will connect to the chosen WiFi network and continue.

Reset WiFi SSID Credentials

If at any time you want to change the WiFi credentials, press and hold the top button for 3 seconds while prayer times are displayed to clear the current WiFi configuration.

Deep Sleep

To conserve battery life, the ESP32 device is forced into Deep-Sleep mode in two places:

  1. if the WiFi Configuration Portal has not been modified for 60 seconds,
  2. after prayer times have been displayed for 60 seconds.

In 1. the device will remain in Deep-Sleep.

In 2. the device will restart after 60 minutes.

The TFT is now placed into Low Power mode. ***

tft.writecommand(ST7789_DISPOFF); // Switch off the display
tft.writecommand(ST7789_SLPIN);  // Sleep the display driver
delay(120); //Allow time to stabilise action before moving-on to enable deep-sleep of ESP32


Wake-Up

As mentioned above, at certain points the device enter Deep-Sleep. You can force a Restart/Wake-up by pressing the lower button.

Serial Debug

With the Serial Monitor enabled, you'll see a flow of information being printed for you to verify that the device is functioning as expected, i.e geolocation data, prayer times API URL string, formatted prayer table etc.

*** Newly added functionality since this instructable was published

Customising

A number of timers,delays and switches are used and are merely a starting point. The default timings are set for optimal viewing time and conservation of battery life. Here are the areas you might want to modify to your preference:

Time until Deep Sleep

This is the length of time the prayer times will remain on-screen before entering Deep-Sleep. Default value is 60000 milliseconds, denoting 60 seconds. Modify the variable 'interval' to your preference:

const unsigned long interval = 60000; // Interval before entering Deep_Sleep - 60 seconds


Deep-Sleep Period.

This is the time the device stays in Deep-Sleep mode until restarting. Default is 60 minutes. Modify the 'TIME_TO_SLEEP' variable to your desired preference:

#define TIME_TO_SLEEP 3600    /* Time ESP32 will go to sleep for... (in seconds) */


Reset WiFi SSID Credentials

If at any time you want to change the WiFi credentials, press and hold the top button for 3 seconds while prayer times are displayed to clear the current WiFi configuration and to restart the device, ready for the WiFi to be configured. You can change the length of time to hold the button by modifying this line:

 delay(3000); // reset delay hold


WiFi Configuration Portal Timeout

Closes the WiFi Portal after 60 seconds on no action. Modify this line to your desired timeout:

 wifiManager.setConfigPortalTimeout(60); // auto close config portal after 60 seconds


Muwaqqit API Endpoint URL

Should you have a need to retrieve prayer times with different settings e.g for Fajr or Isha angles, please consult Muwaqqit's API documentation to further customise your desired settings.

// API endpoint
const char* api_url = "";
const char* api_url1 = "https://www.muwaqqit.com/api.json?d=";
const char* api_url2 = ";lt=";
const char* api_url3 = "&ln=";
const char* api_url4 = ";fa=-18;era=-12&ea=-13&tztype=auto&tz=";


Here is an example of a fully-formed Muwaqqit endpoint:

https://www.muwaqqit.com/api.json?d=2024-12-23;lt=51.4447975&ln=-1.8653843;fa=-18;era=-12&ea=-13&tztype=auto&tz=Europe/London


Google Geocode Location API

You can choose which returned elements you want to display by customising the API endpoint. Detailed information from Google here.

https://maps.googleapis.com/maps/api/geocode/json?

Future Enhancements

Time-Zone ***

Automatically determining the user's time-zone and DST settings may be necessary to return the correct displayed time and passing correct time-zone to the Muwaqqit API. This is a Work-in-Progress and will be incorporated at a future date. In the meantime, feel free to modify the lines shown here for your location:

const long gmt_offset_sec = 0;    // Adjust if necessary for your timezone
const int daylight_offset_sec = 3600; // Adjust for daylight savings

21 Dec - You'll be pleased to learn that this has now been implemented and the change has been committed to the GitHub repository. Its functionality just needs to be confirmed by testing in other worldwide regions...


Multi-SSIDs

Unfortunately, the current version of WiFiManager does not support storage of multiple access points. This functionality is listed in the library's roadmap, so here's hoping...


Map and qibla direction

To display on the TFT, a map of the current location along with a line indicating the direction of prayer. This is easy enough to determine using Google's staticmap API. A working endpoint URL has already been determined as:

https://maps.googleapis.com/maps/api/staticmap?center=50.4423375,-1.8637566&zoom=16&size=240x135&format=jpg&markers=size:tiny%7Ccolor:red%7C50.4423375,-1.8637566&path=geodesic:true|color:red|weight:2|50.4423375,-1.8637566|21.4224779,39.8262775&key=Your Google Maps API Key


Currently having trouble sending the received map to the TFT. Map is being successfully received and stored in SPIFFS, however, the display remains blank. If anyone can get it to work, please let me know. Here's the test sketch:

// Test sketch to:
// a. retrieve image from Google Maps staticmap API
// b. store in SPIFFS file system
// c. send to serial, contents of image file - in Hex
// d. send to TFT display

#include <WiFi.h>
#include <HTTPClient.h>
#include <TFT_eSPI.h>
#include <TJpg_Decoder.h>
#include <SPIFFS.h>

const char *ssid = "Your SSID";
const char *password = "your Password";
const char *apiKey = "Your Google Maps API key"; // Replace with your Google Maps API key
const char *apiUrl = "https://maps.googleapis.com/maps/api/staticmap";
const char *savePath = "/staticmap.jpg"; // Received image saved as staticmap.jpg

TFT_eSPI tft = TFT_eSPI(); // Initialize the TFT display
//extern TJpg_Decoder TJpegDec; // Proper instantiation of the TJpg_Decoder object

// Callback function for TJpg_Decoder
bool tftOutput(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t *bitmap) {
tft.pushImage(x, y, w, h, bitmap);
return 1;
}

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");

if (!SPIFFS.begin(true)) {
Serial.println("Failed to mount file system");
return;
} else {
Serial.println("File system mounted");
}

tft.begin();
tft.setRotation(0);
tft.fillScreen(TFT_BLACK);

// Initialize TJpg_Decoder library
TJpgDec.setJpgScale(1);
TJpgDec.setCallback(tftOutput);

fetchAndSaveMap();
}

void loop() {
}

void fetchAndSaveMap() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String lat = "50.4423385"; // Updated latitude
String lon = "1.8337566"; // Updated longitude
String url = String(apiUrl) + "?center=" + lat + "," + lon + "&zoom=16&size=240x135&format=jpg&markers=size:tiny%7Ccolor:red%7C" + lat + "," + lon + "&path=geodesic:true|color:red|weight:2|" + lat + "," + lon +"|21.4224779,39.8262775&key=" + apiKey; // Adding a red marker and requesting JPEG format

http.begin(url);
int httpCode = http.GET();

if (httpCode == HTTP_CODE_OK) {
fs::File file = SPIFFS.open(savePath, "w");
if (!file) {
Serial.println("Failed to open file for writing");
} else {
http.writeToStream(&file);
file.close();
Serial.println("Map image saved to SPIFFS");

// Verify file size and content
file = SPIFFS.open(savePath, "r");
if (file) {
Serial.printf("File size: %d bytes\n", file.size());
Serial.println("File content: ");
for (int i = 0; i < file.size() && i < file.size(); ++i) { // Print first 100 bytes for debugging
Serial.printf("%02x ", file.read());
}
Serial.println();
file.close();
decodeAndDisplayMap();
} else {
Serial.println("Failed to open file for reading");
}
}
} else {
Serial.println("Error on HTTP request");
}
http.end();
}
}

void decodeAndDisplayMap() {
fs::File file = SPIFFS.open(savePath, "r");
if (!file) {
Serial.println("Failed to open file for reading");
return;
}

int fileSize = file.size();
uint8_t *buffer = new uint8_t[fileSize];
file.read(buffer, fileSize);
file.close();

// Clear screen before displaying image
tft.fillScreen(TFT_BLACK);

// Display image at origin (0, 0)
Serial.printf("Decoding JPEG of size: %d bytes\n", fileSize);

// Get the width and height in pixels of the jpeg if you wish
uint16_t w = 0, h = 0;
TJpgDec.getFsJpgSize(&w, &h, savePath); // Note name preceded with "/"
Serial.print("Width = ");
Serial.print(w);
Serial.print(", height = ");
Serial.println(h);

bool decoded = TJpgDec.drawFsJpg(0, 0, savePath);
if (decoded) {
Serial.println("JPEG image decoded and displayed successfully");
} else {
Serial.println("Failed to decode JPEG image");
}

delete[] buffer;
}


*** Newly added functionality since this instructable was published

Over to You

Feel free to comment with any useful thoughts and how you may have modified this project to suit your needs.

Have fun making it and supporting the services that have made this project possible!