GD32F103VET6实现CAN总线收发函数
时间: 2023-11-18 21:04:16 浏览: 114
以下是基于GD32F103VET6芯片的CAN总线收发函数的样例代码:
首先需要在代码中包含头文件`gd32f10x_can.h`和`gd32f10x.h`:
```
#include "gd32f10x_can.h"
#include "gd32f10x.h"
```
然后需要进行CAN总线的初始化,可以参考如下代码:
```
/* CAN1 GPIOs configuration **************************************************/
/* enable CAN1 GPIO clocks */
rcu_periph_clock_enable(RCU_GPIOA);
/* configure CAN1 GPIOs */
gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_11);
gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_12);
/* CAN1 Periph clock enable */
rcu_periph_clock_enable(RCU_CAN1);
/* CAN1 register init */
can_deinit(CAN1);
/* CAN1 cell init */
can_struct_para_init(&can_parameter);
can_parameter.can_mode = CAN_MODE_NORMAL;
can_parameter.can_sjw = CAN_SJW_1TQ;
can_parameter.can_bs1 = CAN_BS1_9TQ;
can_parameter.can_bs2 = CAN_BS2_8TQ;
can_parameter.can_prescaler = 3;
can_parameter.can_ttc = DISABLE;
can_parameter.can_abom = ENABLE;
can_parameter.can_awu = DISABLE;
can_parameter.can_ard = DISABLE;
can_parameter.can_rflm = DISABLE;
can_parameter.can_nart = ENABLE;
can_parameter.can_txfp = DISABLE;
can_init(CAN1, &can_parameter);
```
接下来是CAN总线的发送函数,可以参考如下代码:
```
/* CAN1 send data */
uint8_t can1_send_data(uint32_t id, uint8_t* data, uint8_t len)
{
can_trasnmit_message_struct transmit_message;
uint8_t mbox;
transmit_message.tx_sfid = id;
transmit_message.tx_efid = 0x00;
transmit_message.tx_ft = CAN_FT_DATA;
transmit_message.tx_ff = CAN_FF_STANDARD;
transmit_message.tx_dlen = len;
memcpy(transmit_message.tx_data, data, len);
mbox = can_message_transmit(CAN1, &transmit_message);
while((can_transmit_status(CAN1, mbox) == CAN_TX_STATUS_PENDING));
if(can_transmit_status(CAN1, mbox) == CAN_TX_STATUS_SUCCESS)
{
return 0;
}
else
{
return 1;
}
}
```
最后是CAN总线的接收函数,可以参考如下代码:
```
/* CAN1 receive data */
uint8_t can1_receive_data(uint32_t* id, uint8_t* data, uint8_t* len)
{
can_receive_message_struct receive_message;
if(can_message_receive(CAN1, CAN_FIFO0, &receive_message) == SUCCESS)
{
*id = receive_message.rx_sfid;
*len = receive_message.rx_dlen;
memcpy(data, receive_message.rx_data, *len);
return 0;
}
else
{
return 1;
}
}
```
需要注意的是,以上代码仅供参考,具体实现过程中需要根据实际情况进行调整。同时,在使用CAN总线时需要注意相关的硬件连接、波特率设置等。
阅读全文