KEA128芯片在Keil环境下使用UART2中断方法接收串口不定长度的16位进制数值类型数据并存存下来一次性从口串口再发送出来使用C语言编写可运行的所有程序
下面是一个在Keil环境下使用UART2中断接收和发送不定长度的16位进制数值类型数据的C语言程序示例:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <LPC17xx.h>
#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;
}
在这个示例中,我们使用了LPC17xx系列芯片的UART2模块来进行串口通信。首先,在UART2_IRQHandler中断处理函数中,我们通过判断LSR寄存器的状态位来接收和发送数据。当RBR接收到数据时,我们将数据存储在rxBuffer中,直到接收到换行符'\r'表示一次完整的数据传输结束。当THRE为空时,我们将txBuffer中的数据发送出去。
在initUART2函数中,我们初始化了UART2模块的相关寄存器,设置了波特率为115200。
sendUART2函数用于将数据发送出去,我们将数据复制到txBuffer中,并通过设置THR寄存器发送第一个字节,然后通过移动数据的方式实现发送缓冲区的循环。
convertHexToAscii函数用于将十六进制数据转换为ASCII字符,我们使用sprintf函数将每个字节转换为两个字符的十六进制表示。
在主函数中,我们通过不断检查newDataReceived标志位来判断是否接收到新的数据。如果接收到新的数据,我们将其转换为ASCII字符,并发送出去。然后清除标志位和接收缓冲区。
请注意,这只是一个示例程序,具体的实现可能需要根据您的具体需求进行适当的修改。
原文地址: https://www.cveoy.top/t/topic/i2U2 著作权归作者所有。请勿转载和采集!