文章目录
- 通信接口
- USART基本结构
- 串口发送
- 串口接收
通信接口
全双工:有两个通道,发送接受可以同时进行
半双工:只有一个通道,不能同时进行
USAER:TX数据发送脚,RX接收脚
I2C:SCL时钟,SDA数据
SPI:SCLK时钟,MOSI主机输出数据脚(发送),MISO输入(接收),CS片选,用于指定通信对象
CAN:用两个引脚表示差分数组
USB:同上
前三个都要共地
差分:抗干扰强,速度快,距离远
USART基本结构
1.开启USART和GPIO的时钟
2.GPIO初始化,TX配置成复用输出,RX输入
3.配置USART初始化USART_Init()
4.开启USART(只需要发送功能)如果还需要接收功能就要配置中断ITConfig和NVICUSART_Cmd()
函数USART_SendData()发送数据写DR寄存器USART_ReceiveData()接收数据读DR寄存器
串口发送
代码
#include"stm32f10x.h"// Device header#include"stdio.h"//单片机没有屏幕需要进行重定向voidSerial_Init(void){RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);GPIO_InitTypeDef GPIO_InitStructure;GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;GPIO_Init(GPIOA,&GPIO_InitStructure);USART_InitTypeDef USART_InitStructure;USART_InitStructure.USART_BaudRate=9600;USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;USART_InitStructure.USART_Mode=USART_Mode_Tx;USART_InitStructure.USART_Parity=USART_Parity_No;USART_InitStructure.USART_StopBits=USART_StopBits_1;USART_InitStructure.USART_WordLength=USART_WordLength_8b;USART_Init(USART1,&USART_InitStructure);USART_Cmd(USART1,ENABLE);}voidSerial_SendByte(uint8_tByte)//发送函数{USART_SendData(USART1,Byte);while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET);//下一次在生成标志位自动清零}voidSerial_SendArray(uint8_t*Array,uint16_tLength)//发送数组{uint16_ti;for(i=0;i<Length;i++){Serial_SendByte(Array[i]);}}voidSerial_SendString(char*String)//发送字符串{uint8_ti;for(i=0;String[i]!=0;i++){Serial_SendByte(String[i]);}}uint32_tSerial_Pow(uint32_tx,uint32_ty){uint32_tResult=1;while(y--){Result*=x;}returnResult;}voidSerial_SendNum(uint32_tNumber,uint32_tLength)//输出数字函数,因为直接Serial_SendByte(123),这里的123会被ascii表识别成其他值{uint8_ti;for(i=0;i<Length;i++){Serial_SendByte(Number/Serial_Pow(10,Length-i-1)%10+0x30);}}intfputc(intch,FILE*f){Serial_SendByte(ch);returnch;}主函数代码
#include"stm32f10x.h"// Device header#include"Delay.h"#include"OLED.h"#include"Serial.h"intmain(void){OLED_Init();Serial_Init();// Serial_SendByte(0x41);// uint8_t MyArray[]={0x41,0x42,0x43,0x44};// Serial_SendArray(MyArray,4);// Serial_SendString("xswl");// Serial_SendNum(12345,5);// printf("Num=%d\r\n",666);charString[100];sprintf(String,"Num=%d\r\n",666);//后面的参数可以变Serial_SendString(String);while(1){}}串口接收
uint8_tSerial_GetRxFlag(void){if(Serial_RxFlag==1){Serial_RxFlag=0;return1;}return0;}uint8_tSerial_GetRxData(void){returnSerial_RxData;}//上面两个函数只是为了获取标志位和数据的voidUSART1_IRQHandler(void)//启动文件{if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET){Serial_RxData=USART_ReceiveData(USART1);Serial_RxFlag=1;USART_ClearITPendingBit(USART1,USART_IT_RXNE);}}