7. CAN Bus Communication7.1. Experimental purpose7.2. Configure pin information7.3. Analysis of experimental flow chart7.4. Core code interpretation7.5. Hardware connection7.6. Experimental effect
Using STM32 CAN communication, using loop mode, key control to send CAN data, interrupt receiving CAN data and print out through serial assistant.
Since each new project needs configuration information, it is troublesome. Fortunately, STM32CubeIDE provides the function of importing.IOC file, which can help us save time.
Import ioc file from Serial project and name it CAN.
Find CAN in Connectivity and check Activated to enable the CAN peripheral.
According to the schematic diagram, the pins of the CAN bus connection are PB8 and PB9, while the default CAN bus pins are PA11 and PA12, so it is necessary to manually modify the pins of the CAN bus to PB8 and PB9.
Set the parameters of the CAN peripheral. Here, we set the baud rate to 1000kbps and the mode to Loopback.
Since this is only used to test communication, select Loopback mode (data collection). If you need to connect a third-party CAN device, select the Normal mode (data receiving/sending is independent).
Turn on the CAN RX0 interrupt in the interrupt setting. If you do not turn on the interrupt, you cannot receive data.
Create the buzzer driver library bsp_can.h and bsp_can.c files in the BSP. Add the following to bsp_can.h:
Add the following content to bsp_can.c:
Can_Init(): initializes CAN peripherals, sets CAN receiving filters, and enables CAN bus communication.
In order to test sending data, a new Can_Test_Send() function is created to send data through CAN and print it to the serial assistant. If you need to modify the sent data, just modify the TxData array before sending.
4.CAN receive interrupt callback function, and print out the received CAN data through serial port. This function name cannot be changed, otherwise this function cannot be called.
In BSP initialization, call the Can_Init() function to initialize the CAN peripheral.
Add the function of sending CAN data after the key is pressed.
Since the loop back mode is used, the CAN interface can not be connected to external devices.
After the program is burned, the LED light flashes every 200 milliseconds, the expansion board is connected to the computer through the micro-USB data cable, and the serial port assistant is opened (specific parameters are shown below). Every time you press the key, the buzzer will ring for 50 milliseconds, and you CAN see that the serial port assistant will display the data sent by CAN and the data received by CAN.