STM32F103C8T6与移远EC600N串口通信代码
时间: 2024-04-30 20:18:25 浏览: 229
以下是STM32F103C8T6与移远EC600N串口通信的基本代码:
```c
#include "stm32f10x.h"
#include "stdio.h"
#define USART1_DR_Base 0x40013804
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (uint8_t) ch);
while (!(USART1->SR & USART_SR_TXE));
return ch;
}
void USART1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
int main(void)
{
char recvByte;
USART1_Init();
while (1) {
if (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == SET) {
recvByte = USART_ReceiveData(USART1);
printf("Recv Data: %c\n", recvByte);
}
}
}
```
其中,使用的是USART1串口通信,串口波特率为115200。在主函数中,通过`USART_GetFlagStatus()`判断是否有数据接收,并通过`printf()`函数输出接收到的数据。你可以根据需要修改代码以满足你的具体应用需求。
阅读全文