GD32F103VET6的CAN通讯代码
时间: 2023-07-02 17:22:48 浏览: 135
STM32F103VET6原理图和pcb.zip
以下是GD32F103VET6的CAN通讯代码示例,包括CAN初始化、CAN发送和接收数据:
```c
#include "gd32f10x.h"
/* CAN初始化函数 */
void CAN_Config(void)
{
/* 使能CAN时钟 */
rcu_periph_clock_enable(RCU_CAN0);
/* 配置CAN GPIO */
gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_8);
gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);
/* CAN单元初始化 */
can_deinit(CAN0);
can_struct_init(&can_initpara);
can_initpara.time_triggered_mode = DISABLE;
can_initpara.auto_bus_off_recovery = ENABLE;
can_initpara.auto_wake_up = DISABLE;
can_initpara.auto_retrans = ENABLE;
can_init(CAN0, &can_initpara);
/* 配置CAN过滤器 */
can_filter_initpara.filter_number = 0;
can_filter_initpara.filter_mode = CAN_FILTERMODE_MASK;
can_filter_initpara.filter_scale = CAN_FILTERSCALE_32BIT;
can_filter_initpara.filter_mask_id_high = 0x0000;
can_filter_initpara.filter_mask_id_low = 0x0000;
can_filter_initpara.filter_id_high = 0x0000;
can_filter_initpara.filter_id_low = 0x0000;
can_filter_initpara.filter_fifo_number = CAN_FIFO0;
can_filter_initpara.filter_enable = ENABLE;
can_filter_init(&can_filter_initpara);
/* 使能CAN中断 */
nvic_irq_enable(CAN0_RX0_IRQn, 0, 0);
can_interrupt_enable(CAN0, CAN_INTEN_RFNEIE0);
}
/* CAN发送数据函数 */
void CAN_SendData(uint8_t* data, uint8_t len)
{
/* 等待发送缓冲区为空 */
while(CAN0->TSR & CAN_TSR_TME0);
/* 设置发送数据长度 */
can_message_struct.length = len;
/* 填充发送数据 */
for(uint8_t i = 0; i < len; i++)
{
can_message_struct.data[i] = data[i];
}
/* 设置发送数据ID */
can_message_struct.format_type = CAN_STDID;
can_message_struct.id = 0x123;
/* 发送数据 */
can_message_transmit(CAN0, &can_message_struct);
/* 等待发送完成 */
while(!(CAN0->TSR & CAN_TSR_TME0));
}
/* CAN接收数据函数 */
void CAN_ReceiveData(uint8_t* data, uint8_t* len)
{
if(CAN0->RFIF & CAN_RFIF_FMP0)
{
/* 获取接收数据长度 */
*len = (uint8_t)(CAN0->sFIFOMailBox[0].RDTR & CAN_RDT0R_DLC);
/* 获取接收数据 */
for(uint8_t i = 0; i < *len; i++)
{
data[i] = (uint8_t)(CAN0->sFIFOMailBox[0].RDLR >> (i * 8));
}
/* 清除接收数据标志 */
CAN0->RFIF &= ~(CAN_RFIF_FMP0);
}
}
/* CAN接收中断服务函数 */
void CAN0_RX0_IRQHandler(void)
{
CAN_ReceiveData(recv_data, &recv_len);
}
```
以上代码仅供参考,具体实现需要根据实际情况进行修改。
阅读全文