The can bus API has provided the function 'can.send(data, id, *, timeout=0, rtr=False)', and the data is an integer to send, or a buffer object. If I want send the data is less than 0x7f,which can be expressed by ASCII, it worked well. for example:
dat=[0x40,0x30,0x20,0x10,0x00,0x00,0x00,0x00]
buf= ''.join([chr(i) for i in dat])
can.send(buf, id)
it would work well. but if one of the data more than 0x7f, which cannot be expressed by ASCII, for example:
dat=[0xab,0x30,0x20,0x10,0x00,0x00,0x00,0x00]
buf= ''.join([chr(i) for i in dat])
can.send(buf, id)
it will say that the buf is too long. who can help me ?
thanks
can bus problem
Re: can bus problem
You can use a bytearray.
You can also use the b prefix on strings: can.send(b'\xab\x30\x20\x10\x00\x00\x0x00', id);
With bytearrays its kind of like an array of integers, so you can modify it after the fact as well: (note that 0x30 was shown as a '0' and 0x20 was shown as a space.
Code: Select all
dat=bytearray([0xab,0x30,0x20,0x10,0x00,0x00,0x00,0x00])
can.send(dat, id)
With bytearrays its kind of like an array of integers, so you can modify it after the fact as well:
Code: Select all
>>> dat=bytearray([0xab,0x30,0x20,0x10,0x00,0x00,0x00,0x00])
>>> dat[5] = 255
>>> dat
bytearray(b'\xab0 \x10\x00\xff\x00\x00')
>>>
-
- Posts: 31
- Joined: Wed Dec 02, 2015 1:47 pm
Re: can bus problem
dhylands wrote:You can use a bytearray.You can also use the b prefix on strings: can.send(b'\xab\x30\x20\x10\x00\x00\x0x00', id);Code: Select all
dat=bytearray([0xab,0x30,0x20,0x10,0x00,0x00,0x00,0x00]) can.send(dat, id)
With bytearrays its kind of like an array of integers, so you can modify it after the fact as well:(note that 0x30 was shown as a '0' and 0x20 was shown as a space.Code: Select all
>>> dat=bytearray([0xab,0x30,0x20,0x10,0x00,0x00,0x00,0x00]) >>> dat[5] = 255 >>> dat bytearray(b'\xab0 \x10\x00\xff\x00\x00') >>>
thank you, it works.
And I have another question, if the data is an integer, the other 7 byes is 0x00 when send data each time? the integer is the 1st data or the 8th data? thank you
Re: can bus problem
The first element of the array (element 0) will be the first byte of the packet sent. You can also allocate a bytearray like this:wwsheldons wrote:And I have another question, if the data is an integer, the other 7 byes is 0x00 when send data each time? the integer is the 1st data or the 8th data? thank you
Code: Select all
>>> dat = bytearray(8)
>>> dat
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')
>>> dat[0] = 0xaa
>>> dat
bytearray(b'\xaa\x00\x00\x00\x00\x00\x00\x00')
>>>