- Create a script called tilt.py to report the state of the tilt switch:
#!/usr/bin/python3
#tilt.py
import RPi.GPIO as GPIO
#HARDWARE SETUP
# GPIO
# 2[===========T=]26[=======]40
# 1[=============]25[=======]39
#Tilt Config
TILT_SW = 24
def tilt_setup():
#Setup the wiring
GPIO.setmode(GPIO.BOARD)
#Setup Ports
GPIO.setup(TILT_SW,GPIO.IN,pull_up_down=GPIO.PUD_UP)
def tilt_moving():
#Report the state of the Tilt Switch
return GPIO.input(TILT_SW)
def main():
import time
tilt_setup()
while True:
print("TILT %s"% (GPIO.input(TILT_SW)))
time.sleep(0.1)
if __name__=='__main__':
try:
main()
finally:
GPIO.cleanup()
print("Closed Everything. END")
#End
- You can test the script by running it directly with the following command:
sudo python3 tilt.py
- Add the following rgbled_pov() function to the rgbled.py script we created previously; this will allow us to display a single line of our image:
def rgbled_pov(led_pattern,color,ontime):
'''Disable all the LEDs and re-enable the LED pattern in the required color'''
led_deactivate(LED,RGB)
for led_num,col_num in enumerate(led_pattern):
if col_num >= 1:
led_activate(LED[led_num],color)
time.sleep(ontime)
- We will now create the following file, called rgbledmessage.py, to perform the required actions to display our message. First, we will import the modules used: the updated rgbled module, the new tilt module, and the Python os module. Initially, we set DEBUG to True, so the Python terminal will display additional information while the script is running:
#!/usr/bin/python3
# rgbledmessage.py
import rgbled as RGBLED
import tilt as TILT
import os
DEBUG = True
- Add a readMessageFile() function to read the content of the letters.txt file and then add processFileContent() to generate a Python dictionary of the LED patterns for each letter:
def readMessageFile(filename):
assert os.path.exists(filename), 'Cannot find the message file: %s' % (filename)
try:
with open(filename, 'r') as theFile:
fileContent = theFile.readlines()
except IOError:
print("Unable to open %s" % (filename))
if DEBUG:print ("File Content START:")
if DEBUG:print (fileContent)
if DEBUG:print ("File Content END")
dictionary = processFileContent(fileContent)
return dictionary
def processFileContent(content):
letterIndex = [] #Will contain a list of letters stored in the file
letterList = [] #Will contain a list of letter formats
letterFormat = [] #Will contain the format of each letter
firstLetter = True
nextLetter = False
LETTERDIC={}
#Process each line that was in the file
for line in content:
# Ignore the # as comments
if '#' in line:
if DEBUG:print ("Comment: %s"%line)
#Check for " in the line = index name
elif '"' in line:
nextLetter = True
line = line.replace('"','') #Remove " characters
LETTER=line.rstrip()
if DEBUG:print ("Index: %s"%line)
#Remaining lines are formatting codes
else:
#Skip firstLetter until complete
if firstLetter:
firstLetter = False
nextLetter = False
lastLetter = LETTER
#Move to next letter if needed
if nextLetter:
nextLetter = False
LETTERDIC[lastLetter]=letterFormat[:]
letterFormat[:] = []
lastLetter = LETTER
#Save the format data
values = line.rstrip().split(' ')
row = []
for val in values:
row.append(int(val))
letterFormat.append(row)
LETTERDIC[lastLetter]=letterFormat[:]
#Show letter patterns for debugging
if DEBUG:print ("LETTERDIC: %s" %LETTERDIC)
if DEBUG:print ("C: %s"%LETTERDIC['C'])
if DEBUG:print ("O: %s"%LETTERDIC['O'])
return LETTERDIC
- Add a createBuffer() function, which will convert a message into a series of LED patterns for each letter (assuming the letter is defined by the letters.txt file):
def createBuffer(message,dictionary):
buffer=[]
for letter in message:
try:
letterPattern=dictionary[letter]
except KeyError:
if DEBUG:print("Unknown letter %s: use _"%letter)
letterPattern=dictionary['_']
buffer=addLetter(letterPattern,buffer)
if DEBUG:print("Buffer: %s"%buffer)
return buffer
def addLetter(letter,buffer):
for row in letter:
buffer.append(row)
buffer.append([0,0,0,0,0])
buffer.append([0,0,0,0,0])
return buffer
- Next, we define a displayBuffer() function to display the LED patterns using the rgbled_pov() function in the rgbled module:
def displayBuffer(buffer):
position=0
while(1):
if(TILT.tilt_moving()==False):
position=0
elif (position+1)<len(buffer):
position+=1
if DEBUG:print("Pos:%s ROW:%s"%(position,buffer[position]))
RGBLED.rgbled_pov(buffer[position],RGBLED.RGB_GREEN,0.001)
RGBLED.rgbled_pov(buffer[position],RGBLED.RGB_BLUE,0.001)
- Finally, we create a main() function to perform each of the required steps:
- Set up the hardware components (RGB LEDs and the tilt switch).
- Read the letters.txt file.
- Define the dictionary of LED letter patterns.
- Generate a buffer to represent the required message.
- Display the buffer using the rgbled module and control it with the tilt module:
def main():
RGBLED.led_setup()
TILT.tilt_setup()
dict=readMessageFile('letters.txt')
buffer=createBuffer('_COOKBOOK_',dict)
displayBuffer(buffer)
if __name__=='__main__':
try:
main()
finally:
RGBLED.led_cleanup()
print("Closed Everything. END")
#End
- Create the following file, called letters.txt, to define the LED patterns needed to display the example '_COOKBOOK_' message. Note that this file only needs to define a pattern for each unique letter or symbol in the message:
#COOKBOOK
"C"
0 1 1 1 0
1 0 0 0 1
1 0 0 0 1
"O"
0 1 1 1 0
1 0 0 0 1
1 0 0 0 1
0 1 1 1 0
"K"
1 1 1 1 1
0 1 0 1 0
1 0 0 0 1
"B"
1 1 1 1 1
1 0 1 0 1
0 1 0 1 0
"_"
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0