CAN example
CAN example
#include <io>
#include <read>
#include <float>
#include <string>
#include <core>
#include <write>
#include <define>
#include <can>
new CAN_Tx_buffer[11]; // Transmission buffer for CAN
new CAN_Rx_buffer[11]; // Receiving CAN buffer
#define CURRENT_CAN CAN1 // This can be eithe CAN1 or CAN2, change it accordingly
#define CAN_BAUDRATE 500000 // Type your CAN baudrate here for the sake of example it's 500kbit/s
#define CAN_CONFIG_USING_ID // Comment which CAN configuration you're not going to use, only one can be possible to use at once
//#define CAN_CONFIG_USING_MASK // Comment which CAN configuration you're not going to use, only one can be possible to use at once
public callback (event)
{
switch(event)
{
case CAN1:
{
ReadCANmsg(CURRENT_CAN, CAN_Rx_buffer); // Incoming CAN message is received into CAN_Rx_buffer buffer
CAN_message_parse(CAN_Rx_buffer[0]); // Call function CAN_message_parse(). CAN_Rx_buffer[0] - Message ID.
}
}
return 0;
}
CAN_buf_send(CAN_ID, CAN_TYPE, NO_OF_BYTES, DATA1, DATA2, DATA3, DATA4, DATA5, DATA6, DATA7, DATA8) // This function sends CAN message, there's an example on how to do it below
{
CAN_Tx_buffer[0] = CAN_ID; // CAN ID
CAN_Tx_buffer[1] = CAN_TYPE; // CAN ID type (STANDARD or EXTENDED)
CAN_Tx_buffer[2] = NO_OF_BYTES; // CAN message Number of bytes of data (0-8)
CAN_Tx_buffer[3] = DATA1; // CAN Data
CAN_Tx_buffer[4] = DATA2; // CAN Data
CAN_Tx_buffer[5] = DATA3; // CAN Data
CAN_Tx_buffer[6] = DATA4; // CAN Data
CAN_Tx_buffer[7] = DATA5; // CAN Data
CAN_Tx_buffer[8] = DATA6; // CAN Data
CAN_Tx_buffer[9] = DATA7; // CAN Data
CAN_Tx_buffer[10] = DATA8; // CAN Data
WriteCANmsg(CURRENT_CAN, CAN_Tx_buffer); // Send CAN message
}
CAN_message_parse(CAN_ID) // This function created to parse incomming CAN messages, add your expected ID cases and parse them as you expect to (configure your ID's or filter accordingly)
{
switch(CAN_ID)
{
case 0x100: // If CAN received 0x100 ID message do this
{
// Parse your message here
}
case 0x215: // If CAN received 0x215 ID message do this
{
// Parse your message here
}
}
}
main()
{
Init(CURRENT_CAN, NORMAL, CAN_BAUDRATE); // Initialize CAN2, normal mode, speed: 500kbit/s
CANconfig(CURRENT_CAN, RESET_FILTER); // CAN configuration
#if defined CAN_CONFIG_USING_ID
CANconfig(CURRENT_CAN, ADD_ID, STANDARD, 0x100); // CAN configuration
CANconfig(CURRENT_CAN, ADD_ID, STANDARD, 0x215); // CAN configuration
#endif
#if defined CAN_CONFIG_USING_MASK
CANconfig(CURRENT_CAN, ADD_MASK_STD, 0x000, 0x000); // Receive all messages
#endif
while(1)
{
CAN_buf_send(0x315, STANDARD, 8, 0x21, 0x11, 0x01, 0x00, 0x00, 0x00, 0x00, 0x15); // Send CAN message using created function above
Delay(2000); // Delay 2 sec.
}
}