📄 candemo.c
字号:
/*----------------------------------------------------------------------------
CAN实验需要两个带CAN接口的板子
CAN实验太复杂了,所以不是简单的配置文件能搞定的事,建议熟悉了STM32后再来做此实验。
准备工作,准备两个CAN板子,连接两个CAN接口,两个板子都下载本程序。
本实验通过CAN总线控制另外一个板子的LED2~LED5闪烁的例子,如果通信正常可以看到两个板子的LED都再闪烁,
如果通信失败或者断开通信线,LED不再闪烁
*---------------------------------------------------------------------------*/
#include <stm32f10x_lib.h> // STM32F10x Library Definitions
#include "STM32_Reg.h" // STM32 register and bit Definitions
#include "STM32_Init.h" // STM32 Initialization
#include "CAN.h" // STM32 CAN adaption layer
#include "MyType.h"
#include "config.h"
/*----------------------------------------------------------------------------
insert a delay time.
*----------------------------------------------------------------------------*/
void delay(unsigned int nCount) {
for(; nCount != 0; nCount--);
}
/*----------------------------------------------------------------------------
initialize CAN interface
*----------------------------------------------------------------------------*/
void can_Init (void) {
CAN_setup (); // setup CAN interface
CAN_wrFilter (33, STANDARD_FORMAT); // Enable reception of messages
/* COMMENT THE LINE BELOW TO ENABLE DEVICE TO PARTICIPATE IN CAN NETWORK */
//CAN_testmode(CAN_BTR_SILM | CAN_BTR_LBKM); // Loopback, Silent Mode (self-test)
//软件仿真使用环回模式
//CAN_testmode(CAN_BTR_SILM | CAN_BTR_LBKM); /* Loopback and */
//硬件仿真使用正常模式
CAN_testmode(0); //正常模式
// leave init mode
//进入正常模式
CAN_start ();
// wait til mbx is empty
//等待CAN就绪
CAN_waitReady ();
}
/*----------------------------------------------------------------------------
MAIN function
*----------------------------------------------------------------------------*/
int main (void)
{
uint32 i;
//uint8 flag=0;
stm32_Init ();
can_Init (); // initialise CAN interface
CAN_TxMsg.id = 33; // initialise message to send
for (i = 0; i < 8; i++) CAN_TxMsg.data[i] = 0;
CAN_TxMsg.len = 4;
CAN_TxMsg.format = STANDARD_FORMAT;//使用标准帧
CAN_TxMsg.type = DATA_FRAME;//数据帧
i=0;
while (1)
{
if (CAN_TxRdy)
{
if(++i==60000)
{
//i=0;
//下面是数据报文
CAN_TxMsg.data[0] = 0;
CAN_TxMsg.data[1] = 0;
CAN_TxMsg.data[2] = 0;
CAN_TxMsg.data[3] = 0;
//发送CAN报文
CAN_TxRdy = 0;
CAN_wrMsg (&CAN_TxMsg);
}
else if(i==120000)
{
i=0;
//下面是数据报文
CAN_TxMsg.data[0] = 1;
CAN_TxMsg.data[1] = 1;
CAN_TxMsg.data[2] = 1;
CAN_TxMsg.data[3] = 1;
//发送CAN报文
CAN_TxRdy = 0;
CAN_wrMsg (&CAN_TxMsg);
}
}
if (CAN_RxRdy)
{
CAN_RxRdy = 0;
if(CAN_RxMsg.data[0]==0)////PC8状态
PC8=0;
else
PC8=1;
if(CAN_RxMsg.data[1]==0)////PC9状态
PC9=0;
else
PC9=1;
if(CAN_RxMsg.data[2]==0)////PC10状态
PC10=0;
else
PC10=1;
if(CAN_RxMsg.data[3]==0)////PC11状态
PC11=0;
else
PC11=1;
}
} // end while
} // end main
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -