I have a CAN bus (PCAN) with several inputs. I try to read the inputs in python and print them on the console. The first message I get from the bus is correct, however if I change the state on the input, the data in the message doesn't change and keeps spitting the first data it got. In PCAN-view I can see the data change, so it isn't a hardware failure.
My code:
import can
from time import sleep
def main():
bus = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=500000)
try:
while True:
# msg = can.Message(arbitration_id=0x232, data=[0x00], is_extended_id=False)
# try:
# bus.send(msg)
# print("message sent on {}".format(bus.channel_info))
# except can.CanError:
# print("message not sent!")
msg = bus.recv(None)
try:
if msg.arbitration_id == 0x1B2:
print(msg)
if msg.arbitration_id == 0x1B3:
print(msg)
if msg.arbitration_id == 0x1B4:
print(msg)
if msg.arbitration_id == 0x1B5:
print(msg)
except AttributeError:
print("Nothing received this time")
sleep(0.2)
except KeyboardInterrupt:
print("Program Exited")
except can.CanError:
print("Message NOT sent")
bus.shutdown()
if __name__ == '__main__':
main()
I tried sending a message before each receive but it didn't help.
Same with calling the can.Listener().stop()
function on a listener after printing the received message.
PCAN-view shows the hardware is working as I can see the changes happening in the screen.
Eg.
- at the beginning, input 0 and 1 are high on unit 0x1B2
- bus.recv returns [00 03], which is correct
- I clear input 0 and 1
- PCAN-view shows data [00 00]
- bus.recv returns [00 03], which is incorrect. It didn't change.
I've read the readthedocs several times but I'm afraid I missed something. Do I need to flush the inputbuffer? I only saw info on a function to flush the output buffer.