KEA128 芯片 UART2 中断接收和发送十六进制数据 (Keil C 语言)

本示例演示了如何在 Keil 环境下使用 KEA128 芯片的 UART2 模块,通过中断方法接收和发送不定长度的十六进制数值类型数据。

程序代码

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <LPC17xx.h> // 替换为 KEA128 芯片的头文件

#define BUFFER_SIZE 100

volatile uint8_t rxBuffer[BUFFER_SIZE];
volatile uint8_t txBuffer[BUFFER_SIZE];
volatile uint8_t rxLength = 0;
volatile bool newDataReceived = false;

void UART2_IRQHandler(void) {
    uint8_t status = LPC_UART2->LSR;
    if (status & 0x01) { // Receive Data Ready
        uint8_t data = LPC_UART2->RBR;
        if (data == '\r') { // End of transmission
            newDataReceived = true;
        } else {
            rxBuffer[rxLength++] = data;
        }
    }
    if (status & 0x20) { // Transmit Holding Register Empty
        if (txBuffer[0] != '\0') {
            LPC_UART2->THR = txBuffer[0];
            memmove(&txBuffer[0], &txBuffer[1], BUFFER_SIZE - 1);
        }
    }
}

void initUART2(void) {
    LPC_SC->PCONP |= (1 << 24); // Enable UART2 power
    LPC_SC->PCLKSEL1 &= ~(3 << 16); // Set PCLK for UART2 to CCLK/4
    LPC_UART2->LCR = (1 << 7); // Enable DLAB
    LPC_UART2->DLL = 9; // Set baud rate to 115200
    LPC_UART2->DLM = 0;
    LPC_UART2->LCR = 0x03; // 8-bit data, no parity, 1 stop bit
    LPC_UART2->IER = (1 << 0) | (1 << 1); // Enable RBR and THRE interrupt
    NVIC_EnableIRQ(UART2_IRQn); // Enable UART2 interrupt
    LPC_UART2->FCR = (1 << 0) | (1 << 1) | (1 << 2); // Enable FIFO, reset RX and TX FIFO
}

void sendUART2(uint8_t* data, uint8_t length) {
    memcpy(txBuffer, data, length);
    LPC_UART2->THR = txBuffer[0];
    memmove(&txBuffer[0], &txBuffer[1], BUFFER_SIZE - 1);
}

void convertHexToAscii(uint8_t* hexData, uint8_t hexLength, uint8_t* asciiData) {
    for (int i = 0; i < hexLength; i++) {
        sprintf((char*)&asciiData[i * 2], "%02X", hexData[i]);
    }
}

int main(void) {
    SystemInit();
    initUART2();

    while (1) {
        if (newDataReceived) {
            uint8_t asciiData[BUFFER_SIZE * 2];
            convertHexToAscii(rxBuffer, rxLength, asciiData);
            sendUART2(asciiData, rxLength * 2);
            newDataReceived = false;
            rxLength = 0;
        }
    }

    return 0;
}

程序功能说明

  1. 初始化 UART2: initUART2 函数负责初始化 UART2 模块,设置波特率、数据格式等参数。
  2. 接收数据: UART2_IRQHandler 中断处理函数负责接收数据,并将数据存储在 rxBuffer 中。接收到的数据以 \r 作为结束符。
  3. 发送数据: sendUART2 函数负责将数据发送到串口。
  4. 数据格式转换: convertHexToAscii 函数负责将十六进制数据转换为 ASCII 字符,以便通过串口发送。
  5. 主函数: 主函数循环判断是否有新的数据接收,如果有则将其转换为 ASCII 字符并发送出去。

修改说明

  • 请将程序代码中的 LPC17xx.h 替换为 KEA128 芯片的对应头文件。
  • 需根据 KEA128 芯片的具体配置修改 UART2 的初始化参数和中断处理函数。
  • 可以根据实际需求修改程序代码中的缓冲区大小等参数。

注意事项

  • 确保 KEA128 芯片上的 UART2 引脚连接到串口设备。
  • 使用串口调试工具进行数据收发调试。
  • 请参考 KEA128 芯片的官方文档了解更详细的 UART2 模块使用说明。

本示例程序提供了一个基本的参考框架,您可以根据实际项目需求进行修改和扩展。

KEA128 芯片 UART2 中断接收和发送十六进制数据 (Keil C 语言)

原文地址: https://www.cveoy.top/t/topic/nMpi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录