Esp8266+TFT1.44(ST7735)实现基本的时钟功能

时间:2025-05-09 08:59:56
//使用TFT_eSPI库实现基本的时钟界面功能 #include <> #include <TFT_eSPI.h> TFT_eSPI tft = TFT_eSPI(); uint32_t targetTime = 0; //更新时间标志(本程序中为1秒更新) byte omm = 99; //时间的背景阴影的刷新标志 bool initial = 1; //代码段初始化标志 byte xcolon = 0; //xpos的中间储存变量 unsigned int colour = 0; static uint8_t conv2d(const char* p) //将字符串中的前两位取出并转换为数字 { uint8_t v = 0; if ('0' <= *p && *p <= '9') //比较字符的ASCII码是否在0和9之间 v = *p - '0'; //转化为数字 return 10 * v + *++p - '0'; //把两个字符转化为两位数字 } //从编译时间中分别获取小时分钟秒,+3表示两位数字和冒号 uint8_t hh=conv2d(__TIME__), mm=conv2d(__TIME__+3), ss=conv2d(__TIME__+6); void setup() { tft.init(); tft.setRotation(1); //旋转90度,屏幕旋转,参数为:0, 1, 2, 3,分别代表 0°、90°、180°、270° tft.fillScreen(TFT_BLACK); //填满黑色 tft.setTextColor(TFT_YELLOW, TFT_BLACK); //文本颜色为黄,背景为黑 targetTime = millis(); //millis()函数用于返回开始运行当前程序以来的时间(毫秒数),累积到50天溢出 } void loop() { if (targetTime + 1000 < millis()) //millis()+1000事先比millis()多1000ms,为否;直到millis()又累计1s,为真 { //每秒 targetTime = millis(); ss++; // Advance second if (ss==60) { ss=0; omm = mm; //刷新标志,每分钟更新一次 mm++; // Advance minute if(mm>59) { mm=0; hh++; // Advance hour if (hh>23) { hh=0; } } } } if (ss==0 || initial) {//每一分钟更新一次 initial = 0; tft.setTextColor(TFT_GREEN, TFT_BLACK); tft.drawCentreString(__DATE__,64,62,1); //以给定的x,y作为中心显示日期,2号类型字体 tft.drawFastHLine(4, 72, 120, TFT_WHITE); tft.setTextColor(TFT_BLUE, TFT_BLACK); tft.drawCentreString("It is windy",64,106,2); } byte xpos = 3; //设置时钟文本起始坐标 byte ypos = 10; if (omm != mm) { tft.setTextColor(0x39C4, TFT_BLACK); tft.drawString("88:88",xpos,ypos,6); //阴影灰色时钟(不变),5号字体 tft.setTextColor(0xFBE0); //电子时钟前景数字(橘色 omm = mm; //omm此处作为刷新标志,每分钟刷新分钟和小时这两个数 //和会返回打印内容的x轴方向变化的长度 if (hh<10) xpos += tft.drawChar('0',xpos,ypos,6); //小时个位数,多绘制一个零 xpos += tft.drawNumber(hh,xpos,ypos,6); //写小时,并返回位置保存在xpos xcolon=xpos; //记录小时后面的冒号x坐标位置 xpos += tft.drawChar(':',xpos,ypos,6); //写冒号 if (mm<10) xpos += tft.drawChar('0',xpos,ypos,6); //分个位数,多绘制一个零 tft.drawNumber(mm,xpos,ypos,6); //分钟 } if (ss%2) { // Flash the colon每两秒刷新冒号 tft.setTextColor(0x39C4, TFT_BLACK); xpos += tft.drawChar(':',xcolon,ypos,6); tft.setTextColor(0xFBE0, TFT_BLACK); } else { tft.drawChar(':',xcolon,ypos,6); colour = random(0xFFFF); //用黑色矩形擦除旧文本,这种方法的有效的祛除了显示闪烁 tft.fillRect(0, 86, 128, 20, TFT_BLACK); //(x,y,w,h,color) tft.setTextColor(colour); tft.drawString("Colour:",22,86,2); // Right justified string drawing to x position 75 String scolour = String(colour,HEX); scolour.toUpperCase(); //小写变大写 char buffer[20]; scolour.toCharArray(buffer,20); tft.drawString(buffer,72,86,2); //打印Colour颜色的十六进制数值 } }