(1)首先,我们要进行串口中断服务函数的配置
void USART1_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* 打开IO时钟和串口时钟 */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
/* 串口IO配置 */
/* Configure USART1 Tx (PA.09) as alternate function push-pull */
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);
/* Configure USART1 Rx (PA.10) as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* 串口1模式配置 */
USART_InitStructure.USART_BaudRate = 115200;
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);
/* 中断分组 */
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);
/* 打开串口中断 */
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
/* 打开串口1 */
USART_Cmd(USART1, ENABLE);
//重定向c库函数printf()到USART1
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (uint8_t) ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
return (ch);
}
}
(2)第二步,初始化和写串口中断服务函数
//参数初始化
double *n;
int num = 0;
u8 Buffer[8], Send_Buffer[8];
double double_data=12.345678;
//主函数
int main(void){
USART1_Config();
while(1){
printf("%f", double_data);
}
}
//中断服务函数
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)//产生中断
{
USART_ClearITPendingBit(USART1,USART_IT_RXNE);//清除中断标志位
Buffer[num++] = USART_ReceiveData(USART1);
if(num==8){
n = (void *)Buffer;
double_data = *n;
num=0;
}
}
}
至此,STM32中的中断服务函数已完成,
运行后,当串口发送端给单片机发送double类型数据时,即可收到相应的双精度数据,这里提供python的接收和发送程序:
import struct import serial ser = serial.Serial() ser.baudrate = 115200 ser.port = 'COM3' print(ser) ser.open() print(ser.is_open) //接收(这里接收到的是bytearray类型数据,要做具体类型转换可参考我的另一篇博客) s = ser.read(8) s1 = struct.unpack('8s', s) print(s1) //发送 value = (1.02255225,) s2 = struct.Struct('d') data = s2.pack(*value) ser.write(data)