|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +This example sends every second a messages over the serial interface and also |
| 4 | +receives incoming messages. |
| 5 | +
|
| 6 | +Expects a /dev/ttyACM0 interface: |
| 7 | +
|
| 8 | + python3 -m examples.serial_com |
| 9 | +
|
| 10 | +""" |
| 11 | + |
| 12 | +import time |
| 13 | +import can |
| 14 | +import threading |
| 15 | + |
| 16 | + |
| 17 | +def time_millis(): |
| 18 | + return int(round(time.time() * 1000)) |
| 19 | + |
| 20 | + |
| 21 | +def send_cyclic(bus, msg, stop_event): |
| 22 | + print("Start to send a message every 1s") |
| 23 | + start_time = time_millis() |
| 24 | + while not stop_event.is_set(): |
| 25 | + msg.timestamp = time_millis() - start_time |
| 26 | + bus.send(msg) |
| 27 | + print("tx: {}".format(tx_msg)) |
| 28 | + time.sleep(1) |
| 29 | + print("Stopped sending messages") |
| 30 | + |
| 31 | + |
| 32 | +def receive(bus, stop_event): |
| 33 | + print("Start receiving messages") |
| 34 | + while not stop_event.is_set(): |
| 35 | + rx_msg = bus.recv(1) |
| 36 | + if rx_msg is not None: |
| 37 | + print("rx: {}".format(rx_msg)) |
| 38 | + print("Stopped receiving messages") |
| 39 | + |
| 40 | +if __name__ == "__main__": |
| 41 | + bus = can.interface.Bus(bustype='serial', channel='/dev/ttyACM0') |
| 42 | + tx_msg = can.Message(arbitration_id=0x01, data=[0x11, 0x22, 0x33, 0x44, |
| 43 | + 0x55, 0x66, 0x77, 0x88]) |
| 44 | + |
| 45 | + # Thread for sending and receiving messages |
| 46 | + stop_event = threading.Event() |
| 47 | + t_send_cyclic = threading.Thread(target=send_cyclic, args=(bus, tx_msg, |
| 48 | + stop_event)) |
| 49 | + t_receive = threading.Thread(target=receive, args=(bus, stop_event)) |
| 50 | + t_receive.start() |
| 51 | + t_send_cyclic.start() |
| 52 | + |
| 53 | + try: |
| 54 | + while True: |
| 55 | + pass |
| 56 | + except KeyboardInterrupt: |
| 57 | + pass |
| 58 | + |
| 59 | + stop_event.set() |
| 60 | + bus.shutdown() |
| 61 | + print("Stopped script") |
0 commit comments