Thursday, 26 May 2011

Arduino LCD Clock

Using the Wire library to read a DS1307 RTC chip (I used this one from Seeed Studio and bits of the example code ) and the LCD3wire library to implement, what is almost the "hello world" of arduino projects, a digital clock. The LCD3wire example uses a 4094 shift register, my parts box only had a 74HC595 so the connections are a little different:





















74HC595LCDArduinopower
14

25

36

414

513

612

711

8

gnd
9


10

+ve
11
4 (clk)
12
2 (strobe)
13

gnd
14
8 (data)
15


16

+ve

1
gnd

2
+ve

3
2.2K to gnd

//the "sketch"
// Example use of LCD3Wire and Wire library
// to read time from RTC and display on LCD

#include <LCD3Wire.h>
#include "Wire.h"
// Arduino pins
#define LCD_LINES 2 // number of lines in your display
#define DOUT_PIN 8 // Dout pin
#define CLK_PIN 4 // Clock pin
#define STR_PIN 2 // Strobe pin

#define DS1307_I2C_ADDRESS 0x68

long previousMillis = 0; // will store last time time was updated
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
long interval = 200;

//create object to control an LCD.
LCD3Wire lcd = LCD3Wire(LCD_LINES, DOUT_PIN, STR_PIN, CLK_PIN);
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return ( (val/10*16) + (val%10) );
}

// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return ( (val/16*10) + (val%16) );
}

// Gets the date and time from the ds1307 and prints result
void getDateDs1307()
{
// Reset the register pointer
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.send(0x00);
Wire.endTransmission();

Wire.requestFrom(DS1307_I2C_ADDRESS, 7);

// A few of these need masks because certain bits are control bits
second = bcdToDec(Wire.receive() & 0x7f);
minute = bcdToDec(Wire.receive());
hour = bcdToDec(Wire.receive() & 0x3f); // Need to change this if 12 hour am/pm
dayOfWeek = bcdToDec(Wire.receive());
dayOfMonth = bcdToDec(Wire.receive());
month = bcdToDec(Wire.receive());
year = bcdToDec(Wire.receive());

}

void printTime()
{
lcd.cursorTo(1, 4); //line=1, x=4.
lcd.print( char( hour/10 + 0x30) );
lcd.print( char( hour%10 + 0x30) );
lcd.print(':');
lcd.print( char(minute/10 + 0x30));
lcd.print( char(minute%10 + 0x30));
lcd.print(':');
lcd.print(char (second/10+0x30));
lcd.print(char (second%10+0x30));

lcd.cursorTo(2, 3); //line=2, x=3.
lcd.print(char(dayOfMonth/10+0x30));
lcd.print(char(dayOfMonth%10+0x30));
lcd.print('/');
lcd.print(char(month/10+0x30));
lcd.print(char(month%10+0x30));
lcd.printIn("/20");
lcd.print(char(year/10+0x30));
lcd.print(char(year%10+0x30));
}

void setup() {
Wire.begin();
getDateDs1307() ;
lcd.init();
lcd.clear();

}

void loop() {

unsigned long currentMillis = millis();

if(currentMillis - previousMillis > interval) {
// save the last time you printed and updated
previousMillis = currentMillis;
printTime();
//read RTC
getDateDs1307() ;
}
}
//end sketch

The result as expected (just a clock :-) ):


No comments: