github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/examples/caninterrupt/main.go (about) 1 package main 2 3 import ( 4 "device/sam" 5 "fmt" 6 "machine" 7 "time" 8 ) 9 10 var ( 11 can0 = machine.CAN0 12 can1 = machine.CAN1 13 ch = make(chan canMsg, 10) 14 ) 15 16 type canMsg struct { 17 bus byte 18 can machine.CANRxBufferElement 19 } 20 21 func main() { 22 go print(ch) 23 24 can1.Configure(machine.CANConfig{ 25 TransferRate: machine.CANTransferRate500kbps, 26 TransferRateFD: machine.CANTransferRate1000kbps, 27 Rx: machine.CAN1_RX, 28 Tx: machine.CAN1_TX, 29 Standby: machine.CAN1_STANDBY, 30 }) 31 // RF0NE : Rx FIFO 0 New Message Interrupt Enable 32 can1.SetInterrupt(sam.CAN_IE_RF0NE, func(can *machine.CAN) { 33 rxMsg := machine.CANRxBufferElement{} 34 can.RxRaw(&rxMsg) 35 msg := canMsg{ 36 bus: 1, 37 can: rxMsg, 38 } 39 select { 40 case ch <- msg: 41 } 42 }) 43 44 can0.Configure(machine.CANConfig{ 45 TransferRate: machine.CANTransferRate500kbps, 46 TransferRateFD: machine.CANTransferRate1000kbps, 47 Rx: machine.CAN0_RX, 48 Tx: machine.CAN0_TX, 49 Standby: machine.NoPin, 50 }) 51 // RF0NE : Rx FIFO 0 New Message Interrupt Enable 52 can0.SetInterrupt(sam.CAN_IE_RF0NE, func(can *machine.CAN) { 53 rxMsg := machine.CANRxBufferElement{} 54 can.RxRaw(&rxMsg) 55 msg := canMsg{ 56 bus: 1, 57 can: rxMsg, 58 } 59 select { 60 case ch <- msg: 61 } 62 }) 63 64 for { 65 can0.Tx(0x123, []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF}, false, false) 66 time.Sleep(time.Millisecond * 500) 67 can1.Tx(0x456, []byte{0xAA, 0xBB, 0xCC}, false, false) 68 time.Sleep(time.Millisecond * 1000) 69 } 70 } 71 72 func print(ch <-chan canMsg) { 73 for { 74 select { 75 case m := <-ch: 76 fmt.Printf("%d %03X %X ", m.bus, m.can.ID, m.can.DLC) 77 for _, d := range m.can.DB[:m.can.Length()] { 78 fmt.Printf("%02X ", d) 79 } 80 fmt.Printf("\r\n") 81 } 82 } 83 }