In this guide you'll learn how to use CircuitPython's
canio module to send and receive data between two supported boards, such as the Feather M4 CAN.
Are you new to using CircuitPython? No worries, there is a full getting started guide here.
Adafruit suggests using the Mu editor to edit your code and have an interactive REPL in CircuitPython. You can learn about Mu and installation in this tutorial.
According to Wikipedia,
A Controller Area Network (CAN bus) is a robust vehicle bus standard designed to allow microcontrollers and devices to communicate with each other's applications without a host computer. It is a message-based protocol, designed originally for multiplex electrical wiring within automobiles to save on copper, but can also be used in many other contexts.
The Controller Area Network is standardized as ISO 11898.
A CAN bus consists of 2 or more devices hooked together with a pair of wires, called H and L. Generally the devices will also share a common GND as well. We'll show networks with just 2 devices, but you can certainly have more. When you have a larger number of devices, you may have to modify the "bus termination resistors" according to the requirements of the CAN specification.
A CAN packet consists of an ID (a 11 or 29 bit number; 29 bit IDs are "extended IDs") which allows devices to listen only for message IDs they are interested in; a "Remote Transmission Request" (RTR) flag which allows one device to request data from another device; and (if it is not a Remote Transmission Request), a data payload of 0 to 8 bytes.
The whole packet is protected against corruption by a CRC (sometimes called a checksum). This means that while packets can sometimes go missing due to garbled transmission, almost all data transmission errors are caught and the invalid data discarded.
Since CAN does not include a way to be sure the intended recipient device has actually received a message, you may find it necessary to implement your own "reliable" transmission method by having the receiving device acknowledge that it has received a packet by sending a packet back. There are other ways of tackling potential lost packets; for instance, if you are a sensor you could just send your sensor data 10 times a second and not care whether just a few packets are lost. The right thing to do depends on your application.
Multiple Adafruit boards such as Feathers and Metros have a CAN bus peripheral. The Feather M4 CAN is the most convenient, as it also includes a CAN transceiver. Other boards need an external CAN transceiver. Supported boards include:
- Feather M4 CAN Express
- Feather STM32F405 Express (requires an external CAN transceiver)
- Metro ESP32-S2 Express (requires an external CAN transceiver)