stm32f407与openmv串口通信代码标准库函数版本通过帧头
时间: 2023-10-09 17:05:34 浏览: 46
以下是基于标准库函数的STM32F407与OpenMV串口通信代码,通过帧头进行数据传输:
STM32F407代码:
```c
#include "stm32f4xx.h"
#include <string.h>
#define RX_BUFFER_SIZE 64
uint8_t rx_buffer[RX_BUFFER_SIZE];
uint8_t rx_index = 0;
uint8_t rx_complete = 0;
void USART2_IRQHandler(void) {
if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) {
uint8_t ch = USART_ReceiveData(USART2);
if (rx_index == 0 && ch != 0xAA) {
return;
}
rx_buffer[rx_index] = ch;
rx_index++;
if (rx_index >= RX_BUFFER_SIZE) {
rx_index = 0;
}
if (rx_index == 4 && rx_buffer[1] == 0x01 && rx_buffer[2] == 0x02) {
rx_complete = 1;
}
}
}
void USART2_Init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
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_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStructure);
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART2, ENABLE);
}
void USART2_SendChar(uint8_t ch) {
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
USART_SendData(USART2, ch);
}
void USART2_SendFrame(uint8_t *buffer, uint8_t size) {
USART2_SendChar(0xAA);
USART2_SendChar(size);
for (uint8_t i = 0; i < size; i++) {
USART2_SendChar(buffer[i]);
}
}
int main(void) {
USART2_Init();
while (1) {
if (rx_complete) {
uint8_t size = rx_buffer[3];
uint8_t buffer[size];
memcpy(buffer, &rx_buffer[4], size);
// 处理接收到的数据
rx_index = 0;
rx_complete = 0;
}
}
}
```
OpenMV代码:
```python
import time
from struct import pack, unpack
uart = UART(3, 115200)
uart.init(115200, bits=8, parity=None, stop=1)
# 发送帧
def send_frame(data):
size = len(data)
header = pack('BBB', 0xAA, 0x01, 0x02)
frame = header + pack('B'*size, *data)
uart.write(frame)
while(True):
if uart.any():
data = uart.read(64)
if data[0] == 0xAA and data[1] == 0x01 and data[2] == 0x02:
size = data[3]
frame = unpack('B'*size, data[4:size+4])
# 处理接收到的数据
```