End of Arduino_GFX setting
******************************************************************************/
#define BACKGROUND BLACK
#define MARK_COLOR WHITE
#define SUBMARK_COLOR DARKGREY // LIGHTGREY
#define HOUR_COLOR WHITE
#define MINUTE_COLOR BLUE // LIGHTGREY
#define SECOND_COLOR RED
// init LCD constant
w = gfx->width();
h = gfx->height();
if (w < h)
{
center = w / 2;
}
else
{
center = h / 2;
}
hHandLen = center * 3 / 8;
mHandLen = center * 2 / 3;
sHandLen = center * 5 / 6;
markLen = sHandLen / 6;
cached_points = (int16_t *)malloc((hHandLen + 1 + mHandLen + 1 + sHandLen + 1) * 2 * 2);
// Draw 60 clock marks
draw_round_clock_mark(
// draw_square_clock_mark(
center - markLen, center,
center - (markLen * 2 / 3), center,
center - (markLen / 2), center);
hh = conv2d(TIME);
mm = conv2d(TIME + 3);
ss = conv2d(TIME + 6);
targetTime = ((millis() / 1000) + 1) * 1000;
}
void loop()
{
unsigned long cur_millis = millis();
if (cur_millis >= targetTime)
{
targetTime += 1000;
ss++; // Advance second
if (ss == 60)
{
ss = 0;
mm++; // Advance minute
if (mm > 59)
{
mm = 0;
hh++; // Advance hour
if (hh > 23)
{
hh = 0;
}
}
}
}
int16_t err = dx / 2;
int8_t xstep = (x0 < x1) ? 1 : -1;
int8_t ystep = (y0 < y1) ? 1 : -1;
x1 += xstep;
int16_t x, y, ox, oy;
for (uint16_t i = 0; i <= dx; i++)
{
if (steep)
{
x = y0;
y = x0;
}
else
{
x = x0;
y = y0;
}
ox = *(cache + (i * 2));
oy = *(cache + (i * 2) + 1);
if ((x == ox) && (y == oy))
{
if (cross_check_second || cross_check_hour)
{
write_cache_pixel(x, y, color, cross_check_second, cross_check_hour);
}
}
else
{
write_cache_pixel(x, y, color, cross_check_second, cross_check_hour);
if ((ox > 0) || (oy > 0))
{
write_cache_pixel(ox, oy, BACKGROUND, cross_check_second, cross_check_hour);
}
*(cache + (i * 2)) = x;
*(cache + (i * 2) + 1) = y;
}
if (err < dy)
{
y0 += ystep;
err += dx;
}
err -= dy;
x0 += xstep;
}
for (uint16_t i = dx + 1; i < cache_len; i++)
{
ox = *(cache + (i * 2));
oy = *(cache + (i * 2) + 1);
if ((ox > 0) || (oy > 0))
{
write_cache_pixel(ox, oy, BACKGROUND, cross_check_second, cross_check_hour);
}
*(cache + (i * 2)) = 0;
*(cache + (i * 2) + 1) = 0;
}
}
void write_cache_pixel(int16_t x, int16_t y, int16_t color, bool cross_check_second, bool cross_check_hour)
{
int16_t *cache = cached_points;
if (cross_check_second)
{
for (uint16_t i = 0; i <= sHandLen; i++)
{
if ((x == *(cache++)) && (y == *(cache)))
{
return;
}
cache++;
}
}
if (cross_check_hour)
{
cache = cached_points + ((sHandLen + 1) * 2);
for (uint16_t i = 0; i <= hHandLen; i++)
{
if ((x == *(cache++)) && (y == *(cache)))
{
return;
}
cache++;
}
}
gfx->writePixel(x, y, color);
}
This Arduino sketch is designed to create a minimalist watch interface using the Arduino_GFX_Library. It primarily handles the drawing and updating of clock hands on a display, managing their movements in real-time. Below is a comprehensive overview of the code, along with some insights and potential improvements.
Overview of the Code
1. Libraries and Definitions
Arduino_GFX_Library.h: This library facilitates graphics rendering on various displays compatible with Arduino.
Color Definitions: Specifies colors for different elements of the watch face, such as the background, clock marks, and the hour, minute, and second hands.
2. Constants and Helper Functions
Mathematical Constants: Defines radians and fractions useful for calculating angles and positions.
conv2d Function: Converts a two-character string (representing time, e.g., "12") into its numerical value. This is used to initialize the hour, minute, and second values from the sketch's compile time (__TIME__).
3. Global Variables
Display Dimensions and Center: Determines the width (w), height (h), and center point of the display for accurate rendering.
Hand Lengths: Defines the lengths of the hour (hHandLen), minute (mHandLen), and second (sHandLen) hands based on the display's center.
Degrees and Coordinates: Stores the current degrees for each hand and their previous (o*) and new (n*) positions.
Cache for Drawing Efficiency: Utilizes a cache (cached_points) to store previously drawn points for efficient redrawing and erasing of hands without redrawing the entire screen.
4. setup() Function
Serial Initialization: Begins serial communication for debugging purposes.
Display Initialization: Starts the display and fills the screen with the background color.
Backlight Control: Sets up the backlight pin if defined (GFX_BL).
Clock Marks Drawing: Draws either round or square clock marks around the center based on the chosen function.
Time Initialization: Sets the initial time using the compile time (__TIME__) and calculates the next target update time.
5. loop() Function
Time Tracking: Checks if the current time has reached the target update time (every second) and increments the seconds, minutes, and hours accordingly.
Hand Position Calculation: Computes the new angles and positions for each hand based on the current time.
Hands Redrawing: Calls functions to redraw the hands efficiently by updating only the changed parts using the cache.
6. Drawing Functions
draw_round_clock_mark and draw_square_clock_mark: Draws 60 marks around the center to represent seconds/minutes and distinguishes every 5th mark as a major mark.
redraw_hands_cached_draw_and_erase: Manages the redrawing of all three hands by utilizing cached points to minimize unnecessary redrawing.
draw_and_erase_cached_line: Implements Bresenham's line algorithm to draw lines (hands) efficiently and erase their previous positions using the cache.
write_cache_pixel: Writes individual pixels to the display while handling overlapping hands to ensure correct layering (e.g., second hand doesn't overwrite hour hand).
Potential Improvements and Considerations
1. Memory Management
Dynamic Memory Allocation: The cached_points array is allocated memory using malloc. While this is acceptable for microcontrollers with sufficient memory, it's crucial to ensure that the memory is managed correctly to prevent leaks or fragmentation.
Suggestion: Free the allocated memory in case the sketch is ever modified to allow dynamic reallocation or when using certain microcontrollers with limited memory.
2. Floating-Point Calculations
Performance Impact: The use of floating-point arithmetic (float types) can be computationally intensive, especially on microcontrollers without a hardware floating-point unit.
Suggestion: Consider using fixed-point arithmetic or integer math to improve performance and reduce computational overhead. This can be especially beneficial for smoother animations and lower power consumption.
3. Delay in loop()
delay(1) Usage: Introducing a delay(1) can cause slight pauses in the loop, potentially affecting the responsiveness or smoothness of the clock updates.
Suggestion: Evaluate if the delay is necessary. If it's meant to yield to other processes (like on ESP8266 with its limited multitasking), consider alternative methods like yield() or adjusting the loop's timing mechanism.
4. Code Optimization
Redundant Calculations: Some calculations, like angle adjustments, might be optimized or precomputed if they follow a predictable pattern.
Suggestion: Profile the code to identify bottlenecks and optimize the most resource-intensive sections.
5. Error Handling
Display Initialization Failure: The setup() function prints an error message if gfx->begin() fails but doesn't halt the program or attempt recovery.
Suggestion: Implement a retry mechanism or a safe fallback if the display fails to initialize, ensuring the device doesn't remain in an undefined state.
6. Extend Functionality
Additional Features: Depending on the project requirements, you might want to add features like setting alarms, displaying date, or integrating with other sensors.
Suggestion: Modularize the code to allow easy integration of additional features without disrupting the core clock functionality.
Final Thoughts
The provided sketch is a solid foundation for a minimalist watch using the Arduino platform and the Arduino_GFX library. It efficiently handles real-time clock updates and optimizes drawing operations to minimize resource usage. By addressing the potential improvements mentioned above, you can enhance the performance, reliability, and functionality of your watch project.
If you have specific questions, encounter issues, or need further assistance with particular aspects of the code, feel free to ask!