Page 1 of 1

Working with binary data

Posted: Thu Apr 01, 2021 9:52 pm
by mc2software
I'm working on a project that uses the MAX7219 for a few 7-segment led displays. The libraries I've found do a good job of displaying text, numbers, etc. I updated one function to do a more flexible way of display text, so the last update I need to do is light up the individual segments, because I couldn't find a library that does that. I've adopted a function from my Arduino project, but am having an issue manipulating the binary data. I think I've narrowed the issue to the formatting of the binary data. When I run this code:

Code: Select all

>>>bi = 0b01000000
>>>digit = 0
>>>bytearray([digit, bi])
I get:

Code: Select all

bytearray(b'\x00@')
There are times where I get an extra space padded to the end

Code: Select all

bytearray(b'\x00 ')
Then when I run this through any iteration, I get:

Code: Select all

bytearray(b'\x00\x10')
So my code seems to be concatenating the binary values, but I don't understand why that '@' is being appended to the binary value. I'm thinking this is causing the problem, but am not sure.

I can include all the other code if this is not enough.

Re: Working with binary data

Posted: Thu Apr 01, 2021 10:01 pm
by dhylands
That's just the way python tries to print strings. It uses ASCII codes whenever it can and only uses the \xXX notation for non-ASCII chars. So the space is 0x20 and @ is 0x40. So this is what you get (even in regular python):

Code: Select all

>>> bytearray([0x31, 0x32, 0xff, 0x20, 0x40, 0xee])
bytearray(b'12\xff @\xee')
0x31 is the number '1' in ASCII
0x32 is the number '2' in ASCII
0xff doesn't have an ASCII representation so it gets printed as \xff
0x20 is an ASCII space
0x40 is an ASCII @
0xee doesn't have an ASCII representation so it gets printed as \xee

Re: Working with binary data

Posted: Fri Apr 02, 2021 3:06 am
by mc2software
So am I supplying bad binary formatted data or doing bad calculations leading to badly formatted binary data?

I'm trying to write to execute and spi.write() to do a circular rotation on the LED

Code: Select all

def setRow(display,digit,bi):
    display.cs(0)
    display._spi.write(bytearray([_DIGIT0 + digit, bi]))
    display.cs(1)

Code: Select all

def drawCircle(max7219, digit, speed=1):
    setRow(max7219,digit,0b01000000) #Segment A
    sleep(speed)
    setRow(max7219,digit,0b00100000) #Segment B
    sleep(speed)
    setRow(max7219,digit,0b00010000) #Segment C
    sleep(speed)
    setRow(max7219,digit,0b00001000) #Segment D
    sleep(speed)
    setRow(max7219,digit,0b00000100) #Segment E
    sleep(speed)
    setRow(max7219,digit,0b00000010) #Segment F
    sleep(speed)
    setRow(max7219,digit,0b00000000) #clear last segment
    sleep(speed)
This code does the circle but concatenates the "bi" value and lights up other LEDs.

Code: Select all

drawCircle(max7219,0)
I need to clean up some of the other py files. I'll post them as attachments tomorrow.