前言
本篇文章记录了如何使用stm32f103zet6核心板(下位机)通过串口向stm32f103zet6学习板(上位机)发送数据,stm32f103zet6学习板完成接收,并将接收到的数据显示在LCD显示屏上。
一、硬件准备及接线
硬件准备
正点原子精英STM32F103ZET6学习板一块(带2.8寸显示屏)
STM32F103ZET6核心板一块 电源适配器、数据线以及杜邦线若干。
接线
PA2(核心板)------------PA3(学习板) GND(核心板)----------GND(学习板)
二、程序
上位机程序
main.c文件:
#include "sys.h"
#include "lcd.h"
#include "delay.h"
#include "usart.h"
#include "usart2.h"
int main()
{
u8 x=0,i=0;
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
uart2_init(115200);
uart_init(115200);
LCD_Init();
POINT_COLOR=RED;
while(1)
{
for(i=0;i<10;i++)
{
LCD_ShowxNum(20*(i+1),120,receive_buff[i],1,24,1);
}
x++;
delay_ms(100);
if(x == 10)
{
LCD_Clear(WHITE);
x = 0;
}
}
}
usart2.c文件:
#include "sys.h"
#include "usart2.h"
#include "stm32f10x.h"
#if EN_USART2_RX
u8 receive_buff[10] = {0};
u8 i=0;
u8 rx_state = 0;
void uart2_init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
USART_DeInit(USART2);
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_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3 ;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_InitStructure.USART_BaudRate = bound;
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(USART2,&USART_InitStructure);
USART_ITConfig(USART2,USART_IT_RXNE, ENABLE);
USART_Cmd(USART2,ENABLE);
}
void USART2_IRQHandler(void)
{
if(USART_GetITStatus(USART2,USART_IT_RXNE) != RESET)
{
if(rx_state == 1)
{
receive_buff[i] = USART_ReceiveData(USART2);
i++;
if(i == 10)
{
rx_state = 0;
i = 0;
}
}
if(USART_ReceiveData(USART2) == 0x0d)
{
rx_state = 1;
}
}
}
#endif
下位机程序
main.c文件:
#include "sys.h"
#include "usart2.h"
#include "delay.h"
#include "led.h"
u8 send_buff[10] = {0,1,2,3,4,5,6,7,8,9};
void Usart2_Sendata()
{
u8 i = 0;
USART_SendData(USART2,0x0d);
while( USART_GetFlagStatus(USART2,USART_FLAG_TC)!= SET);
for(i = 0;i < 11;i++)
{
USART_SendData(USART2,send_buff[i]);
while( USART_GetFlagStatus(USART2,USART_FLAG_TC)!= SET);
}
}
int main(void)
{
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
uart2_init(115200);
while(1)
{
Usart2_Sendata();
}
}
三、运行结果
后记
两块stm32单片机串口通信完整工程文件点此获得。
|