Advertisement
igendel

Arduino/AT24C64A I2C Interface demo

Dec 21st, 2015
503
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <Wire.h>
  2.  
  3. const int AT24CAddr = 0x50;
  4. byte i = 1;
  5.  
  6. void AT24CWrite(int deviceaddress, unsigned int eeaddress, byte data) {
  7.  
  8.   int rdata = data;
  9.  
  10.   Wire.beginTransmission(deviceaddress);
  11.   Wire.write(eeaddress >> 8); // MSB
  12.   Wire.write(eeaddress & 0xFF); // LSB
  13.   Wire.write(rdata);
  14.   Wire.endTransmission();
  15.  
  16. }
  17.  
  18. int16_t AT24CRead(int deviceaddress, unsigned int eeaddress) {
  19.    
  20.   int16_t rdata = -1;
  21.    
  22.   Wire.beginTransmission(deviceaddress);
  23.   Wire.write(eeaddress >> 8); // MSB
  24.   Wire.write(eeaddress & 0xFF); // LSB
  25.   Wire.endTransmission();
  26.   Wire.requestFrom(deviceaddress,1);
  27.   if (Wire.available()) rdata = Wire.read();
  28.    
  29.   return rdata;
  30.  
  31. }
  32.  
  33. void resetRec() {
  34.   AT24CWrite(AT24CAddr, 0, 0);
  35.   delay(10);  
  36. }
  37.  
  38. void record() {
  39.  
  40.   uint32_t m = millis();
  41.   byte t, state = HIGH;
  42.  
  43.   while (1) {
  44.  
  45.     // Wait for state change
  46.     while (digitalRead(A0) == state) {
  47.       if (millis() - m > 3000) {
  48.         AT24CWrite(AT24CAddr, i, 0);
  49.         return;
  50.       }
  51.     }
  52.     // Record time
  53.     t = (millis() - m) / 10;
  54.     m = millis();
  55.     AT24CWrite(AT24CAddr, i++, t);
  56.     digitalWrite(13, state);
  57.     delay(10);
  58.     state = !state;
  59.  
  60.   }  
  61.    
  62. }
  63.  
  64. void playback() {
  65.  
  66.   uint32_t m = millis();
  67.   byte t, state = HIGH;
  68.  
  69.   while (t = AT24CRead(AT24CAddr, i++)) {
  70.  
  71.     delay((uint32_t)t * 10);
  72.     digitalWrite(13, state);
  73.     state = !state;
  74.    
  75.   }
  76.  
  77. }
  78.  
  79. void setup() {
  80.  
  81.   pinMode(A0, INPUT_PULLUP);
  82.   pinMode(13, OUTPUT);
  83.   digitalWrite(13, HIGH);
  84.  
  85.   Wire.begin();
  86.  
  87.   // To reset the EEPROM data indicator:
  88.   //resetRec();
  89.   //return;
  90.  
  91.   // Light goes off when ready to record/playback
  92.   delay(1000);
  93.   digitalWrite(13, LOW);
  94.  
  95.   Serial.println(AT24CRead(AT24CAddr, 0));
  96.   if (AT24CRead(AT24CAddr, 0) != 123) {
  97.    
  98.     record();
  99.     delay(10);
  100.     if (i > 1) AT24CWrite(AT24CAddr, 0, 123); // Mark "recorded"
  101.    
  102.   } else {
  103.       playback();
  104.       digitalWrite(13, LOW);
  105.       while (1);
  106.     }
  107.  
  108. }
  109.  
  110. void loop() {
  111.  
  112.   digitalWrite(13, !digitalRead(13));
  113.   delay(50);  
  114.  
  115. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement