GD32F103CBT6can通讯代码
时间: 2023-07-09 20:40:18 浏览: 112
以下是基于 GD32F103CBT6 的 CAN 通讯代码示例:
```c
#include "gd32f10x.h"
#include "gd32f10x_can.h"
void CAN_Configuration(void)
{
CAN_InitPara CAN_InitStructure;
CAN_FilterInitPara CAN_FilterInitStructure;
RCC_APB1PeriphClock_Enable(RCC_APB1PERIPH_CAN0, ENABLE);
RCC_AHBPeriphClock_Enable(RCC_AHBPERIPH_GPIOB, ENABLE);
GPIO_InitPara GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_PIN_8 | GPIO_PIN_9;
GPIO_InitStructure.GPIO_Speed = GPIO_SPEED_50MHZ;
GPIO_InitStructure.GPIO_Mode = GPIO_MODE_IPU;
GPIO_Init(GPIOB,&GPIO_InitStructure);
CAN_InitStructure.CAN_TTCM = DISABLE;
CAN_InitStructure.CAN_ABOM = DISABLE;
CAN_InitStructure.CAN_AWUM = DISABLE;
CAN_InitStructure.CAN_NART = DISABLE;
CAN_InitStructure.CAN_RFLM = DISABLE;
CAN_InitStructure.CAN_TXFP = DISABLE;
CAN_InitStructure.CAN_Mode = CAN_MODE_NORMAL;
CAN_InitStructure.CAN_SJW = CAN_SJW_1TQ;
CAN_InitStructure.CAN_BS1 = CAN_BS1_8TQ;
CAN_InitStructure.CAN_BS2 = CAN_BS2_7TQ;
CAN_InitStructure.CAN_Prescaler = 6;
CAN_Init(CAN0, &CAN_InitStructure);
CAN_FilterInitStructure.CAN_FilterNumber=0;
CAN_FilterInitStructure.CAN_FilterMode=CAN_FILTERMODE_MASK;
CAN_FilterInitStructure.CAN_FilterScale=CAN_FILTERSCALE_32BIT;
CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000;
CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000;
CAN_FilterInitStructure.CAN_FilterIdLow=0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment=CAN_FILTER_FIFO0;
CAN_FilterInitStructure.CAN_FilterActivation=ENABLE;
CAN_FilterInit(&CAN_FilterInitStructure);
CAN_ITConfig(CAN0, CAN_IT_FF0, ENABLE);
}
void CAN_SendData(uint8_t* data, uint8_t len, uint32_t id)
{
CanTxMessage TxMessage;
TxMessage.StdId = id;
TxMessage.ExtId = 0x00;
TxMessage.IDE = CAN_ID_STD;
TxMessage.RTR = CAN_RTR_DATA;
TxMessage.DLC = len;
for(uint8_t i=0;i<len;i++)
{
TxMessage.Data[i] = data[i];
}
CAN_Transmit(CAN0, &TxMessage);
}
void USB_LP_CAN0_RX0_IRQHandler(void)
{
CanRxMessage RxMessage;
CAN_Receive(CAN0, CAN_FIFO0, &RxMessage);
// 处理接收到的数据
}
```
注意:在使用 CAN 通讯时,需要正确配置 CAN 引脚以及过滤器。同时,需要在中断处理函数中处理接收到的数据。
阅读全文