Sonntag, 18. November 2012

Simple Clock with I2C, Python and Raspberry PI

I happened to come across a simple 7 segment display (4 digits) controlled by the common SAA1064 . The chip uses I2C which is cool because the Raspberry Pi comes with I2C onboard.
Follow this guide to get going with I2C on the Raspberry and Python.

For the Raspberry Pi I got a Slice of Pie add on board which makes the physical connection easier. I attached the SAA1064 directly to the onboard 5V powersupply. This works, but is probably deprecated since it may draw more power than the specs for the Raspi recommend. 7 Segments * 4 Digitis * 3 mA minimum @ 5V = a bit less than 500mW. So maybe you might want a seperate power supply to be on the save side.

I am not a python programmer, I guess this is probably m first python script ever so it's probably a bit clumsy. I am impressed by the simplicity how everything comes together. Of course, the possibilities of a four digit 7 segment display are not unlimited, but it's just cool ...

The following script is installed as a cronjob

sudo crontab -e 
and add the following line (change it to your path)
* * * * * python /home/pi/7seg.py
save 

the script will be executed once every minute. And as it is once a minute means pretty much exactly when the seconds hit 60. (Of course, this is not suitable for real time applications, bu who cares if the display has a an update jitter of a few 10 to 100 millisecs)

Add the Hex-Codes of the Lines to get the corrsponding Hex number of a char.


Two things to mention:
- Don't get confused by the adress 0x38. This equals to 0x70 without the LSB.
- the variable cmd refers to page 6 (subadressig) of the datasheet

________________________
7seg.py
________________________

import smbus
import time
import datetime
bus = smbus.SMBus(0)
addr = 0x38
cmd = 0x00
val = 0x27
bus.write_byte_data(addr,cmd,val)

def numToSeg(num):
retval = 0x00; #default val
if num==0:
retval = 0x7E
elif num==1:
retval = 0x30
        elif num==2:
                retval = 0x6D
        elif num==3:
                retval = 0x79
        elif num==4:
                retval = 0x33
        elif num==5:
                retval = 0x5B
        elif num==6:
                retval = 0x5F
        elif num==7:
                retval = 0x70
        elif num==8:
                retval = 0x7F
        elif num==9:
                retval = 0x7B
        return retval

now = datetime.datetime.now()
hour_str   = now.strftime("%H")
minute_str = now.strftime("%M")
h_0   = int(hour_str[0])
h_1        = int(hour_str[1])
m_0        = int(minute_str[0])
m_1        = int(minute_str[1])

cmd = 0x01
val = numToSeg(h_0)
bus.write_byte_data(addr,cmd,val)

cmd = 0x02
val = numToSeg(h_1)
bus.write_byte_data(addr,cmd,val)

cmd = 0x03
val = numToSeg(m_0)
bus.write_byte_data(addr,cmd,val)

cmd = 0x04
val = numToSeg(m_1)
bus.write_byte_data(addr,cmd,val)      


1 Kommentar: