can provides an interface to a CAN bus to read and write frames. The library is based on the SocketCAN network stack on Linux.
I'm using a Raspberry Pi 2 Model B and PiCAN2 CAN-Bus board for Raspberry Pi 2 to connect to a CAN bus.
The Raspberry Pi runs Raspbian. After connecting to the CAN bus you have to set up the can network interface for a specific bitrate, i.e. 50 kB
sudo ip link set can0 up type can bitrate 50000
Running ifconfig
should now include the can0
interface.
You should test if you actually receive data from the CAN bus. You can either use the candump
tool from the can-utils or a simple reimplementation under cmd/candump.go
.
Either way you will see something like this
> go run $GOSRC/github.com/brutella/can/cmd/candump.go -if can0
can0 100 [6] 20 83 0C 00 67 29 ' ...g)'
can0 701 [1] 05 '.'
bus, _ := can.NewBusForInterfaceWithName("can0")
bus.ConnectAndPublish()
frm := Frame{
ID: 0x701,
Length: 1,
Flags: 0,
Res0: 0,
Res1: 0,
Data: [8]uint8{0x05},
}
bus.Publish(frm)
bus.SubscribeFunc(handleCANFrame)
func handleCANFrame(frm can.Frame) {
...
}
There is more to learn from the documentation.
Matthias Hochgatterer
Github: https://github.com/brutella
Twitter: https://twitter.com/brutella
can is available under the MIT license. See the LICENSE file for more info.