Bill Reason Bill Reason - 1 month ago 6
Python Question

Why do I receive error with this rgb code?

I was a writing a program to run on the Raspberry Pi Sensehat. I wrote this code:

from time import gmtime, strftime
from random import randint
from sense_hat import SenseHat
sense = SenseHat()
sense.clear()
def hilo(a, b, c):
if c < b: b, c = c, b
if b < a: a, b = b, a
if c < b: b, c = c, b
return a + c
def complement(r, g, b):
k = hilo(r, g, b)
return tuple(k - u for u in (r, g, b))
while True:
r=randint(0, 255)
g=randint(0, 255)
b=randint(0, 255)
while True:
x, y, z = sense.get_accelerometer_raw().values()
x = abs(x)
y = abs(y)
z = abs(z)
sense.show_message(strftime('%H:%M', gmtime()), scroll_speed= 0.05, text_colour=[r, g, b], back_colour=[complement(r, g, b)])
if x > 2 or y > 2 or z > 2 :
break
else:
continue


And I got this error message:

Traceback (most recent call last):
File "/home/pi/Desktop/Bill's stuff/billrclock2-0*UNFINISHED*.py", line 23, in <module>
sense.show_message(strftime('%H:%M', gmtime()), scroll_speed= 0.05, text_colour=[r, g, b], back_colour=[complement(r, g, b)])
File "/usr/lib/python2.7/dist-packages/sense_hat/sense_hat.py", line 449, in show_message
self.set_pixels(coloured_pixels[start:end])
File "/usr/lib/python2.7/dist-packages/sense_hat/sense_hat.py", line 269, in set_pixels
raise ValueError('Pixel at index %d is invalid. Pixels must contain 3 elements: Red, Green and Blue' % index)
ValueError: Pixel at index 0 is invalid. Pixels must contain 3 elements: Red, Green and Blue


I noticed it said that 'pixels must contain 3 elements: r, g, b' but in this case the pixels do contain r, g and b. Why is this happening? Thanks for any answers.

Answer

The documentation states that both colors should be a three item list.

You are passing it a one item list, which happens to contain a 3 item tuple.

The simple way to solve this is to convert the result from your complement method to a list.

You can do it two ways, at the method itself:

def complement(r, g, b):
    k = hilo(r, g, b)
    return [k - u for u in (r, g, b)]

# .. later down

sense.show_message(strftime('%H:%M', gmtime()),
                   scroll_speed= 0.05,
                   text_colour=[r, g, b],
                   back_colour=complement(r, g, b))

Or you can convert the result to a list:

def complement(r, g, b):
    k = hilo(r, g, b)
    return tuple(k - u for u in (r, g, b))

sense.show_message(strftime('%H:%M', gmtime()),
                       scroll_speed= 0.05,
                       text_colour=[r, g, b],
                       back_colour=list(complement(r, g, b)))
Comments