#include <EEPROM.h>
void setup()
{
Serial.begin(115200);
}
void loop()
{
SetSavedState( random(0,8), random(0,2));
delay(3000);
}
// Return a byte with a random pattern.
byte functiontogetstateofrelaysfromeeprom()
{
byte result = 0;
for(int i=0; i<8; i++)
bitWrite(result, i, random(0,2));
return( result);
}
// Request the data from EEPROM and change it and send it
// Relay: 0...7
// State: 0 or 1
void SetSavedState(int Relay, int State)
{
// Get it
byte myRelaysOld = functiontogetstateofrelaysfromeeprom();
// Change it
byte myRelaysNew = myRelaysOld;
bitWrite( myRelaysNew, Relay, State);
// Conver it to text
char text[] = "00000000"; // must be 8 characters of 0
for( int i=0; i<8; i++)
{
if( bitRead( myRelaysNew, 7-i) == 1) // start with higest bit
text[i] = '1';
}
// Print everything
Serial.print("From EEPROM: ");
for( int i=7; i>=0; i--) // print zeros in front
{
if( bitRead( myRelaysOld, i) == 0)
Serial.print('0');
else
break;
}
Serial.print( myRelaysOld, BIN);
Serial.print(", Relay = ");
Serial.print(Relay);
Serial.print(", State = ");
Serial.print(State);
Serial.print(", result as text = ");
Serial.println(text);
}