PCF8583 and Espruino

Looking for a I2C device to test and play with it, I found an old PCF8583 board I bought a long time ago from Futurlec. I would have guess about 10 years ago. I remember it can handle 3.3V and has the needed pull-up resistors via jumpers. Perfect for testing!

Unexpectedly I found no library for that chip at http://www.espruino.com/modules/, but looking at the data sheet, it’s not really needed. Setting time and reading time is straightforward:

I2C1.setup({sda: D5, scl: D4});

pcf8583Addr=0x51;

function BCDToBinary(n) {
  return (n>>4)*10+(n&0x0f);
}
function binaryToBCD(n) {
  return ((n/10)<<4) + (n % 10);
}
function BCDToString(n) {
  return String.fromCharCode((n>>4)+48, (n&0x0f)+48);
}
    
function getPCFTime() {
  I2C1.writeTo(pcf8583Addr, 1);
  let d=I2C1.readFrom(pcf8583Addr, 4);
  return `${BCDToString(d[3])}:${BCDToString(d[2])}:${BCDToString(d[1])}.${BCDToString(d[0])}`;
}

function getPCFDate() {
  I2C1.writeTo(pcf8583Addr, 5);
  let d=I2C1.readFrom(pcf8583Addr, 2);
  let year=(2020+((d[0]&0xc0)>>6)).toString();
  let month=BCDToString(d[1] & 0x1f);
  let day=BCDToString(d[0] & 0x3f);
  return `${year}-${month}-${day}`;
}

function setPCFTime(h, m, s) {
  I2C1.writeTo(pcf8583Addr, [0, 0x80, 0, binaryToBCD(s), binaryToBCD(m), binaryToBCD(h)]);
  I2C1.writeTo(pcf8583Addr, 0, [0x00]);
}

function start(){
 g.clear();
 g.drawString("Starting...", 0, 0);
 g.flip(); 
}

var g = require("SSD1306").connect(I2C1, start, {height:64});
require("Font8x12").add(Graphics);
g.setFont8x12();

function updateDisplay() {
  g.clear();
  g.drawString(getPCFDate(), 0, 0);
  g.drawString(getPCFTime(), 0, 20);
  g.flip();
}

setInterval(updateDisplay, 1000);

By the way, the most amazing part of this test was that the included CR2032 Lithium battery still works after that many years.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create your website with WordPress.com
Get started
%d bloggers like this: