STM32串口通信(使用C8T6)
芯片引脚
USART 1:
Tx:30,PA9
Rx: 31,PA10
CTS:PA11,RTS:PA12
USART 2:
Tx:12,PA2
Rx: 13,PA3
CTS:10 PA0 RTS:11,PA1
printf的使用
添加代码如下:
int fputc(int ch, FILE *f) { USART_SendData(USART1, (uint8_t) ch); while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET) {} return ch; } int GetKey (void) { while (!(USART1->SR & USART_FLAG_RXNE)); return ((int)(USART1->DR & 0x1FF)); } //fputc也可以这样 int fputc(int ch, FILE *f) { USART_SendData(USART1, (unsigned char) ch);// USART1 可以换成 USART2 等 while (!(USART1->SR & USART_FLAG_TXE)); return (ch); }
在工程属性的 “Target" -> "Code Generation" 选项中勾选 "Use MicroLIB"”
核心代码
初始化代码
GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE); //ʹÄÜUSART1£¬GPIOAʱÖÓ //USART1_TX GPIOA.9 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.9 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //¸´ÓÃÍÆÍìÊä³ö GPIO_Init(GPIOA, &GPIO_InitStructure);//³õʼ»¯GPIOA.9 //USART1_RX GPIOA.10³õʼ»¯ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;//PA10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//¸¡¿ÕÊäÈë GPIO_Init(GPIOA, &GPIO_InitStructure);//³õʼ»¯GPIOA.10 //Usart1 NVIC ÅäÖà NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//ÇÀÕ¼ÓÅÏȼ¶3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //×ÓÓÅÏȼ¶3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨµÀʹÄÜ NVIC_Init(&NVIC_InitStructure); //¸ù¾ÝÖ¸¶¨µÄ²ÎÊý³õʼ»¯VIC¼Ä´æÆ÷ //USART ³õʼ»¯ÉèÖà USART_InitStructure.USART_BaudRate = baud;//´®¿Ú²¨ÌØÂÊ USART_InitStructure.USART_WordLength = USART_WordLength_8b;//×Ö³¤Îª8λÊý¾Ý¸ñʽ 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); //³õʼ»¯´®¿Ú1 USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//¿ªÆô´®¿Ú½ÓÊÜÖÐ¶Ï USART_Cmd(USART1, ENABLE); //ʹÄÜ´®¿Ú1
如果是UART2初始化,
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA, ENABLE);
需要改成
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
接收数据
void USART2_IRQHandler(void) // { u8 Res; if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET){ Res=USART_ReceiveData(USART2); ...... } }
发送数据
USART_SendData(USART2, buffer[t%BUF_SIZE]);// while(USART_GetFlagStatus(USART2,USART_FLAG_TC)!=SET);//等待发送完成