51单片机串口通讯接收openmv数据控制led亮灭的代码
时间: 2024-05-08 16:15:46 浏览: 15
以下是基于STM32F103单片机的串口通讯接收OpenMV数据并控制LED亮灭的代码:
```
#include "stm32f10x.h"
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
void USART1_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE); // 使能USART1和GPIOA时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; // USART1_TX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; // USART1_RX
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; // 数据位8位
USART_InitStructure.USART_StopBits = USART_StopBits_1; // 停止位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);
USART_Cmd(USART1, ENABLE); // 使能USART1
}
void LED_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE); // 使能GPIOC时钟
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; // PC13
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // 推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) // 判断是否接收到数据
{
uint8_t data = USART_ReceiveData(USART1); // 读取数据
if (data == '1') // 如果接收到'1',则点亮LED
{
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
}
else if (data == '0') // 如果接收到'0',则熄灭LED
{
GPIO_SetBits(GPIOC, GPIO_Pin_13);
}
}
}
int main(void)
{
USART1_Init();
LED_Init();
NVIC_EnableIRQ(USART1_IRQn); // 使能USART1中断
while (1)
{
}
}
```
在OpenMV中,可以使用`uart.write()`函数发送数据到串口。例如,发送'1'即可点亮LED:
```
import sensor, image, time, pyb
uart = pyb.UART(3, 115200)
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time = 2000)
clock = time.clock()
while(True):
clock.tick()
img = sensor.snapshot()
uart.write('1')
print(clock.fps())
```