ht32跟51单片机串口通信代码
时间: 2023-11-09 18:06:59 浏览: 178
以下是HT32和51单片机之间的串口通信代码,其中假定使用了8051的P2口作为串口的TXD和RXD引脚,HT32的USART2作为串口:
HT32代码:
```
#include "ht32.h"
#include "ht32_board.h"
void USART2_IRQHandler(void)
{
if (USART_GetFlagStatus(HT_USART2, USART_FLAG_RXDNE) == SET)
{
uint8_t data = USART_ReceiveData(HT_USART2);
//处理接收到的数据...
}
}
void USART_Configuration(void)
{
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WORDLENGTH_8B;
USART_InitStructure.USART_StopBits = USART_STOPBITS_1;
USART_InitStructure.USART_Parity = USART_PARITY_NO;
USART_InitStructure.USART_Mode = USART_MODE_TX_RX;
USART_InitStructure.USART_HardwareFlowControl = USART_HARDWAREFLOWCONTROL_NONE;
USART_Init(HT_USART2, &USART_InitStructure);
USART_ITConfig(HT_USART2, USART_IT_RXDNE, ENABLE);
NVIC_EnableIRQ(USART2_IRQn);
USART_Cmd(HT_USART2, ENABLE);
}
int main(void)
{
CKCU_Configuration();
USART_Configuration();
while(1)
{
//发送数据
USART_SendData(HT_USART2, 'H');
USART_SendData(HT_USART2, 'e');
USART_SendData(HT_USART2, 'l');
USART_SendData(HT_USART2, 'l');
USART_SendData(HT_USART2, 'o');
USART_SendData(HT_USART2, '\r');
USART_SendData(HT_USART2, '\n');
//延时
for(int i=0; i<1000000; i++);
}
}
```
51代码:
```
#include <reg52.h>
void UART_Init()
{
TMOD |= 0x20;
TH1 = 0xFD;
TL1 = 0xFD;
TR1 = 1;
SM0 = 0;
SM1 = 1;
EA = 1;
ES = 1;
}
void UART_TX_Char(unsigned char dat)
{
SBUF = dat;
while(TI == 0);
TI = 0;
}
void UART_RX_Char() interrupt 4
{
unsigned char dat;
if(RI == 1)
{
dat = SBUF;
RI = 0;
//处理接收到的数据...
}
}
void main()
{
UART_Init();
while(1)
{
//发送数据
UART_TX_Char('H');
UART_TX_Char('e');
UART_TX_Char('l');
UART_TX_Char('l');
UART_TX_Char('o');
UART_TX_Char('\r');
UART_TX_Char('\n');
//延时
for(int i=0; i<10000; i++);
}
}
```
阅读全文