【Arduino】189种传感器模块系列实验(资料代码+仿真编程+图形编程)
实验二百四十九:1.28寸圆形彩色TFT显示屏 高清IPS 模块 240*240 SPI接口GC9A01驱动
项目之四十九:GC9A01屏之通过显示动态的渐变颜色来模拟太阳升起与落下的效果
实验开源代码
- /*
- 【Arduino】189种传感器模块系列实验(资料代码+仿真编程+图形编程)
- 实验二百四十九:1.28寸圆形彩色TFT显示屏 高清IPS 模块 240*240 SPI接口GC9A01驱动
- 项目之四十九:GC9A01屏之通过显示动态的渐变颜色来模拟太阳升起与落下的效果
- */
-
- // GC9A01---------- ESP32
- // RST ------------ NC(复位引脚,此处未连接)
- // CS ------------- D4(片选引脚,连接到ESP32的D4引脚)
- // DC ------------- D2(数据/命令选择引脚,连接到ESP32的D2引脚)
- // SDA ------------ D23 (green)(主数据输出引脚,连接到ESP32的D23引脚,绿色线)
- // SCL ------------ D18 (yellow)(时钟信号引脚,连接到ESP32的D18引脚,黄色线)
- // GND ------------ GND(接地引脚,连接到ESP32的接地端)
- // VCC -------------3V3(电源引脚,连接到ESP32的3.3V电源)
-
- #include "SPI.h"
- #include "Adafruit_GFX.h"
- #include "Adafruit_GC9A01A.h"
-
- // 定义屏幕引脚
- #define TFT_CS 4 // 片选引脚
- #define TFT_DC 2 // 数据/命令引脚
- #define TFT_RST -1 // 重置引脚(未使用时设置为 -1)
-
- // 初始化屏幕对象
- Adafruit_GC9A01A tft = Adafruit_GC9A01A(TFT_CS, TFT_DC, TFT_RST);
-
- // 屏幕参数
- #define SCREEN_WIDTH 240
- #define SCREEN_HEIGHT 240
- #define SUN_RADIUS 20
- #define FRAME_DELAY 50
-
- // 定义颜色
- uint16_t nightColor = tft.color565(10, 10, 50); // 深蓝色(夜晚)
- uint16_t dawnColor = tft.color565(255, 100, 50); // 橙色(黎明/黄昏)
- uint16_t dayColor = tft.color565(135, 206, 235); // 天空蓝(白天)
- uint16_t sunColor = tft.color565(255, 255, 0); // 太阳黄色
-
- // 颜色插值函数
- uint16_t interpolateColor(uint16_t color1, uint16_t color2, float fraction) {
- uint8_t r1 = (color1 >> 11) & 0x1F;
- uint8_t g1 = (color1 >> 5) & 0x3F;
- uint8_t b1 = color1 & 0x1F;
-
- uint8_t r2 = (color2 >> 11) & 0x1F;
- uint8_t g2 = (color2 >> 5) & 0x3F;
- uint8_t b2 = color2 & 0x1F;
-
- uint8_t r = r1 + fraction * (r2 - r1);
- uint8_t g = g1 + fraction * (g2 - g1);
- uint8_t b = b1 + fraction * (b2 - b1);
-
- return (r << 11) | (g << 5) | b;
- }
-
- // 绘制背景渐变
- void drawBackground(float time) {
- uint16_t color;
-
- if (time < 0.5) { // 从深夜到白天
- color = interpolateColor(nightColor, dawnColor, time * 2);
- } else { // 从白天到夜晚
- color = interpolateColor(dawnColor, nightColor, (time - 0.5) * 2);
- }
-
- tft.fillScreen(color);
- }
-
- // 绘制太阳
- void drawSun(float time) {
- // 计算太阳的位置,沿弧线轨迹移动
- float x = SCREEN_WIDTH / 2 + cos(time * 3.14159 * 2 - 3.14159 / 2) * (SCREEN_WIDTH / 2 - SUN_RADIUS);
- float y = SCREEN_HEIGHT / 2 + sin(time * 3.14159 * 2 - 3.14159 / 2) * (SCREEN_HEIGHT / 2 - SUN_RADIUS);
-
- tft.fillCircle((int)x, (int)y, SUN_RADIUS, sunColor);
- }
-
- void setup() {
- Serial.begin(115200);
- tft.begin();
- tft.setRotation(0);
- tft.fillScreen(nightColor); // 初始化为夜晚
- }
-
- void loop() {
- static float time = 0.0; // 时间变量,范围为 [0.0, 1.0]
-
- tft.fillScreen(GC9A01A_BLACK); // 清屏
-
- drawBackground(time); // 绘制渐变背景
- drawSun(time); // 绘制太阳
-
- delay(FRAME_DELAY); // 控制帧速率
-
- time += 0.01; // 时间递增
- if (time >= 1.0) { // 循环时间
- time = 0.0;
- }
- }
复制代码
|