起始位:0xaa告诉机器我们要开始传输数据了。
校验位:等于前几项数据位的相加。
结束位:结束传输。
自定义UART数据格式:
1》CPU与CPU之间
2》外设与CPU之间
这里举例,利用串口调试助手发送一串数据,来控制4个LED灯。
数据格式
例如
LED1点亮:aa 01 01 02 ff
LED2熄灭:aa 02 00 02 ff
- 先对串口中断和UART进行配置
void Uart1_Configuration(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //TX 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_10; //TX GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); 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_Tx | USART_Mode_Rx; USART_Init(USART1, &USART_InitStructure); USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); USART_Cmd(USART1, ENABLE); } void Uart1_NVIC_Init(void) { NVIC_InitTypeDef NVIC_InitStructure; NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); 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); }
- LED配置
void Led_Configuration(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); }
- UART中断
void control_LED(unsigned int led_number, unsigned int status) { GPIO_WriteBit(GPIOA, (uint16_t)1<<led_number, (BitAction)status); } void USART1_IRQHandler(void) { static unsigned int i = 1; static unsigned int flag = 0; static unsigned int arr[5] = {0, 0, 0, 0, 0}; unsigned char ch; while(USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == SET) { ch = USART_ReceiveData(USART1); if(ch == 0xaa) { arr[0] = ch; flag = 1; } if(ch != 0xaa && flag == 1) { arr[i++] = ch; if(i == 5) { flag = 0; i = 1; if(((arr[i]+arr[2]) == arr[3]) && arr[4] == 0xff) control_LED(arr[1], arr[2]); } } } }
static unsigned int arr[5] = {0, 0, 0, 0, 0};如果直接定义arr,这样每次进中断arr都会被初始化为0,所以我们必须在arr的定义类型前加static,把它变为全局变量。这样arr只会在第一次的时候初始化,随后每次进中断时arr都不会被重新赋值了。
同理这里定义flag,用来判断,是否开始传输,是则为1,否则为0。
本实验接线:TTL:RX》A10,TX》A9,5V》5V,GND》GND,4个LED灯接在A1,A2,A3,A4,