感谢
首先先感谢一下安信可举办的活动,
抱着陪跑的心态参加了抽奖,没想到居然中奖了
感谢园长
作品
这次使用的是之前参加活动送的 Ai-M61-32S-Kit
再次感谢园长
代码
先给雷达模块刷入了精准测距固件
查阅手册得到了数据帧的格式
然后写个一个解析数据帧的解析器
typedef enum
{
WAITING_HEADER,
HEADER_FOUND,
STATUS,
DISTANCE_1,
DISTANCE_2
} ParserState;
// 数据帧解析器结构体
typedef struct
{
ParserState state;
unsigned char target_status;
unsigned short distance;
} DataFrameParser;
// 初始化解析器
void init_parser(DataFrameParser *parser)
{
parser->state = WAITING_HEADER;
parser->target_status = 0;
parser->distance = 0;
}
// 解析单个字节
void parse_byte(DataFrameParser *parser, unsigned char byte)
{
// 雷达数据格式
// 帧头(2) 目标信息(1) 距离信息(2) 帧尾(2)
// AA AA 01 2F 00 55 55
switch (parser->state)
{
case WAITING_HEADER:
if (byte == 0xAA)
{
parser->state = HEADER_FOUND;
}
break;
case HEADER_FOUND:
if (byte == 0xAA)
{
parser->state = STATUS;
}
else
{
parser->state = WAITING_HEADER;
}
break;
case STATUS:
if (byte == 0x00 || byte == 0x01 || byte == 0x02)
{
parser->target_status = byte;
parser->state = DISTANCE_1;
}
else
{
parser->state = WAITING_HEADER;
}
break;
case DISTANCE_1:
parser->distance = byte;
parser->state = DISTANCE_2;
break;
case DISTANCE_2:
parser->distance |= (byte << 8);
parser->state = WAITING_HEADER;
// printf("目标状态: %d\n", parser->target_status);
// printf("距离信息: %d\n", parser->distance);
break;
}
}
unsigned get_distance(DataFrameParser *parser)
{
return parser->distance;
}
然后就是其他应用代码
void red_on()
{
bflb_gpio_set(gpio, RED_LIGHT_PIN);
}
void red_off()
{
bflb_gpio_reset(gpio, RED_LIGHT_PIN);
}
void green_on()
{
bflb_gpio_set(gpio, GREED_LIGHT_PIN);
}
void green_off()
{
bflb_gpio_reset(gpio, GREED_LIGHT_PIN);
}
int main(void)
{
DataFrameParser parser;
init_parser(&parser);
board_init();
gpio = bflb_device_get_by_name("gpio");
uart1 = bflb_device_get_by_name("uart1");
bflb_gpio_init(gpio, RED_LIGHT_PIN, GPIO_OUTPUT | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_0);
bflb_gpio_init(gpio, GREED_LIGHT_PIN, GPIO_OUTPUT | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_0);
bflb_gpio_set(gpio, RED_LIGHT_PIN);
bflb_gpio_set(gpio, GREED_LIGHT_PIN);
bflb_gpio_uart_init(gpio, GPIO_PIN_31, GPIO_UART_FUNC_UART1_TX);
bflb_gpio_uart_init(gpio, GPIO_PIN_30, GPIO_UART_FUNC_UART1_RX);
struct bflb_uart_config_s cfg2 = {
.baudrate = 256000,
.data_bits = UART_DATA_BITS_8,
.stop_bits = UART_STOP_BITS_1,
.parity = UART_PARITY_NONE,
.flow_ctrl = 0,
.tx_fifo_threshold = 7,
.rx_fifo_threshold = 7,
};
bflb_uart_init(uart1, &cfg2);
int ch = -1;
int len = 0;
while (1)
{
// printf("test Messages");
if (bflb_uart_rxavailable(uart1))
{
ch = bflb_uart_getchar(uart1);
parse_byte(&parser, ch);
len = get_distance(&parser);
printf("距离信息: %d\n", len);
}
//设置的为大于50厘米为绿灯,小于50是红灯
if (len < 50 && len != 0)
{
green_off();
red_on();
}
else
{
green_on();
red_off();
}
}
}
效果
大于50厘米
小于50厘米
结束 |