Skip to content

Instantly share code, notes, and snippets.

@joewalnes
Created December 17, 2011 23:33
Show Gist options
  • Save joewalnes/1491793 to your computer and use it in GitHub Desktop.
Save joewalnes/1491793 to your computer and use it in GitHub Desktop.
atmega32u4, leonardo, i2c and serial problem
#include "Wire.h"
#define DS1307_ADDRESS 0x68
struct DateTime {
int second;
int minute;
int hour;
int weekDay;
int monthDay;
int month;
int year;
} dateTime;
void setup(){
Wire.begin();
Serial.begin(57600);
pinMode(13, OUTPUT);
}
long previousMillis = 0;
long interval = 100;
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
requestDateTime(); // Read dateTime using I2C
Serial.println(dateTime.second); // Print
digitalWrite(13, (dateTime.second % 2 == 0) ? HIGH : LOW); // Toggle LED every second
}
}
void requestDateTime() {
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write((byte)0);
Wire.endTransmission();
Wire.requestFrom(DS1307_ADDRESS, 7);
dateTime.second = bcdToDec(Wire.read());
dateTime.minute = bcdToDec(Wire.read());
dateTime.hour = bcdToDec(Wire.read() & 0b111111); // 24hr
dateTime.weekDay = bcdToDec(Wire.read()); // 1-7: Sun-Sat
dateTime.monthDay = bcdToDec(Wire.read());
dateTime.month = bcdToDec(Wire.read());
dateTime.year = bcdToDec(Wire.read());
}
byte bcdToDec(byte v) {
return (v / 16 * 10) + (v % 16);
}
@alexellis
Copy link

@joewalnes Does this code work over i2c (brought here by Google)? I noticed none of the pins on the Arduino are labelled SDA/SCL etc.. does this mean any pin can 'speak' I2C?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment