Cananka, the Raspberry Pi HAT: Software

[This post is part five in the series.]

One of the requirements I've stated was that we should use as much of Linux driver defaults as possible. In this step we should reap benefits of that as all needed to enable CAN should be:

# sudo bash -c 'echo "dtoverlay=mcp2515-can0,oscillator=16000000,spimaxfrequency=10000000,interrupt=25" >> /boot/config.txt'
# sudo reboot

After reboot, we should see device loaded:

# ip -d link show can0
3: can0: <NOARP,ECHO> mtu 16 qdisc noop state DOWN mode DEFAULT group default qlen 10
link/can promiscuity 0
can state STOPPED restart-ms 0
mcp251x: tseg1 3..16 tseg2 2..8 sjw 1..4 brp 1..64 brp-inc 1
clock 8000000

When I was setting this for the first time I was brought on a wild goose chase as nothing really worked. No matter what I did, can0 device would not appear (Cannot find device "can0"). It took me a while to notice something is off:

# dmesg | egrep "spi|can"
spi_bcm2835: disagrees about version of symbol module_layout

As this Raspberry was used for other projects and I've updated it multiple times it seems at one point something went wrong with drivers. A fresh reinstall of Raspbian sorted that out.

More careful among you will notice that CAN interface is actually down upon boot. This is easy to correct and the only piece of data we need is the bus speed (this example will use 125 kHz):

# sudo ip link set can0 up type can bitrate 125000
# ip -d link show can0
3: can0: <NOARP,UP,LOWER_UP,ECHO> mtu 16 qdisc pfifo_fast state UNKNOWN mode DEFAULT group default qlen 10
link/can promiscuity 0
can state ACTIVE restart-ms 0
bitrate 125000 sample-point 0.875
tq 500 prop-seg 6 phase-seg1 7 phase-seg2 2 sjw 1
mcp251x: tseg1 3..16 tseg2 2..8 sjw 1..4 brp 1..64 brp-inc 1
clock 8000000

Unfortunately this doesn't survive the reboot. To make it stick just execute:

# sudo bash -c 'echo >> /etc/network/interfaces'
# sudo bash -c 'echo "auto can0" >> /etc/network/interfaces'
# sudo bash -c 'echo "iface can0 inet manual" >> /etc/network/interfaces'
# sudo bash -c 'echo " pre-up ip link set \$IFACE type can bitrate 125000" >> /etc/network/interfaces'
# sudo bash -c 'echo " up /sbin/ifconfig \$IFACE up" >> /etc/network/interfaces'
# sudo bash -c 'echo " down /sbin/ifconfig \$IFACE down" >> /etc/network/interfaces'

For testing install can-utils:

# sudo apt-get install can-utils

With them you can use cansend and candump, e.g.:

# cansend can0 02A#FEED
# candump can0

At this moment we have are HAT working. However, without EEPROM, we cannot really call it a HAT. So, guess what's next...

Leave a Reply

Your email address will not be published. Required fields are marked *