CAN
Description
This features is present on OI-Core/OI-CoreLite (x1).
This is a standard CAN 2.0B bus.
A termination resistor of 120Ω is built into the module between CAN_H and CAN_L.
The CAN controller adheres to the standard ISO 11989-1, while the CAN transceiver complies with standards ISO-11898-2 and ISO-11898-5. The bus speed can be set up to 1Mbit/sec (user-selectable in code). The CAN functionality is managed internally via SPI, but there’s no need to worry as a ready-to-use API is already implemented to assist you.
Code examples
The example code below demonstrates how to use CAN (standard frame).
#include "OpenIndus.h"
#include "Arduino.h"
Core core;
CAN_Message_t rxMsg;
CAN_Message_t txMsg;
void setup(void)
{
Serial.begin(115200);
core.can.begin(); // Initialize CAN peripheral
txMsg.id = 11;
txMsg.size = 8;
txMsg.msg[0] = 'A';
txMsg.msg[1] = 'U';
txMsg.msg[2] = 'R';
txMsg.msg[3] = 'E';
txMsg.msg[4] = 'L';
txMsg.msg[5] = 'I';
txMsg.msg[6] = 'E';
txMsg.msg[7] = 'N';
txMsg.IDE = false; // Standard ID
txMsg.RTR = false; // No remote request frame
core.can.write(txMsg);
core.can.setStandardFilter(0xFF0, 0x0AA);
}
void loop(void)
{
if(core.can.available()) {
rxMsg = core.can.read();
Serial.printf("ID: %lx Size: %d Data: ", rxMsg.id, rxMsg.size);
for(int i =0; i <rxMsg.size; i++) {
Serial.printf("%x", rxMsg.msg[i]);
}
Serial.printf("\n");
}
delay(100);
}
Note
To use CAN Extended mode, simply modify the message identifier and the relevant flags in the example above to use an extended identifier (29 bits) and enable the extended frame flag in the CAN API. Refer to the API documentation for the exact parameters to adjust.
Software API
-
class CAN
CAN bus class.
Public Functions
-
CAN(spi_host_device_t host, gpio_num_t cs, gpio_num_t intr)
Construct a new CAN object.
- Parameters:
host – SPI host device
cs – Chip select pin
intr – Interrupt pin
-
void begin(unsigned long baudrate = 1000000, bool extended_mode = false)
Initialize the CAN communication.
- Parameters:
baudrate – CAN baudrate in bits/s (default: 1000000)
extended_mode – Enable extended frame mode
-
void write(CAN_Message_t msg)
Write a CAN message to the bus.
- Parameters:
msg – CAN message structure
-
int available(void)
Get the number of messages available for reading.
- Returns:
Number of available messages
-
CAN_Message_t read(void)
Read a CAN message from the bus.
- Returns:
CAN message structure
-
CAN(spi_host_device_t host, gpio_num_t cs, gpio_num_t intr)