串口及其中断初始化
void USART1Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_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_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
USART_ClearFlag(USART1,USART_FLAG_TC);
USART_Cmd(USART1, ENABLE);
}
void NVIC_USART1_Init(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
串口发送一个字节函数
void Usart1SendByte(char byte)//发送一个字节 硬件连接选用的为USART1
{
USART1->SR;
USART_SendData(USART1, (uint8_t) byte);
while( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET);
}
数据打包发送函数
void ADC_ConvertSend(float value)
{
unsigned char temp[6];
char CheckStart='~';//数据传输开始
char CheckEnd='!';//表示一次传输完成
unsigned short i=0,j=0;
float floatVariable=value;
unsigned char *pdata = (unsigned char *)&floatVariable;
temp[0]=CheckStart;//数据包头
for(i=0;i<4;i++)
{
temp[i+1] = *pdata++;//float转BYTE
}
temp[5]=CheckEnd;//数据包尾
for( j=0;j<6;j++)
{
Usart1SendByte(temp[j]);
}
}
上一篇:STM32按键控制LED(不用固件库)
下一篇:关于STM32F4的串口注意的坑
推荐阅读最新更新时间:2024-03-16 16:27