stm32f103c8t6双版CAN通讯
时间: 2023-07-26 21:03:49 浏览: 118
双板CAN通讯需要至少两个CAN控制器,每个控制器都需要一个CAN总线收发器。对于STM32F103C8T6,它只有一个CAN控制器,因此需要外接CAN总线收发器来实现双板CAN通讯。
下面是一个简单的示例代码,可以让STM32F103C8T6通过CAN总线与另一块板子进行双板通讯:
```c
#include "stm32f10x.h"
#include "stm32f10x_can.h"
#include "stm32f10x_gpio.h"
void CAN_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
CAN_InitTypeDef CAN_InitStructure;
// 使能GPIO和CAN时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1, ENABLE);
// 配置CAN1 RX引脚为复用功能推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 配置CAN1 TX引脚为复用功能推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// CAN总线配置
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_4tq;
CAN_InitStructure.CAN_BS2 = CAN_BS2_3tq;
CAN_InitStructure.CAN_Prescaler = 6;
CAN_Init(CAN1, &CAN_InitStructure);
// CAN总线过滤器配置
CAN_FilterInitTypeDef CAN_FilterInitStructure;
CAN_FilterInitStructure.CAN_FilterNumber = 0;
CAN_FilterInitStructure.CAN_FilterMode = CAN_FilterMode_IdMask;
CAN_FilterInitStructure.CAN_FilterScale = CAN_FilterScale_32bit;
CAN_FilterInitStructure.CAN_FilterIdHigh = 0x0000;
CAN_FilterInitStructure.CAN_FilterIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdHigh = 0x0000;
CAN_FilterInitStructure.CAN_FilterMaskIdLow = 0x0000;
CAN_FilterInitStructure.CAN_FilterFIFOAssignment = 0;
CAN_FilterInitStructure.CAN_FilterActivation = ENABLE;
CAN_FilterInit(&CAN_FilterInitStructure);
}
void CAN_SendData(void)
{
CanTxMsg TxMessage;
TxMessage.StdId = 0x321;
TxMessage.IDE = CAN_Id_Standard;
TxMessage.RTR = CAN_RTR_Data;
TxMessage.DLC = 2;
TxMessage.Data[0] = 0x55;
TxMessage.Data[1] = 0xAA;
CAN_Transmit(CAN1, &TxMessage);
}
void CAN_ReceiveData(void)
{
CanRxMsg RxMessage;
if (CAN_MessagePending(CAN1, CAN_FIFO0) != 0)
{
CAN_Receive(CAN1, CAN_FIFO0, &RxMessage);
// 处理接收到的数据
}
}
int main(void)
{
CAN_Configuration();
while (1)
{
CAN_SendData();
CAN_ReceiveData();
}
}
```
在这个例子中,我们将CAN1的RX和TX引脚分别连接到另一块板子的CAN总线收发器的RX和TX引脚上。然后,我们通过CAN_SendData函数发送一条长度为2的数据包,数据包的ID为0x321,数据内容为0x55和0xAA。在主循环中,我们不断地发送数据并接收数据。当接收到数据时,我们可以在CAN_ReceiveData函数中对接收到的数据进行处理。
阅读全文