STM32F103配置串列埠中斷服務函式並接收double雙精度資料,python傳送和接收雙精度資料
(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)