stm32f103c8t6串口2代码
时间: 2023-08-27 18:07:00 浏览: 86
下面是STM32F103C8T6串口2的代码示例,包含发送和接收功能:
```c
#include "stm32f10x.h"
#include <stdio.h>
#include <string.h>
#define USART2_DR_BASE 0x40004404
#define USART2_SR_TC_BIT 6
#define USART2_SR_RXNE_BIT 5
void USART2_Init(void)
{
// Enable GPIOA and USART2 clock
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO | RCC_APB2Periph_USART1, ENABLE);
// Configure PA2 as TX and PA3 as RX
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
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_3;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure USART2
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_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART2, &USART_InitStructure);
// Enable USART2
USART_Cmd(USART2, ENABLE);
}
void USART2_SendChar(char c)
{
// Wait for the transmit data register to be empty
while ((USART2->SR & (1 << USART2_SR_TC_BIT)) == 0);
// Send the character
USART2->DR = (c & 0xFF);
}
void USART2_SendString(const char* str)
{
const char* p = str;
while (*p) {
USART2_SendChar(*p++);
}
}
char USART2_ReceiveChar(void)
{
// Wait for the receive data register to be non-empty
while ((USART2->SR & (1 << USART2_SR_RXNE_BIT)) == 0);
// Read the character
return USART2->DR & 0xFF;
}
int main(void)
{
// Initialize USART2
USART2_Init();
// Send a string
USART2_SendString("Hello, world!\r\n");
// Receive a character and send it back
while (1) {
char c = USART2_ReceiveChar();
USART2_SendChar(c);
}
}
```
此代码使用 PA2 和 PA3 作为 USART2 的 TX 和 RX 引脚,波特率为 9600。USART2_SendChar 函数用于发送单个字符,USART2_SendString 函数用于发送字符串。USART2_ReceiveChar 函数用于接收单个字符。在主函数中,发送一个字符串后,进入一个死循环,不断接收一个字符并发送回去。
阅读全文