利用串口进行OpenMV与STM32(其他单片机同理)进行通讯
OpenMV程序,串口发送函数:
from pyb import UART
import struct
def sending_data(x1,y1):
data =struct.pack("<bbhhb",
0x2C,
0x12,
int(x1),
int(y1),
)
uart.write(data);
print(data)
单片机解码程序:
extern u8 OpenMV_Rx_BUF[6];
void uart3_init(u32 bound)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3,ENABLE);
GPIO_PinAFConfig(GPIOB,GPIO_PinSource10,GPIO_AF_USART3);
GPIO_PinAFConfig(GPIOB,GPIO_PinSource11,GPIO_AF_USART3);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB,&GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = bound;
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(USART3, &USART_InitStructure);
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
USART_ITConfig(USART3, USART_IT_IDLE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority =2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART3, ENABLE);
}
void USART3_IRQHandler(void)
{
uint8_t Clear=Clear;
static uint8_t rebuf[6]={0},i=0;
#if SYSTEM_SUPPORT_OS
OSIntEnter();
#endif
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)
{
rebuf[i++] =USART_ReceiveData(USART3);
if(rebuf[0]!=0x2c)
{
i=0;
}
if((i==2)&&(rebuf[1]!=0x12))
{
i=0;
}
if(i>=6)
{
memcpy(OpenMV_Rx_BUF,rebuf,i);
i=0;
}
}
else if(USART_GetITStatus(USART3,USART_IT_IDLE)!=RESET)
{
Clear=USART3->SR;
Clear=USART3->DR;
}
#if SYSTEM_SUPPORT_OS
OSIntExit();
#endif
}
亲测可行
|