This commit fixes an error

This commit fixes an error

--- TinyScreenClockAndDisplay.ino
+++ TinyScreenClockAndDisplay.ino
@@ -35,7 +35,6 @@
   display.setFlip(1);
   display.setBrightness(4);
   RTC.start();
-  displayBattery();
   display.fontColor(GREEN,BLACK);
   display.setFont(liberationSans_16ptFontInfo);
   display.setCursor(0,10);
@@ -57,7 +56,6 @@
   	}
     if(buttons == 0){
       countdown=countdown-1;
-      Serial.println(countdown);
     }
   if (countdown<=0){
   displayState=0;
@@ -101,7 +99,7 @@
 display.print(hours);
   display.print(":");

-  if (RTC.getMinutes() < 10) // if minutes under 10
+  if (RTC.getMinutes() < 10)
    {
      display.fontColor(YELLOW,BLACK);
      display.print("0");
@@ -113,11 +111,11 @@
      display.print(minute);
    }

-  display.fontColor(GREEN,BLACK); // set color
+  display.fontColor(GREEN,BLACK);

   display.print(":");

-   if (RTC.getSeconds() < 10) // if seconds under 10
+   if (RTC.getSeconds() < 10)
    {
      display.fontColor(RED,BLACK);
      display.print("0");


Revert change     * examples/SodaqOne-TTN-Mapper-binary/SodaqOne-TTN-Mapper-binary.ino:

--- examples/SodaqOne-TTN-Mapper-binary/SodaqOne-TTN-Mapper-binary.ino
+++ examples/SodaqOne-TTN-Mapper-binary/SodaqOne-TTN-Mapper-binary.ino
@@ -97,7 +97,7 @@
   join_result = myLora.initABP("02017201", "8D7FFEF938589D95AAD928C2E2E7E48F", "AE17E567AECC8787F749A62F5541D522");

   //OTAA: initOTAA(String AppEUI, String AppKey);
-  //join_result = myLora.initOTAA("70B3D57EF0001F39", "55D517528FD26BA78E65D5E934BF4F8A");
+  //join_result = myLora.initOTAA("70B3D57ED00001A6", "A23C96EE13804963F8C2BD6285448198");

   while(!join_result)
   {


Arduino sketch for I2C remote and servos

--- ARDUINO/i2c_rx_and_servo/i2c_rx_and_servo.ino
+++ ARDUINO/i2c_rx_and_servo/i2c_rx_and_servo.ino
@@ -1,10 +1,10 @@
-/*//
+/*

   Author : Vincent Jaunet
-
+

  This sketch is made for
-  - Get RC from Rx receiver
+  - Get RC from Rx receiver
   - transmit to Rpi pilot
   - Receive ESC and Servos input from Rpi Pilot

@@ -14,11 +14,11 @@

 // include the pinchangeint library - see the links in the related topics section above for details
 #include <PinChangeInt.h>
-#include <Wire.h>
+#include <WSWire.h>
 #include <Servo.h>

 //Define I2C variables
-#define SLAVE_ADDRESS 0x04
+#define SLAVE_ADDRESS 0x11

 //LED pin for checking
 #define LED_PIN 13
@@ -50,7 +50,7 @@
 volatile uint8_t bUpdateFlagsShared;

 // shared variables are updated by the ISR and read by loop.
-// In loop we immediatley take local copies so that the ISR can keep ownership of the
+// In loop we immediatley take local copies so that the ISR can keep ownership of the
 // shared ones. To access these in loop
 // we first turn interrupts off with noInterrupts
 // we take a copy to use in loop and the turn interrupts back on
@@ -82,6 +82,13 @@
 //define Servo variables
 Servo MOTOR[SERVO_NUM];

+//servo values updated by Rpi
+volatile union int_byt{
+  uint8_t b[2];
+  uint16_t i;
+} *rcv_data = new int_byt[SERVO_NUM];
+
+

 void setup()
 {
@@ -92,19 +99,25 @@

   // using the PinChangeInt library, attach the interrupts
   // used to read the channels
-  PCintPort::attachInterrupt(THROTTLE_IN_PIN, calcThrottle,CHANGE);
-  PCintPort::attachInterrupt(YAW_IN_PIN, calcYaw,CHANGE);
-  PCintPort::attachInterrupt(PITCH_IN_PIN, calcPitch,CHANGE);
-  PCintPort::attachInterrupt(ROLL_IN_PIN, calcRoll,CHANGE);
-
-  // attach servo objects, these will generate the correct
+  PCintPort::attachInterrupt(THROTTLE_IN_PIN, calcThrottle,CHANGE);
+  PCintPort::attachInterrupt(YAW_IN_PIN, calcYaw,CHANGE);
+  PCintPort::attachInterrupt(PITCH_IN_PIN, calcPitch,CHANGE);
+  PCintPort::attachInterrupt(ROLL_IN_PIN, calcRoll,CHANGE);
+
+  // attach servo objects, these will generate the correct
   // pulses for driving Electronic speed controllers, servos or other devices
-  // designed to interface directly with RC Receivers
+  // designed to interface directly with RC Receivers
   MOTOR[0].attach(FL_MOTOR_OUT_PIN);
   MOTOR[1].attach(FR_MOTOR_OUT_PIN);
   MOTOR[2].attach(BL_MOTOR_OUT_PIN);
   MOTOR[3].attach(BR_MOTOR_OUT_PIN);
-  Wire.onReceive(SetServos);
+
+  //Set servo values to min
+  for (int i=0;i<SERVO_NUM;i++)
+    {
+      MOTOR[i].writeMicroseconds(RC_MIN);
+    }
+

   // initialize i2c as slave
   // define call backs ofr I2C
@@ -116,67 +129,20 @@

 void loop()
 {
-  // create local variables to hold a local copies of the channel inputs
-  // these are declared static so that thier values will be retained
-  // between calls to loop.
-  static uint16_t unThrottleIn;
-  static uint16_t unYawIn;
-  static uint16_t unPitchIn;
-  static uint16_t unRollIn;
-  // local copy of update flags
-  static uint8_t bUpdateFlags;
-
-  // check shared update flags to see if any channels have a new signal
-  if(bUpdateFlagsShared)
-    {
-      noInterrupts(); // turn interrupts off quickly while we take local copies of the shared variables
-
-      // take a local copy of which channels were updated in case we need to use this in the rest of loop
-      bUpdateFlags = bUpdateFlagsShared;
-
-      // in the current code, the shared values are always populated
-      // so we could copy them without testing the flags
-      // however in the future this could change, so lets
-      // only copy when the flags tell us we can.
-
-      if(bUpdateFlags & THROTTLE_FLAG)
-	{
-	  unThrottleIn = unThrottleInShared;
-	}
-
-      if(bUpdateFlags & YAW_FLAG)
-	{
-	  unYawIn = unYawInShared;
-	}
-
-      if(bUpdateFlags & PITCH_FLAG)
-	{
-	  unPitchIn = unPitchInShared;
-	}
-
-      if(bUpdateFlags & ROLL_FLAG)
-	{
-	  unRollIn = unRollInShared;
-	}
-
-      // clear shared copy of updated flags as we have already take
-      // we still have a local copy if we need to use it in bUpdateFlags
-      bUpdateFlagsShared = 0;
-
-      interrupts(); // we have local copies of the inputs, so now we can turn interrupts back on
-      // as soon as interrupts are back on, we can no longer use the shared copies, the interrupt
-      // service routines own these and could update them at any time. During the update, the
-      // shared copies may contain junk. Luckily we have our local copies to work with :-)
-    }
-
-  bUpdateFlags = 0;
+  // noInterrupts();
+
+  //Update servo values
+  for (int i=0;i<SERVO_NUM;i++)
+    {
+      MOTOR[i].writeMicroseconds(rcv_data[i].i);
+    }
+
+  //  interrupts();
 }

 // On request I2C data Sends shared values the Remote values
 // for Throttle, Yaw, Pitch and Roll
-// Note interrupts sotpped while sending values, should not
-// take much time
 void SendRemote()
 {

@@ -186,6 +152,9 @@
     float d;
   } RCsignal[4];

+
+  //Note we don't use shared volatile vars
+  //sot that ISRs keep priority on them
   RCsignal[0].d=
     (float) (unThrottleInShared-THR_MIN)/
     (THR_MAX-THR_MIN) * 100.0;
@@ -198,7 +167,7 @@
   RCsignal[3].d=
      ((float) unRollInShared-(RC_MAX+RC_MIN)/2)/
     (RC_MAX-RC_MIN) * K_ROLL;
-
+

   byte data[16];
@@ -209,7 +178,7 @@
 	data[ii+4*i] = RCsignal[i].b[ii];
       }
     }
-
+
   Wire.write(data,16);

 }
@@ -219,7 +188,7 @@
 {
   // if the pin is high, its a rising edge of the signal pulse, so lets record its value
   if(digitalRead(THROTTLE_IN_PIN) == HIGH)
-    {
+    {
       ulThrottleStart = micros();
     }
   else
@@ -235,7 +204,7 @@
 void calcYaw()
 {
   if(digitalRead(YAW_IN_PIN) == HIGH)
-    {
+    {
       ulYawStart = micros();
     }
   else
@@ -248,7 +217,7 @@
 void calcPitch()
 {
   if(digitalRead(PITCH_IN_PIN) == HIGH)
-    {
+    {
       ulPitchStart = micros();
     }
   else
@@ -261,7 +230,7 @@
 void calcRoll()
 {
   if(digitalRead(ROLL_IN_PIN) == HIGH)
-    {
+    {
       ulRollStart = micros();
     }
   else
@@ -277,52 +246,18 @@

 // the RPI shoud send 4 x 1 uint16_t (2 bytes) values
 // one for each PID updated Motor speed
-
-  union int_byt{
-    uint8_t b[2];
-    uint16_t i;
-  };
-
-  uint8_t trash;
-
-  //Expected bytes to be received
-  union int_byt *rcv_data = new int_byt[SERVO_NUM];
-
   if (byteCount == 8)
     {
       while(Wire.available()) {
-
+
 	for (int i=0;i<SERVO_NUM;i++)
 	  {
 	    rcv_data[i].b[0] = Wire.read(); //upper bits?
 	    rcv_data[i].b[1] = Wire.read(); //upper bits?
+
 	  }
       }
-
-    }
-  else {
-    //short read from master
-    //Do nothing
-    // Serial.println("Short read from master :");
-    // Serial.print("Expected 8 bytes,");
-    // Serial.print("Received ");
-    // Serial.print(byteCount);
-    // Serial.println(" bytes");
-
-    return;
-  }
-
-  //Update servo values
-  for (int i=0;i<SERVO_NUM;i++)
-    {
-      	    // Serial.print("Received value ");
-	    // Serial.print(i);
-	    // Serial.print(" = ");
-	    // Serial.println(rcv_data[i].i);
-
-      MOTOR[i].writeMicroseconds(rcv_data[i].i);
     }

   return;
-
-}
+}


Add source pool

Add source pool

--- Arduino/noise_multiplier/noise_multiplier.ino
+++ Arduino/noise_multiplier/noise_multiplier.ino
@@ -1,13 +1,14 @@
 #include "AES.h"

-#define COLLECTING 0
-#define CONDITIONING 1
+#define CHAIN_SIZE 2
+#define BLOCK_SIZE 16
+#define SAMPLE_SIZE BLOCK_SIZE * CHAIN_SIZE

 AES128 aes128;
-byte key[32] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+byte key[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                     0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};

-int state = COLLECTING;
+byte sourcePool[SAMPLE_SIZE];

 void setup()
 {
@@ -47,31 +48,46 @@
 }

-ISR(TIMER1_COMPA_vect) {
-  if (state == COLLECTING){
-    byte pinVal = 0;
-    pinVal = PIND >> 7;
-    collectBit(pinVal);
+ISR(TIMER1_COMPA_vect) {
+  static byte currentByte = 0x00;
+  byte pinVal = PIND >> 7;
+  boolean byteReady = collectBit(pinVal, &currentByte);
+
+  if (byteReady){
+    Serial.println(currentByte);
+    boolean poolFull = collectByte(currentByte);
+    if (poolFull){
+      conditionPool();
+      //TODO: transmit MAC
+    }
+    currentByte = 0;
   }
 }

-void collectBit(byte inputBit){
-  static byte currentByte = 0x00;
+boolean collectBit(byte inputBit, byte *currentByte){
   static int bitCounter = 0;
-  currentByte |= inputBit << bitCounter;
-
-  if (bitCounter == 7) {
-    Serial.println(currentByte);
-    currentByte = 0;
+  *currentByte |= inputBit << bitCounter;
+   bitCounter = ++bitCounter % 8;
+
+  if (bitCounter == 0) {
+    return true;
   }
-
-  bitCounter = ++bitCounter % 8;
+  return false;
 }

-void processByte(byte currentByte){
+boolean collectByte(byte currentByte){
+  static int byteCount = 0;
+  sourcePool[byteCount] = currentByte;
+  byteCount = ++byteCount % SAMPLE_SIZE;
+  if (byteCount == 0){
+    return true;
+  }
+  return false;
+}

-
+void conditionPool(){
+
 }

 void loop()


Update chorus-rf-laptimer.ino

Update chorus-rf-laptimer.ino

--- Arduino/chorus-rf-laptimer/chorus-rf-laptimer.ino
+++ Arduino/chorus-rf-laptimer/chorus-rf-laptimer.ino
@@ -770,7 +770,7 @@
 }
 // ----------------------------------------------------------------------------
 void incBand() {
-    if (bandIndex < 7) {
+    if (bandIndex < MAX_BAND) {
         bandIndex++;
     }
     setChannelModule(channelIndex, bandIndex);
@@ -786,7 +786,7 @@
 }
 // ----------------------------------------------------------------------------
 void setBand(uint8_t band) {
-    if (band >= 0 && band <= 5) {
+    if (band >= 0 && band <= MAX_BAND) {
         bandIndex = band;
         setChannelModule(channelIndex, bandIndex);
         wait_rssi_ready();
@@ -883,4 +883,4 @@

     voltageA = voltageA/VOLTAGE_READS; // average of RSSI_READS readings
     return voltageA;
-}+}


fix

fix

change read status from relay pin, extend timeout wifimanager

--- Hotel_Room/Hotel_Room.ino
+++ Hotel_Room/Hotel_Room.ino
@@ -47,7 +47,7 @@
 const char *password = "";
 //const char* mqtt_server = "192.168.43.252";
 const char* mqtt_server = "192.168.9.1";
-//const char* mqtt_server = "192.168.8.50";
+//const char* mqtt_server = "192.168.8.50"; .9.1
 const int relayPin = D1;
 const int statusPin = D2;
 const int buzzer=D5; //Buzzer control port, default D5
@@ -143,7 +143,8 @@
       bstop = false;

     } else if ((char)payload[0] == '2') {       // 2 - get status from D2 (connect D2 <---> D1)
-        statusvalue = digitalRead(statusPin);
+        // statusvalue = digitalRead(statusPin);
+        statusvalue = digitalRead(relayPin);
         if (statusvalue == HIGH) {
           client.publish(room_status, "ON");
       }
@@ -254,7 +255,7 @@
   //sets timeout until configuration portal gets turned off
   //useful to make it all retry or go to sleep
   //in seconds
-  wifiManager.setTimeout(60);
+  wifiManager.setTimeout(300);

   /*
   // We start by connecting to a WiFi network
@@ -293,7 +294,7 @@
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());

-
+  /*
   WiFi.macAddress(mac);
   Serial.print("MAC: ");
   Serial.print(mac[0],HEX);
@@ -307,6 +308,7 @@
   Serial.print(mac[4],HEX);
   Serial.print(":");
   Serial.println(mac[5],HEX);
+  */

 }


Multivitamine

Multivitamine

--- Buddy/Iris_buddy_workFile/Iris_buddy_workFile.ino
+++ Buddy/Iris_buddy_workFile/Iris_buddy_workFile.ino
@@ -41,8 +41,12 @@
 void loop()
 {
   static int oldvalue = 0;
-
   int _infrared = (oldvalue + (analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0) + analogRead(0)) / 8) / 2; //
+
+  int _infrared = 0;
+  for (int i = 0; i < 8; i++) _infrared += analogRead(0);
+  _infrared /= 8;
+
   oldvalue = _infrared;
   Serial.println(_infrared); //0-1023
   //Serial.println( analogRead _infrared);


extract contrast command to its own function for ease if use

--- Nokia_5110/Nokia_5110.ino
+++ Nokia_5110/Nokia_5110.ino
@@ -11,6 +11,18 @@
     digitalWrite(CE, HIGH);
 }

+/**
+ * @param contrast could be 1 to 17
+ */
+void contrast(short contrast){
+    byte list[17] = {0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF};
+
+    if(contrast < 1 || contrast > 17)
+        return;
+
+    lcdCommand(list[contrast - 1]);
+}
+
 void setup() {
     pinMode(RST, OUTPUT);
     pinMode(CE, OUTPUT);
@@ -22,7 +34,7 @@
     digitalWrite(RST, HIGH);

     lcdCommand(0x21); // LCD extended commands
-    lcdCommand(0xB8); // set LCD Vop (contrast)
+    contrast(6);
     lcdCommand(0x04); // set temp coefficent
     lcdCommand(0x14); // LCD bias mode 1:40
     lcdCommand(0x20); // LCD basic commands


CT4 setup to send data to ESP

CT4 setup to send data to ESP

Updated sketch with note that it is CT4 that needs to be used with the shield to send data to the ESP.

--- OpenEnergyMonitor/ArduinoShield/ArduinoShield.ino
+++ OpenEnergyMonitor/ArduinoShield/ArduinoShield.ino
@@ -1,6 +1,9 @@
-/*
-  ArduinoShield.ino for Leonardo or Uno WAS LeoShieldCT1234v3.ino with DS18B20 option from:
+*
+  USE CT4 !!!!!
+  ArduinoShieldV3.ino for Leonardo or Uno WAS LeoShieldCT1234v3.ino with DS18B20 option from:
   https://github.com/openenergymonitor/emontx-shield/blob/master/firmware/Shield_CT1234_Voltage_SerialOnly/Shield_CT1234_Voltage_SerialOnly.ino
+  Use micro USB to upload new sketches NOT TTL, TTL is just to receive data and only requires 2 pins GND and TX (labelled RX on shield as it
+  goes to RX allocated pin on the ESP).
   EmonTx CT1234 Voltage Serial Only example
   Part of the openenergymonitor.org project
   Licence: GNU GPL V3
@@ -52,18 +55,19 @@
     Serial1.begin(115200); // start Serial1 on Leonardo
   #endif
   // Calibration factor = CT ratio / burden resistance = (100A / 0.05A) / 33 Ohms = 60.606
-  ct1.current(1, 60.606); // range of 58.18 to 63.02 for shield and default x with range 86.35 – 95.45 emonTx
+  ct1.current(1, 60.606); // range of 58.18 to 63.02 for shield [default 90.9 with range 86.35 – 95.45 for emonTx 22 Ohms]
   ct2.current(2, 60.606);
   ct3.current(3, 60.606);
-  ct4.current(4, 60.606);
+  // CT 4 is high accuracy @ low power - 4.5kW Max for emonTx but NOT shield (2000 turns / 120 Ohm burden resistor = 16.66 for emonTx)
+  ct4.current(4, 58.50); // shield doesn't have high accuracy CT4, normal 33 Ohms

   /* (ADC input, calibration, phase_shift)  // use CalVRef.ino sketch to get READVCC_CALIBRATION_CONST 1115000L for Leonardo
   default normally: ct1.voltage(0, 300.6, 1.7);         // Robert thinks new CT's might need 1.85
   */
-  ct1.voltage(0, 268.8, 1.25);      // phase 1.7 default is calculated by comparing real and apparent with 100% PF device
-  ct2.voltage(0, 265.8, 1.25);
-  ct3.voltage(0, 265.8, 1.25);      // 268.97 per https://learn.openenergymonitor.org/electricity-monitoring/ctac/calibration
-  ct4.voltage(0, 265.8, 1.25);
+  ct1.voltage(0, 268.97, 1.205);      // phase 1.7 default is calculated by comparing real and apparent with 100% PF device
+  ct2.voltage(0, 268.97, 1.205);      // was 265.8, 1.25
+  ct3.voltage(0, 268.97, 1.205);      // 268.97 per https://learn.openenergymonitor.org/electricity-monitoring/ctac/calibration
+  ct4.voltage(0, 268.97, 1.205);

   // Setup indicator LED
   pinMode(LEDpin, OUTPUT);
@@ -124,10 +128,12 @@
   }

    if (DEBUG==1) {  // for Leonardo will print to Serial and Serial1, but just Serial for Uno
-    Serial.print("ct1:");   Serial.print(int(ct1.realPower * 100));
-    Serial.print(",ct2:");  Serial.print(int(ct2.realPower * 100));
-    Serial.print(",ct3:");  Serial.print(int(ct3.realPower * 100));
-    Serial.print(",ct4:");  Serial.print(int(ct4.realPower * 100));
+    Serial.print("ct1:");   Serial.print(ct1.realPower);
+    //Serial.print(",ct1ap:");  Serial.print(int(ct1.apparentPower)); // was only used for "1.7" phase cal
+    Serial.print(",ct2:");  Serial.print(int(ct2.realPower));
+    Serial.print(",ct3:");  Serial.print(int(ct3.realPower));
+    Serial.print(",ct4:");  Serial.print(int(ct4.realPower));
+    //Serial.print(",ct4ap:");  Serial.print(int(ct4.apparentPower)); // was only used for "1.7" phase cal
     Serial.print(",vrms:"); Serial.print(int(ct1.Vrms * 100));
     Serial.print(",pulse:");Serial.print(emontx.pulseCount);
     if (DS18B20_STATUS==1){
@@ -136,15 +142,16 @@
         Serial.print(emontx.temp[j]);
       }
     }
+    Serial.print(",mA:");Serial.print(int(ct4.Irms * 1000));  // TODO ONLY amps from one CT for apparent power calcs
     Serial.println();
     delay(50);
   }

 #ifdef FOUND_LEONARDO
-    Serial1.print("ct1:");   Serial1.print(int(ct1.realPower * 100));
-    Serial1.print(",ct2:");  Serial1.print(int(ct2.realPower * 100));
-    Serial1.print(",ct3:");  Serial1.print(int(ct3.realPower * 100));
-    Serial1.print(",ct4:");  Serial1.print(int(ct4.realPower * 100));
+    Serial1.print("ct1:");   Serial1.print(int(ct1.realPower));
+    Serial1.print(",ct2:");  Serial1.print(int(ct2.realPower));
+    Serial1.print(",ct3:");  Serial1.print(int(ct3.realPower));
+    Serial1.print(",ct4:");  Serial1.print(int(ct4.realPower));
     Serial1.print(",vrms:"); Serial1.print(int(ct1.Vrms * 100));
     Serial1.print(",pulse:");Serial1.print(emontx.pulseCount);
     if (DS18B20_STATUS==1){
@@ -153,6 +160,7 @@
         Serial1.print(emontx.temp[j]);
       }
     }
+    Serial1.print(",mA:");Serial1.print(int(ct4.Irms * 1000));  // TODO ONLY amps from one CT for apparent power calcs
     Serial1.println();
     delay(50);
 #endif


Use non-deprecated methos in demo

Use non-deprecated methos in demo

--- examples/FTDebouncer_demo/FTDebouncer_demo.ino
+++ examples/FTDebouncer_demo/FTDebouncer_demo.ino
@@ -28,7 +28,7 @@
 	pinDebouncer.addPin(17, LOW);
 	pinDebouncer.addPin(18, HIGH);
 	pinDebouncer.addPin(19, LOW);
-	pinDebouncer.init();
+	pinDebouncer.begin();
 	Serial.println(sizeof(pinDebouncer));
 	Serial.println(pinDebouncer.getPinCount());
 	delay(5000);
@@ -36,7 +36,7 @@
 void loop(){
 	unsigned long us = micros();
 	unsigned long usElapsed;
-	pinDebouncer.run();
+	pinDebouncer.update();
 	usElapsed = micros() - us;
 	Serial.println(usElapsed);
 }


making the displayed data more readable

making the displayed data more readable

--- MSDOS/MSDOS.ino
+++ MSDOS/MSDOS.ino
@@ -15,9 +15,9 @@
 const char *menuCAN =
   "\nSelect a CAN option\n"
   "0: Back to main menu\n"
-  "1: Set a value in the MC *WIP*\n"
+  "1: Set a value in the MC\n"
   "2: Read a value from MC\n"
-  "3: Configure MC register for polling\n";
+  "3: Configure MC register for polling *TODO*\n";

 const char *readMCRegMenu =
   "\nSelect a register to read from\n"
@@ -37,8 +37,8 @@
 const char *setMCRegMenu =
   "\nSelect a register to set\n"
   "0: Back to CAN menu\n"
-  "1: REG_SPEEDVAL\n"
-  "2: REG_SPEEDLIM\n"
+  "1: Speed value in RPM\n"
+  "2: RPM limit\n"
   "3: Comparison value 1\n"
   "4: Comparison value 2\n"
   "5: Comparison value 3\n"
@@ -52,8 +52,6 @@

 //CAN stuffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

-//static uint8_t hex[17] = "0123456789abcdef";
-
 class CANClass : public CANListener
 {
 public:
@@ -70,17 +68,16 @@
 void CANClass::printFrame(CAN_message_t &frame, int mailbox)
 {
    Serial.print("This just in!\n");
-   Serial.print("ID: ");
+   Serial.print("ID: 0x");
    Serial.print(frame.id, HEX);

    //Print regID from buf[0]
-   Serial.print(" RegID: ");
+   Serial.print(" RegID: 0x");
    Serial.print(frame.buf[0], HEX);

    //Print value from register in reverse byte order
-   Serial.print(" Data: ");
+   Serial.print(" Data: 0x");
    Serial.print(frame.buf[2], HEX);
-   Serial.print(" ");
    Serial.print(frame.buf[1], HEX);

    Serial.write('\n');
@@ -159,20 +156,19 @@
   clearSerialBuf();

   Serial.print(F("\nAre you sure you want to send: \n"));
-  Serial.print("ID: ");
+  Serial.print("ID: 0x");
   Serial.print(message.id, HEX);

   //Print regID from buf[0]
-  Serial.print(" RegID: ");
+  Serial.print(" RegID: 0x");
   Serial.print(message.buf[0], HEX);

   //Print value from register in reverse byte order
-  Serial.print(" Data: ");
+  Serial.print(" Data: 0x");
   Serial.print(message.buf[2], HEX);
-  Serial.print(" ");
   Serial.print(message.buf[1], HEX);

-  Serial.print(F("\ny/n?\n"));
+  Serial.print(F("\ny/n? "));

   while(waitingOnUser)
@@ -204,11 +200,12 @@

         default:
           Serial.print(F("Invalid syntax\n"));
-          Serial.print(F("\ny/n?\n"));
+          Serial.print(F("\ny/n? "));
         break;
       }
     }
   }
+  Serial.println(rx_byte);

   return feedback;
 }
@@ -286,7 +283,8 @@
 }

-//TODO: WORK ON THIS///////////////////////////////////
+//Mostly working (need to check for certain but seems okay now)
+//function for setting a register value in the MC
 void setMCReg()
 {
   bool caseSetMCReg = true;


ability to modify and store current enable threshold

--- short-circuit-limiter/short-circuit-limiter.ino
+++ short-circuit-limiter/short-circuit-limiter.ino
@@ -1,10 +1,14 @@
+#include <EEPROM.h>
 #include <U8g2lib.h>
 #include <OneWire.h>
 #include <DallasTemperature.h>
 #include "CTSensor.h"

+#define CURRENT_MCB_CUT 16
 #define DEFAULT_CURRENT_ENABLE_THRESHOLD 0.2
-#define CURRENT_MCB_CUT 16
+#define CURRENT_THRESHOLD_STRIDE 0.01
+#define MIN_ENABLE_CURRENT_THRESHOLD 0.01
+#define ADDRESS_STORE_CURRENT_ENABLE 0

 #define TEMP_MAX 85
 #define TEMP_WARN 70
@@ -69,15 +73,6 @@
 bool isBacklightAlwaysOn = false;

 float currentEnableThreshold;
-
-float getEnableThresholdFromEEProm(){
-  return DEFAULT_CURRENT_ENABLE_THRESHOLD;
-}
-
-void changeEnableThreshold(float newThreshold){
-  currentEnableThreshold = newThreshold;
-}
-

 void setup() {

@@ -495,18 +490,38 @@
   }
 }

+float getEnableThresholdFromEEProm(){
+
+  float value;
+
+  EEPROM.get(ADDRESS_STORE_CURRENT_ENABLE, value);
+
+  if(isnan(value)){
+      return DEFAULT_CURRENT_ENABLE_THRESHOLD;
+  } else {
+    return value;
+  }
+
+}
+
 void updateCurrentThresholdForCertainModes(){
   float newThreshold = currentEnableThreshold;

   if(isTopButtonPressed()){
-    changeEnableThreshold(currentEnableThreshold += 0.01);
+    newThreshold += CURRENT_THRESHOLD_STRIDE;
   }

   if(isBottomButtonPressed()){
-    changeEnableThreshold(currentEnableThreshold -= 0.01);
-  }
-
-
+    newThreshold -= CURRENT_THRESHOLD_STRIDE;
+  }
+
+
+  if(newThreshold != currentEnableThreshold
+    && newThreshold >= MIN_ENABLE_CURRENT_THRESHOLD){
+
+    currentEnableThreshold = newThreshold;
+    EEPROM.put(ADDRESS_STORE_CURRENT_ENABLE, currentEnableThreshold);
+  }

 }


code optimisation

code optimisation

--- arduino/src/myletterclock.ino
+++ arduino/src/myletterclock.ino
@@ -3,7 +3,7 @@
 #include <DS1307RTC.h>
 #include <Time.h>
 #include "Adafruit_NeoPixel.h"
-#include "TimerOne.h"
+/* #include "TimerOne.h" */
 #include "DCF77.h"

 #define DCF_PIN 2                // Connection pin to DCF 77 device
@@ -11,7 +11,7 @@
 DCF77 DCF = DCF77(DCF_PIN,DCF_INTERRUPT, true);

 //define the data pin
-#define PIN 10
+#define LEDPIN 10
 //define number of pixels
 #define NUMPIXEL 144
 // Parameter 1 = number of pixels in strip
@@ -21,9 +21,10 @@
 //   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
 //   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
 //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
-Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXEL, PIN, NEO_GRB | NEO_KHZ800);
+Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXEL, LEDPIN, NEO_GRB | NEO_KHZ800);

 unsigned int i = 0;
+static unsigned long msLast = 0;

 typedef uint32_t Color;
 Color cBlack = 0;
@@ -34,11 +35,13 @@

 void setup ()
 {
-    Timer1.initialize(1000000);       // Initialize timer to 1s
-    Timer1.attachInterrupt(checktime);  // Attach funciton checktime to timer interupt
+    /* Timer1.initialize(1000000);       // Initialize timer to 1s */
+    /* Timer1.attachInterrupt(checktime);  // Attach funciton checktime to timer interupt */
     Serial.begin(57600);
     strip.begin();                  // Initialize NeoPixel object
     strip.show();                   // Initialize all pixels to '}ff'
+
+    msLast = millis();

     DCF.Start();

@@ -52,6 +55,12 @@

 void loop ()
 {
+    unsigned long msNow = millis();
+    if((msNow - msLast > 999) || (msNow < msLast))
+    {
+        msLast= millis();
+        checktime();
+    }
 }

 void checktime()
@@ -73,7 +82,7 @@
     {
         lightWar(cForeground);
     }
-    if(minutemod5 == 0 || minutemod5 == 3 || minutemod5 == 4)
+    else// if(minutemod5 == 0 || minutemod5 == 3 || minutemod5 == 4)
     {
         lightIst(cForeground);
     }


added proper switches for non-existant sensors

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -96,12 +96,12 @@
 /////////////////////////////////////////////////////////////////////////////
 // humidity sensor stuff ////////////////////////////////////////////////////
 DHT dht(12, DHT22); // what digital pin we're connected to, plus type DHT22 aka AM2302
-const boolean GOT_HUMID_SENSOR = true;
+const boolean GOT_HUMID_SENSOR = false;

 /////////////////////////////////////////////////////////////////////////////
 // Light sensor stuff ///////////////////////////////////////////////////////
 Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)
-const boolean GOT_LIGHT_SENSOR = true;
+const boolean GOT_LIGHT_SENSOR = false;

 /////////////////////////////////////////////////////////////////////////////
 // RC switch stuff //////////////////////////////////////////////////////////
@@ -410,13 +410,17 @@
 // sensor/actuator stuff ////////////////////////////////////////////////////
 void startPeripherals() {
   mySwitch.enableTransmit(13);   // RC Transmitter is connected to Pin #13
-
+
+  if(GOT_TEMP_SENSOR){
   tempSensor.begin();     // Start the onewire temperature sensor
   tempSensor.getAddress(tempAddr, 0);
   tempSensor.setResolution(tempAddr, 12);    // set the resolution to 12 bit (DS18B20 goes from 9-12 bit)
-
+  }
+
+  if(GOT_HUMID_SENSOR)
   dht.begin();    // Start the humidity and air temperature sensor

+  if(GOT_LIGHT_SENSOR){
   // You can change the gain of the light sensor on the fly, to adapt to brighter/dimmer light situations
   //tsl.setGain(TSL2591_GAIN_LOW);    // 1x gain (bright light)
   tsl.setGain(TSL2591_GAIN_MED);      // 25x gain
@@ -432,6 +436,7 @@
   //tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS);  // longest integration time (dim light)

   tsl.begin();    // Start the light sensor
+  }
 }

 void updateSensorData(monitor_t *monitorData) {
@@ -480,18 +485,24 @@
 void printMonitorEntry(monitor_t m, String* buf) {
   buf->concat("timestamp: ");
   buf->concat(m.timestamp);
+  if(GOT_TEMP_SENSOR){
   buf->concat(", Water Temp: ");
   buf->concat(m.waterCelsius);
   buf->concat(" °C");
+  }
+  if(GOT_HUMID_SENSOR){
   buf->concat(", Air Temp: ");
   buf->concat(m.airCelsius);
   buf->concat(" °C");
   buf->concat(", Humidity: ");
   buf->concat(m.airHumid);
-  buf->concat(" %RH");
+  buf->concat(" %RH");
+  }
+  if(GOT_LIGHT_SENSOR){
   buf->concat(", Light: ");
   buf->concat(m.lux);
-  buf->concat(" lux");
+  buf->concat(" lux");
+  }
 }
 void getTemperature(float* waterCelsius) {
   float _waterCelsius = *waterCelsius;


Add bmp180 board

Add bmp180 board

--- arduino/PrometheusSensor.ino
+++ arduino/PrometheusSensor.ino
@@ -1,3 +1,5 @@
+
+
 /* DHTServer - ESP8266 Webserver with a DHT sensor as an input

    Based on ESP8266Webserver, DHTexample, and BlinkWithoutDelay (thank you)
@@ -7,8 +9,12 @@
 #include <ESP8266WiFi.h>
 #include <WiFiClient.h>
 #include <DHT.h>
+#include <Wire.h>
+#include <Adafruit_BMP085.h>
 #define DHTTYPE DHT22
-#define DHTPIN  2
+#define DHTPIN  4
+#define DHTPWR  13
+

 #define WIFI_SSID           "Embedded Pie"
 #define WIFI_PASSWORD       "embedded"
@@ -33,6 +39,8 @@
 // This is for the ESP8266 processor on ESP-01
 DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266

+Adafruit_BMP085 bmp;
+
 // Generally, you should use "unsigned long" for variables that hold time
 unsigned long previousMillis = 0;        // will store last temp was read
 const long interval = 2000;              // interval at which to read sensor
@@ -42,17 +50,24 @@
 {
   // You can open the Arduino IDE Serial Monitor window to see what the code is doing
   Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable
+  // Power on the DHT22 sensor first.
+  pinMode(DHTPWR, OUTPUT);
+  digitalWrite(DHTPWR, HIGH);
   dht.begin();           // initialize temperature sensor
-
+
   // Connect to WiFi network
   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
   Serial.print("\n\r \n\rWorking to connect");
   // Wait for connection
   while (WiFi.status() != WL_CONNECTED) {
-    delay(500);
+    delay(250);
     Serial.print(".");
   }
   Serial.println("");
+  Wire.pins(12, 14);
+  if (!bmp.begin()) {
+    Serial.println("BMP init error!");
+  }
   Serial.println("DHT Weather Reading Client");
   Serial.print("Connected to ");
   Serial.println(WIFI_SSID);
@@ -88,21 +103,61 @@
   client.stop();
 }

+bool isValidHumidity(float humidity) {
+  return (!isnan(humidity) && humidity >= 0 && humidity <= 100);
+}
+
+bool isValidTemp(float temp) {
+  return (!isnan(temp) && temp >= -100 && temp <= 212);
+}
+
+float pascalsToInchesHg(int64 pascals) {
+  return pascals * 0.000295299830714;
+}
+
+float tempCtoTempF(float tempC) {
+  return (tempC + 32) * 9 / 5;
+}
+
 void loop(void)
 {
-  float temp = dht.readTemperature(true);  // Request temperature in F
-  float humidity = dht.readHumidity();
+  float temp, humidity;
+  for (int i = 0; i < 4; i++) {
+    temp = dht.readTemperature(true);
+    if (!isValidTemp(temp)) {
+      delay(250);
+      continue;
+    }
+    break;
+  }
+  for (int i = 0; i < 4; i++) {
+    humidity = dht.readHumidity();
+    if (!isValidHumidity(humidity)) {
+      delay(250);
+      continue;
+    }
+    break;
+  }
+
   String out;
-  if (!isnan(humidity) && humidity >= 0 && humidity <= 100) {
+  if (isValidHumidity(humidity)) {
     out += makeSensorVar("humidity") + " " + String(humidity) + "\n";
   }
-  if (!isnan(temp) && temp >= -100 && temp <= 212) {
+  if (isValidTemp(temp)) {
     out +=  makeSensorVar("tempF") + " " + String(temp) + "\n";
   }
   out += makeSensorVar("battery_millivolts") + " " + String(ESP.getVcc()) + "\n";
   out += makeSensorVar("free_heap") + " " + String(ESP.getFreeHeap()) + "\n";
+  out += makeSensorVar("bmp_tempC") + " " + String(bmp.readTemperature()) + "\n";
+  out += makeSensorVar("pressure") + " " + String(bmp.readPressure()) + "\n";
+  out += makeSensorVar("altitude") + " " + String(bmp.readAltitude()) + "\n";
   Serial.println(out);
   sendMetrics(out);
-  delay(30000);
+  // Power off the sensor while the esp is in deep sleep.
+  digitalWrite(DHTPWR, LOW);
+  ESP.deepSleep(120000000, WAKE_RF_DEFAULT);
+  // It can take a while for the ESP to actually go to sleep.
+  // When it wakes up we start again in setup().
+  delay(5000);
 }


Add grayshade falloff to black

Add grayshade falloff to black

--- Valokepakko.ino
+++ Valokepakko.ino
@@ -81,6 +81,11 @@
     int colorIndex = pgm_read_byte_near(PIXELS + pixelIndex);
     memcpy_PF(&rgb, (uint_farptr_t) &PALETTE[colorIndex], sizeof(RGB));
   }
+
+  if (rgb.r + rgb.g + rgb.b < 40) {
+    rgb = {0, 0, 0};
+  }
+
   return strip.Color(rgb.r, rgb.g, rgb.b);
 }


Update AC Current Gain Tuning Demo

Update AC Current Gain Tuning Demo

Committer: Tiago Lobão <tiago_lobao@localhost.localdomain>
On behalf of Maurizio Malaspina

- Bug fix: row 214, the mask "reg | 0x00800000" simply becomes "0x00800000". In this way clearing DRDY flag works i general, not only for this example.

- Optimization: row 142, added "SYS_GAIN" as factor in the "SCALE_REGISTER_FRACTION" definition. This make uniform the conversion factors after and before the AC current gain calibration.

--- examples/CS5490_AC_Current_Gain_Tuning_demo/CS5490_AC_Current_Gain_Tuning_demo.ino
+++ examples/CS5490_AC_Current_Gain_Tuning_demo/CS5490_AC_Current_Gain_Tuning_demo.ino
@@ -1,499 +1,482 @@
-#include <CS5490.h>
-#include <EEPROM.h>
-
-#define rx 11 // Referred to Arduino, must be cross-connected to tx pin of the CS5490
-#define tx 12
-#define Reset 10
-
-/* Choose your board */
-
-/* Arduino UNO and ESP8622 */
-CS5490 line(MCLK_default,rx,tx,Reset);
-
-/* ESP and MEGA  (Uses Serial2)*/
-//CS5490 line(MCLK_default,Reset);
-
-// Comment out the following in order to activate tuning mode for AC Igain (shunt method is used in this example)
-//#define TUNING_MODE_ACTIVE
-
-// The following parameters are application dependent, therefore must be properly set according your external hardware
-#define R_SHUNT_OHM   0.069  // Application dependent
-#define V_ALFA        (1000.0/1689000.0) // Resistor partition ratio on V input: on CDB5490U 4 * 422kOhm + 1kOhm
-#define SYS_GAIN      1.25
-#define V_FS          0.6
-#define V_FS_RMS_V    0.17676 // 250mVpp
-#define V_MAX_RMS     (V_FS_RMS_V/V_ALFA)
-#define I_FS          0.6
-#define I_FS_RMS_V    0.17676 // 250mVpp with GAIN 10x, otherwise with GAIN 50x 50mVpp --> 0.3535 Vrms
-#define I_MAX_RMS_A   (I_FS_RMS_V/R_SHUNT_OHM)
-#define P_FS          0.36
-#define P_COEFF       ((V_MAX_RMS * I_MAX_RMS_A) / (P_FS * SYS_GAIN * SYS_GAIN))
-#define P_COEFF_CALIBRATED       ((V_MAX_RMS * I_MAX_RMS_A) / (P_FS * SYS_GAIN)) // Once current gain calibrated the contribute of SYS_GAIN disappears during normal operation
-#define SAMPLE_COUNT_DEFAULT  4000 // Number of sample used to compute the output low rate computation (with quartz 4.096MHz --> 1 measure/s).
-
-bool calibrated;
-bool resetRequired;
-uint32_t CriticalRegisterChecksum;
-
-/* TUNING OPERATIONS */
-bool CS5490_testReset(void)
-{
-  // Activate HPF on I current (to remove the DC component: it's an AC application)
-  uint32_t reg = line.readReg(16,0);
-  reg |= 0x0000000A;
-  line.write(16,0,reg);
-
-  // Set to single conversion in order to force CRC computing
-  line.singConv();
-
-	uint32_t regChk = line.getRegChk();
-  if (!line.areLastReadingOperationsSucceeded()) return false;
-
-  if(regChk != 0x00DD8BD6) return false;
-
-  return true; // Reset OK
-}
-
-
-/* NORMAL OPERATIONS */
-
-void CS5490_SendConfiguration(void)
-{
-  uint32_t IgainCalibrated;
-  uint8_t calibrationData[7];
-
-  // Look for calibration data stored in EEPROM
-  uint8_t CRC = 0;
-  for(uint8_t i=0; i<7;i++)
-  {
-    calibrationData[i] = EEPROM.read(i);
-    //Serial.println(calibrationData[i], HEX);
-    CRC ^=calibrationData[i];
-  }
-
-  if(!CRC) // EEPROM CRC OK
-  {
-    IgainCalibrated = ((uint32_t)calibrationData[0]) * 65536 + ((uint32_t)calibrationData[1]) * 256 + calibrationData[2];
-    CriticalRegisterChecksum = ((uint32_t)calibrationData[3]) * 65536 + ((uint32_t)calibrationData[4]) * 256 + calibrationData[5];
-
-    Serial.println("___CALIBRATION DATA READ FROM EEPROM___ ");
-    Serial.print("   IgainCalibrated: ");
-    Serial.println(IgainCalibrated, HEX);
-
-    Serial.print("   CriticalRegisterChecksum: ");
-    Serial.println(CriticalRegisterChecksum, HEX);
-
-    // Send calibration data
-    line.write(16,33,IgainCalibrated);
-    uint32_t IgainCalibratedReadBack = line.readReg(16, 33);
-    if (line.areLastReadingOperationsSucceeded() && IgainCalibratedReadBack == IgainCalibrated)
-    {
-      Serial.println("Igain written and verified");
-      calibrated = true;
-    }
-    else
-    {
-      Serial.println("Igain error!");
-    }
-  }
-  else // No valid calibration parameters found in EEPROM --> APPLY DEFAULTS 0xDD8BD6
-  {
-    Serial.println("CALIBRATION DATA NOT FOUND: apply default CriticalRegisterChecksum: 0xDD8BD6");
-    CriticalRegisterChecksum = 0xDD8BD6;
-  }
-
-  // Activate HPF on I current (Don't alterate critical registers checksum)
-  uint32_t reg = line.readReg(16,0);
-  reg |= 0x0000000A;
-  line.write(16,0,reg);
-
-  //line.setDOpinFunction(DO_V_ZERO_CROSSING, false); // Test the zero crossing feature
-
-  // Set to continous conversion
-  line.contConv();
-}
-
-void setup() {
-
-  //Initializing communication with CS5490
-  //600 is the default baud rate velocity.
-   line.begin(baudRate_default);
-
-  line.hardwareReset();
-  resetRequired = false;
-
-  calibrated = false; // In order to keep into considaration SYS_GAIN or not
-
-  //Initializing communication arduino/PC to show results in Monitor Serial
-  Serial.begin(115200);
-  // wait for serial port to connect. Needed for Leonardo only
-  while (!Serial);
-
-#ifndef TUNING_MODE_ACTIVE
-  CS5490_SendConfiguration();
-#endif
-}
-
-void loop() {
-
-#ifdef TUNING_MODE_ACTIVE
-
-  // The application is AC (mains voltage) with shunt resistor used to measure the current.
-  // Perform the Igain calibration with a reference instruments (a calibrated digital power meter) in the condition of more less HALF LOAD
-  // Implementation based on "CIRRUS LOGIC AN366REV2" pag. 15 "Main Calibration Flow" https://statics.cirrus.com/pubs/appNote/AN366REV2.pdf
-  // Calibration should be performed with PF=1 --> pure resistive load
-
-  #define I_CAL_RMS_A  1.3126 // Moreless 1/2 max load
-  #define SCALE_REGISTER_FRACTION  (0.6 * (I_CAL_RMS_A / I_MAX_RMS_A)) // For not full load calibration
-  #define SCALE_REGISTER_VALUE ((uint32_t)(SCALE_REGISTER_FRACTION * 0x800000))
-
-  // Verify that reset is ok: HW RESET --> START SINGLE CONVERSION --> CHECK RESET CHECKSUM
-  while(!CS5490_testReset())
-  {
-    Serial.println( "RESET issue... retry" );
-    line.resolve();
-  }
-
-  Serial.println( "RESET OK! Default parameters applied." );
-
-  line.write(18, 63, SCALE_REGISTER_VALUE); // Set scale register for not full load AC current gain calibration --> THIS MODIFY THE critical registers checksum!!!
-
-  Serial.println( "Scale register set --> Start continuos conversion..." );
-
-  line.contConv();
-
-  delay(2000); // Wait 2 seconds
-
-  line.haltConv();
-
-  double rmsV = line.getRmsV();
-  double freq = line.getFreq();
-  double rmsI = line.getRmsI();
-  double PF = line.getPF();
-  double P = line.getAvgP();
-  double Q = line.getAvgQ();
-  double S = line.getAvgS();
-
-  if(line.areLastReadingOperationsSucceeded())
-  {
-        Serial.print("Vac RMS: ");
-        rmsV = (((rmsV/SYS_GAIN)/V_FS)*V_FS_RMS_V)/V_ALFA;
-        Serial.print( rmsV, 2 );
-        Serial.print(" [V] @ ");
-        Serial.print(freq*SAMPLE_COUNT_DEFAULT, 2);
-        Serial.println(" Hz");
-        Serial.print("Iac RMS: ");
-        rmsI  = (((rmsI/SYS_GAIN)/I_FS)*I_FS_RMS_V)/R_SHUNT_OHM;
-        Serial.print( rmsI, 4 );
-        Serial.println(" [A]");
-        Serial.print("PF: ");
-        Serial.println( PF, 4 );
-        Serial.print("Active power: ");
-        Serial.print( P * P_COEFF , 4 );
-        Serial.println(" W");
-        Serial.print("Reactive power: ");
-        Serial.print( Q * P_COEFF, 4 );
-        Serial.println(" VAR");
-        Serial.print("Apparent power: ");
-        Serial.print( S * P_COEFF, 4 );
-        Serial.println(" VA");
-
-        Serial.println();
-        Serial.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-        Serial.println("Please check if measures are in the expected range, otherwise the calibration is invalid.");
-        Serial.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-        Serial.println();
-
-        bool tuningSubSequenceIsOK = true;
-
-        line.write(16, 57, 0x1F40); // Set Tsettle to 2000ms
-        uint32_t reg = line.readReg(16, 57);
-        if (!line.areLastReadingOperationsSucceeded() || reg != 0x1F40) tuningSubSequenceIsOK = false;
-
-        line.write(16, 51, 0x3E80); // Set sample count register to 16000
-        reg = line.readReg(16, 51);
-        if (!line.areLastReadingOperationsSucceeded() || reg != 0x3E80) tuningSubSequenceIsOK = false;
-
-        reg = line.readReg(0, 23); // Status0 register (in order to manage the DRDY bit)
-        if (!line.areLastReadingOperationsSucceeded()) tuningSubSequenceIsOK = false;
-        line.write(0, 23, reg | 0x00800000); // Clear DRDY by setting it
-        uint32_t status0_reg_verify = line.readReg(0, 23);
-        if (!line.areLastReadingOperationsSucceeded() || reg & 0x7FFFFF != status0_reg_verify) tuningSubSequenceIsOK = false;
-
-        if(tuningSubSequenceIsOK)
-        {
-          line.sendCalibrationCommand(Gain, Current);  // Start current gain calibration
-
-          // Wait for DRDY set, with 3000ms time-out
-          unsigned long startMillis = millis();
-          bool DRDY;
-          do
-          {
-            reg = line.readReg(0, 23); // Status0 register (in order to manage the DRDY bit)
-            if(line.areLastReadingOperationsSucceeded() && reg & 0x800000)
-              DRDY = true;
-            else
-              DRDY = false;
-          }
-          while( !DRDY && ( (millis()-startMillis) < 3000));
-
-          if(DRDY)
-          {
-            line.contConv();
-
-            delay(2000);
-
-            double rmsV = line.getRmsV();
-            double freq = line.getFreq();
-            double rmsI = line.getRmsI();
-            double PF = line.getPF();
-            uint32_t Igain = line.readReg(16, 33);
-
-            // Power read always 0 in this calibration phase (experimental result)
-            // double P = line.getAvgP();
-            // double Q = line.getAvgQ();
-            // double S = line.getAvgS();
-
-            if(line.areLastReadingOperationsSucceeded())
-            {
-                  Serial.print("Vac RMS: ");
-                  rmsV = (((rmsV/SYS_GAIN)/V_FS)*V_FS_RMS_V)/V_ALFA;
-                  Serial.print( rmsV, 2 );
-                  Serial.print(" [V] @ ");
-                  Serial.print(freq*SAMPLE_COUNT_DEFAULT, 2);
-                  Serial.println(" Hz");
-                  Serial.print("Iac RMS: ");
-                  rmsI  = (((rmsI/SYS_GAIN)/I_FS)*I_FS_RMS_V)/R_SHUNT_OHM;
-                  Serial.print( rmsI, 4 );
-                  Serial.println(" [A]");
-                  Serial.print("PF: ");
-                  Serial.println( PF, 4 );
-
-                  // Power read always 0 in this calibration phase (experimental result)
-                  // Serial.print("Active power: ");
-                  // Serial.print( P * P_COEFF , 4 );
-                  // Serial.println(" W");
-                  // Serial.print("Reactive power: ");
-                  // Serial.print( Q * P_COEFF, 4 );
-                  // Serial.println(" VAR");
-                  // Serial.print("Apparent power: ");
-                  // Serial.print( S * P_COEFF, 4 );
-                  // Serial.println(" VA");
-
-                  // Verify that reset is ok: HW RESET --> START SINGLE CONVERSION --> CHECK RESET CHECKSUM
-                  while(!CS5490_testReset())
-                  {
-                    Serial.println( "RESETTING CS5490..." );
-                    line.hardwareReset();
-                  }
-
-                  line.write(16, 33, Igain);
-                  uint32_t IgainReadBack = line.readReg(16, 33);
-                  if ( line.areLastReadingOperationsSucceeded() && IgainReadBack == Igain)
-                  {
-                    line.singConv(); // In order to compute the critical register checksum
-                    delay(1000);
-
-                    uint32_t regChk = line.getRegChk();
-                    if(line.areLastReadingOperationsSucceeded())
-                    {
-                        Serial.print("I gain: ");
-                        Serial.println(Igain, HEX);
-                        Serial.print("Critical registers checksum: "); // Must be compared with the one expected for the current configuration (stored in the eeprom). In case of mismatch --> reset CS5490
-                        Serial.println(regChk, HEX);
-                        Serial.println( "RESET OK! Tuned parameters applied." );
-
-                        uint8_t calibrationData[6];
-                        calibrationData[0] = (uint8_t)(Igain>>16); // MSB
-                        calibrationData[1] = (uint8_t)(Igain>>8);
-                        calibrationData[2] = (uint8_t)Igain;       // LSB
-                        calibrationData[3] = (uint8_t)(regChk>>16); // MSB
-                        calibrationData[4] = (uint8_t)(regChk>>8);
-                        calibrationData[5] = (uint8_t)regChk;       // LSB
-
-                        uint8_t CRC = 0;
-                        for(uint8_t i=0; i<6;i++)
-                        {
-                          CRC ^= calibrationData[i];
-                          EEPROM.update(i, calibrationData[i]);
-                          delay(100);
-                        }
-                        EEPROM.update(6, CRC);
-                        delay(100);
-
-                        // EEPROM saved data verification
-                        CRC = 0;
-                        for(uint8_t i=0; i<7;i++)
-                          CRC ^= EEPROM.read(i);
-
-                        if(!CRC)
-                        {
-                          Serial.println();
-                          Serial.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-                          Serial.println("Calibration data Igain has been saved in the EEPROM and will be restored at the normal startup");
-                          Serial.println("Please check if measures are in the expected range, otherwise the calibration is invalid.");
-                          Serial.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-                          Serial.println();
-                        }
-                        else
-                        {
-                          Serial.println("Calibration data storage issue!\n Please try restart the calibration or replace the logic board\n");
-                        }
-                    }
-                    else
-                    {
-                      Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
-                    }
-                  }
-                  else
-                  {
-                    Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
-                  }
-            }
-            else
-            {
-              Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
-            }
-
-
-          }
-          else
-          {
-            Serial.println("Calibration measuring time-out error\n Please try restart the calibration\n");
-          }
-
-        }
-        else
-        {
-          Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
-        }
-  }
-  else
-  {
-     Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
-  }
-
-
-
-  for(;;);
-
-#else
-
-   //--------------------------------------------------------------------------------------------------------------------------------------------------------------------
-   // Demo application:
-   // the evaluation board CDB5490 measures electrical parameters directly from the mains (max 300Vrms).
-   // The current is sensed using a shunt resistor between IN+ and IN- (J32) - J7 on IN- , J8 on IN+, J44 and J46 closed, J53 and J54 open
-   // The voltage is connected between LINE and GND (J4) using the builtin attenuation network - J6 in line and J11 on GND, J45 open
-   // UART connection with Arduino on J19 (TX, RX, RESET and GND1) - J20 in TX-DIGITAL position - R37, R38 and R43 must be removed to avoid collision with onboard uC
-   // J23 on the RESET line must be closed.
-   //--------------------------------------------------------------------------------------------------------------------------------------------------------------------
-
-  static uint8_t communicationMaxRetries = 5;
-  static uint8_t measureErrorDetectionCounter = 10;
-
-  // Acquire data and control that read operations are all OK
-  double rmsV = line.getRmsV();
-  double freq = line.getFreq();
-  double rmsI = line.getRmsI();
-  double PF = line.getPF();
-  double P = line.getAvgP();
-  double Q = line.getAvgQ();
-  double S = line.getAvgS();
-	uint32_t regChk = line.getRegChk();
-  bool internalVoltageReferenceOK = line.checkInternalVoltageReference();
-
-  // If all data are valid and the meter configuration is not corrupted, print results
-  if(line.areLastReadingOperationsSucceeded())
-  {
-    if(regChk == CriticalRegisterChecksum)
-    {
-      Serial.print("Vac RMS: ");
-      rmsV = (((rmsV/SYS_GAIN)/V_FS)*V_FS_RMS_V)/V_ALFA;
-      Serial.print( rmsV, 2 );
-      Serial.print(" [V] @ ");
-      Serial.print(freq*SAMPLE_COUNT_DEFAULT, 2);
-      Serial.println(" Hz");
-      Serial.print("Iac RMS: ");
-
-      if(calibrated)
-              rmsI  = (((rmsI)/I_FS)*I_FS_RMS_V)/R_SHUNT_OHM; // Once current gain calibrated the contribute of SYS_GAIN disappears during normal operation
-      else
-              rmsI  = (((rmsI/SYS_GAIN)/I_FS)*I_FS_RMS_V)/R_SHUNT_OHM;
-
-      Serial.print( rmsI, 4 );
-      Serial.println(" [A]");
-      Serial.print("PF: ");
-      Serial.println( PF, 4 );
-      Serial.print("Active power: ");
-      if(calibrated)
-        Serial.print( P * P_COEFF_CALIBRATED , 4 );
-      else
-        Serial.print( P * P_COEFF , 4 );
-      Serial.println(" W");
-      Serial.print("Reactive power: ");
-      if(calibrated)
-        Serial.print( Q * P_COEFF_CALIBRATED, 4 );
-      else
-        Serial.print( Q * P_COEFF, 4 );
-      Serial.println(" VAR");
-      Serial.print("Apparent power: ");
-      if(calibrated)
-        Serial.print( S * P_COEFF_CALIBRATED, 4 );
-      else
-         Serial.print( S * P_COEFF, 4 );
-      Serial.println(" VA");
-      Serial.print("Critical registers checksum: "); // Must be compared with the one expected for the current configuration (stored in the eeprom). In case of mismatch --> reset CS5490
-      Serial.println(regChk, HEX);
-
-      if(internalVoltageReferenceOK)
-        Serial.println("Voltage reference OK");
-      else
-      {
-        Serial.println("Voltage reference drift ERROR - CS5490 hardware reset required!");
-        resetRequired = true;
-      }
-
-      if(rmsV==0 && rmsI==0) // Sometimes the meter could enter some meta-state, reporting all 0s
-      {
-        Serial.println("Potential measuring error - CS5490 hardware reset required!");
-        measureErrorDetectionCounter--;
-        if(!measureErrorDetectionCounter)
-          resetRequired = true;
-      }
-    }
-    else
-    {
-      // Critical registes checksum error
-      Serial.println("Critical registes checksum error - CS5490 hardware reset required!");
-      Serial.print("regChk: ");
-      Serial.println(regChk, HEX);
-      Serial.print("CriticalRegisterChecksum: ");
-      Serial.println(CriticalRegisterChecksum, HEX);
-      resetRequired = true;
-    }
-
-  }
-  else
-  {
-   Serial.println("Communication error - no reply!");
-   communicationMaxRetries--;
-   if(!communicationMaxRetries)
-          resetRequired = true;
-  }
-
-  if(resetRequired)
-  {
-      resetRequired = false;
-      measureErrorDetectionCounter = 10;
-      communicationMaxRetries = 5;
-
-      line.resolve();
-      CS5490_SendConfiguration();
-
-      Serial.println("RESET PERFORMED");
-  }
-
-  Serial.println("");
-  delay(1000);
-  #endif
-}
+#include <CS5490.h>
+#include <EEPROM.h>
+
+#define rx 11 // Referred to Arduino, must be cross-connected to tx pin of the CS5490
+#define tx 12
+#define Reset 10
+
+/* Choose your board */
+
+/* Arduino UNO and ESP8622 */
+CS5490 line(MCLK_default,rx,tx,Reset);
+
+/* ESP and MEGA  (Uses Serial2)*/
+//CS5490 line(MCLK_default,Reset);
+
+// Comment out the following in order to activate tuning mode for AC Igain (shunt method is used in this example)
+//#define TUNING_MODE_ACTIVE
+
+// The following parameters are application dependent, therefore must be properly set according your external hardware
+#define R_SHUNT_OHM   0.069  // Application dependent
+#define V_ALFA        (1000.0/1689000.0) // Resistor partition ratio on V input: on CDB5490U 4 * 422kOhm + 1kOhm
+#define SYS_GAIN      1.25
+#define V_FS          0.6
+#define V_FS_RMS_V    0.17676 // 250mVpp
+#define V_MAX_RMS     (V_FS_RMS_V/V_ALFA)
+#define I_FS          0.6
+#define I_FS_RMS_V    0.17676 // 250mVpp with GAIN 10x, otherwise with GAIN 50x 50mVpp --> 0.3535 Vrms
+#define I_MAX_RMS_A   (I_FS_RMS_V/R_SHUNT_OHM)
+#define P_FS          0.36
+#define P_COEFF       ((V_MAX_RMS * I_MAX_RMS_A) / (P_FS * SYS_GAIN * SYS_GAIN))
+#define SAMPLE_COUNT_DEFAULT  4000 // Number of sample used to compute the output low rate computation (with quartz 4.096MHz --> 1 measure/s).
+
+bool resetRequired;
+uint32_t CriticalRegisterChecksum;
+
+/* TUNING OPERATIONS */
+bool CS5490_testReset(void)
+{
+  // Activate HPF on I current (to remove the DC component: it's an AC application)
+  uint32_t reg = line.readReg(16,0);
+  reg |= 0x0000000A;
+  line.write(16,0,reg);
+
+  // Set to single conversion in order to force CRC computing
+  line.singConv();
+
+	uint32_t regChk = line.getRegChk();
+  if (!line.areLastReadingOperationsSucceeded()) return false;
+
+  if(regChk != 0x00DD8BD6) return false;
+
+  return true; // Reset OK
+}
+
+
+/* NORMAL OPERATIONS */
+
+void CS5490_SendConfiguration(void)
+{
+  uint32_t IgainCalibrated;
+  uint8_t calibrationData[7];
+
+  // Look for calibration data stored in EEPROM
+  uint8_t CRC = 0;
+  for(uint8_t i=0; i<7;i++)
+  {
+    calibrationData[i] = EEPROM.read(i);
+    //Serial.println(calibrationData[i], HEX);
+    CRC ^=calibrationData[i];
+  }
+
+  if(!CRC) // EEPROM CRC OK
+  {
+    IgainCalibrated = ((uint32_t)calibrationData[0]) * 65536 + ((uint32_t)calibrationData[1]) * 256 + calibrationData[2];
+    CriticalRegisterChecksum = ((uint32_t)calibrationData[3]) * 65536 + ((uint32_t)calibrationData[4]) * 256 + calibrationData[5];
+
+    Serial.println("___CALIBRATION DATA READ FROM EEPROM___ ");
+    Serial.print("   IgainCalibrated: ");
+    Serial.println(IgainCalibrated, HEX);
+
+    Serial.print("   CriticalRegisterChecksum: ");
+    Serial.println(CriticalRegisterChecksum, HEX);
+
+    // Send calibration data
+    line.write(16,33,IgainCalibrated);
+    uint32_t IgainCalibratedReadBack = line.readReg(16, 33);
+    if (line.areLastReadingOperationsSucceeded() && IgainCalibratedReadBack == IgainCalibrated)
+    {
+      Serial.println("Igain written and verified");
+    }
+    else
+    {
+      Serial.println("Igain error!");
+    }
+  }
+  else // No valid calibration parameters found in EEPROM --> APPLY DEFAULTS 0xDD8BD6
+  {
+    Serial.println("CALIBRATION DATA NOT FOUND: apply default CriticalRegisterChecksum: 0xDD8BD6");
+    CriticalRegisterChecksum = 0xDD8BD6;
+  }
+
+  // Activate HPF on I current (Don't alterate critical registers checksum)
+  uint32_t reg = line.readReg(16,0);
+  reg |= 0x0000000A;
+  line.write(16,0,reg);
+
+  //line.setDOpinFunction(DO_V_ZERO_CROSSING, false); // Test the zero crossing feature
+
+  // Set to continous conversion
+  line.contConv();
+}
+
+void setup() {
+
+  //Initializing communication with CS5490
+  //600 is the default baud rate velocity.
+   line.begin(baudRate_default);
+
+  line.hardwareReset();
+  resetRequired = false;
+
+  //Initializing communication arduino/PC to show results in Monitor Serial
+  Serial.begin(115200);
+  // wait for serial port to connect. Needed for Leonardo only
+  while (!Serial);
+
+#ifndef TUNING_MODE_ACTIVE
+  CS5490_SendConfiguration();
+#endif
+}
+
+void loop() {
+
+#ifdef TUNING_MODE_ACTIVE
+
+  // The application is AC (mains voltage) with shunt resistor used to measure the current.
+  // Perform the Igain calibration with a reference instruments (a calibrated digital power meter) in the condition of more less HALF LOAD
+  // Implementation based on "CIRRUS LOGIC AN366REV2" pag. 15 "Main Calibration Flow" https://statics.cirrus.com/pubs/appNote/AN366REV2.pdf
+  // Calibration should be performed with PF=1 --> pure resistive load
+
+  #define I_CAL_RMS_A  1.3126 // Moreless 1/2 max load
+  #define SCALE_REGISTER_FRACTION  (0.6 * SYS_GAIN * (I_CAL_RMS_A / I_MAX_RMS_A)) // For not full load calibration
+  #define SCALE_REGISTER_VALUE ((uint32_t)(SCALE_REGISTER_FRACTION * 0x800000))
+
+  // Verify that reset is ok: HW RESET --> START SINGLE CONVERSION --> CHECK RESET CHECKSUM
+  while(!CS5490_testReset())
+  {
+    Serial.println( "RESET issue... retry" );
+    line.resolve();
+  }
+
+  Serial.println( "RESET OK! Default parameters applied." );
+
+  line.write(18, 63, SCALE_REGISTER_VALUE); // Set scale register for not full load AC current gain calibration --> THIS MODIFY THE critical registers checksum!!!
+
+  Serial.println( "Scale register set --> Start continuos conversion..." );
+
+  line.contConv();
+
+  delay(2000); // Wait 2 seconds
+
+  line.haltConv();
+
+  double rmsV = line.getRmsV();
+  double freq = line.getFreq();
+  double rmsI = line.getRmsI();
+  double PF = line.getPF();
+  double P = line.getAvgP();
+  double Q = line.getAvgQ();
+  double S = line.getAvgS();
+
+  if(line.areLastReadingOperationsSucceeded())
+  {
+        Serial.print("Vac RMS: ");
+        rmsV = (((rmsV/SYS_GAIN)/V_FS)*V_FS_RMS_V)/V_ALFA;
+        Serial.print( rmsV, 2 );
+        Serial.print(" [V] @ ");
+        Serial.print(freq*SAMPLE_COUNT_DEFAULT, 2);
+        Serial.println(" Hz");
+        Serial.print("Iac RMS: ");
+        rmsI  = (((rmsI/SYS_GAIN)/I_FS)*I_FS_RMS_V)/R_SHUNT_OHM;
+        Serial.print( rmsI, 4 );
+        Serial.println(" [A]");
+        Serial.print("PF: ");
+        Serial.println( PF, 4 );
+        Serial.print("Active power: ");
+        Serial.print( P * P_COEFF , 4 );
+        Serial.println(" W");
+        Serial.print("Reactive power: ");
+        Serial.print( Q * P_COEFF, 4 );
+        Serial.println(" VAR");
+        Serial.print("Apparent power: ");
+        Serial.print( S * P_COEFF, 4 );
+        Serial.println(" VA");
+
+        Serial.println();
+        Serial.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+        Serial.println("Please check if measures are in the expected range, otherwise the calibration is invalid.");
+        Serial.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+        Serial.println();
+
+        bool tuningSubSequenceIsOK = true;
+
+        line.write(16, 57, 0x1F40); // Set Tsettle to 2000ms
+        uint32_t reg = line.readReg(16, 57);
+        if (!line.areLastReadingOperationsSucceeded() || reg != 0x1F40) tuningSubSequenceIsOK = false;
+
+        line.write(16, 51, 0x3E80); // Set sample count register to 16000
+        reg = line.readReg(16, 51);
+        if (!line.areLastReadingOperationsSucceeded() || reg != 0x3E80) tuningSubSequenceIsOK = false;
+
+        reg = line.readReg(0, 23); // Status0 register (in order to manage the DRDY bit)
+        if (!line.areLastReadingOperationsSucceeded()) tuningSubSequenceIsOK = false;
+        line.write(0, 23, 0x00800000); // Clear DRDY by setting it
+        uint32_t status0_reg_verify = line.readReg(0, 23);
+        if (!line.areLastReadingOperationsSucceeded() || reg & 0x7FFFFF != status0_reg_verify) tuningSubSequenceIsOK = false;
+
+        if(tuningSubSequenceIsOK)
+        {
+          line.sendCalibrationCommand(Gain, Current);  // Start current gain calibration
+
+          // Wait for DRDY set, with 3000ms time-out
+          unsigned long startMillis = millis();
+          bool DRDY;
+          do
+          {
+            reg = line.readReg(0, 23); // Status0 register (in order to manage the DRDY bit)
+            if(line.areLastReadingOperationsSucceeded() && reg & 0x800000)
+              DRDY = true;
+            else
+              DRDY = false;
+          }
+          while( !DRDY && ( (millis()-startMillis) < 3000));
+
+          if(DRDY)
+          {
+            line.contConv();
+
+            delay(2000);
+
+            double rmsV = line.getRmsV();
+            double freq = line.getFreq();
+            double rmsI = line.getRmsI();
+            double PF = line.getPF();
+            uint32_t Igain = line.readReg(16, 33);
+
+            // Power read always 0 in this calibration phase (experimental result)
+            // double P = line.getAvgP();
+            // double Q = line.getAvgQ();
+            // double S = line.getAvgS();
+
+            if(line.areLastReadingOperationsSucceeded())
+            {
+                  Serial.print("Vac RMS: ");
+                  rmsV = (((rmsV/SYS_GAIN)/V_FS)*V_FS_RMS_V)/V_ALFA;
+                  Serial.print( rmsV, 2 );
+                  Serial.print(" [V] @ ");
+                  Serial.print(freq*SAMPLE_COUNT_DEFAULT, 2);
+                  Serial.println(" Hz");
+                  Serial.print("Iac RMS: ");
+                  rmsI  = (((rmsI/SYS_GAIN)/I_FS)*I_FS_RMS_V)/R_SHUNT_OHM;
+                  Serial.print( rmsI, 4 );
+                  Serial.println(" [A]");
+                  Serial.print("PF: ");
+                  Serial.println( PF, 4 );
+
+                  // Power read always 0 in this calibration phase (experimental result)
+                  // Serial.print("Active power: ");
+                  // Serial.print( P * P_COEFF , 4 );
+                  // Serial.println(" W");
+                  // Serial.print("Reactive power: ");
+                  // Serial.print( Q * P_COEFF, 4 );
+                  // Serial.println(" VAR");
+                  // Serial.print("Apparent power: ");
+                  // Serial.print( S * P_COEFF, 4 );
+                  // Serial.println(" VA");
+
+                  // Verify that reset is ok: HW RESET --> START SINGLE CONVERSION --> CHECK RESET CHECKSUM
+                  while(!CS5490_testReset())
+                  {
+                    Serial.println( "RESETTING CS5490..." );
+                    line.hardwareReset();
+                  }
+
+                  line.write(16, 33, Igain);
+                  uint32_t IgainReadBack = line.readReg(16, 33);
+                  if ( line.areLastReadingOperationsSucceeded() && IgainReadBack == Igain)
+                  {
+                    line.singConv(); // In order to compute the critical register checksum
+                    delay(1000);
+
+                    uint32_t regChk = line.getRegChk();
+                    if(line.areLastReadingOperationsSucceeded())
+                    {
+                        Serial.print("I gain: ");
+                        Serial.println(Igain, HEX);
+                        Serial.print("Critical registers checksum: "); // Must be compared with the one expected for the current configuration (stored in the eeprom). In case of mismatch --> reset CS5490
+                        Serial.println(regChk, HEX);
+                        Serial.println( "RESET OK! Tuned parameters applied." );
+
+                        uint8_t calibrationData[6];
+                        calibrationData[0] = (uint8_t)(Igain>>16); // MSB
+                        calibrationData[1] = (uint8_t)(Igain>>8);
+                        calibrationData[2] = (uint8_t)Igain;       // LSB
+                        calibrationData[3] = (uint8_t)(regChk>>16); // MSB
+                        calibrationData[4] = (uint8_t)(regChk>>8);
+                        calibrationData[5] = (uint8_t)regChk;       // LSB
+
+                        uint8_t CRC = 0;
+                        for(uint8_t i=0; i<6;i++)
+                        {
+                          CRC ^= calibrationData[i];
+                          EEPROM.update(i, calibrationData[i]);
+                          delay(100);
+                        }
+                        EEPROM.update(6, CRC);
+                        delay(100);
+
+                        // EEPROM saved data verification
+                        CRC = 0;
+                        for(uint8_t i=0; i<7;i++)
+                          CRC ^= EEPROM.read(i);
+
+                        if(!CRC)
+                        {
+                          Serial.println();
+                          Serial.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+                          Serial.println("Calibration data Igain has been saved in the EEPROM and will be restored at the normal startup");
+                          Serial.println("Please check if measures are in the expected range, otherwise the calibration is invalid.");
+                          Serial.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+                          Serial.println();
+                        }
+                        else
+                        {
+                          Serial.println("Calibration data storage issue!\n Please try restart the calibration or replace the logic board\n");
+                        }
+                    }
+                    else
+                    {
+                      Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
+                    }
+                  }
+                  else
+                  {
+                    Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
+                  }
+            }
+            else
+            {
+              Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
+            }
+
+
+          }
+          else
+          {
+            Serial.println("Calibration measuring time-out error\n Please try restart the calibration\n");
+          }
+
+        }
+        else
+        {
+          Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
+        }
+  }
+  else
+  {
+     Serial.print("Calibration aborted due to serial communication errors.\n Please try restart the calibration\n");
+  }
+
+
+
+  for(;;);
+
+#else
+
+   //--------------------------------------------------------------------------------------------------------------------------------------------------------------------
+   // Demo application:
+   // the evaluation board CDB5490 measures electrical parameters directly from the mains (max 300Vrms).
+   // The current is sensed using a shunt resistor between IN+ and IN- (J32) - J7 on IN- , J8 on IN+, J44 and J46 closed, J53 and J54 open
+   // The voltage is connected between LINE and GND (J4) using the builtin attenuation network - J6 in line and J11 on GND, J45 open
+   // UART connection with Arduino on J19 (TX, RX, RESET and GND1) - J20 in TX-DIGITAL position - R37, R38 and R43 must be removed to avoid collision with onboard uC
+   // J23 on the RESET line must be closed.
+   //--------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+  static uint8_t communicationMaxRetries = 5;
+  static uint8_t measureErrorDetectionCounter = 10;
+
+  // Acquire data and control that read operations are all OK
+  double rmsV = line.getRmsV();
+  double freq = line.getFreq();
+  double rmsI = line.getRmsI();
+  double PF = line.getPF();
+  double P = line.getAvgP();
+  double Q = line.getAvgQ();
+  double S = line.getAvgS();
+	uint32_t regChk = line.getRegChk();
+  bool internalVoltageReferenceOK = line.checkInternalVoltageReference();
+
+  // If all data are valid and the meter configuration is not corrupted, print results
+  if(line.areLastReadingOperationsSucceeded())
+  {
+    if(regChk == CriticalRegisterChecksum)
+    {
+      Serial.print("Vac RMS: ");
+      rmsV = (((rmsV/SYS_GAIN)/V_FS)*V_FS_RMS_V)/V_ALFA;
+      Serial.print( rmsV, 2 );
+      Serial.print(" [V] @ ");
+      Serial.print(freq*SAMPLE_COUNT_DEFAULT, 2);
+      Serial.println(" Hz");
+      Serial.print("Iac RMS: ");
+
+      rmsI  = (((rmsI/SYS_GAIN)/I_FS)*I_FS_RMS_V)/R_SHUNT_OHM;
+
+      Serial.print( rmsI, 4 );
+      Serial.println(" [A]");
+      Serial.print("PF: ");
+      Serial.println( PF, 4 );
+      Serial.print("Active power: ");
+      Serial.print( P * P_COEFF , 4 );
+      Serial.println(" W");
+      Serial.print("Reactive power: ");
+      Serial.print( Q * P_COEFF, 4 );
+      Serial.println(" VAR");
+      Serial.print("Apparent power: ");
+      Serial.print( S * P_COEFF, 4 );
+      Serial.println(" VA");
+      Serial.print("Critical registers checksum: "); // Must be compared with the one expected for the current configuration (stored in the eeprom). In case of mismatch --> reset CS5490
+      Serial.println(regChk, HEX);
+
+      if(internalVoltageReferenceOK)
+        Serial.println("Voltage reference OK");
+      else
+      {
+        Serial.println("Voltage reference drift ERROR - CS5490 hardware reset required!");
+        resetRequired = true;
+      }
+
+      if(rmsV==0 && rmsI==0) // Sometimes the meter could enter some meta-state, reporting all 0s
+      {
+        Serial.println("Potential measuring error - CS5490 hardware reset required!");
+        measureErrorDetectionCounter--;
+        if(!measureErrorDetectionCounter)
+          resetRequired = true;
+      }
+    }
+    else
+    {
+      // Critical registes checksum error
+      Serial.println("Critical registes checksum error - CS5490 hardware reset required!");
+      Serial.print("regChk: ");
+      Serial.println(regChk, HEX);
+      Serial.print("CriticalRegisterChecksum: ");
+      Serial.println(CriticalRegisterChecksum, HEX);
+      resetRequired = true;
+    }
+
+  }
+  else
+  {
+   Serial.println("Communication error - no reply!");
+   communicationMaxRetries--;
+   if(!communicationMaxRetries)
+          resetRequired = true;
+  }
+
+  if(resetRequired)
+  {
+      resetRequired = false;
+      measureErrorDetectionCounter = 10;
+      communicationMaxRetries = 5;
+
+      line.resolve();
+      CS5490_SendConfiguration();
+
+      Serial.println("RESET PERFORMED");
+  }
+
+  Serial.println("");
+  delay(1000);
+  #endif
+}


basic valve stepper; new arrangement for debug prints to serial line

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -100,7 +100,7 @@
   float airHumid;
   uint16_t lux;
   float pH;
-  long waterLevel1;
+  long waterLevel1; // TODO should be an array
   long waterLevel2;
   long waterLevel3;
   // TODO add last reboot
@@ -114,6 +114,18 @@
 void postSensorData(monitor_t *monitorData);
 void printMonitorEntry(monitor_t m, String* buf);
 void formatMonitorEntry(monitor_t *m, String* buf, bool JSON);
+
+/////////////////////////////////////////////////////////////////////////////
+// misc utils ///////////////////////////////////////////////////////////////
+void ledOn();
+void ledOff();
+String ip2str(IPAddress address);
+#define dbg(b, s) if(b) Serial.print(s)
+#define dln(b, s) if(b) Serial.println(s)
+#define valveDBG true
+#define monitorDBG false
+#define netDBG false
+#define miscDBG false

 /////////////////////////////////////////////////////////////////////////////
 // temperature sensor stuff /////////////////////////////////////////////////
@@ -196,14 +208,15 @@
   char dryMins = 45;            // mins to leave bed drained per cycle
   // in beds with overflows can be 0; else will be cycle time minus fill time
   long startTime = -1;          // when to start cycling (after boot)
-  bool running = false;         // true when cycling started
   bool gotOverflow = false;     // does the growbed have an overflow?
   char fillLevel = 5;           // cms below the level sensor: drain point
+  bool filling = false;         // true when closed / on
+  long lastFlip = -1;           // millis at last state change

   Valve() { number = counter++; }
   void stateChange(bool newState) { // turn on or off
-    Serial.print("valve ");
-    Serial.print(number);
+    dbg(valveDBG, "valve ");
+    dbg(valveDBG, number);
     int pumpMcpPin = valvePinMap[number][0];
     int solenoidMcpPin = valvePinMap[number][1];

@@ -211,21 +224,33 @@
     if(newState == true){
       mcp.digitalWrite(pumpMcpPin, HIGH);
       mcp.digitalWrite(solenoidMcpPin, HIGH);
-      Serial.println(" on");
+      filling = true;
+      dln(valveDBG, " on");
     } else {
       mcp.digitalWrite(pumpMcpPin, LOW);
       mcp.digitalWrite(solenoidMcpPin, LOW);
-      Serial.println(" off");
-    }
+      filling = false;
+      dln(valveDBG, " off");
+    }
+
+    lastFlip = millis();
   }
   void on()  { stateChange(true); }  // fill time
   void off() { stateChange(false); } // drain time
-  void step(monitor_t* now) {        // check conditions and adjust state
-    if(! running) {
-      if(startTime >= millis())
-        running = true;
-      else
-        return;
+  void step(monitor_t* now, char cycleMins) { // check conditions and adjust
+    if(!filling && startTime >= millis()) {   // time to start filling
+      on();
+      startTime = startTime += (cycleMins * 60 * 1000);
+    }
+    if(full(now))                    // we're full
+      off();
+  }
+  int full(monitor_t *now) {
+    switch(number) {
+      case 1: return ( now->waterLevel1 <= fillLevel );
+      case 2: return ( now->waterLevel2 <= fillLevel );
+      case 3: return ( now->waterLevel3 <= fillLevel );
+      default: return -1;
     }
   }
 };
@@ -234,7 +259,7 @@
 class FlowController { // the set of valves and their config ////////////////
   public:
   int numValves = 3;            // WARNING! call init if resetting!
-  char cycleMins = 60;          // how long is a flood/drain cycle?
+  char cycleMins = 6;//TODO    // how long is a flood/drain cycle?
   char maxSimultDrainers = 1;   // how many beds can drain simultaneously?
   char minBedsWet = 1;          // min beds that are full or filling
   char maxBedsWet = 2;          // max beds that are full or filling
@@ -259,7 +284,7 @@
   }
   void step(monitor_t* now) {
     for(int i = 0; i < numValves; i++)
-      valves[i].step(now);
+      valves[i].step(now, cycleMins);
   }
 };
 FlowController flowController;
@@ -270,12 +295,6 @@
 void setCloudShare(boolean b);
 String getSvrAddr();
 void setSvrAddr(String s);
-
-/////////////////////////////////////////////////////////////////////////////
-// misc utils ///////////////////////////////////////////////////////////////
-void ledOn();
-void ledOff();
-String ip2str(IPAddress address);

 /////////////////////////////////////////////////////////////////////////////
 // setup ////////////////////////////////////////////////////////////////////
@@ -304,9 +323,9 @@

   // try and set the host name
   if(WiFi.hostname("waterelf"))
-    Serial.println("set hostname succeeded");
+    dln(netDBG, "set hostname succeeded");
   else
-    Serial.println("set hostname failed");
+    dln(netDBG, "set hostname failed");
   delay(300); blink(3);         // signal we've finished config
 }

@@ -345,12 +364,12 @@
   }

   if(loopCounter == TICK_WIFI_DEBUG) {
-    Serial.print("SSID: "); Serial.print(apSSID);
-    Serial.print("; IP address(es): local="); Serial.print(WiFi.localIP());
-    Serial.print("; AP="); Serial.println(WiFi.softAPIP());
+    dbg(netDBG, "SSID: "); dbg(netDBG, apSSID);
+    dbg(netDBG, "; IP address(es): local="); dbg(netDBG, WiFi.localIP());
+    dbg(netDBG, "; AP="); dln(netDBG, WiFi.softAPIP());
   }
   if(loopCounter == TICK_HEAP_DEBUG) {
-    Serial.print("free heap="); Serial.println(ESP.getFreeHeap());
+    dbg(miscDBG, "free heap="); dln(miscDBG, ESP.getFreeHeap());
   }

   if(loopCounter++ == LOOP_ROLLOVER) loopCounter = 0;
@@ -362,20 +381,20 @@
   WiFi.mode(WIFI_AP_STA);
   WiFi.softAPConfig(apIP, apIP, netMsk);
   WiFi.softAP(apSSID);
-  Serial.println("Soft AP started");
+  dln(netDBG, "Soft AP started");
 }
 void startDNS() {
   dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
   dnsServer.start(DNS_PORT, "*", apIP);
-  Serial.println("DNS server started");
+  dln(netDBG, "DNS server started");
 }
 void printIPs() {
-  Serial.print("AP SSID: ");
-  Serial.print(apSSID);
-  Serial.print("; IP address(es): local=");
-  Serial.print(WiFi.localIP());
-  Serial.print("; AP=");
-  Serial.println(WiFi.softAPIP());
+  dbg(netDBG, "AP SSID: ");
+  dbg(netDBG, apSSID);
+  dbg(netDBG, "; IP address(es): local=");
+  dbg(netDBG, WiFi.localIP());
+  dbg(netDBG, "; AP=");
+  dln(netDBG, WiFi.softAPIP());
 }
 void startWebServer() {
   webServer.on("/", handle_root);
@@ -395,16 +414,16 @@
   webServer.on("/valve2", handle_valve2);
   webServer.on("/valve3", handle_valve3);
   webServer.begin();
-  Serial.println("HTTP server started");
+  dln(netDBG, "HTTP server started");
 }
 void handleNotFound() {
-  Serial.print("URI Not Found: ");
-  Serial.println(webServer.uri());
+  dbg(netDBG, "URI Not Found: ");
+  dln(netDBG, webServer.uri());
   // TODO send redirect to /? or just use handle_root?
   webServer.send(200, "text/plain", "URI Not Found");
 }
 void handle_root() {
-  Serial.println("serving page notionally at /");
+  dln(netDBG, "serving page notionally at /");
   String toSend = pageTop;
   toSend += pageTop2;
   toSend += pageDefault;
@@ -412,7 +431,7 @@
   webServer.send(200, "text/html", toSend);
 }
 void handle_data() {
-  Serial.println("serving page at /data");
+  dln(netDBG, "serving page at /data");
   String toSend = pageTop;
   toSend += ": Sensor Data";
   toSend += pageTop2;
@@ -444,24 +463,24 @@
   const char *checked = " checked";

   int n = WiFi.scanNetworks();
-  Serial.print("scan done: ");
+  dbg(netDBG, "scan done: ");
   if(n == 0) {
-    Serial.println("no networks found");
+    dln(netDBG, "no networks found");
     f += "No wifi access points found :-( ";
     f += "Back
Try again?
\n";
   } else {
-    Serial.print(n);
-    Serial.println(" networks found");
+    dbg(netDBG, n);
+    dln(netDBG, " networks found");
     f += "<form method='POST' action='wfchz'> ";
     for(int i = 0; i < n; ++i) {
       // print SSID and RSSI for each network found
-      Serial.print(i + 1);
-      Serial.print(": ");
-      Serial.print(WiFi.SSID(i));
-      Serial.print(" (");
-      Serial.print(WiFi.RSSI(i));
-      Serial.print(")");
-      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
+      dbg(netDBG, i + 1);
+      dbg(netDBG, ": ");
+      dbg(netDBG, WiFi.SSID(i));
+      dbg(netDBG, " (");
+      dbg(netDBG, WiFi.RSSI(i));
+      dbg(netDBG, ")");
+      dln(netDBG, (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");

       f.concat("<input type='radio' name='ssid' value='");
       f.concat(WiFi.SSID(i));
@@ -483,13 +502,13 @@
   return f;
 }
 void handle_wifi() {
-  Serial.println("serving page at /wifi");
+  dln(netDBG, "serving page at /wifi");
   String toSend = genAPForm();
   webServer.send(200, "text/html", toSend);
 }

 void handle_wifistatus() {
-  Serial.println("serving page at /wifistatus");
+  dln(netDBG, "serving page at /wifistatus");

   String toSend = pageTop;
   toSend += ": Wifi Status";
@@ -532,7 +551,7 @@
   webServer.send(200, "text/html", toSend);
 }
 void handle_wfchz() {
-  Serial.println("serving page at /wfchz");
+  dln(netDBG, "serving page at /wfchz");
   String toSend = pageTop;
   toSend += ": joining wifi network";
   toSend += pageTop2;
@@ -540,7 +559,7 @@
   String key = "";

   for(uint8_t i = 0; i < webServer.args(); i++ ) {
-    //Serial.println(" " + webServer.argName(i) + ": " + webServer.arg(i));
+    //dln(netDBG, " " + webServer.argName(i) + ": " + webServer.arg(i));
     if(webServer.argName(i) == "ssid")
       ssid = webServer.arg(i);
     else if(webServer.argName(i) == "key")
@@ -582,12 +601,12 @@
   return f;
 }
 void handle_serverconf() {
-  Serial.println("serving page at /serverconf");
+  dln(netDBG, "serving page at /serverconf");
   String toSend = genServerConfForm();
   webServer.send(200, "text/html", toSend);
 }
 void handle_svrchz() {
-  Serial.println("serving page at /svrchz");
+  dln(netDBG, "serving page at /svrchz");
   String toSend = pageTop;
   toSend += ": data sharing configured";
   toSend += pageTop2;
@@ -617,7 +636,7 @@
   webServer.send(200, "text/html", toSend);
 }
 void handle_actuate() {
-  Serial.println("serving page at /actuate");
+  dln(netDBG, "serving page at /actuate");
   String toSend = pageTop;
   toSend += ": Setting Actuator";
   toSend += pageTop2;
@@ -633,10 +652,10 @@
   // now we trigger the 433 transmitter
   if(newState == true){
     mySwitch.switchOn(RCSW_CHANNEL, RCSW_HEATER);
-    Serial.println("Actuator on");
+    dln(netDBG, "Actuator on");
   } else {
     mySwitch.switchOff(RCSW_CHANNEL, RCSW_HEATER);
-    Serial.println("Actuator off");
+    dln(netDBG, "Actuator off");
   }

   toSend += "
Actuator triggered
\n";
@@ -650,8 +669,8 @@
 void handle_valve2() { handle_valve(1); } // ...numbered from 1, but...
 void handle_valve3() { handle_valve(2); } // ...from 0 in the FlowController
 void handle_valve(int valveNum) {
-  Serial.print("serving page at /valve");
-  Serial.println(valveNum + 1);
+  dbg(valveDBG, "serving page at /valve");
+  dln(valveDBG, valveNum + 1);
   String toSend = pageTop;
   toSend += ": Setting Water Valve ";
   toSend += valveNum + 1;
@@ -679,7 +698,7 @@
 /////////////////////////////////////////////////////////////////////////////
 // sensor/actuator stuff ////////////////////////////////////////////////////
 void startPeripherals() {
-  Serial.println("\nstartPeripherals...");
+  dln(monitorDBG, "\nstartPeripherals...");
   mySwitch.enableTransmit(15);   // RC transmitter is connected to Pin 15

   tempSensor.begin();     // start the onewire temperature sensor
@@ -693,7 +712,7 @@
   float airHumid = dht.readHumidity();
   float airCelsius = dht.readTemperature();
   if (isnan(airHumid) || isnan(airCelsius)) {
-    Serial.println("failed to find humidity sensor");
+    dln(monitorDBG, "failed to find humidity sensor");
   } else {
     GOT_HUMID_SENSOR = true;
   }
@@ -734,11 +753,11 @@
   error = Wire.endTransmission();
   if(error==0){
     GOT_PH_SENSOR = true;
-    Serial.println("Found pH sensor");
+    dln(monitorDBG, "Found pH sensor");
   }
 }
 void postSensorData(monitor_t *monitorData) {
-  //Serial.println("\npostSensorData");
+  //dln(monitorDBG, "\npostSensorData");

   // create a JSON form
   String jsonBuf = "";
@@ -749,19 +768,19 @@
   envelope += jsonBuf.length();
   envelope += "\nConnection: close\n\n";
   envelope += jsonBuf;
-  //Serial.println(envelope);
+  //dln(monitorDBG, envelope);

   WiFiClient couchClient;
   if(couchClient.connect(svrAddr.c_str(), 5984)) {
-    Serial.print(svrAddr);
-    Serial.println(" - connected as couch server");
+    dbg(netDBG, svrAddr);
+    dln(monitorDBG, " - connected as couch server");
     couchClient.print(envelope);
   } else {
-    Serial.print(svrAddr);
-    Serial.println(" - no couch server");
-  }
-
-  Serial.println("");
+    dbg(netDBG, svrAddr);
+    dln(monitorDBG, " - no couch server");
+  }
+
+  dln(monitorDBG, "");
   return;
 }
 void formatMonitorEntry(monitor_t *m, String* buf, bool JSON) {
@@ -814,29 +833,29 @@
 void getTemperature(float* waterCelsius) {
   tempSensor.requestTemperatures(); // send command to get temperatures
   (*waterCelsius) = tempSensor.getTempC(tempAddr);
-  Serial.print("Water temp: ");
-  Serial.print(*waterCelsius);
-  Serial.println(" C, ");
+  dbg(monitorDBG, "Water temp: ");
+  dbg(monitorDBG, *waterCelsius);
+  dln(monitorDBG, " C, ");
   return;
 }
 void getHumidity(float* airCelsius, float* airHumid) {
   (*airCelsius) = dht.readTemperature();
   (*airHumid) = dht.readHumidity();
-  Serial.print("Air Temp: ");
-  Serial.print(*airCelsius);
-  Serial.print(" C, ");
-  Serial.print("Humidity: ");
-  Serial.print(*airHumid);
-  Serial.println(" %RH, ");
+  dbg(monitorDBG, "Air Temp: ");
+  dbg(monitorDBG, *airCelsius);
+  dbg(monitorDBG, " C, ");
+  dbg(monitorDBG, "Humidity: ");
+  dbg(monitorDBG, *airHumid);
+  dln(monitorDBG, " %RH, ");
   return;
 }
 void getLight(uint16_t* lux) {
   sensors_event_t event;
   tsl.getEvent(&event);
   (*lux) = event.light;
-  Serial.print("Light: ");
-  Serial.print(*lux);
-  Serial.println(" Lux");
+  dbg(monitorDBG, "Light: ");
+  dbg(monitorDBG, *lux);
+  dln(monitorDBG, " Lux");
   return;
 }
 void getPH(float* pH) {
@@ -857,9 +876,9 @@
   float milliVolts = (((float)adc_result/4096)*vRef)*1000;
   float temp = ((((vRef*(float)pH7Cal)/4096)*1000) - milliVolts) / opampGain;
   (*pH) = 7-(temp/pHStep);
-  Serial.print("pH: ");
-  Serial.print(*pH);
-  Serial.println(" pH");
+  dbg(monitorDBG, "pH: ");
+  dbg(monitorDBG, *pH);
+  dln(monitorDBG, " pH");
   return;
 }
 void getLevel(int echoPin, long* waterLevel) {
@@ -875,9 +894,9 @@

   (*waterLevel) = (duration/2) / 29.1;

-  Serial.print("Water Level: ");
-  Serial.print(*waterLevel);
-  Serial.println(" cm, ");
+  dbg(monitorDBG, "Water Level: ");
+  dbg(monitorDBG, *waterLevel);
+  dln(monitorDBG, " cm, ");
   return;
 }


have a maximum threshold to prevent current enable threshold from overflowing

--- short-circuit-limiter/short-circuit-limiter.ino
+++ short-circuit-limiter/short-circuit-limiter.ino
@@ -8,6 +8,7 @@
 #define DEFAULT_CURRENT_ENABLE_THRESHOLD 0.2
 #define CURRENT_THRESHOLD_STRIDE 0.01
 #define MIN_ENABLE_CURRENT_THRESHOLD 0.01
+#define MAX_ENABLE_CURRENT_THRESHOLD 10.00
 #define ADDRESS_STORE_CURRENT_ENABLE 0

 #define TEMP_MAX 85
@@ -517,7 +518,8 @@

   if(newThreshold != currentEnableThreshold
-    && newThreshold >= MIN_ENABLE_CURRENT_THRESHOLD){
+    && newThreshold >= MIN_ENABLE_CURRENT_THRESHOLD
+    && newThreshold <= MAX_ENABLE_CURRENT_THRESHOLD){

     currentEnableThreshold = newThreshold;
     EEPROM.put(ADDRESS_STORE_CURRENT_ENABLE, currentEnableThreshold);


Sketch can now turn on any combination of LEDs

This still uses a 2x2 matrix but can be expanded
to add more.
Right now, there is only one combination it can
turn on and it is hardcoded.

Signed-off-by: nisha <ba6353e519422079c5746796dcd035c620a84798@gmail.com>

--- sketch_blinkybracelet/sketch_blinkybracelet.ino
+++ sketch_blinkybracelet/sketch_blinkybracelet.ino
@@ -7,36 +7,66 @@
  * nishakumarx@gmail.com
  */

-// struct to store led pin high and pin low
+/*
+ * struct to store led pin high and pin low
+ */
 typedef struct{
   int pinHigh;
   int pinLow;
+  int pinHiImp; // we do this because we are charlieplexing
 } LED;

-// array of leds
-// This is assuming the LEDs look like this
-// 1 2
-// 3 4
-LED leds[4] = {{13, 11}, {13, 10}, {12, 11}, {12, 10}};
+/*
+ * Array of leds
+ * This is assuming the LEDs look like this
+ * 1 2
+ * 3 4
+ */
+LED leds[4] = {{9, 10, 11}, {10, 9, 11},
+               {10, 11, 9}, {11, 10, 9}};
+
+/*
+ * Reset all LEDs
+ * This means turn all pins into
+ * OUTPUT and bring them down to LOW
+ */
+void reset()
+{
+  pinMode(9, OUTPUT);
+  pinMode(10, OUTPUT);
+  pinMode(11, OUTPUT);
+  digitalWrite(9, LOW);
+  digitalWrite(10, LOW);
+  digitalWrite(11, LOW);
+}
+
+/*
+ * Turn on a list of LEDs
+ * We need to do a list because the LEDs
+ * are all tied together
+ */
+void turnOn(int indexArray[], int no)
+{
+  for (int i=0; i<no; i++)
+  {
+    int ledNo = indexArray[i]-1;
+    // set pinmode
+    pinMode(leds[ledNo].pinHigh, OUTPUT);
+    pinMode(leds[ledNo].pinLow, OUTPUT);
+    pinMode(leds[ledNo].pinHiImp, INPUT);
+    // turn it on
+    digitalWrite(leds[ledNo].pinLow, LOW);
+    digitalWrite(leds[ledNo].pinHigh, HIGH);
+    delay(1);
+  }
+}

 void setup() {
-  // initialize digital PWM pins
-  pinMode(13, OUTPUT);
-  pinMode(12, OUTPUT);
-  pinMode(11, OUTPUT);
-  pinMode(10, OUTPUT);
-
+  reset();
 }

 void loop() {
-  // This runs in a loop
-  for (int i=0; i<4; i++){
-    //bring the pinHigh high and the pinLow low
-    int pinHigh = leds[i].pinHigh;
-    int pinLow = leds[i].pinLow;
-    digitalWrite(pinHigh, HIGH);
-    digitalWrite(pinLow, LOW);
-    delay(1000);
-    digitalWrite(pinHigh, LOW);
-  }
+  // Turn on 1 and 4
+  int onLeds[] = {1, 4};
+  turnOn(onLeds, sizeof(onLeds));
 }


Fix to remove registered Scratch from other machine.

--- esp4scratch/esp4scratch.ino
+++ esp4scratch/esp4scratch.ino
@@ -140,12 +140,12 @@
             content += String(scratch_ip[0]) + '.' + String(scratch_ip[1]) + '.' + String(scratch_ip[2]) + '.' + String(scratch_ip[3]);
             content += "
";
         } else {
-            content += "
";
-            content += "Add New Scratch";
-            content += " | ";
-            content += "Remove Registered Scratch";
-            content += "
";
-        }
+        }
+        content += "
";
+        content += "Add New Scratch";
+        content += " | ";
+        content += "Remove Registered Scratch";
+        content += "
";
         content += "
Return to Top
";
         content += "
Registered:
";
         content += "
";
@@ -211,16 +211,16 @@
                 content += String(scratch_clients[i].ip[0]) + '.' + String(scratch_clients[i].ip[1]) + '.' + String(scratch_clients[i].ip[2]) + '.' + String(scratch_clients[i].ip[3]);
                 content += "";
                 content += "<input name='scratch_ip_0' maxlength=3 value='";
-                content += String(client_ip[0]);
+                content += String(scratch_clients[i].ip[0]);
                 content += "' type='hidden'>";
                 content += "<input name='scratch_ip_1' maxlength=3 value='";
-                content += String(client_ip[1]);
+                content += String(scratch_clients[i].ip[1]);
                 content += "' type='hidden'>";
                 content += "<input name='scratch_ip_2' maxlength=3 value='";
-                content += String(client_ip[2]);
+                content += String(scratch_clients[i].ip[2]);
                 content += "' type='hidden'>";
                 content += "<input name='scratch_ip_3' maxlength=3 value='";
-                content += String(client_ip[3]);
+                content += String(scratch_clients[i].ip[3]);
                 content += "' type='hidden'>";
                 content += " <input type='submit' value='remove'>";
                 content += "</form>
";


Add power control

Add power control

--- arduino/scetch/scetch.ino
+++ arduino/scetch/scetch.ino
@@ -1,11 +1,11 @@
-const byte powerPins[] = {53, 51, 49, 47, 45, 43, 41, 39};
+const byte adjPowerPin = 45;
 const byte latchPin = 37;
 const byte eePin = 35;
 const byte emPin = 33;
 const byte prrPin = 31;
 const byte buttonPin = A0;

-const byte powerLevel = 255;
+const byte powerLevel = 50;

 const byte auxToPowerMillis = 100;
 const byte powerToLatchMillis = 100;
@@ -21,15 +21,12 @@
 boolean inAfterStartState = true;

 void setup() {
-  for(byte i = 0; i < 8; i++) {
-    pinMode(powerPins[i], OUTPUT);
-  }
+  pinMode(adjPowerPin, OUTPUT);
   pinMode(latchPin, OUTPUT);
   pinMode(eePin, OUTPUT);
   pinMode(emPin, OUTPUT);
   pinMode(prrPin, OUTPUT);
   pinMode(buttonPin, INPUT);
-
   pinMode(ledPin, OUTPUT);
   Serial.begin(9600);
 }
@@ -75,7 +72,7 @@
 }

 void submitPower(byte lvl) {
-  for(byte i = 0; i < 8; i++) {
-    digitalWrite(powerPins[i], ((1 << i) & lvl) == (1 << i));
+  if (lvl >= 0 && lvl <= 100) {
+    analogWrite(adjPowerPin, map(lvl, 0, 100, 0, 200));
   }
 }


Deal with two interupts setting each other off

--- arduino/sender/sender.ino
+++ arduino/sender/sender.ino
@@ -43,13 +43,23 @@
 // Store the pir states on interupt.
 volatile byte flags = 0;

+volatile byte motionUp = 0;
+volatile byte motionDown = 0;
+
+volatile byte motion = 0;
+
+// Motion on either interupt
+void isrMotion() {
+  motion = 1;
+}
+
 // Interupt on PIR_UP_PIN
 void isrPirUp()
 {
   // Motion detected.
   bitSet(flags, F_UP);
   bitSet(flags, F_UP_STAT);
-
+  motionUp = 1;
   /*
   // Cannot detect both at once, so see if the other fired too.
   if (!bitRead(flags, F_DOWN_STAT)) {
@@ -67,6 +77,7 @@
   // Motion detected.
   bitSet(flags, F_DOWN);
   bitSet(flags, F_DOWN_STAT);
+  motionDown = 1;

   /*
   // Cannot detect both at once, so see if the other fired too.
@@ -184,9 +195,10 @@
     vw_set_tx_pin(RF_TX_PIN);
     vw_setup(2000);      // Bits per sec

-
-    attachInterrupt(0, isrPirUp, RISING);
-    attachInterrupt(1, isrPirDown, RISING);
+    // Been having issues with two interupt pins seemingly setting each other off.
+    // so both call the same isr and only one motion is used.
+    attachInterrupt(0, isrMotion, RISING);
+    attachInterrupt(1, isrMotion, RISING);

 }

@@ -194,30 +206,87 @@
 {
   sleepNow();

+  if (motion) {
+
+    if (digitalRead(PIR_DOWN_PIN) == HIGH) {
+      //digitalWrite(DEBUG_LED_MOTION, HIGH);
+
+      char buf[50];
+      sprintf(buf, "c=%lu,F_DOWN_STAT", count);
+      transmit(buf);
+
+      count++;
+    } else if (digitalRead(PIR_UP_PIN) == HIGH) {
+      //digitalWrite(DEBUG_LED_MOTION, HIGH);
+
+      char buf[50];
+      sprintf(buf, "c=%lu,F_UP_STAT", count);
+      transmit(buf);
+
+      count++;
+    }
+
+    // Motion delt with, reset to zero
+    motion = 0;
+  }
+
+  /*
+  if (motionUp) {
+    motionUp = 0;
+    char buf[50];
+    sprintf(buf, "c=%lu,F_UP_STAT", count);
+    transmit(buf);
+
+    count++;
+  }
+
+  if (motionDown) {
+    motionDown = 0;
+    char buf[50];
+    sprintf(buf, "c=%lu,F_DOWN_STAT", count);
+    transmit(buf);
+
+    count++;
+  }
+  */
+
+  /*
   // Movement detected
   if (bitRead(flags, F_UP_STAT)) {
     bitClear(flags, F_UP_STAT);
     bitClear(flags, F_UP);
-    digitalWrite(DEBUG_LED_MOTION, HIGH);
-
-    char buf[50];
-    sprintf(buf, "c=%lu,F_UP_STAT", count);
-    transmit(buf);
-
-    count++;
-
-  } else if (bitRead(flags, F_DOWN_STAT)) {
+
+    if (digitalRead(PIR_UP_PIN) == HIGH) {
+      //digitalWrite(DEBUG_LED_MOTION, HIGH);
+
+      char buf[50];
+      sprintf(buf, "c=%lu,F_UP_STAT", count);
+      transmit(buf);
+
+      count++;
+    }
+
+
+
+  }
+
+  if (bitRead(flags, F_DOWN_STAT)) {
     bitClear(flags, F_DOWN_STAT);
     bitClear(flags, F_DOWN);
-    digitalWrite(DEBUG_LED_MOTION, HIGH);
-
-    char buf[50];
-    sprintf(buf, "c=%lu,F_DOWN_STAT", count);
-    transmit(buf);
-
-    count++;
-
-  }
+
+    if (digitalRead(PIR_DOWN_PIN) == HIGH) {
+      //digitalWrite(DEBUG_LED_MOTION, HIGH);
+
+      char buf[50];
+      sprintf(buf, "c=%lu,F_DOWN_STAT", count);
+      transmit(buf);
+
+      count++;
+    }
+
+
+  }
+  */

 }


Add analog example to BaconDemo

Add analog example to BaconDemo

The slider value is read and displayed on the console

--- arduino-makefile/examples/BaconDemo/BaconDemo.ino
+++ arduino-makefile/examples/BaconDemo/BaconDemo.ino
@@ -5,7 +5,7 @@
 //  Push Button Connected to P8_19, Digital Pin 7

 int pushButton = 7;
-
+int sliderPot  = 20;
 void setup() {
   // initialise digital pins as inputs
   pinMode(pushButton, INPUT);
@@ -15,8 +15,10 @@
 void loop() {
   // read the input pin:
   int buttonState = digitalRead(pushButton);
+  int sliderState = analogRead(sliderPot);
+
   // print out the state of the button:
-  printf("%d\n", buttonState);
+  printf("Button State:%d Slider State:%d\n", buttonState, sliderState);
   delay(10);        // delay in between reads for stability
 }


working communication for atmel

working communication for atmel

--- rov/sensors/axuillarymicros/current/current.ino
+++ rov/sensors/axuillarymicros/current/current.ino
@@ -5,50 +5,47 @@

 //define pin connections

-#define CS_PIN1 7
-#define CS_PIN2 8
-#define CS_PIN3 12
-#define CS_PIN4 13
+#define CS_PIN1 14
+#define CS_PIN2 14
+#define CS_PIN3 14
+#define CS_PIN4 14
 //consider using ICSP instead of these pins

-#define CLOCK_PIN 9
-#define MOSI_PIN 11
-#define MISO_PIN 10
+#define CLOCK_PIN 17
+#define MOSI_PIN 15
+#define MISO_PIN 16

 MCP3008 adc1(CLOCK_PIN, MOSI_PIN, MISO_PIN, CS_PIN1);
 MCP3008 adc2(CLOCK_PIN, MOSI_PIN, MISO_PIN, CS_PIN2);
-MCP3008 adc3(CLOCK_PIN, MOSI_PIN, MISO_PIN, CS_PIN3);
-MCP3008 adc4(CLOCK_PIN, MOSI_PIN, MISO_PIN, CS_PIN4);
-
+int currentdata[16];
+int idx = 0;
+int off = 0;
 void setup() {
   // put your setup code here, to run once:
-  Wire.begin(0x76);
+  Wire.begin(0x2B);
   Wire.onRequest(writeData);
 }

 void loop() {
-
+    for (int i=0; i < 8; i++) {
+    int val1 = adc1.readADC(i);
+    //val1 = off + i;
+    currentdata[i] = val1;
+  }
+
+/*  for (int i = 0; i < 8; i++) {
+    int val2 = adc2.readADC(i);
+    val2 = off + i + 8;
+    currentdata[i+8] = val2;
+  }*/
 }

 void writeData() {
-  for (int i=0; i < 8; i++) {
-    int val1 = adc1.readADC(i);
-    Wire.write(val1);
-  }
-
-  for (int i = 0; i < 8; i++) {
-    int val2 = adc2.readADC(i);
-    Wire.write(val2);
-  }
-
-  for (int i = 0; i < 8; i++) {
-    int val3 = adc3.readADC(i);
-    Wire.write(val3);
-  }
-
-  for (int i = 0; i < 8; i++) {
-    int val4 = adc4.readADC(i);
-    Wire.write(val4);
-  }
+      Wire.write(currentdata[idx]);
+      ++idx;
+      if(idx>=16){
+        idx = 0;
+      }
+      off++;
 }


Update Kochen.ino

Update Kochen.ino

Timer ":" animiert