实验代码 要求:使用STM32的串口来发送和接收数据。STM32通过串口和上位机的对话,STM32在收到上位机发过来的字符串后,原原本本的返回给上位机。
时间: 2024-03-17 11:40:25 浏览: 55
STM32 自定义HID 设备, 通过快传输接收上位机发来的数据。上位机使用Libusb库函数实现,接口简单
5星 · 资源好评率100%
下面是一个简单的实验代码,可以实现STM32与上位机的串口通信,收到上位机发来的字符串后,原样返回给上位机:
```
#include "stm32f10x.h"
#include <stdio.h>
void USART1_Init(void);
void USART1_SendChar(char ch);
void USART1_SendString(char* str);
char USART1_ReceiveChar(void);
void USART1_ReceiveString(char* buffer, int buffer_size);
int main(void)
{
USART1_Init(); // 初始化串口
char buffer[128];
while (1)
{
USART1_ReceiveString(buffer, sizeof(buffer)); // 接收上位机发来的字符串
USART1_SendString(buffer); // 原样返回给上位机
}
}
void USART1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// 打开USART1和GPIOA的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
// 配置USART1的TX引脚为复用推挽输出
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);
// 配置USART1的RX引脚为浮空输入
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置USART1
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);
// 配置USART1中断
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// 启动USART1
USART_Cmd(USART1, ENABLE);
}
void USART1_SendChar(char ch)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET); // 等待发送缓冲区为空
USART_SendData(USART1, ch); // 发送一个字符
}
void USART1_SendString(char* str)
{
while (*str)
{
USART1_SendChar(*str++);
}
}
char USART1_ReceiveChar(void)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET); // 等待接收缓冲区非空
return USART_ReceiveData(USART1); // 返回接收到的字符
}
void USART1_ReceiveString(char* buffer, int buffer_size)
{
int i = 0;
char ch;
while (1)
{
ch = USART1_ReceiveChar();
if (ch == '\r' || ch == '\n' || i == buffer_size - 1) // 收到回车、换行符或缓冲区满了,就停止接收
{
buffer[i] = '\0';
break;
}
buffer[i++] = ch;
}
}
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) // 接收到一个字符
{
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}
}
```
在上位机的串口调试助手中,可以发送任意字符串给STM32,STM32将收到的字符串原样返回给上位机。
阅读全文