add lvgl, add can
authorkyz <kongyuzhong@google.com>
Wed, 21 Oct 2026 11:24:56 +0000 (19:24 +0800)
committerkyz <kongyuzhong@google.com>
Wed, 21 Oct 2026 12:44:59 +0000 (20:44 +0800)
20 files changed:
APP/BSP/bsp_init.c
APP/BSP/can_comm.c [new file with mode: 0644]
APP/BSP/can_comm.h [new file with mode: 0644]
APP/BSP/comm_task.c [new file with mode: 0644]
APP/BSP/comm_task.h [new file with mode: 0644]
APP/BSP/dev_can.c [new file with mode: 0644]
APP/BSP/dev_can.h [new file with mode: 0644]
APP/BSP/dev_lcd.c
APP/BSP/modbus_layer.c [new file with mode: 0644]
APP/BSP/modbus_layer.h [new file with mode: 0644]
APP/IC_Driver/lcd_st7789.c
APP/UI/ui_test_button.c [new file with mode: 0644]
APP/UI/ui_test_button.h [new file with mode: 0644]
APP/main.c
CSL/CMSIS/DeviceSupport/system_SWM341.c
Middleware/lvgl/lv_examples/lv_ex_conf.h
Middleware/lvgl/lvgl/examples/porting/lv_port_disp.c
Middleware/lvgl/lvgl/examples/porting/lv_port_indev.c
Middleware/lvgl/lvgl/lv_conf.h
dispboard_app.uvprojx

index bfd6012a26dd827f1e7cdcb44082557b43c0647a..10d0d52a915fa83d4ea74642b6e5f04b445f64c2 100644 (file)
@@ -34,13 +34,15 @@ void bsp_init(void)
     sfc_init();   //³õʼ»¯×ÜÏßÉÏÍâ¹ÒµÄSPI-Flash, ½«ÆäÓ³ÉäÖÁMCUÄÚ²¿(¿ÉÑ¡ÍâÉè)
     sdram_init(); //³õʼ»¯×ÜÏßÉÏÍâ¹ÒµÄSDRAM<оƬÄÚÖÃ>, ½«ÆäÓ³ÉäÖÁMCUÄÚ²¿(¿ÉÑ¡ÍâÉè)
     */
-
+    SystemInit();
+    sdram_init();
+    memset( (void*)0x80000000, 0, 0x800000 );
     gpio_init();
 
     //__disable_irq();
     nvic_init();
 
-    systick_init();
+    //systick_init();
     uart_debug_init();
     ///jpeg_init();
     ///crc_init();
@@ -82,6 +84,7 @@ static void nvic_init(void)
 
 void lcd_gpio_init( void )
 {
+    #if 1
     // R- 5 bit : [ 3 ~ 7 ] -- PC9-R3 PC10-R4 PC11-R5 PC12-R6  PC13-R7
     PORT_Init(PORTC, PIN9, PORTC_PIN9_LCD_R3, 0);
     PORT_Init(PORTC, PIN10, PORTC_PIN10_LCD_R4, 0);
@@ -107,7 +110,7 @@ void lcd_gpio_init( void )
     PORT_Init(PORTB, PIN2, PORTB_PIN2_LCD_VSYNC, 0);
     PORT_Init(PORTB, PIN3, PORTB_PIN3_LCD_HSYNC, 0);
     PORT_Init(PORTB, PIN4, PORTB_PIN4_LCD_DEN, 0);
-
+#endif
     //RST PD1
     GPIO_Init(GPIOD, PIN1, 1, 0, 0, 0 );
     GPIO_SetBit(GPIOD, PIN1);
@@ -125,6 +128,16 @@ void lcd_gpio_init( void )
     PORT_Init(PORTN, PIN5, PORTN_PIN5_SPI1_MOSI, 0);
 }
 
+int is_key_pressed( int id )
+{
+    GPIO_TypeDef * ports[5] = { GPIOD, GPIOD, GPIOD, GPIOD, GPIOD };
+    int pin[5] = { PIN2, PIN3, PIN4, PIN5, PIN6 };
+    if( id < 5 && GPIO_GetBit(ports[id], pin[id]) == 0 )
+        return 1;
+    else
+        return 0;
+}
+
 void key_gpio_init( void )
 {
     //KEY0-4 PD2-6
diff --git a/APP/BSP/can_comm.c b/APP/BSP/can_comm.c
new file mode 100644 (file)
index 0000000..593fbeb
--- /dev/null
@@ -0,0 +1,334 @@
+/*
+ * can_comm.c - CAN 通信层实现 (MCU/FreeRTOS 版)
+ *
+ * 由 PC demo 的 can_layer.c 移植而来,将 socketcan/pthread 实现
+ * 替换为基于 dev_can.c 的 CAN1 硬件驱动 + FreeRTOS 队列。
+ *
+ * 工作流程:
+ *   [ISR] dev_can CAN1_Handler 收到原始帧
+ *     → 回调 can_rx_isr_cb() → xQueueSendFromISR(s_rx_frame_q)
+ *   [中继任务 can_relay_task]
+ *     → 从 s_rx_frame_q 取原始帧
+ *     → 组包 reassembly → 完整 Modbus 帧
+ *     → 按地址 bit7 分流到 resp/cmd 队列
+ *     → 顺带处理 s_tx_q 中的待发帧 (分片发送)
+ */
+
+#include "can_comm.h"
+
+#include <string.h>
+
+#include "task.h"
+
+#include "dev_can.h"
+
+/* ======================== 队列参数 ======================== */
+#define RX_FRAME_Q_DEPTH   8       /* 原始帧队列深度 */
+#define MODBUS_Q_DEPTH     4       /* resp/cmd/tx 帧队列深度 */
+
+/* ======================== 队列句柄 ======================== */
+static QueueHandle_t s_rx_frame_q = NULL;   /* can_frame_t */
+static QueueHandle_t s_resp_q     = NULL;   /* can_modbus_msg_t */
+static QueueHandle_t s_cmd_q      = NULL;   /* can_modbus_msg_t */
+static QueueHandle_t s_tx_q       = NULL;   /* can_modbus_msg_t */
+
+static TaskHandle_t s_relay_task  = NULL;
+
+/* ======================== 令牌辅助 (与 PC demo 一致) ======================== */
+
+void can_token_init(can_token_t *token, uint8_t device_addr)
+{
+    if (!token)
+        return;
+    memset(token, 0, sizeof(*token));
+    token->device_addr = device_addr & 0x7F;
+    token->has_token = true;
+    token->token_seq = 0;
+}
+
+uint16_t can_token_build_pass_frame(can_token_t *token,
+                                    uint8_t slave_addr,
+                                    uint8_t *buf, uint16_t buf_size)
+{
+    if (!token || !buf || buf_size < 8)
+        return 0;
+
+    uint8_t seq = token->token_seq + 1;
+    if (seq == 0) seq = 1;   /* 跳过 0, 255→1 回绕 */
+
+    /* 写线圈 (0x05): 线圈 44 (0x002C), 值 0xFFxx */
+    buf[0] = MODBUS_ADDR_MAKE_REQUEST(slave_addr);
+    buf[1] = FUNC_WRITE_SINGLE_COIL;
+    buf[2] = 0x00;
+    buf[3] = 44;
+    buf[4] = 0xFF;
+    buf[5] = seq;
+
+    return modbus_add_crc(buf, 6);
+}
+
+void can_token_after_send(can_token_t *token)
+{
+    if (!token)
+        return;
+    token->token_seq = (token->token_seq + 1) & 0xFF;
+    token->has_token = false;
+}
+
+void can_token_after_recv(can_token_t *token, uint8_t received_seq)
+{
+    if (!token)
+        return;
+    token->token_seq = received_seq;
+    token->has_token = true;
+}
+
+/* ======================== ISR 接收回调 ========================
+ * 在 CAN1_Handler 中断上下文中被调用,只做入队,不做耗时操作。
+ */
+static void can_rx_isr_cb(uint32_t id, const uint8_t *data, uint8_t len)
+{
+    can_frame_t frame = {0};
+    BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+
+    if (!s_rx_frame_q)
+        return;
+
+    frame.id = id;
+    frame.dlc = (len > CAN_MAX_DATA) ? CAN_MAX_DATA : len;
+    if (frame.dlc > 0)
+        memcpy(frame.data, data, frame.dlc);
+
+    xQueueSendFromISR(s_rx_frame_q, &frame, &xHigherPriorityTaskWoken);
+}
+
+/* ======================== 组包 (与 PC demo 一致) ======================== */
+
+typedef struct {
+    uint8_t  packets[MAX_PACKETS][MODBUS_PER_PACKET];
+    uint8_t  packet_lens[MAX_PACKETS];
+    bool     received[MAX_PACKETS];
+    uint8_t  total_packets;
+    int      packets_rcvd;
+    uint32_t can_id;
+} reassembly_t;
+
+static void reassembly_reset(reassembly_t *rs)
+{
+    rs->total_packets = 0;
+    rs->packets_rcvd = 0;
+    rs->can_id = 0;
+    memset(rs->received, 0, sizeof(rs->received));
+    memset(rs->packet_lens, 0, sizeof(rs->packet_lens));
+}
+
+static void reassembly_init(reassembly_t *rs)
+{
+    memset(rs, 0, sizeof(*rs));
+}
+
+static bool reassembly_feed(reassembly_t *rs,
+                            const can_frame_t *frame,
+                            can_modbus_msg_t *out)
+{
+    if (frame->dlc < 2)
+        return false;
+
+    uint8_t pkt_total = frame->data[0];
+    uint8_t pkt_seq   = frame->data[1];
+
+    if (pkt_seq >= MAX_PACKETS)
+        return false;
+
+    if (rs->total_packets == 0) {
+        rs->total_packets = pkt_total;
+        if (rs->total_packets > MAX_PACKETS)
+            rs->total_packets = MAX_PACKETS;
+        rs->can_id = frame->id;
+    } else if (rs->total_packets != pkt_total) {
+        /* 新帧开始, 重置 */
+        rs->total_packets = pkt_total;
+        if (rs->total_packets > MAX_PACKETS)
+            rs->total_packets = MAX_PACKETS;
+        rs->packets_rcvd = 0;
+        rs->can_id = frame->id;
+        memset(rs->received, 0, sizeof(rs->received));
+    }
+
+    if (!rs->received[pkt_seq]) {
+        uint8_t chunk_len = frame->dlc > 2 ? frame->dlc - 2 : 0;
+        if (chunk_len > MODBUS_PER_PACKET)
+            chunk_len = MODBUS_PER_PACKET;
+        memcpy(rs->packets[pkt_seq], &frame->data[2], chunk_len);
+        rs->packet_lens[pkt_seq] = chunk_len;
+        rs->received[pkt_seq] = true;
+        rs->packets_rcvd++;
+    }
+
+    if (rs->packets_rcvd >= (int)rs->total_packets) {
+        uint8_t raw[MAX_MODBUS_FRAME];
+        uint16_t raw_len = 0;
+
+        for (int i = 0; i < rs->total_packets; i++) {
+            if (rs->packet_lens[i] > 0) {
+                memcpy(raw + raw_len, rs->packets[i], rs->packet_lens[i]);
+                raw_len += rs->packet_lens[i];
+            }
+        }
+
+        uint16_t frame_len = modbus_trim_padding(raw, raw_len);
+        if (frame_len == 0)
+            frame_len = raw_len;
+
+        out->can_id = rs->can_id;
+        out->len = (frame_len < COMM_MSG_MAX) ? frame_len : COMM_MSG_MAX;
+        memcpy(out->data, raw, out->len);
+
+        reassembly_reset(rs);
+        return true;
+    }
+
+    return false;
+}
+
+/* ======================== 发送分片 ======================== */
+
+static int can_send_modbus_frames(uint32_t id,
+                                  const uint8_t *modbus_data, uint16_t len)
+{
+    uint8_t total_packets = (len + MODBUS_PER_PACKET - 1) / MODBUS_PER_PACKET;
+
+    for (uint8_t pkt_seq = 0; pkt_seq < total_packets; pkt_seq++) {
+        uint16_t offset = pkt_seq * MODBUS_PER_PACKET;
+        uint8_t can_data[CAN_MAX_DATA] = {0};
+
+        can_data[0] = total_packets;
+        can_data[1] = pkt_seq;
+
+        uint8_t chunk_len;
+        if (offset + MODBUS_PER_PACKET <= len)
+            chunk_len = MODBUS_PER_PACKET;
+        else
+            chunk_len = len - offset;
+        memcpy(&can_data[2], modbus_data + offset, chunk_len);
+
+        if (can_send_frame(id, can_data, 2 + chunk_len) < 0)
+            return -1;
+    }
+    return 0;
+}
+
+/* ======================== RX 中继任务 ======================== */
+
+static void can_relay_task(void *arg)
+{
+    (void)arg;
+    reassembly_t rs;
+    can_frame_t  frame;
+
+    reassembly_init(&rs);
+
+    printf("[CAN-COMM] Relay task started\n");
+
+    for (;;) {
+        /* 1. 从 ISR 队列取原始帧并组包 */
+        if (xQueueReceive(s_rx_frame_q, &frame,
+                          pdMS_TO_TICKS(10)) == pdTRUE) {
+            can_modbus_msg_t rx_msg;
+            if (reassembly_feed(&rs, &frame, &rx_msg)) {
+                if (MODBUS_ADDR_IS_RESPONSE(rx_msg.data[0])) {
+                    xQueueSend(s_resp_q, &rx_msg, 0);
+                } else {
+                    xQueueSend(s_cmd_q, &rx_msg, 0);
+                }
+            }
+        }
+
+        /* 2. 处理 TX 队列 (分片发送) */
+        can_modbus_msg_t tx_msg;
+        if (xQueueReceive(s_tx_q, &tx_msg, 0) == pdTRUE) {
+            can_send_modbus_frames(tx_msg.can_id, tx_msg.data, tx_msg.len);
+        }
+    }
+}
+
+/* ======================== 生命周期 ======================== */
+
+void can_comm_init(void)
+{
+    if (s_rx_frame_q)
+        return;
+
+    s_rx_frame_q = xQueueCreate(RX_FRAME_Q_DEPTH, sizeof(can_frame_t));
+    s_resp_q     = xQueueCreate(MODBUS_Q_DEPTH, sizeof(can_modbus_msg_t));
+    s_cmd_q      = xQueueCreate(MODBUS_Q_DEPTH, sizeof(can_modbus_msg_t));
+    s_tx_q       = xQueueCreate(MODBUS_Q_DEPTH, sizeof(can_modbus_msg_t));
+
+    can_register_rx_callback(can_rx_isr_cb);
+
+    printf("[CAN-COMM] queues created\n");
+}
+
+void can_comm_start(void)
+{
+    if (s_relay_task)
+        return;
+
+    if (xTaskCreate(can_relay_task, (const char *)"cancomm",
+                    384, NULL, 2, &s_relay_task) != pdPASS) {
+        printf("[CAN-COMM] failed to create relay task\n");
+    }
+}
+
+/* ======================== 队列句柄 getter ======================== */
+
+QueueHandle_t can_comm_tx_queue(void)   { return s_tx_q; }
+QueueHandle_t can_comm_resp_queue(void) { return s_resp_q; }
+QueueHandle_t can_comm_cmd_queue(void)  { return s_cmd_q; }
+
+/* ======================== 异步收发 API ======================== */
+
+int can_send_modbus_async(QueueHandle_t tx, uint32_t id,
+                          const uint8_t *modbus_data, uint16_t len)
+{
+    can_modbus_msg_t msg;
+
+    if (!tx || !modbus_data || len == 0)
+        return -1;
+    if (len > COMM_MSG_MAX)
+        len = COMM_MSG_MAX;
+
+    msg.can_id = id;
+    msg.len = len;
+    memcpy(msg.data, modbus_data, len);
+
+    return (xQueueSend(tx, &msg, 0) == pdTRUE) ? 0 : -1;
+}
+
+int can_recv_modbus_async(QueueHandle_t rx,
+                          uint32_t *id, uint8_t *modbus_data,
+                          uint16_t max_len, uint16_t *len,
+                          TickType_t timeout)
+{
+    can_modbus_msg_t msg;
+
+    if (!rx || !modbus_data || !len)
+        return -1;
+
+    *len = 0;
+
+    if (xQueueReceive(rx, &msg, timeout) != pdTRUE)
+        return -1;
+
+    if (msg.len > max_len) {
+        printf("[CAN-COMM] frame too large: %u > %u, skipped\n",
+               msg.len, max_len);
+        return -1;
+    }
+
+    memcpy(modbus_data, msg.data, msg.len);
+    *len = msg.len;
+    if (id)
+        *id = msg.can_id;
+    return 0;
+}
\ No newline at end of file
diff --git a/APP/BSP/can_comm.h b/APP/BSP/can_comm.h
new file mode 100644 (file)
index 0000000..4f26f49
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * can_comm.h - CAN 通信层 (MCU/FreeRTOS 版)
+ *
+ * 由 PC demo 的 can_layer.h 移植而来:
+ *   - 物理层:基于 dev_can.c 的 CAN1 硬件驱动 (ISR + 回调)
+ *   - 分包层:Modbus 帧分包/组包 (CAN 帧数据 8 字节)
+ *   - 任务层:RX 中继任务,将 ISR 收到的原始帧重组为 Modbus 帧,
+ *             按地址 bit7 分流到 resp/cmd 队列;并负责发送 TX 队列数据
+ *   - 令牌管理:can_token_*
+ *
+ * Modbus 帧分片协议 (与 PC demo 一致):
+ *   Data[0] = 总包数
+ *   Data[1] = 包序号 (0-based)
+ *   Data[2..7] = Modbus 数据 (6 字节/包,最后包按实际长度)
+ */
+
+#ifndef APP_CAN_COMM_H
+#define APP_CAN_COMM_H
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#include "FreeRTOS.h"
+#include "queue.h"
+
+#include "modbus_layer.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ======================== CAN 标识符定义 ======================== */
+#define CAN_ID_MASTER       0x001   /* 主机 CAN ID */
+#define CAN_ID_SLAVE        0x002   /* 从机 CAN ID */
+#define CAN_MAX_DATA        8       /* CAN 帧最大数据长度 */
+
+/* ======================== Modbus 分片参数 ======================== */
+#define MODBUS_PER_PACKET   6       /* 每 CAN 包携带的 Modbus 数据字节数 */
+#define MAX_PACKETS         32      /* 单个 Modbus 帧最多分片数 */
+#define MAX_MODBUS_FRAME    (MAX_PACKETS * MODBUS_PER_PACKET)  /* 192 字节 */
+
+/* ======================== 原始 CAN 帧结构 ======================== */
+typedef struct {
+    uint32_t id;                    /* CAN 标识符 */
+    uint8_t  dlc;                   /* 数据长度 (0-8) */
+    uint8_t  data[CAN_MAX_DATA];    /* 数据 */
+} can_frame_t;
+
+/* ======================== Modbus 帧消息 (队列元素) ======================== */
+#define COMM_MSG_MAX    MAX_MODBUS_FRAME   /* 192 */
+
+typedef struct {
+    uint32_t can_id;                /* 来源/目的 CAN ID */
+    uint16_t len;                   /* 数据长度 */
+    uint8_t  data[COMM_MSG_MAX];    /* Modbus 帧数据 (含 CRC) */
+} can_modbus_msg_t;
+
+/* ======================== 令牌管理 ========================
+ *
+ * 令牌机制用于多主站冲突避免:
+ *   - 持有令牌的一方作为 Master,负责轮询
+ *   - 通过写线圈 44 (传递令牌) 传递,数据为 0xFFxx (xx=令牌序号)
+ *   - 令牌序号 1→2→...→255→0→1→... 循环
+ */
+typedef struct {
+    uint8_t  token_seq;             /* 当前令牌序号 (0-255) */
+    bool     has_token;             /* true = 持有令牌 (当前为 master) */
+    uint8_t  device_addr;           /* 本机设备地址 (1-127) */
+} can_token_t;
+
+/* ======================== 生命周期管理 ======================== */
+
+/**
+ * can_comm_init - 初始化通信层
+ *   - 创建原始帧/响应/指令/发送队列
+ *   - 向 dev_can 注册 ISR 接收回调
+ * 调用时机: main 中 can_init() 之后, 调度器启动前后均可。
+ */
+void can_comm_init(void);
+
+/**
+ * can_comm_start - 启动 RX 中继任务
+ * 必须由可调用 xTaskCreate/调度器的上下文调用。
+ */
+void can_comm_start(void);
+
+/* ======================== 队列句柄 ======================== */
+
+/** 发送队列 (comm 层把待发 Modbus 帧压入, 由中继任务分片发送) */
+QueueHandle_t can_comm_tx_queue(void);
+/** 响应帧队列 (modbus bit7=1, master 模式读取) */
+QueueHandle_t can_comm_resp_queue(void);
+/** 指令帧队列 (modbus bit7=0, slave 模式读取) */
+QueueHandle_t can_comm_cmd_queue(void);
+
+/* ======================== 异步收发 API ======================== */
+
+/**
+ * can_send_modbus_async - 异步发送 Modbus 帧
+ * @tx:    TX 队列 (can_comm_tx_queue())
+ * @id:    CAN 标识符
+ * @modbus_data: Modbus 帧数据 (含 CRC)
+ * @len:   长度
+ * 返回值: 0 成功, -1 队列满/参数错误
+ */
+int can_send_modbus_async(QueueHandle_t tx, uint32_t id,
+                          const uint8_t *modbus_data, uint16_t len);
+
+/**
+ * can_recv_modbus_async - 从队列接收一个完整 Modbus 帧 (阻塞可超时)
+ * @rx:        RX 队列 (can_comm_resp_queue() / can_comm_cmd_queue())
+ * @id:        CAN 标识符 (输出)
+ * @modbus_data: 接收缓冲区
+ * @max_len:   缓冲区大小
+ * @len:       实际长度 (输出)
+ * @timeout:   超时 (ticks, 可用 pdMS_TO_TICKS(x) 传入毫秒)
+ * 返回值: 0 成功, -1 超时/参数错误
+ */
+int can_recv_modbus_async(QueueHandle_t rx,
+                          uint32_t *id, uint8_t *modbus_data,
+                          uint16_t max_len, uint16_t *len,
+                          TickType_t timeout);
+
+/* ======================== 令牌管理 API ======================== */
+
+/** 初始化令牌状态: 默认持有令牌, token_seq=0 */
+void can_token_init(can_token_t *token, uint8_t device_addr);
+
+/** 构建令牌传递 Modbus 帧 (写线圈 44, 0xFFxx),返回帧长度 */
+uint16_t can_token_build_pass_frame(can_token_t *token,
+                                    uint8_t slave_addr,
+                                    uint8_t *buf, uint16_t buf_size);
+
+/** 发送令牌后更新本地状态: 释放令牌并递增序号 */
+void can_token_after_send(can_token_t *token);
+
+/** 收到令牌后更新本地状态: 获取令牌并记录序号 */
+void can_token_after_recv(can_token_t *token, uint8_t received_seq);
+
+/** 是否持有令牌 (是否为主设备) */
+static inline bool can_token_is_master(const can_token_t *token)
+{
+    return token->has_token;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* APP_CAN_COMM_H */
\ No newline at end of file
diff --git a/APP/BSP/comm_task.c b/APP/BSP/comm_task.c
new file mode 100644 (file)
index 0000000..6eff94e
--- /dev/null
@@ -0,0 +1,502 @@
+/*
+ * comm_task.c - BDM120 通信任务 (令牌状态机 + Master 轮询)
+ *
+ * 由 app_on_pc/main.c 的 comm_task() 移植到 FreeRTOS:
+ *   - 物理/分包层来自 can_comm
+ *   - Modbus 建/解析来自 modbus_layer
+ *   - 令牌状态机与 PC demo 完全一致
+ *
+ * 寄存器缓存为精简版 (仅缓存本阶段使用的关键区域),
+ * 后续 UI 阶段可扩充 POLL_AREAS。
+ */
+
+#include "comm_task.h"
+
+#include <string.h>
+#include <stdio.h>
+
+#include "FreeRTOS.h"
+#include "task.h"
+
+#include "can_comm.h"
+#include "modbus_layer.h"
+
+/* ======================== Modbus 从站地址 ======================== */
+#define SLAVE_ADDR      MODBUS_DEFAULT_ADDR
+
+/* 缓冲区大小 */
+#define MODBUS_REQ_BUF  32
+#define MODBUS_RESP_BUF COMM_MSG_MAX   /* 192 */
+
+/* ======================== 令牌传递常量 (与 PC demo 一致) ======================== */
+#define TOKEN_COIL_ADDR         44
+#define TOKEN_RETRY_MAX         3
+#define TOKEN_WAIT_BEFORE_SEND  2000    /* 发令牌前等待 2 秒 */
+#define TOKEN_RESP_TIMEOUT      2000    /* 等待回应超时 2 秒 */
+#define TOKEN_CMD_TIMEOUT       500     /* 等待指令超时 0.5 秒 */
+
+#define SLEEP_CHUNK_MS          50
+
+/* ======================== 令牌状态机 ======================== */
+typedef enum {
+    STATE_MASTER_POLL,          /* 持有令牌, 轮询全部数据 */
+    STATE_MASTER_PRE_SEND,      /* 等待 2 秒后发送令牌 */
+    STATE_SEND_TOKEN,           /* 正在发送切换指令 */
+    STATE_WAIT_TOKEN_RESP,      /* 等待切换指令回应 */
+    STATE_SLAVE_WAIT_CMD,       /* 从机模式, 等待令牌回传 */
+} token_state_t;
+
+static token_state_t g_token_state = STATE_MASTER_POLL;
+static int           g_token_seq = 0;
+static int           g_retry_count = 0;
+static int64_t       g_state_timer_ms = 0;
+static int           g_next_token_seq = 0;
+
+/* 轮询统计 */
+static struct {
+    uint32_t cycles;
+    uint32_t success;
+    uint32_t failed;
+    uint32_t total_regs_read;
+} g_stats;
+
+/* ======================== 精简寄存器缓存 ======================== */
+typedef struct {
+    int      start_addr;
+    int      count;
+    uint16_t *values;       /* pvPortMalloc 分配 */
+    bool     *valid;
+    const char *name;
+} reg_area_cache_t;
+
+#define POLL_AREAS_NUM  7
+static reg_area_cache_t g_areas[POLL_AREAS_NUM] = {
+    { 0,      78, NULL, NULL, "遥测遥信"     },
+    { 100,    40, NULL, NULL, "遥测一次值"   },
+    { 200,    12, NULL, NULL, "统计信息"     },
+    { 400,    35, NULL, NULL, "逻辑变量"     },
+    { 600,    79, NULL, NULL, "版本信息"     },
+    { 1000,   80, NULL, NULL, "保护参数"     },
+    { 40000,  24, NULL, NULL, "计量芯片转换值" },
+};
+
+static bool g_cache_inited = false;
+
+/* ======================== 时间工具 (1ms tick) ======================== */
+static int64_t get_time_ms(void)
+{
+    return (int64_t)xTaskGetTickCount(); /* configTICK_RATE_HZ=1000 */
+}
+
+static void safe_sleep(int total_ms)
+{
+    while (total_ms > 0) {
+        int chunk = (total_ms > SLEEP_CHUNK_MS) ? SLEEP_CHUNK_MS : total_ms;
+        vTaskDelay(pdMS_TO_TICKS(chunk));
+        total_ms -= chunk;
+    }
+}
+
+/* ======================== 寄存器缓存 API ======================== */
+
+static int reg_cache_init(void)
+{
+    if (g_cache_inited)
+        return 0;
+
+    size_t total_bytes = 0;
+    for (int i = 0; i < POLL_AREAS_NUM; i++) {
+        size_t sv = sizeof(uint16_t) * g_areas[i].count;
+        size_t sb = sizeof(bool) * g_areas[i].count;
+        uint8_t *mem = pvPortMalloc(sv + sb);
+        if (!mem) {
+            printf("[COMM] cache alloc failed for area %s\n",
+                   g_areas[i].name);
+            return -1;
+        }
+        memset(mem, 0, sv + sb);
+        g_areas[i].values = (uint16_t *)mem;
+        g_areas[i].valid  = (bool *)(mem + sv);
+        total_bytes += sv + sb;
+    }
+
+    g_cache_inited = true;
+    printf("[COMM] register cache ready (%u bytes)\n",
+           (unsigned)total_bytes);
+    return 0;
+}
+
+uint16_t comm_get_reg_value(uint16_t addr)
+{
+    if (!g_cache_inited)
+        return 0;
+    for (int i = 0; i < POLL_AREAS_NUM; i++) {
+        if (g_areas[i].valid && addr >= g_areas[i].start_addr &&
+            addr < (uint16_t)(g_areas[i].start_addr + g_areas[i].count)) {
+            return g_areas[i].values[addr - g_areas[i].start_addr];
+        }
+    }
+    return 0;
+}
+
+bool comm_reg_is_valid(uint16_t addr)
+{
+    if (!g_cache_inited)
+        return false;
+    for (int i = 0; i < POLL_AREAS_NUM; i++) {
+        if (g_areas[i].valid && addr >= g_areas[i].start_addr &&
+            addr < (uint16_t)(g_areas[i].start_addr + g_areas[i].count)) {
+            return g_areas[i].valid[addr - g_areas[i].start_addr];
+        }
+    }
+    return false;
+}
+
+static void reg_update_area(const reg_area_cache_t *area,
+                            const uint16_t *values)
+{
+    if (!area->values)
+        return;
+    for (int i = 0; i < area->count; i++) {
+        area->values[i] = values[i];
+        area->valid[i] = true;
+    }
+}
+
+/* ======================== 令牌辅助函数 ======================== */
+
+static int send_token_pass_frame(uint8_t next_seq)
+{
+    uint8_t req[8];
+    uint16_t value = (0xFF << 8) | next_seq;   /* 0xFFxx */
+
+    req[0] = MODBUS_ADDR_MAKE_REQUEST(SLAVE_ADDR);
+    req[1] = FUNC_WRITE_SINGLE_COIL;           /* 0x05 */
+    req[2] = (TOKEN_COIL_ADDR >> 8) & 0xFF;
+    req[3] = TOKEN_COIL_ADDR & 0xFF;
+    req[4] = (value >> 8) & 0xFF;
+    req[5] = value & 0xFF;
+    modbus_add_crc(req, 6);
+
+    printf("[TOKEN] >>> Sending token pass: coil %d, value=0x%04X "
+           "(seq=%d)\n", TOKEN_COIL_ADDR, value, next_seq);
+
+    return can_send_modbus_async(can_comm_tx_queue(), CAN_ID_MASTER,
+                                 req, 8);
+}
+
+static int send_token_pass_response(uint8_t addr, uint16_t coil,
+                                    uint16_t value)
+{
+    uint8_t resp[8];
+    uint8_t resp_addr = MODBUS_ADDR_MAKE_RESPONSE(
+                            MODBUS_ADDR_GET_DEVICE(addr));
+
+    resp[0] = resp_addr;
+    resp[1] = FUNC_WRITE_SINGLE_COIL;
+    resp[2] = (coil >> 8) & 0xFF;
+    resp[3] = coil & 0xFF;
+    resp[4] = (value >> 8) & 0xFF;
+    resp[5] = value & 0xFF;
+    modbus_add_crc(resp, 6);
+
+    return can_send_modbus_async(can_comm_tx_queue(), CAN_ID_MASTER,
+                                 resp, 8);
+}
+
+static int check_token_pass_response(int *out_seq, uint32_t timeout_ms)
+{
+    uint8_t resp[MODBUS_RESP_BUF];
+    uint16_t resp_len;
+    uint32_t can_id;
+
+    if (can_recv_modbus_async(can_comm_resp_queue(), &can_id,
+                              resp, sizeof(resp), &resp_len,
+                              pdMS_TO_TICKS(timeout_ms)) < 0)
+        return -1;   /* 超时 */
+
+    if (resp_len < 8)
+        return -1;
+
+    if (!MODBUS_ADDR_IS_RESPONSE(resp[0]) ||
+        MODBUS_ADDR_GET_DEVICE(resp[0]) != SLAVE_ADDR)
+        return -1;
+    if (resp[1] != FUNC_WRITE_SINGLE_COIL)
+        return -1;
+
+    uint16_t coil = ((uint16_t)resp[2] << 8) | resp[3];
+    if (coil != TOKEN_COIL_ADDR)
+        return -1;
+
+    uint16_t val = ((uint16_t)resp[4] << 8) | resp[5];
+    if ((val >> 8) != 0xFF)
+        return -1;
+
+    if (!modbus_check_crc(resp, resp_len))
+        return -1;
+
+    if (out_seq)
+        *out_seq = val & 0xFF;
+
+    return 0;
+}
+
+static int check_token_pass_cmd(int *out_seq, uint32_t timeout_ms)
+{
+    uint8_t cmd[MODBUS_RESP_BUF];
+    uint16_t cmd_len;
+    uint32_t can_id;
+
+    if (can_recv_modbus_async(can_comm_cmd_queue(), &can_id,
+                              cmd, sizeof(cmd), &cmd_len,
+                              pdMS_TO_TICKS(timeout_ms)) < 0)
+        return -1;   /* 超时 */
+
+    if (cmd_len < 8)
+        return -1;
+
+    if (MODBUS_ADDR_IS_RESPONSE(cmd[0]))
+        return -1;   /* 必须是指令帧 (bit7=0) */
+    if (cmd[1] != FUNC_WRITE_SINGLE_COIL)
+        return -1;
+
+    uint16_t coil = ((uint16_t)cmd[2] << 8) | cmd[3];
+    if (coil != TOKEN_COIL_ADDR)
+        return -1;
+
+    uint16_t val = ((uint16_t)cmd[4] << 8) | cmd[5];
+    if ((val >> 8) != 0xFF)
+        return -1;
+
+    if (!modbus_check_crc(cmd, cmd_len))
+        return -1;
+
+    /* 发送回应 */
+    int new_seq = val & 0xFF;
+    send_token_pass_response(cmd[0], coil, val);
+
+    printf("[TOKEN] <<< Received token pass cmd: seq=%d, "
+           "response sent\n", new_seq);
+
+    if (out_seq)
+        *out_seq = new_seq;
+
+    return 0;
+}
+
+/* ======================== 单个区域轮询 ======================== */
+
+static int poll_area_async(const reg_area_cache_t *area)
+{
+    uint8_t  req[MODBUS_REQ_BUF];
+    uint8_t  resp[MODBUS_RESP_BUF];
+    uint16_t req_len, resp_len;
+    uint16_t values[MODBUS_RESP_BUF / 2];
+    uint32_t can_id;
+
+    req_len = modbus_build_read_holding_regs(SLAVE_ADDR,
+                                             area->start_addr,
+                                             area->count, req);
+    if (req_len == 0) {
+        printf("[POLL] Failed to build request for %s\n", area->name);
+        return -1;
+    }
+
+    if (can_send_modbus_async(can_comm_tx_queue(), CAN_ID_MASTER,
+                              req, req_len) < 0) {
+        printf("[POLL] TX queue full for %s\n", area->name);
+        return -1;
+    }
+
+    if (can_recv_modbus_async(can_comm_resp_queue(), &can_id,
+                              resp, sizeof(resp), &resp_len,
+                              pdMS_TO_TICKS(2000)) < 0) {
+        printf("[POLL] Timeout for %s (0x%04X, %u regs)\n",
+               area->name, area->start_addr, area->count);
+        return -1;
+    }
+
+    if (can_id != CAN_ID_SLAVE) {
+        printf("[POLL] Unexpected source: 0x%03X\n", (unsigned)can_id);
+        return -1;
+    }
+
+    int count = modbus_parse_read_response(resp, resp_len, values,
+                                           MODBUS_RESP_BUF / 2);
+    if (count < 0) {
+        printf("[POLL] Parse error for %s (code=%d)\n", area->name, count);
+        return -1;
+    }
+
+    reg_update_area(area, values);
+
+    return (int)area->count;
+}
+
+static int do_poll_cycle(void)
+{
+    int cycle_success = 0;
+    int cycle_failed  = 0;
+    int total_regs    = 0;
+
+    for (int i = 0; i < POLL_AREAS_NUM; i++) {
+        int ret = poll_area_async(&g_areas[i]);
+        if (ret >= 0) {
+            cycle_success++;
+            total_regs += ret;
+        } else {
+            cycle_failed++;
+        }
+    }
+
+    g_stats.cycles++;
+    g_stats.success += cycle_success;
+    g_stats.failed  += cycle_failed;
+    g_stats.total_regs_read += total_regs;
+
+    printf("[CYCLE #%u] OK=%d, FAIL=%d, regs=%d/%d areas\n",
+           g_stats.cycles, cycle_success, cycle_failed,
+           total_regs, POLL_AREAS_NUM);
+
+    return cycle_failed;
+}
+
+/* ======================== 通信任务主体 ======================== */
+
+static void comm_task_entry(void *arg)
+{
+    (void)arg;
+    const char *role_str = "MASTER";
+    int64_t last_stat_ts = 0;
+    token_state_t shown_state = (token_state_t)-1;
+
+    printf("[COMM] Task started, token seq=%d, role=MASTER\n", g_token_seq);
+
+    for (;;) {
+        int64_t start_ms = get_time_ms();
+
+        switch (g_token_state) {
+
+        case STATE_MASTER_POLL: {
+            role_str = "MASTER";
+            do_poll_cycle();
+
+            printf("[TOKEN] Poll complete, waiting %dms before "
+                   "sending token (seq=%d -> %d)\n",
+                   TOKEN_WAIT_BEFORE_SEND,
+                   g_token_seq, g_next_token_seq);
+
+            g_state_timer_ms = get_time_ms();
+            g_token_state = STATE_MASTER_PRE_SEND;
+            break;
+        }
+
+        case STATE_MASTER_PRE_SEND: {
+            role_str = "MASTER";
+            int64_t elapsed = get_time_ms() - g_state_timer_ms;
+            if (elapsed >= TOKEN_WAIT_BEFORE_SEND) {
+                printf("[TOKEN] Pre-send wait done (%lldms), "
+                       "sending token seq=%d\n",
+                       (long long)elapsed, g_next_token_seq);
+                g_token_state = STATE_SEND_TOKEN;
+            } else {
+                int remain = (int)(TOKEN_WAIT_BEFORE_SEND - elapsed);
+                safe_sleep(remain > 0 ? remain : 50);
+            }
+            break;
+        }
+
+        case STATE_SEND_TOKEN: {
+            role_str = "MASTER";
+            int ret = send_token_pass_frame(
+                          (uint8_t)(g_next_token_seq & 0xFF));
+            if (ret == 0) {
+                g_state_timer_ms = get_time_ms();
+                g_token_state = STATE_WAIT_TOKEN_RESP;
+                printf("[TOKEN] Token frame sent, retry=%d/%d\n",
+                       g_retry_count, TOKEN_RETRY_MAX);
+            } else {
+                printf("[TOKEN] Failed to send token frame, retrying\n");
+                safe_sleep(100);
+            }
+            break;
+        }
+
+        case STATE_WAIT_TOKEN_RESP: {
+            role_str = "MASTER";
+            int resp_seq = 0;
+            if (check_token_pass_response(&resp_seq,
+                                           TOKEN_RESP_TIMEOUT) == 0) {
+                g_token_seq = g_next_token_seq;
+                printf("[TOKEN] <<< Token pass ACK (seq=%d), "
+                       "switching to SLAVE\n", resp_seq);
+                g_state_timer_ms = get_time_ms();
+                g_token_state = STATE_SLAVE_WAIT_CMD;
+                g_retry_count = 0;
+            } else {
+                g_retry_count++;
+                printf("[TOKEN] Response timeout (attempt %d/%d)\n",
+                       g_retry_count, TOKEN_RETRY_MAX);
+                if (g_retry_count >= TOKEN_RETRY_MAX) {
+                    printf("[TOKEN] Max retries, staying MASTER, "
+                           "restart poll\n");
+                    g_retry_count = 0;
+                    g_token_state = STATE_MASTER_POLL;
+                } else {
+                    g_token_state = STATE_SEND_TOKEN;
+                }
+            }
+            break;
+        }
+
+        case STATE_SLAVE_WAIT_CMD: {
+            role_str = "SLAVE";
+            int cmd_seq = 0;
+            if (check_token_pass_cmd(&cmd_seq, TOKEN_CMD_TIMEOUT) == 0) {
+                g_token_seq = cmd_seq;
+                g_next_token_seq = (cmd_seq + 1) & 0xFF;
+                if (g_next_token_seq == 0)
+                    g_next_token_seq = 1;
+                printf("[TOKEN] <<< Token from other board (seq=%d), "
+                       "switching to MASTER\n", cmd_seq);
+                g_token_state = STATE_MASTER_POLL;
+            } else {
+                safe_sleep(50);
+            }
+            break;
+        }
+
+        default:
+            g_token_state = STATE_MASTER_POLL;
+            break;
+        }
+
+        /* 每 1000ms 打印一次状态变化 */
+        if (get_time_ms() - last_stat_ts > 1000) {
+            last_stat_ts = get_time_ms();
+            if (shown_state != g_token_state) {
+                shown_state = g_token_state;
+                printf("[STATS] State=%d | Role=%s | TokenSeq=%d | "
+                       "Cycles=%u (OK=%u, FAIL=%u, regs=%u)\n",
+                       g_token_state, role_str, g_token_seq,
+                       g_stats.cycles, g_stats.success, g_stats.failed,
+                       g_stats.total_regs_read);
+            }
+        }
+
+        (void)start_ms;
+    }
+}
+
+int comm_task_create(void)
+{
+    if (reg_cache_init() < 0)
+        return -1;
+
+    if (xTaskCreate(comm_task_entry, (const char *)"comm",
+                    512, NULL, 3, NULL) != pdPASS) {
+        printf("[COMM] failed to create comm task\n");
+        return -1;
+    }
+    return 0;
+}
\ No newline at end of file
diff --git a/APP/BSP/comm_task.h b/APP/BSP/comm_task.h
new file mode 100644 (file)
index 0000000..7d8d6e0
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * comm_task.h - BDM120 通信任务 (令牌状态机)
+ *
+ * 由 PC demo app_on_pc/main.c 的 comm_task 移植而来:
+ *   - 主从令牌状态机 (MASTER 轮询 / 传递令牌 / SLAVE 等待令牌)
+ *   - Master 持有令牌时通过 CAN 轮询保护板寄存器
+ *   - 维护精简的寄存器缓存, 供后续 UI 层读取
+ */
+
+#ifndef APP_COMM_TASK_H
+#define APP_COMM_TASK_H
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * comm_task_create - 创建通信任务 (FreeRTOS task)
+ * 返回 0 成功, -1 失败
+ */
+int comm_task_create(void);
+
+/**
+ * comm_get_reg_value - 读取缓存的寄存器值
+ * @addr: Modbus 地址
+ * 返回值: 缓存值, 地址不在缓存中返回 0
+ */
+uint16_t comm_get_reg_value(uint16_t addr);
+
+/**
+ * comm_reg_is_valid - 判断某地址的寄存器是否已成功读到
+ */
+bool comm_reg_is_valid(uint16_t addr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* APP_COMM_TASK_H */
\ No newline at end of file
diff --git a/APP/BSP/dev_can.c b/APP/BSP/dev_can.c
new file mode 100644 (file)
index 0000000..8b7748c
--- /dev/null
@@ -0,0 +1,123 @@
+/**
+ * @file dev_can.c
+ * @brief CAN 底层驱动实现
+ * @version 0.2
+ * @date 2026-10-16
+ *
+ * 基于 SWM341 CAN1 硬件驱动:
+ *   - 500kbps, 正常模式
+ *   - 标准帧, 接收过滤器 0x001(Master)/0x002(Slave)
+ *   - 中断接收, 经由回调上报给 can_comm
+ *   - 发送采用阻塞式 (等待发送完成)
+ */
+
+#include "SWM341.h"
+
+#include <stdio.h>
+
+#include "dev_can.h"
+
+/* CAN 标识符 */
+#define CAN_ID_MASTER       0x001
+#define CAN_ID_SLAVE        0x002
+#define CAN_MAX_DATA        8
+
+static volatile can_rx_callback_t s_rx_cb = NULL;
+
+void can_init(void)
+{
+    CAN_InitStructure CAN_initStruct;
+
+    PORT_Init(PORTM, PIN0, PORTM_PIN0_CAN1_TX, 0);  /* GPIOM.0 -> CAN1 TX */
+    PORT_Init(PORTM, PIN1, PORTM_PIN1_CAN1_RX, 1);  /* GPIOM.1 -> CAN1 RX */
+
+    CAN_initStruct.Mode = CAN_MODE_NORMAL;
+    CAN_initStruct.CAN_bs1 = CAN_BS1_5tq;
+    CAN_initStruct.CAN_bs2 = CAN_BS2_4tq;
+    CAN_initStruct.CAN_sjw = CAN_SJW_2tq;
+    CAN_initStruct.Baudrate = 1000000;   /* 500 kbps */
+    CAN_initStruct.RXNotEmptyIEn = 1;
+    CAN_initStruct.ArbitrLostIEn = 0;
+    CAN_initStruct.ErrPassiveIEn = 1;
+    CAN_Init(CAN1, &CAN_initStruct);
+
+    CAN_INTEn(CAN1, CAN_IT_ERR_WARN | CAN_IT_RX_OVERFLOW);
+
+    /* 标准帧过滤器: ID 0x001 (Master) 和 0x002 (Slave) */
+    CAN_SetFilter16b(CAN1, CAN_FILTER_1, 0x001, 0x7FF, 0x002, 0x7FF);
+    CAN_SetFilter16b(CAN1, CAN_FILTER_2, 0x001, 0x7FF, 0x002, 0x7FF);
+
+    CAN_Open(CAN1);
+
+    printf("[CAN] CAN1 initialized @500kbps\n");
+}
+
+int can_send_frame(uint32_t id, const uint8_t *data, uint8_t len)
+{
+    uint8_t tx_data[CAN_MAX_DATA] = {0};
+    int i;
+
+    if (len > CAN_MAX_DATA)
+        len = CAN_MAX_DATA;
+    if (id > 0x7FF)
+        return -1;
+
+    for (i = 0; i < len; i++)
+        tx_data[i] = data[i];
+
+    if (CAN_TXBufferReady(CAN1) == 0)
+        return -1;
+
+    CAN_Transmit(CAN1, CAN_FRAME_STD, id, tx_data, len, 1);
+
+    /* 等待发送完成 (带简单超时, 防止总线关闭时死等) */
+    while (CAN_TXComplete(CAN1) == 0) {
+        if (CAN1->SR & CAN_SR_BUSOFF_Msk) {
+            CAN_Open(CAN1);   /* Bus Off 恢复 */
+            return -1;
+        }
+        __NOP();
+    }
+    return 0;
+}
+
+void can_register_rx_callback(can_rx_callback_t cb)
+{
+    s_rx_cb = cb;
+}
+
+void CAN1_Handler(void)
+{
+    uint32_t int_sr = CAN_INTStat(CAN1);
+
+    if (int_sr & CAN_IF_RXDA_Msk) {
+        CAN_RXMessage msg;
+
+        CAN_Receive(CAN1, &msg);
+
+        if (msg.size > 0) {
+            if (s_rx_cb)
+                s_rx_cb(msg.id, msg.data, msg.size);
+        }
+    }
+
+    if (int_sr & CAN_IF_RXOV_Msk) {
+        printf("[CAN] RX Overflow\n");
+        CAN_Close(CAN1);
+        __NOP();
+        CAN_Open(CAN1);
+    }
+
+    if (int_sr & CAN_IF_ERRWARN_Msk) {
+        if (CAN1->SR & CAN_SR_BUSOFF_Msk) {
+            printf("[CAN] Bus Off, recovering\n");
+            CAN_Open(CAN1);
+        } else if (CAN1->SR & CAN_SR_ERRWARN_Msk) {
+            printf("[CAN] Error Warning\n");
+        }
+    }
+
+    if (int_sr & CAN_IF_ERRPASS_Msk) {
+        printf("[CAN] Error Passive\n");
+    }
+}
\ No newline at end of file
diff --git a/APP/BSP/dev_can.h b/APP/BSP/dev_can.h
new file mode 100644 (file)
index 0000000..81dabfe
--- /dev/null
@@ -0,0 +1,57 @@
+/**
+ * @file dev_can.h
+ * @brief CAN 底层驱动接口
+ * @version 0.2
+ * @date 2026-10-16
+ *
+ * 供上层 can_comm.c 使用的硬件抽象:
+ *   - can_init:        CAN1 初始化 (500kbps, 标准帧, 过滤器 0x001/0x002)
+ *   - can_send_frame:  发送一帧原始 CAN 数据 (阻塞等待空闲)
+ *   - can_register_rx_callback: 注册 ISR 接收回调
+ */
+
+#ifndef __DEV_CAN_H__
+#define __DEV_CAN_H__
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * CAN 接收回调函数原型。
+ * @param id   CAN 标识符
+ * @param data 数据指针 (最多 8 字节)
+ * @param len  数据长度
+ * 该回调在 CAN1_Handler 中断上下文中被调用,
+ * 回调内禁止调用阻塞函数,仅可入队。
+ */
+typedef void (*can_rx_callback_t)(uint32_t id,
+                                  const uint8_t *data, uint8_t len);
+
+/**
+ * @brief CAN1 初始化 (500kbps, 标准帧, 接收过滤器 0x001/0x002)
+ */
+void can_init(void);
+
+/**
+ * @brief 发送一帧标准帧 CAN 数据
+ * @param id   CAN 标识符 (11 位标准帧)
+ * @param data 数据指针 (最多 8 字节)
+ * @param len  数据长度 (0-8)
+ * @return 0 成功, -1 失败
+ */
+int can_send_frame(uint32_t id, const uint8_t *data, uint8_t len);
+
+/**
+ * @brief 注册 CAN 接收中断回调 (每个驱动仅支持一个回调)
+ * @param cb 回调函数, 传 NULL 取消
+ */
+void can_register_rx_callback(can_rx_callback_t cb);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //__DEV_CAN_H__
\ No newline at end of file
index 12e0219b5e7229538812d010d9e061cb714a0f53..da481300083cc9f838bd1343a30cca358f878f9e 100644 (file)
@@ -59,7 +59,7 @@ void lcd_init(void)
     lcd_st7789_spi_init();
 
     /** 320*240 */
-    LCD_initStruct.ClkDiv = 5;
+    LCD_initStruct.ClkDiv = 10;
     LCD_initStruct.Format = LCD_FMT_RGB565;
     LCD_initStruct.HnPixel = LCD_HDOT;
     LCD_initStruct.VnPixel = LCD_VDOT;
@@ -80,7 +80,7 @@ void lcd_init(void)
     /* 0-ʧÄÜ´«ÊäÍê³ÉÖжÏ, Ë¢ÍêÒ»Ö¡×Ô¶¯¿ªÊ¼Ë¢ÐÂÏÂÒ»Ö¡(Óû§ÎÞÐë²ÎÓë)
      * 1-ʹÄÜ´«ÊäÍê³ÉÖжÏ, ÐëÔÚÖжÏÄÚÈí¼þÆô¶¯Ë¢ÐÂÏÂÒ»Ö¡(¿ªÆôºó¿ÉÌṩ½Ó¿ÚÒÔ²âÊÔʵ¼ÊÖ¡ÂÊ) 
      */
-    LCD_initStruct.IntEOTEn = 0;
+    LCD_initStruct.IntEOTEn = 1;
 
     /* LCD Ä£¿é³õʼ»¯ */
     LCD_Init(LCD, &LCD_initStruct);
@@ -154,9 +154,21 @@ void lcd_set_bg_light(uint8_t percentage)
 
 /**
  * @brief   LCD ISR Callback
+ *
+ * @note    (TEAR-FREE) The flushing routine lv_port_disp.c ½ö½öµÇ¼Ç×îеľÍÐ÷Ö¡µØÖ·
+ *          (lvgl_show_addr), ²¢²»»áÔÚÖÐ;Çл»Ó²¼þ ADDR. ±¾ÖжÏÔÚ"´«ÊäÍê³É"(Ò»Ö¡½áÊø,
+ *          ¼´´¹Ö±ÏûÒþÇø)±»´¥·¢, ´Ëʱ²Å°Ñ×îоÍÐ÷Ö¡µØÖ·Í¬²½Ð´Èë LCD ²ã ADDR ²¢ÖØÔØ,
+ *          ´Ó¶ø±£Ö¤ÆÁÄ»²»»áÏÔʾ³öÒ»°ë¾ÉÖ¡ + Ò»°ëÐÂÖ¡µÄ˺ÁÑ»­Ãæ.
  */
 void isr_lcd_transfer_done(void)
 {
+    extern volatile uint32_t lvgl_show_addr;
+
     LCD_INTClr(LCD);
+
+    /* ÔÚ´¹Ö±ÏûÒþÆÚͬ²½Çл»ÏÔ´æµØÖ·, VBPRELOAD ÈÃеØÖ·ÔÚÏÂÒ»¸ö VBP ÖÜÆÚÉúÐ§ÖØÔØ */
+    LCD->L[LCD_LAYER_1].ADDR = lvgl_show_addr;
+    LCD->CR |= (1 << LCD_CR_VBPRELOAD_Pos);
+
     LCD_Start(LCD);
-}
+}
\ No newline at end of file
diff --git a/APP/BSP/modbus_layer.c b/APP/BSP/modbus_layer.c
new file mode 100644 (file)
index 0000000..645f27a
--- /dev/null
@@ -0,0 +1,279 @@
+/*
+ * modbus_layer.c - Modbus RTU 协议层实现 (MCU 移植版)
+ *
+ * 实现 CRC-16-IBM (多项式 0xA001),与 PC demo 端保持一致。
+ * 所有的数据均使用大端序网络字节序 (MSB first)。
+ *
+ * 由 app_on_pc/modbus_layer.c 移植而来,仅将 fprintf(stderr, ...)
+ * 改为 printf(...) 以适配嵌入式串口重定向输出。
+ */
+
+#include "modbus_layer.h"
+
+#include <string.h>
+#include <stdio.h>
+
+/* ======================== CRC16 实现 ======================== */
+
+uint16_t modbus_crc16(const uint8_t *data, uint16_t len)
+{
+    uint16_t crc = 0xFFFF;
+
+    for (uint16_t i = 0; i < len; i++) {
+        crc ^= data[i];
+        for (int j = 0; j < 8; j++) {
+            if (crc & 0x0001)
+                crc = (crc >> 1) ^ 0xA001;
+            else
+                crc >>= 1;
+        }
+    }
+    return crc;
+}
+
+bool modbus_check_crc(const uint8_t *frame, uint16_t len)
+{
+    if (len < 4)
+        return false;
+
+    uint16_t recv_crc = (uint16_t)frame[len - 2] |
+                       ((uint16_t)frame[len - 1] << 8);
+    uint16_t calc_crc = modbus_crc16(frame, len - 2);
+    return recv_crc == calc_crc;
+}
+
+uint16_t modbus_add_crc(uint8_t *frame, uint16_t len)
+{
+    uint16_t crc = modbus_crc16(frame, len);
+    frame[len]     = crc & 0xFF;       /* CRC 低字节在前 */
+    frame[len + 1] = (crc >> 8) & 0xFF; /* CRC 高字节在后 */
+    return len + 2;
+}
+
+/* ======================== 构建请求帧 ======================== */
+
+uint16_t modbus_build_read_holding_regs(uint8_t slave_addr,
+                                         uint16_t start_addr,
+                                         uint16_t quantity,
+                                         uint8_t *buf)
+{
+    buf[0] = MODBUS_ADDR_MAKE_REQUEST(slave_addr);
+    buf[1] = FUNC_READ_HOLDING_REGS;
+    buf[2] = (start_addr >> 8) & 0xFF;
+    buf[3] = start_addr & 0xFF;
+    buf[4] = (quantity >> 8) & 0xFF;
+    buf[5] = quantity & 0xFF;
+    return modbus_add_crc(buf, 6);
+}
+
+uint16_t modbus_build_read_coils(uint8_t slave_addr,
+                                  uint16_t start_addr,
+                                  uint16_t quantity,
+                                  uint8_t *buf)
+{
+    buf[0] = MODBUS_ADDR_MAKE_REQUEST(slave_addr);
+    buf[1] = FUNC_READ_COILS;
+    buf[2] = (start_addr >> 8) & 0xFF;
+    buf[3] = start_addr & 0xFF;
+    buf[4] = (quantity >> 8) & 0xFF;
+    buf[5] = quantity & 0xFF;
+    return modbus_add_crc(buf, 6);
+}
+
+uint16_t modbus_build_write_single_reg(uint8_t slave_addr,
+                                        uint16_t reg_addr,
+                                        uint16_t value,
+                                        uint8_t *buf)
+{
+    buf[0] = MODBUS_ADDR_MAKE_REQUEST(slave_addr);
+    buf[1] = FUNC_WRITE_SINGLE_REG;
+    buf[2] = (reg_addr >> 8) & 0xFF;
+    buf[3] = reg_addr & 0xFF;
+    buf[4] = (value >> 8) & 0xFF;
+    buf[5] = value & 0xFF;
+    return modbus_add_crc(buf, 6);
+}
+
+uint16_t modbus_build_write_multiple_regs(uint8_t slave_addr,
+                                           uint16_t start_addr,
+                                           const uint16_t *values,
+                                           uint16_t count,
+                                           uint8_t *buf,
+                                           uint16_t buf_size)
+{
+    uint16_t req_len = 7 + count * 2 + 2; /* header + data + crc */
+    if (buf_size < req_len)
+        return 0;
+
+    buf[0] = MODBUS_ADDR_MAKE_REQUEST(slave_addr);
+    buf[1] = FUNC_WRITE_MULTIPLE_REGS;
+    buf[2] = (start_addr >> 8) & 0xFF;
+    buf[3] = start_addr & 0xFF;
+    buf[4] = (count >> 8) & 0xFF;
+    buf[5] = count & 0xFF;
+    buf[6] = count * 2;  /* 字节数 */
+
+    for (uint16_t i = 0; i < count; i++) {
+        buf[7 + i * 2]     = (values[i] >> 8) & 0xFF;
+        buf[7 + i * 2 + 1] = values[i] & 0xFF;
+    }
+
+    return modbus_add_crc(buf, 7 + count * 2);
+}
+
+uint16_t modbus_build_write_single_coil(uint8_t slave_addr,
+                                         uint16_t coil_addr,
+                                         bool on,
+                                         uint8_t *buf)
+{
+    buf[0] = MODBUS_ADDR_MAKE_REQUEST(slave_addr);
+    buf[1] = FUNC_WRITE_SINGLE_COIL;
+    buf[2] = (coil_addr >> 8) & 0xFF;
+    buf[3] = coil_addr & 0xFF;
+    buf[4] = on ? 0xFF : 0x00;
+    buf[5] = on ? 0x00 : 0x00;
+    return modbus_add_crc(buf, 6);
+}
+
+/* ======================== 解析响应帧 ======================== */
+
+int modbus_parse_read_response(const uint8_t *frame, uint16_t len,
+                                uint16_t *values, uint16_t max)
+{
+    if (!frame || !values || len < 5)
+        return -1;
+
+    /* CRC 校验 */
+    if (!modbus_check_crc(frame, len))
+        return -1;
+
+    uint8_t raw_addr = frame[0];
+    uint8_t func     = frame[1];
+    uint8_t bc       = frame[2];  /* 字节数 */
+    uint16_t count    = bc / 2;
+
+    /* 校验地址标志: 响应帧 bit7 必须为 1 */
+    if (!MODBUS_ADDR_IS_RESPONSE(raw_addr)) {
+        printf("[MODBUS] Not a response frame: addr=0x%02X\n",
+                raw_addr);
+        return -1;
+    }
+    uint8_t addr = MODBUS_ADDR_GET_DEVICE(raw_addr);
+
+    /* 检查功能码 */
+    if (func == (FUNC_READ_HOLDING_REGS | 0x80)) {
+        printf("[MODBUS] Slave returned exception 0x%02X "
+                "(addr=%d, func=0x%02X)\n",
+                len > 3 ? frame[3] : 0, addr, func & 0x7F);
+        return -2;
+    }
+
+    if (func != FUNC_READ_HOLDING_REGS && func != FUNC_READ_COILS) {
+        printf("[MODBUS] Unexpected function code: 0x%02X\n", func);
+        return -1;
+    }
+
+    /* 检查长度 */
+    if (len < (uint16_t)(3 + bc + 2)) {
+        printf("[MODBUS] Frame too short: %u < %u\n",
+                len, 3 + bc + 2);
+        return -1;
+    }
+
+    if (count > max)
+        count = max;
+
+    /* 提取寄存器值 (大端序转换) */
+    for (uint16_t i = 0; i < count; i++) {
+        values[i] = ((uint16_t)frame[3 + i * 2] << 8) |
+                     (uint16_t)frame[3 + i * 2 + 1];
+    }
+
+    return (int)count;
+}
+
+int modbus_parse_coils_response(const uint8_t *frame, uint16_t len,
+                                 bool *coils, uint16_t max)
+{
+    if (!frame || !coils || len < 5)
+        return -1;
+
+    if (!modbus_check_crc(frame, len))
+        return -1;
+
+    uint8_t raw_addr = frame[0];
+    uint8_t func     = frame[1];
+    uint8_t bc       = frame[2];  /* 数据字节数 */
+
+    /* 校验地址标志: 响应帧 bit7 必须为 1 */
+    if (!MODBUS_ADDR_IS_RESPONSE(raw_addr)) {
+        printf("[MODBUS] Not a response frame: addr=0x%02X\n",
+                raw_addr);
+        return -1;
+    }
+    uint8_t addr = MODBUS_ADDR_GET_DEVICE(raw_addr);
+    (void)addr;
+
+    if (func != FUNC_READ_COILS) {
+        if (func == (FUNC_READ_COILS | 0x80)) {
+            printf("[MODBUS] Coils read exception 0x%02X\n",
+                    len > 3 ? frame[3] : 0);
+            return -2;
+        }
+        return -1;
+    }
+
+    if (len < (uint16_t)(3 + bc + 2))
+        return -1;
+
+    /* 解析线圈位 */
+    uint16_t count = 0;
+    for (uint8_t i = 0; i < bc && count < max; i++) {
+        for (int bit = 0; bit < 8 && count < max; bit++) {
+            coils[count++] = (frame[3 + i] >> bit) & 0x01;
+        }
+    }
+
+    return (int)count;
+}
+
+/* ======================== CAN 填充修剪 ======================== */
+
+uint16_t modbus_trim_padding(const uint8_t *data, uint16_t len)
+{
+    /* CAN 组包填充零修剪。
+     *
+     * 优化策略:
+     *   利用地址字节 bit7 区分请求/响应帧:
+     *   - 响应帧 (bit7=1): 通过协议头直接算出精确长度,O(1)
+     *   - 请求帧 (bit7=0): 回退到 CRC 遍历
+     */
+    if (len < 5)
+        return 0;
+
+    /* ---- 响应帧: 协议头直接算长度 ---- */
+    if (MODBUS_ADDR_IS_RESPONSE(data[0])) {
+        uint8_t func = data[1];
+
+        if (func == FUNC_READ_HOLDING_REGS || func == FUNC_READ_COILS) {
+            uint16_t byte_count = data[2];
+            uint16_t expected = (uint16_t)3 + byte_count + 2;
+            if (expected <= len && modbus_check_crc(data, expected))
+                return expected;
+        } else if (func & 0x80) {
+            if (modbus_check_crc(data, 5))
+                return 5;
+        } else {
+            /* 写操作响应 (0x05/0x06/0x10): 固定 8 字节 */
+            if (len >= 8 && modbus_check_crc(data, 8))
+                return 8;
+        }
+    }
+
+    /* ---- 请求帧或协议头推算失败: CRC 遍历 ---- */
+    for (int i = (int)len; i >= 5; i--) {
+        if (modbus_check_crc(data, (uint16_t)i))
+            return (uint16_t)i;
+    }
+    return 0;
+}
\ No newline at end of file
diff --git a/APP/BSP/modbus_layer.h b/APP/BSP/modbus_layer.h
new file mode 100644 (file)
index 0000000..7289894
--- /dev/null
@@ -0,0 +1,183 @@
+/*
+ * modbus_layer.h - Modbus RTU 协议层
+ *
+ * 实现 Modbus RTU 帧的构建和解析:
+ *   - CRC16 校验
+ *   - 功能码 0x03: 读保持寄存器
+ *   - 功能码 0x06: 写单个寄存器
+ *   - 功能码 0x10: 写多个寄存器
+ *   - 功能码 0x05: 写单个线圈
+ *
+ * 数据格式:大端序 (MSB first),与标准 Modbus RTU 一致。
+ * CRC 使用 CRC-16-IBM (多项式 0xA001)。
+ *
+ * 本文件为 PC demo (app_on_pc/modbus_layer.h) 的 MCU 移植版,
+ * 为平台无关层。
+ */
+
+#ifndef MODBUS_LAYER_H
+#define MODBUS_LAYER_H
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ======================== Modbus 协议常量 ======================== */
+#define MODBUS_BROADCAST_ADDR   0   /* 广播地址 */
+#define MODBUS_DEFAULT_ADDR     1   /* 默认从站地址 */
+
+/*
+ * 设备地址编码规则 (bit7 标志):
+ *   bit7 = 0: 主动发出的 Modbus 指令 (request)
+ *   bit7 = 1: 响应帧 (response)
+ *   bit6-0: 设备地址 (1-127)
+ */
+#define MODBUS_ADDR_MAKE_REQUEST(addr)  ((uint8_t)((addr) & 0x7F))
+#define MODBUS_ADDR_MAKE_RESPONSE(addr) ((uint8_t)((addr) | 0x80))
+#define MODBUS_ADDR_IS_RESPONSE(addr)   (((uint8_t)(addr) & 0x80) != 0)
+#define MODBUS_ADDR_GET_DEVICE(addr)    ((uint8_t)(addr) & 0x7F)
+
+/* 功能码 */
+#define FUNC_READ_COILS             0x01
+#define FUNC_READ_HOLDING_REGS      0x03
+#define FUNC_WRITE_SINGLE_COIL      0x05
+#define FUNC_WRITE_SINGLE_REG       0x06
+#define FUNC_WRITE_MULTIPLE_REGS    0x10
+
+/* ======================== API 函数 ======================== */
+
+/**
+ * modbus_crc16 - 计算 Modbus CRC16 校验值
+ * @data: 数据缓冲区
+ * @len:  数据长度
+ * 返回值: CRC16 校验值
+ */
+uint16_t modbus_crc16(const uint8_t *data, uint16_t len);
+
+/**
+ * modbus_check_crc - 检查 CRC 是否匹配
+ * @frame: 包含 CRC 的完整 Modbus 帧 (最后2字节为 CRC)
+ * @len:   帧长度
+ * 返回值: true 校验通过, false 失败
+ */
+bool modbus_check_crc(const uint8_t *frame, uint16_t len);
+
+/**
+ * modbus_add_crc - 在帧末尾添加 CRC
+ * @frame: Modbus 帧 (不含 CRC)
+ * @len:   帧长度 (不含 CRC)
+ * 返回值: 添加 CRC 后的总长度 (len + 2)
+ */
+uint16_t modbus_add_crc(uint8_t *frame, uint16_t len);
+
+/**
+ * modbus_build_read_holding_regs - 构建读保持寄存器请求 (0x03)
+ * @slave_addr: 从站地址
+ * @start_addr: 起始寄存器地址
+ * @quantity:   寄存器数量
+ * @buf:        输出缓冲区 (至少 8 字节)
+ * 返回值: 请求帧长度 (一般为 8)
+ */
+uint16_t modbus_build_read_holding_regs(uint8_t slave_addr,
+                                         uint16_t start_addr,
+                                         uint16_t quantity,
+                                         uint8_t *buf);
+
+/**
+ * modbus_build_read_coils - 构建读线圈请求 (0x01)
+ * @slave_addr: 从站地址
+ * @start_addr: 起始线圈地址
+ * @quantity:   线圈数量
+ * @buf:        输出缓冲区 (至少 8 字节)
+ * 返回值: 请求帧长度 (一般为 8)
+ */
+uint16_t modbus_build_read_coils(uint8_t slave_addr,
+                                  uint16_t start_addr,
+                                  uint16_t quantity,
+                                  uint8_t *buf);
+
+/**
+ * modbus_build_write_single_reg - 构建写单个寄存器请求 (0x06)
+ * @slave_addr: 从站地址
+ * @reg_addr:   寄存器地址
+ * @value:      写入值
+ * @buf:        输出缓冲区 (至少 8 字节)
+ * 返回值: 请求帧长度 (一般为 8)
+ */
+uint16_t modbus_build_write_single_reg(uint8_t slave_addr,
+                                        uint16_t reg_addr,
+                                        uint16_t value,
+                                        uint8_t *buf);
+
+/**
+ * modbus_build_write_multiple_regs - 构建写多个寄存器请求 (0x10)
+ * @slave_addr: 从站地址
+ * @start_addr: 起始寄存器地址
+ * @values:     写入值数组
+ * @count:      寄存器数量
+ * @buf:        输出缓冲区
+ * @buf_size:   缓冲区大小
+ * 返回值: 请求帧长度, 0 表示缓冲区不足
+ */
+uint16_t modbus_build_write_multiple_regs(uint8_t slave_addr,
+                                           uint16_t start_addr,
+                                           const uint16_t *values,
+                                           uint16_t count,
+                                           uint8_t *buf,
+                                           uint16_t buf_size);
+
+/**
+ * modbus_build_write_single_coil - 构建写单个线圈请求 (0x05)
+ * @slave_addr: 从站地址
+ * @coil_addr:  线圈地址
+ * @on:         true=置ON (0xFF00), false=置OFF (0x0000)
+ * @buf:        输出缓冲区 (至少 8 字节)
+ * 返回值: 请求帧长度 (一般为 8)
+ */
+uint16_t modbus_build_write_single_coil(uint8_t slave_addr,
+                                         uint16_t coil_addr,
+                                         bool on,
+                                         uint8_t *buf);
+
+/**
+ * modbus_parse_read_response - 解析 0x03 读响应帧
+ * @frame:  响应帧 (含 CRC)
+ * @len:    帧长度
+ * @values: 输出寄存器值数组 (大端序已转换)
+ * @max:    数组最大容量
+ * 返回值: 实际解析出的寄存器数量, -1 表示错误
+ */
+int modbus_parse_read_response(const uint8_t *frame, uint16_t len,
+                                uint16_t *values, uint16_t max);
+
+/**
+ * modbus_parse_coils_response - 解析 0x01 线圈响应帧
+ * @frame:  响应帧
+ * @len:    帧长度
+ * @coils:  输出线圈状态数组
+ * @max:    数组最大容量
+ * 返回值: 实际解析出的线圈数量, -1 表示错误
+ */
+int modbus_parse_coils_response(const uint8_t *frame, uint16_t len,
+                                 bool *coils, uint16_t max);
+
+/**
+ * modbus_trim_padding - 从 CAN 组包后的数据中提取有效 Modbus 帧
+ *
+ * CAN 组包会在最后一个包填充 0x00,此函数通过 CRC 校验
+ * 查找有效长度。
+ *
+ * @data:  CAN 组包后的原始数据 (包含填充)
+ * @len:   数据总长度 (6 的倍数)
+ * 返回值: 有效 Modbus 帧长度, 0 表示未找到
+ */
+uint16_t modbus_trim_padding(const uint8_t *data, uint16_t len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MODBUS_LAYER_H */
\ No newline at end of file
index 5ed1e8b8dfb0efadf1a6b52134022ed6fd7809b4..2f49cc5e6c5fe5a4c3594aa81b4a10a9dc8ceeb6 100644 (file)
@@ -104,8 +104,10 @@ static void spi_write_cmd(unsigned char cmd)
     spi_delay_time();
 #else
     uint32_t wr_cm = cmd;
-    L_CS();
+    L_CS(); 
+    spi_delay_time();
     SPI_ReadWrite(SPI1, wr_cm);
+    spi_delay_time();
     H_CS();
 #endif
 }
@@ -150,8 +152,10 @@ static void spi_write_data(unsigned char data)
     spi_delay_time();
 #else
     uint32_t wr_dt = data;
-    L_CS();
+    L_CS(); 
+    spi_delay_time();
     SPI_ReadWrite(SPI1, wr_dt|0x100);
+    spi_delay_time();
     H_CS();
 #endif
 }
@@ -188,7 +192,7 @@ static void spi_port_init(void)
        SPI_initStruct.clkDiv = SPI_CLKDIV_32;
        SPI_initStruct.FrameFormat = SPI_FORMAT_SPI;
        SPI_initStruct.SampleEdge = SPI_SECOND_EDGE;
-       SPI_initStruct.IdleLevel = SPI_LOW_LEVEL;
+       SPI_initStruct.IdleLevel = SPI_HIGH_LEVEL;
        SPI_initStruct.WordSize = 9;
        SPI_initStruct.Master = 1;
        SPI_initStruct.RXThreshold = 0;
@@ -207,6 +211,10 @@ static void spi_port_init(void)
 /**
  * @brief Í¨¹ý SPI Í¨Ñ¶³õʼ»¯ÆÁÄ»
  */
+volatile uint32_t lcd_chip_id = 0;
+
+#define systick_delay_ms(ms)  vTaskDelay(ms)
+
 void lcd_st7789_spi_init(void)
 {
     spi_port_init();
@@ -215,129 +223,102 @@ void lcd_st7789_spi_init(void)
     H_RST();
     systick_delay_ms(10);
     L_RST();
-    systick_delay_ms(80);
+    systick_delay_ms(10); // >5ms
     H_RST();
-    systick_delay_ms(600);
-    
+    systick_delay_ms(200); // >120ms
+
     spi_write_cmd(0x11);
     systick_delay_ms(120);
 
-    spi_write_cmd(0xF0);
-    spi_write_data(0x11);
-
-    spi_write_cmd(0xD6);
-    spi_write_data(0xCB);
-
-    spi_write_cmd(0xB1);
-    spi_write_data(0x05);
-    spi_write_data(0x4C);
-    spi_write_data(0x4C);
-
-    spi_write_cmd(0xB2);
-    spi_write_data(0x05);
-    spi_write_data(0x4C);
-    spi_write_data(0x05);
-    spi_write_data(0x05);
-    spi_write_data(0x05);
-    spi_write_data(0x05);
-    spi_write_data(0x05);   
-    spi_write_data(0x05);
-    spi_write_data(0x4C);
-    spi_write_data(0x4C);
-
-    spi_write_cmd(0xB3);
-    spi_write_data(0x05);
-    spi_write_data(0x4C);
-    spi_write_data(0x4C);
-    spi_write_data(0x05);
-    spi_write_data(0x4C);
-    spi_write_data(0x4C);
-
-    spi_write_cmd(0xB4);     //Dot inversion
-    spi_write_data(0x03);
-
-    spi_write_cmd(0xC0);
-    spi_write_data(0x42);
-    spi_write_data(0x02);
-    spi_write_data(0x84);
-
-    spi_write_cmd(0xC1);
-    spi_write_data(0xA8);
-
-    spi_write_cmd(0xC2);
-    spi_write_data(0x0D);
-    spi_write_data(0x00);
-
-    spi_write_cmd(0xC3);
-    spi_write_data(0x8D);
-    spi_write_data(0x2A);
-
-    spi_write_cmd(0xC4);
-    spi_write_data(0x8D);
-    spi_write_data(0xEE);
-
-    spi_write_cmd(0xC5);
-    spi_write_data(0x0E);
-
-    spi_write_cmd(0xE0);
-    spi_write_data(0x12);
-    spi_write_data(0x0E);
-    spi_write_data(0x0A);
-    spi_write_data(0x00);
-    spi_write_data(0x1A);
-    spi_write_data(0x10);
-    spi_write_data(0x0B);
-    spi_write_data(0x0B);
-    spi_write_data(0x0C);
-    spi_write_data(0x0E);
-    spi_write_data(0x1E);
-    spi_write_data(0x35);
-    spi_write_data(0x10);
-    spi_write_data(0x10);
-    spi_write_data(0x01);
-    spi_write_data(0x10);
-
-    spi_write_cmd(0xE1);
-    spi_write_data(0x14);
-    spi_write_data(0x0D);
-    spi_write_data(0x04);
-    spi_write_data(0x00);
-    spi_write_data(0x0E);
-    spi_write_data(0x08);
-    spi_write_data(0x03);
-    spi_write_data(0x06);
-    spi_write_data(0x08);
-    spi_write_data(0x0B);
-    spi_write_data(0x17);
-    spi_write_data(0x37);
-    spi_write_data(0x10);
-    spi_write_data(0x11);
-    spi_write_data(0x02);
-    spi_write_data(0x10);
-
-    spi_write_cmd(0x35);
-    spi_write_data(0x00);
-
-    spi_write_cmd(0x3A);     //65k mode
-    spi_write_data(0x05);
+    spi_write_cmd(0x21); //inv
 
     spi_write_cmd(0x36);
-    spi_write_data(0xc8);   //c8
+    spi_write_data(0xA0);   //c8
     
 
     spi_write_cmd(0x2A);
     spi_write_data(0x00);
-    spi_write_data(0x02);
     spi_write_data(0x00);
-    spi_write_data(0x81);
+    spi_write_data((319>>8)&0xff);    
+    spi_write_data(319&0xff);
 
     spi_write_cmd(0x2B);
     spi_write_data(0x00);
-    spi_write_data(0x03);
     spi_write_data(0x00);
-    spi_write_data(0x82);
+    spi_write_data(239);
+    spi_write_data(0);
 
-    spi_write_cmd(0x29);     //Display on
+    spi_write_cmd(0xB0);
+    spi_write_data(0x11);
+    spi_write_data(0xc8);
+
+    spi_write_cmd(0xB1);
+    spi_write_data(0x42);
+    spi_write_data(4); //vbp
+    spi_write_data(10); //hbp
+    
 
-    spi_write_cmd(0x2C);
+#define LCD_WR_REG( dev, cmd )  spi_write_cmd(cmd)
+#define LCD_WR_DATA( dev, data )  spi_write_data(data)
+    LCD_WR_REG(LCD, 0xb2);
+    LCD_WR_DATA(LCD, 0x0c);
+    LCD_WR_DATA(LCD, 0x0c);
+    LCD_WR_DATA(LCD, 0x00);
+    LCD_WR_DATA(LCD, 0x33);
+    LCD_WR_DATA(LCD, 0x33);
+    LCD_WR_REG(LCD, 0xb7);
+    LCD_WR_DATA(LCD, 0x35);
+
+    LCD_WR_REG(LCD, 0xbb);
+    LCD_WR_DATA(LCD, 0x2b);
+    LCD_WR_REG(LCD, 0xc3);
+    LCD_WR_DATA(LCD, 0x17);
+    LCD_WR_REG(LCD, 0xc4);
+    LCD_WR_DATA(LCD, 0x20);
+    LCD_WR_REG(LCD, 0xc6); // NLA2 NLA1 NLA0 (0x00: dot/0x07: column) RTNA4  RTNA3 RTNA2 RTNA1 RTNA0    Frame
+    LCD_WR_DATA(LCD, 0x0f);
+
+    LCD_WR_REG(LCD, 0x3A);
+    LCD_WR_DATA(LCD, 0x55);
+
+    LCD_WR_REG(LCD, 0xd0);
+    LCD_WR_DATA(LCD, 0xa4);
+    LCD_WR_DATA(LCD, 0xa2);
+
+    LCD_WR_REG(LCD, 0xe0);
+    LCD_WR_DATA(LCD, 0xf0);
+    LCD_WR_DATA(LCD, 0x00);
+    LCD_WR_DATA(LCD, 0x0a);
+    LCD_WR_DATA(LCD, 0x10);
+    LCD_WR_DATA(LCD, 0x12);
+    LCD_WR_DATA(LCD, 0x1b);
+    LCD_WR_DATA(LCD, 0x39);
+    LCD_WR_DATA(LCD, 0x44);
+    LCD_WR_DATA(LCD, 0x47);
+    LCD_WR_DATA(LCD, 0x28);
+    LCD_WR_DATA(LCD, 0x12);
+    LCD_WR_DATA(LCD, 0x10);
+    LCD_WR_DATA(LCD, 0x16);
+    LCD_WR_DATA(LCD, 0x1b);
+    LCD_WR_REG(LCD, 0xe1);
+    LCD_WR_DATA(LCD, 0xf0);
+    LCD_WR_DATA(LCD, 0x00);
+    LCD_WR_DATA(LCD, 0x0a);
+    LCD_WR_DATA(LCD, 0x10);
+    LCD_WR_DATA(LCD, 0x11);
+    LCD_WR_DATA(LCD, 0x1a);
+    LCD_WR_DATA(LCD, 0x3b);
+    LCD_WR_DATA(LCD, 0x34);
+    LCD_WR_DATA(LCD, 0x4e);
+    LCD_WR_DATA(LCD, 0x3a);
+    LCD_WR_DATA(LCD, 0x17);
+    LCD_WR_DATA(LCD, 0x16);
+    LCD_WR_DATA(LCD, 0x21);
+    LCD_WR_DATA(LCD, 0x22);
+    
+    LCD_WR_REG(LCD, 0x11);
+    LCD_WR_REG(LCD, 0x29);
 }
+
+
+
diff --git a/APP/UI/ui_test_button.c b/APP/UI/ui_test_button.c
new file mode 100644 (file)
index 0000000..9be276f
--- /dev/null
@@ -0,0 +1,163 @@
+/**
+ *******************************************************************************************************************************************
+ * @file        ui_test_button.c
+ * @brief       LVGL °´¼üÏìÓ¦²âÊÔ³ÌÐò - ÓÒ²àÊúÏòÈí°´¼ü + ÎïÀí°´¼üÁª¶¯
+ * @details     È«ÆÁºÚÉ«±³¾°: ÖмäÁô¿ÕÏÔÊ¾Çø, ÓÒ²àÊúÏò·ÅÖà5 ¸öÈí°´¼ü(Ãû×Ö 1~5)¡£
+ *              °´¼ü¼ì²â½»¸ø LVGL ÒÑ×¢²áµÄ Button ÊäÈëÉ豸(lv_port_indev.c):
+ *              Ã¿¸öÎïÀí°´¼üÓ³Éäµ½ÆÁĻij¸ö×ø±êµã(btn_points), °´ÏÂ/ËÉ¿ªÊ± LVGL
+ *              »áÏò¸Ã×ø±ê´¦×îÉϲãµÄ¿Éµã»÷¶ÔÏóÅÉ·¢ PRESSED/RELEASED Ê¼þ¡£
+ *              ´¥·¢Ô¼¶¨:
+ *                - PRESSED   : Èí°´¼ü¸ßÁÁ(°´ÏÂÉ«), Í¬Ê±µãÁÁ¶ÔÓ¦ LED(GPIO)
+ *                - RELEASED  : Èí°´¼ü»Ö¸´(³£Ì¬É«), Í¬Ê±Ï¨Ãð¶ÔÓ¦ LED(GPIO)
+ *******************************************************************************************************************************************
+ */
+#include <stdio.h>
+#include <string.h>
+#include "lvgl.h"
+#include "ui_test_button.h"
+#include "SWM341.h"
+
+/* 5 ¸öÈí°´¼üÏÔʾÃû×Ö (Êý×Ö 1~5) */
+static const char *softkey_name[5] = {
+    "1", "2", "3", "4", "5",
+};
+
+/* 5 ¸öÈí°´¼üʹÓõĠGPIO: LED0~LED4 (µÍµçƽµãÁÁ) */
+static GPIO_TypeDef *led_port[5] = { GPIOD, GPIOD, GPIOC, GPIOC, GPIOC };
+static uint32_t      led_pin[5]  = { PIN7, PIN0, PIN4, PIN5, PIN8 };
+
+/* ½çÃæ¶ÔÏóÒýÓÃ(¹©Ê¼þ»Øµ÷ÐÞ¸Ä) */
+static lv_obj_t *softkey[5];          /* ÓÒ²à 5 ¸öÈí°´¼ü */
+
+#define NUM_KEYS 5
+
+/* Èí°´¼üÑÕÉ« */
+static const lv_color_t color_released = LV_COLOR_GRAY;  /* ³£Ì¬ */
+static const lv_color_t color_pressed  = LV_COLOR_ORANGE;/* °´Ï */
+
+/**
+ * @brief µãÁÁ/ϨÃð LED
+ */
+static void led_set(int idx, int on)
+{
+    if (idx < 0 || idx >= NUM_KEYS) return;
+    if (on)
+        GPIO_ClrBit(led_port[idx], led_pin[idx]);   /* µÍµçƽµãÁÁ */
+    else
+        GPIO_SetBit(led_port[idx], led_pin[idx]);   /* ¸ßµçƽϨÃð */
+}
+
+/**
+ * @brief Èí°´¼üʼþ»Øµ÷
+ * @note   user_data Öб£´æ¸ÃÈí°´¼ü¶ÔÓ¦µÄ°´¼üË÷Òý(0~4)
+ */
+static void softkey_event_cb(lv_obj_t *obj, lv_event_t event)
+{
+    int i;
+    int idx = -1;
+
+    /* Í¨¹ý¶ÔÏóÖ¸Õ붨λÈí°´¼üË÷Òý */
+    for (i = 0; i < NUM_KEYS; i++)
+    {
+        if (softkey[i] == obj)
+        {
+            idx = i;
+            break;
+        }
+    }
+    if (idx < 0)
+        return;
+
+    if (event == LV_EVENT_PRESSED)
+    {
+        /* °´ÏÂ: Èí°´¼ü¸ßÁÁ + LED µãÁÁ */
+        lv_obj_set_style_local_bg_color(obj, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, color_pressed);
+        led_set(idx, 1);
+    }
+    else if (event == LV_EVENT_RELEASED)
+    {
+        /* ÊÍ·Å: Èí°´¼ü»Ö¸´³£Ì¬ + LED Ï¨Ãð */
+        lv_obj_set_style_local_bg_color(obj, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, color_released);
+        led_set(idx, 0);
+    }
+}
+
+/**
+ * @brief ´´½¨²¢Æô¶¯°´¼üÏìÓ¦²âÊÔ½çÃæ
+ * @note   °´¼üʼþÓÉ lv_port_indev.c µÄ Button ÊäÈëÉ豸Çý¶¯,
+ *         ÎÞÐè¶îÍâ lv_task ÂÖѯ¡£Èí°´¼üÖÐÐÄ×ø±ê±ØÐëÓë
+ *         lv_port_indev.c µÄ btn_points Ò»Ö¡£
+ *
+ * ²¼¾Ö(320x240, ÏñËØ×ø±ê):
+ *   - ×îÍâ²ã 1px °×É«±ß¿òȦסÕû¸öÆÁÄ»
+ *   - x[0..238]   ×ó²àÏÔÊ¾Çø, À¶É«µ×
+ *   - x[239]      °×É«´¹Ö±·Ö¸îÏß(1px)
+ *   - x[240..318] ÓÒ²àÈí°´¼üÇø, ÉîÀ¶É«µ×(ÉÔ¼ÓÉî)
+ *   - 5 ¸öÈí°´¼üÖÐÐÄ x=280, y=24/72/120/168/216(´¹Ö±¾ùÔÈ·Ö²¼)
+ */
+void ui_test_button(void)
+{
+    int i;
+    lv_obj_t *scr = lv_scr_act();
+
+    /* ×îÍâ²ã: È«ÆÁ 1px °×¿ò(ºÚµ×) */
+    lv_obj_t *obj_bg = lv_obj_create(scr, NULL);
+    lv_obj_set_size(obj_bg, LV_HOR_RES_MAX, LV_VER_RES_MAX);
+    lv_obj_set_style_local_bg_color(obj_bg, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK);
+    lv_obj_set_style_local_border_width(obj_bg, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, 1);
+    lv_obj_set_style_local_border_color(obj_bg, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_WHITE);
+    lv_obj_set_style_local_radius(obj_bg, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, 0);
+
+    /* ×ó²àÏÔÊ¾Çø: x[0,252], ÉîÀ¶¿Æ¼¼·çÊúÖ±½¥±ä */
+    lv_obj_t *obj_left = lv_obj_create(obj_bg, NULL);
+    lv_obj_set_pos(obj_left, 0, 0);
+    lv_obj_set_size(obj_left, 253, LV_VER_RES_MAX);
+    lv_obj_set_style_local_bg_color(obj_left, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_MAKE(0x00, 0x30, 0x60));
+    lv_obj_set_style_local_bg_grad_color(obj_left, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_MAKE(0x00, 0x08, 0x18));
+    lv_obj_set_style_local_bg_grad_dir(obj_left, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_GRAD_DIR_VER);
+    lv_obj_set_style_local_border_width(obj_left, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, 0);
+    lv_obj_set_style_local_radius(obj_left, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, 0);
+
+    /* ×ó²àÏÔÊ¾ÇøÖÐÑë±êÌâÎÄ×Ö */
+    lv_obj_t *obj_title = lv_label_create(obj_left, NULL);
+    lv_label_set_text(obj_title, "DISPBOARD");
+    lv_obj_align(obj_title, NULL, LV_ALIGN_CENTER, 0, 0);
+    lv_obj_set_style_local_text_color(obj_title, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_WHITE);
+
+    /* ÓÒ²àÈí°´¼üÇø: x[253,318] ÉîÀ¶µ×(±È×ó²àÉî, ½üºÚ) */
+    lv_obj_t *obj_right = lv_obj_create(obj_bg, NULL);
+    lv_obj_set_pos(obj_right, 253, 0);
+    lv_obj_set_size(obj_right, 66, LV_VER_RES_MAX);
+    lv_obj_set_style_local_bg_color(obj_right, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_MAKE(0x00, 0x10, 0x30));
+    lv_obj_set_style_local_border_width(obj_right, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, 0);
+    lv_obj_set_style_local_radius(obj_right, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, 0);
+
+    /* 5 ¸öÈí°´¼ü, ÓҲఴ¼üÇøÄÚ¾«È·ÅŲ¼.
+     * ¿í 62 ²»±ä, ¸ß 43, Ô²½Ç 8.
+     * °´¼üÓÒÔµ¾àÓÒ°×Ïß 2px; ¶¥²¿¾àÉϰ×Ïß 4px, °´¼ü¼ä¡¢µ×²¿
+     * ¼ä¾à¾ù 4px:
+     *   °´¼ü x = [255,316], ÖÐÐÄ x = 285
+     *   µÚ i ¼ü¶¥ y = 4 + 47i (i=0..4), ¼ü¸ß 43, ¼ü¼ä¼ä¾à 4px,
+     *   ÖÐÐÄ y = 26/73/120/167/214, ÐëÓë btn_points Ò»Ö¡£ */
+    for (i = 0; i < NUM_KEYS; i++)
+    {
+        lv_obj_t *pad = lv_obj_create(scr, NULL);
+        lv_obj_set_size(pad, 62, 43);
+        lv_obj_set_pos(pad, 255, 4 + i * 47);
+        lv_obj_set_style_local_bg_color(pad, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, color_released);
+        lv_obj_set_style_local_border_width(pad, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, 1);
+        lv_obj_set_style_local_border_color(pad, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_WHITE);
+        lv_obj_set_style_local_radius(pad, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, 8);
+
+        /* °´¼üÃû×Ö±êÇ© */
+        lv_obj_t *lbl = lv_label_create(pad, NULL);
+        lv_label_set_text(lbl, softkey_name[i]);
+        lv_obj_align(lbl, NULL, LV_ALIGN_CENTER, 0, 0);
+        lv_obj_set_style_local_text_color(lbl, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_WHITE);
+
+        softkey[i] = pad;
+
+        /* ×¢²áʼþ»Øµ÷ */
+        lv_obj_set_event_cb(pad, softkey_event_cb);
+    }
+}
\ No newline at end of file
diff --git a/APP/UI/ui_test_button.h b/APP/UI/ui_test_button.h
new file mode 100644 (file)
index 0000000..f17d239
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ *******************************************************************************************************************************************
+ * @file        ui_test_button.h
+ * @brief       LVGL °´¼üÏìÓ¦²âÊÔ³ÌÐò½Ó¿Ú
+ * @details     È«ÆÁ»æÖư´Å¥/ָʾµÆ/É«¿é, ÂÖѯ PD2-PD6 ÉÏ 5 ¸ö°´¼ü, °´¼ü°´ÏÂʱ½çÃæÊµÊ±±ä»¯
+ *******************************************************************************************************************************************
+ */
+#ifndef UI_TEST_BUTTON_H
+#define UI_TEST_BUTTON_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** @brief ´´½¨²¢Æô¶¯°´¼üÏìÓ¦²âÊÔ½çÃæ */
+void ui_test_button(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* UI_TEST_BUTTON_H */
\ No newline at end of file
index 9c129302f520c27b3a1dd3bb2e19edb8d42235a0..42bb63023ecbfcc66e224a1b4785c5099bffbb6c 100644 (file)
@@ -72,10 +72,25 @@ void task_can(void *arg)
 
        /* é\80\9aä¿¡å±\82ä»»å\8a? (relay/comm) å·²ç\8b¬ç«\8bå\88\9bå»?, æ\9c?ä»»å\8a¡ä½¿å\91½å®\8cæ\88\90 */
        //vTaskDelete(NULL);
+    can_init();
   while(1){
-    vTaskDelay(10000);
+    can_send_frame(0x123, (uint8_t *)"Hello123", 8);
+    vTaskDelay(2000);
   }
 }
+void task_ui(void *arg)
+{
+       gui_init();
+
+       /* LVGL ?????????????? */
+       ui_test_button();
+
+       /* ???????? LVGL ???/???????, ????????????????? */
+    while(1){
+        lv_task_handler();
+        vTaskDelay(5);
+    }
+}
 /*******************************************************************************************************************************************
  * Public Function
  *******************************************************************************************************************************************/
@@ -85,7 +100,7 @@ void task_can(void *arg)
 int main(void)
 {
     /* ÔÚµ÷²â½×¶Î(°æ±¾ Release Ê±¿É×¢ÊÍ), Ô¤·À³ÌÐòÅܷɺó, ÉϵçÎÞ·¨¶ÁÈ¡ MCU ÄÚºË, Ò²¿ÉÓÃ×÷µÈ´ý¸ö±ðÓ²¼þÄ£¿éÉϵçÎȶ¨ */
-    for (uint32_t i = 0; i < 666666 * 88; ++i) __NOP();
+    //for (uint32_t i = 0; i < 666666 * 88; ++i) __NOP();
 
 #if (__TARGET_CONST__ == 0xFF)
 #include "userboot.h"
@@ -103,21 +118,14 @@ int main(void)
     printf("\r\n  V%d.%d.%d build-release %d-%d-%d   \r\n", 7, 9, 0, 2023, 05, 12);
     printf("\r\n   @Copyright by Synwit Technology   \r\n");
        printf("\r\n*************************************\r\n");
-    
-       gui_init();
-       user_app();
 
-       xTaskCreate(task_can, (const char *)"can", 1024, NULL, 2, NULL);
+
+
+       xTaskCreate(task_ui, (const char *)"ui", 1024, NULL, 2, NULL);
+    xTaskCreate(task_can, (const char *)"can", 1024, NULL, 2, NULL);
     vTaskStartScheduler();
 
-    for (;;)
-    {
-        /* Òª´¦Àí LVGL µÄÈÎÎñ, ÄúÐèÒª¶¨ÆÚµ÷Óàlv_task_handler() (¼ä¸ô´óԼΪ 5ms ×óÓÒ)
-         * Òª×¢Òâ LVGL Ä¬Èϲ»ÊÇḬ̈߳²È«µÄ, Ò»°ã·ÅÓÚÈÎÎñ¶ÓÁнϵ͵ÄÓÅÏȼ¶
-         * ÔÚ RTOS ÖÐʹÓÃʱ£¬Ó¦¸Ã¿¼ÂÇͨ¹ý»¥³âÁ¿À´½¨Á¢ÁÙ½çÇøÀ´±ÜÃâ lv_task_handler() Óë lv_tick_inc() ²úÉú ¾ºÕù³åÍ»
-         */
-        lv_task_handler();
-    }
+
 #endif
     return 0;
 }
index 0d5369f82b19a0aacf8ad05091340079aa3ed5cd..c7e04e9fc6c73d3e79d2963ce999edfc9ba5b73a 100644 (file)
@@ -36,7 +36,7 @@
 
 #define __HSI          (20000000UL)    // high speed internal clock
 #define __LSI          (   32000UL)    // low speed internal clock
-#define __HSE          (16000000UL)    // high speed external clock
+#define __HSE          (12000000UL)    // high speed external clock
 #define __LSE          (   32768UL)    // low speed external clock
 
 
index 171c077eae7086e847999c26ae849e651955b703..93f683138dff280605d0ca6712ed9eeda6ef8a96 100644 (file)
@@ -25,7 +25,7 @@
  *********************/
 
 /*Show some widget*/
-#define LV_USE_DEMO_WIDGETS        1 
+#define LV_USE_DEMO_WIDGETS        0 
 #if LV_USE_DEMO_WIDGETS
 #define LV_DEMO_WIDGETS_SLIDESHOW  0
 #endif
index 916983c5e923cc127ee37b9ad23298faa1f9bd4c..4b17c584f4c07166ec6acc7ae689f622cc2e6f2c 100644 (file)
@@ -13,6 +13,8 @@
 
 #include "bsp_init.h"
 
+#include <stdio.h>
+
 /* SWM341 LVGL
 
 ## 移植说明
@@ -210,11 +212,10 @@ static void disp_init(void)
     /* You code here */
     lcd_init();
        LCD->L[LCD_LAYER_1].ADDR = (uint32_t)lcdbuf_gui; /* 指向 LCD 显存区域 */
-    if (0 != (LCD->CR & LCD_CR_AUTORESTA_Msk)) 
-    {
-        /* 软件启动 LCD (仅使能 LCD 中断后有效) */
-        LCD_Start(LCD);
-    }
+    /* 启动 LCD 输出。
+     * IntEOTEn=1(手动重启模式)时 AUTORESTA 未置位, 必须在此显式启动一次,
+     * 之后每帧传输完成中断 isr_lcd_transfer_done() 会负责切换并重启后续帧。 */
+    LCD_Start(LCD);
        
 #if  (0 == LVGL_DISP_MODE || 1 == LVGL_DISP_MODE || 2 == LVGL_DISP_MODE)
        /* 若在 lv_disp_1 下配置 LCD 双缓冲, 则需要在 lv_task_handler() 被调用处后添加 void gui2show(void) 函数调用 */
index 486f80cf93264993f5007e2fe00ea3b21f314897..d5fe49594322693f00665fa428baeb8b26236b32 100644 (file)
@@ -57,7 +57,8 @@ static bool button_is_pressed(uint8_t id);
 /**********************
  *  STATIC VARIABLES
  **********************/
-static lv_indev_t * indev_touchpad;
+//static lv_indev_t * indev_touchpad;
+static lv_indev_t * indev_button;
 
 #if USB_HID_ENABLE
 static lv_indev_t * indev_mouse;
@@ -76,6 +77,69 @@ static lv_indev_state_t encoder_state;
  *   GLOBAL FUNCTIONS
  **********************/
 
+
+/*------------------
+ * Button
+ * -----------------*/
+static int8_t button_get_pressed_id(void);
+static bool button_is_pressed(uint8_t id);
+
+/* Initialize your buttons */
+static void button_init(void)
+{
+    /*Your code comes here*/
+}
+
+/* Will be called by the library to read the button */
+static bool button_read(lv_indev_drv_t * indev_drv, lv_indev_data_t * data)
+{
+
+    static uint8_t last_btn = 0;
+
+    /*Get the pressed button's ID*/
+    int8_t btn_act = button_get_pressed_id();
+
+    if(btn_act >= 0) {
+        data->state = LV_INDEV_STATE_PR;
+        last_btn = btn_act;
+    } else {
+        data->state = LV_INDEV_STATE_REL;
+    }
+
+    /*Save the last pressed button's ID*/
+    data->btn_id = last_btn;
+
+    /*Return `false` because we are not buffering and no more data to read*/
+    return false;
+}
+
+int is_key_pressed( int id );
+/*Get ID  (0, 1, 2 ..) of the pressed button*/
+static int8_t button_get_pressed_id(void)
+{
+    uint8_t i;
+
+    /*Check to buttons see which is being pressed (assume there are 2 buttons)*/
+    for(i = 0; i < 5; i++) {
+        /*Return the pressed button's ID*/
+        if(button_is_pressed(i)) {
+            return i;
+        }
+    }
+
+    /*No button pressed*/
+    return -1;
+}
+
+/*Test if `id` button is pressed or not*/
+static bool button_is_pressed(uint8_t id)
+{
+
+    /*Your code comes here*/
+    return is_key_pressed( id ) == 1;
+}
+
+
 void lv_port_indev_init(void)
 {
     /* Here you will find example implementation of input devices supported by LittelvGL:
@@ -89,18 +153,44 @@ void lv_port_indev_init(void)
      *  You should shape them according to your hardware
      */
     lv_indev_drv_t indev_drv;
+ /*------------------
+     * Button
+     * -----------------*/
+    /*Initialize your button if you have*/
+    button_init();
 
+    /*Register a button input device*/
+    lv_indev_drv_init(&indev_drv);
+    indev_drv.type = LV_INDEV_TYPE_BUTTON;
+    indev_drv.read_cb = button_read;
+    indev_button = lv_indev_drv_register(&indev_drv);
+
+    /*Assign buttons to points on the screen.
+     * The 5 points must fall inside the 5 softkey objects created by
+     * ui_test_button() so LVGL dispatches PRESSED/RELEASED events to them.
+     * The softkeys are laid out vertically on the right edge; these are their centers. */
+    static const lv_point_t btn_points[5] = {
+            {285, 26},   //Softkey 0
+            {285, 73},   //Softkey 1
+            {285, 120},  //Softkey 2
+            {285, 167},  //Softkey 3
+            {285, 214},  //Softkey 4
+    };
+    lv_indev_set_button_points(indev_button, btn_points);
+
+#if 0
     /*------------------
      * Touchpad
      * -----------------*/
     /*Initialize your touchpad if you have*/
-    touchpad_init();
+    //touchpad_init();
 
     /*Register a touchpad input device*/
     lv_indev_drv_init(&indev_drv);
     indev_drv.type = LV_INDEV_TYPE_POINTER;
     indev_drv.read_cb = touchpad_read;
     indev_touchpad = lv_indev_drv_register(&indev_drv);
+#endif
 
 #if USB_HID_ENABLE
     /*------------------
@@ -167,10 +257,16 @@ void lv_port_indev_init(void)
     indev_drv.read_cb = button_read;
     indev_button = lv_indev_drv_register(&indev_drv);
 
-    /*Assign buttons to points on the screen*/
-    static const lv_point_t btn_points[2] = {
-            {10, 10},   //Button 0 -> x:10; y:10
-            {40, 100},  //Button 1 -> x:40; y:100
+    /*Assign buttons to points on the screen.
+     * The 5 points must fall inside the 5 indicator objects created by
+     * ui_test_button() so LVGL dispatches PRESSED/RELEASED events to them.
+     * Those objects are laid out vertically on the right edge; these are their centers. */
+    static const lv_point_t btn_points[5] = {
+            {285, 26},   //Softkey 0
+            {285, 73},   //Softkey 1
+            {285, 120},  //Softkey 2
+            {285, 167},  //Softkey 3
+            {285, 214},  //Softkey 4
     };
     lv_indev_set_button_points(indev_button, btn_points);
        #endif
@@ -449,4 +545,4 @@ static bool button_is_pressed(uint8_t id)
 
 /* This dummy typedef exists purely to silence -Wpedantic. */
 typedef int keep_pedantic_happy;
-#endif
+#endif
\ No newline at end of file
index 921168e18a1ac3a7ced3f4eef85e65fe5d435a8a..a99abe8e1c33d4750e25eec409c23d673d88fc94 100644 (file)
@@ -158,7 +158,7 @@ typedef int16_t lv_coord_t;
  *==================*/
 
 /*1: Enable the Animations */
-#define LV_USE_ANIMATION        1
+#define LV_USE_ANIMATION        0
 #if LV_USE_ANIMATION
 
 /*Declare the type of the user data of animations (can be e.g. `void *`, `int`, `struct`)*/
@@ -707,7 +707,7 @@ typedef void * lv_obj_user_data_t;
 #endif
 
 /*Preload (dependencies: lv_arc, lv_anim)*/
-#define LV_USE_SPINNER      1
+#define LV_USE_SPINNER      0
 #if LV_USE_SPINNER != 0
 #  define LV_SPINNER_DEF_ARC_LENGTH   60      /*[deg]*/
 #  define LV_SPINNER_DEF_SPIN_TIME    1000    /*[ms]*/
index 35a2a20cb7eac6ff05700747696067297be3df06..64117085f96d3c6ab8c9e5c51d4b06410e54c96b 100644 (file)
           </ArmAdsMisc>
           <Cads>
             <interw>1</interw>
-            <Optim>5</Optim>
+            <Optim>1</Optim>
             <oTime>0</oTime>
             <SplitLS>0</SplitLS>
             <OneElfS>1</OneElfS>
             <TextAddressRange>0x00000000</TextAddressRange>
             <DataAddressRange>0x00000000</DataAddressRange>
             <pXoBase></pXoBase>
-            <ScatterFile>.\Linker_Scatter_File\SWM34S_Link_SPI_Flash.sct</ScatterFile>
+            <ScatterFile>.\Linker_Scatter_File\SWM34S_NoLink_SPI_Flash.sct</ScatterFile>
             <IncludeLibs></IncludeLibs>
             <IncludeLibsPath></IncludeLibsPath>
             <Misc></Misc>
               <FileType>1</FileType>
               <FilePath>.\APP\Bsp\dev_io_i2c.c</FilePath>
             </File>
+            <File>
+              <FileName>can_comm.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\BSP\can_comm.c</FilePath>
+            </File>
+            <File>
+              <FileName>comm_task.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\BSP\comm_task.c</FilePath>
+            </File>
+            <File>
+              <FileName>modbus_layer.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\BSP\modbus_layer.c</FilePath>
+            </File>
+            <File>
+              <FileName>dev_can.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\BSP\dev_can.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>
                 </FileArmAds>
               </FileOption>
             </File>
+            <File>
+              <FileName>ui_test_button.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\UI\ui_test_button.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>
               <FileName>lv_demo_widgets.c</FileName>
               <FileType>1</FileType>
               <FilePath>.\Middleware\lvgl\lv_examples\src\lv_demo_widgets\lv_demo_widgets.c</FilePath>
+              <FileOption>
+                <CommonProperty>
+                  <UseCPPCompiler>2</UseCPPCompiler>
+                  <RVCTCodeConst>0</RVCTCodeConst>
+                  <RVCTZI>0</RVCTZI>
+                  <RVCTOtherData>0</RVCTOtherData>
+                  <ModuleSelection>0</ModuleSelection>
+                  <IncludeInBuild>0</IncludeInBuild>
+                  <AlwaysBuild>2</AlwaysBuild>
+                  <GenerateAssemblyFile>2</GenerateAssemblyFile>
+                  <AssembleAssemblyFile>2</AssembleAssemblyFile>
+                  <PublicsOnly>2</PublicsOnly>
+                  <StopOnExitCode>11</StopOnExitCode>
+                  <CustomArgument></CustomArgument>
+                  <IncludeLibraryModules></IncludeLibraryModules>
+                  <ComprImg>1</ComprImg>
+                </CommonProperty>
+                <FileArmAds>
+                  <Cads>
+                    <interw>2</interw>
+                    <Optim>0</Optim>
+                    <oTime>2</oTime>
+                    <SplitLS>2</SplitLS>
+                    <OneElfS>2</OneElfS>
+                    <Strict>2</Strict>
+                    <EnumInt>2</EnumInt>
+                    <PlainCh>2</PlainCh>
+                    <Ropi>2</Ropi>
+                    <Rwpi>2</Rwpi>
+                    <wLevel>0</wLevel>
+                    <uThumb>2</uThumb>
+                    <uSurpInc>2</uSurpInc>
+                    <uC99>2</uC99>
+                    <uGnu>2</uGnu>
+                    <useXO>2</useXO>
+                    <v6Lang>0</v6Lang>
+                    <v6LangP>0</v6LangP>
+                    <vShortEn>2</vShortEn>
+                    <vShortWch>2</vShortWch>
+                    <v6Lto>2</v6Lto>
+                    <v6WtE>2</v6WtE>
+                    <v6Rtti>2</v6Rtti>
+                    <VariousControls>
+                      <MiscControls></MiscControls>
+                      <Define></Define>
+                      <Undefine></Undefine>
+                      <IncludePath></IncludePath>
+                    </VariousControls>
+                  </Cads>
+                </FileArmAds>
+              </FileOption>
             </File>
             <File>
               <FileName>lv_demo_benchmark.c</FileName>
               <FileType>1</FileType>
               <FilePath>.\APP\Bsp\dev_io_i2c.c</FilePath>
             </File>
+            <File>
+              <FileName>can_comm.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\BSP\can_comm.c</FilePath>
+            </File>
+            <File>
+              <FileName>comm_task.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\BSP\comm_task.c</FilePath>
+            </File>
+            <File>
+              <FileName>modbus_layer.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\BSP\modbus_layer.c</FilePath>
+            </File>
+            <File>
+              <FileName>dev_can.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\BSP\dev_can.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>
                 </FileArmAds>
               </FileOption>
             </File>
+            <File>
+              <FileName>ui_test_button.c</FileName>
+              <FileType>1</FileType>
+              <FilePath>.\APP\UI\ui_test_button.c</FilePath>
+            </File>
           </Files>
         </Group>
         <Group>