Other Projects

[sensors] RTC Python Module on Banana Pro/LeMaker Guitar

1 2040
DS1307serial real-time clock (RTC) is a low power, full binary-coded decimal (BCD)clock/calendar. Address and data are transferred serially through an I2C,bidirectional bus. The clock/calendar provides seconds, minutes, hours, day,date, month, and year information. The end of the month date is automaticallyadjusted for months with fewer than 31 days, including corrections for leapyear. The clock operates in either the 24-hour or 12-hour format with AM/PMindicator. DS1307 has a built-in power-sense circuit that detects power failures and can switches automatically to the backup supply. Timekeeping operation continues while the part operates from the backup supply.
1.png
RTC Module use I2C connections to the Banana Pro/LeMaker Guitar, we can simply choose these I2C pins to connect as in the following:
QQ截图20151229181227.png
In the first step, we should detect if the RTC connections works. Open the terminal and use i2c-tools to detect its address (should be 0x68):
  1. $ sudo i2cdetect -y 2
Copy the Code
2.jpg

Here is the RTC Python Module that I'd like to share with you working on Banana Pro/LeMaker Guitar. TheRTC Module simply provide the same exact date and time as the BananaPro/LeMaker Guitar system: second, minute, hour, day, month, and year.
  1. #!/usr/bin/env python
  2. #
  3. # RTC_DS1307.py Python Driver Code
  4. # only works in 24 hour mode

  5. from datetime import datetime

  6. import smbus


  7. def _bcd_to_int(bcd):
  8.     """Decode a 2x4bit BCD to a integer.
  9.     """
  10.     out = 0
  11.     for d in (bcd >> 4, bcd):
  12.         for p in (1, 2, 4 ,8):
  13.             if d & 1:
  14.                 out += p
  15.             d >>= 1
  16.         out *= 10
  17.     return out / 10


  18. def _int_to_bcd(n):
  19.     """Encode a one or two digits number to the BCD.
  20.     """
  21.     bcd = 0
  22.     for i in (n // 10, n % 10):
  23.         for p in (8, 4, 2, 1):
  24.             if i >= p:
  25.                 bcd += 1
  26.                 i -= p
  27.             bcd <<= 1
  28.     return bcd >> 1


  29. class RTC_DS1307():
  30.     _REG_SECONDS = 0x00
  31.     _REG_MINUTES = 0x01
  32.     _REG_HOURS = 0x02
  33.     _REG_DAY = 0x03
  34.     _REG_DATE = 0x04
  35.     _REG_MONTH = 0x05
  36.     _REG_YEAR = 0x06
  37.     _REG_CONTROL = 0x07


  38.     def __init__(self, twi=2, addr=0x68):
  39.         self._bus = smbus.SMBus(twi)
  40.         self._addr = addr



  41.     def _write(self, register, data):
  42.         #print "addr =0x%x register = 0x%x data = 0x%x %i " % (self._addr, register, data,_bcd_to_int(data))
  43.         self._bus.write_byte_data(self._addr, register, data)


  44.     def _read(self, data):

  45.         returndata = self._bus.read_byte_data(self._addr, data)
  46.         #print "addr = 0x%x data = 0x%x %i returndata = 0x%x %i " % (self._addr, data, data, returndata, _bcd_to_int(returndata))
  47.         return returndata

  48.     def _read_seconds(self):
  49.         return _bcd_to_int(self._read(self._REG_SECONDS))


  50.     def _read_minutes(self):
  51.         return _bcd_to_int(self._read(self._REG_MINUTES))


  52.     def _read_hours(self):
  53.         d = self._read(self._REG_HOURS)
  54.         if (d == 0x64):
  55.                 d = 0x40
  56.         return _bcd_to_int(d & 0x3F)


  57.     def _read_day(self):
  58.         return _bcd_to_int(self._read(self._REG_DAY))


  59.     def _read_date(self):
  60.         return _bcd_to_int(self._read(self._REG_DATE))


  61.     def _read_month(self):
  62.         return _bcd_to_int(self._read(self._REG_MONTH))


  63.     def _read_year(self):
  64.         return _bcd_to_int(self._read(self._REG_YEAR))


  65.     def read_all(self):
  66.         """Return a tuple such as (year, month, date, day, hours, minutes,
  67.         seconds).
  68.         """
  69.         return (self._read_year(), self._read_month(), self._read_date(),
  70.                 self._read_day(), self._read_hours(), self._read_minutes(),
  71.                 self._read_seconds())


  72.     def read_str(self):
  73.         """Return a string such as 'YY-DD-MMTHH-MM-SS'.
  74.         """
  75.         return '%02d-%02d-%02dT%02d:%02d:%02d' % (self._read_year(),
  76.                 self._read_month(), self._read_date(), self._read_hours(),
  77.                 self._read_minutes(), self._read_seconds())


  78.     def read_datetime(self, century=21, tzinfo=None):
  79.         """Return the datetime.datetime object.
  80.         """
  81.         return datetime((century - 1) * 100 + self._read_year(),
  82.                 self._read_month(), self._read_date(), self._read_hours(),
  83.                 self._read_minutes(), self._read_seconds(), 0, tzinfo=tzinfo)


  84.     def write_all(self, seconds=None, minutes=None, hours=None, day=None,
  85.             date=None, month=None, year=None, save_as_24h=True):
  86.         """Direct write un-none value.
  87.         Range: seconds [0,59], minutes [0,59], hours [0,23],
  88.                day [0,7], date [1-31], month [1-12], year [0-99].
  89.         """
  90.         if seconds is not None:
  91.             if seconds < 0 or seconds > 59:
  92.                 raise ValueError('Seconds is out of range [0,59].')
  93.             self._write(self._REG_SECONDS, _int_to_bcd(seconds))

  94.         if minutes is not None:
  95.             if minutes < 0 or minutes > 59:
  96.                 raise ValueError('Minutes is out of range [0,59].')
  97.             self._write(self._REG_MINUTES, _int_to_bcd(minutes))

  98.         if hours is not None:
  99.             if hours < 0 or hours > 23:
  100.                 raise ValueError('Hours is out of range [0,23].')
  101.             self._write(self._REG_HOURS, _int_to_bcd(hours))  # not | 0x40 as in the orignal code

  102.         if year is not None:
  103.             if year < 0 or year > 99:
  104.                 raise ValueError('Years is out of range [0,99].')
  105.             self._write(self._REG_YEAR, _int_to_bcd(year))

  106.         if month is not None:
  107.             if month < 1 or month > 12:
  108.                 raise ValueError('Month is out of range [1,12].')
  109.             self._write(self._REG_MONTH, _int_to_bcd(month))

  110.         if date is not None:
  111.             if date < 1 or date > 31:
  112.                 raise ValueError('Date is out of range [1,31].')
  113.             self._write(self._REG_DATE, _int_to_bcd(date))

  114.         if day is not None:
  115.             if day < 1 or day > 7:
  116.                 raise ValueError('Day is out of range [1,7].')
  117.             self._write(self._REG_DAY, _int_to_bcd(day))


  118.     def write_datetime(self, dt):
  119.         """Write from a datetime.datetime object.
  120.         """
  121.         self.write_all(dt.second, dt.minute, dt.hour,
  122.                 dt.isoweekday(), dt.day, dt.month, dt.year % 100)


  123.     def write_now(self):
  124.         """Equal to DS1307.write_datetime(datetime.datetime.now()).
  125.         """
  126.         self.write_datetime(datetime.now())

Copy the Code
To use this RTC Python Module is as simple as following:  
  1. #!/usr/bin/env python
  2. #
  3. # Test RTC_DS1307

  4. import sys
  5. import time
  6. import datetime

  7. import RTC_DS1307

  8. # Main Program

  9. print "Program Started at:"+ time.strftime("%Y-%m-%d %H:%M:%S")

  10. filename = time.strftime("%Y-%m-%d%H:%M:%SRTCTest") + ".txt"
  11. starttime = datetime.datetime.utcnow()

  12. ds1307 = RTC_DS1307.RTC_DS1307(2, 0x68)
  13. ds1307.write_now()

  14. # Main Loop - sleeps 10 minutes, then reads and prints values of all clocks


  15. while True:

  16.         currenttime = datetime.datetime.utcnow()

  17.         deltatime = currenttime - starttime

  18.         print ""
  19.         print "System Time = \t" + time.strftime("%Y-%m-%d %H:%M:%S")
  20.        
  21.         print "DS1307 = \t\t%s" % ds1307.read_datetime()

  22.         time.sleep(10.0)
Copy the Code
QQ截图20151229184203.png








Rate

1

View Rating Log

Thanks for sharing!

You have to log in before you can reply Login | Sign Up

Points Rules