Here is the version of code I had working before the deep update:-
//MONITOR-REV5.0
// This #include statement was automatically added by the Spark IDE.
#include "flashee-eeprom/flashee-eeprom.h"
using namespace Flashee;
#include "application.h"
#include "spark_disable_wlan.h"
#include "spark_disable_cloud.h"
#define tempPin A0
#define batPin A1
#define solarmAPin A2
#define loadmAPin A3
#define latchAPin D0
#define latchBPin D1
#define batAorBPin D2
static uint16_t tableindex;
static short mVA = 0;
static short mVB = 0;
static short loadmA = 0;
static short solarmA = 0;
int Latch(String command);
int CheckTime();
void GetData();
void Table();
void ReadBat();
void TCPClientCall();
void netinfo();
static float zoneoffset = 2; // Sets time offset to UTC
static int sleepflag = 1;
int year;
int month;
int date;
int hours;
int mins;
int secs;
unsigned long datetimestamp; // unsigned 32 bit number in format YYMMDDhhmm so limited to year 2042 without increasing bytes
static const int MINUTE_MILLIS = 60 * 1000; // 1 minute milliseconds count
static const int HOUR_MILLIS = 60*30*1000; // 1 hour milliseconds count
static const int DATA_BLOCK_SIZE = 60;
static const int MAX_DATA_BLOCK = 2000;
float tempC;
static const float tempoffset = 0; // Offset correction for temp sensor location and intrinsic error
static const short mVoffset = 60; // Correction for voltage loss between battery terminal and pcb regulator
static const float mAmVfactor =0.62; //Correction for load mA
static const float Vfactor = 1.61; // factor to account for reading through potential divider
static const float mAfactor = 2; //load mamp current proportional to mvolts across load resistor 0.5 ohms
static const float loagain = 1.2; // load op amp correction for current multiplier
static const float loaoffset = -0.088;
static const float soagain = 4.412; //solar op amp correction for current multiplier
static const float soabiasfactor =0.18; //diif amplifier bias to reduce supply voltage measure
static const float soaoffset = -9; // mA offset with night or panel disconnected
//char table_data[MAX_DATA_BLOCK*DATA_BLOCK_SIZE];
char NVdata[DATA_BLOCK_SIZE];
char Coredata[52] = "awaiting MAC, SN, Build, Version";
char Battdata[DATA_BLOCK_SIZE] = {"Wait a minute!"};
TCPServer server(8002);
FlashDevice* flash;
void setup()
{
WiFi.on();
while(WiFi.status() != WIFI_ON)
SPARK_WLAN_Loop(); // run backgound task so wifi can turn off
Spark.connect();
delay(1000);
// flash = Devices::createAddressErase(); // Set up extenal EEPROM for data logging etc.
flash = Devices::createWearLevelErase();
uint8_t valid = EEPROM.read(20);
if(valid == 82) // ASCII for 'R' you can read a valid table address
tableindex = EEPROM.read(21) + (256*EEPROM.read(22));
else
{
tableindex = 0;
EEPROM.write(21,0);
EEPROM.write(22,0);
EEPROM.write(20,82); //table index now ok to read
}
// valid = EEPROM.read(3);
// if(valid == 82) // ASCII for 'R' you can read valid calibration data
// {
// tempoffset = EEPROM.read(4);
// tempoffset += EEPROM.read(5)/100;
// }
// else
// {
// tempoffset = 0.0;
// EEPROM.write(4,0);
// EEPROM.write(5,0);
// EEPROM.write(3,82); //Calibration OK to read
// }
delay(200);
// for(int i = 0; i <MAX_DATA_BLOCK; i++)
// {
// flash->writeString(Battdata,i*DATA_BLOCK_SIZE);
// delay(2);
// }
Time.zone(zoneoffset); // Set timezone for Core location
Spark.function("Latch", Latch ); // 100ms square wave to latch switch
Spark.variable("Battery",Battdata, STRING); // Returns Centigrade from TMP36 device
server.begin();
Serial.begin(9600);
delay(100);
pinMode(tempPin, INPUT); //analog input tied to 3.3v reference 12 bit adc ( giving approx 0.8mV per unit)
pinMode(batPin, INPUT); //analog input tied to 3.3v reference 12 bit adc ( giving approx 0.8mV per unit)
pinMode(loadmAPin, INPUT); //analog input tied to 3.3v reference 12 bit adc ( giving approx 0.8mV per unit)
pinMode(solarmAPin, INPUT); //analog input tied to 3.3v reference 12 bit adc ( giving approx 0.8mV per unit)
pinMode(batAorBPin, INPUT); // digital input true if above 3v threshold
pinMode(latchAPin, OUTPUT); // digital output for pulse on latch reset
pinMode(latchBPin, OUTPUT); // digital output for pulse on latch set
Spark.syncTime();
delay(1000);
year = Time.year();
month = Time.month();
date = Time.day();
hours = Time.hour();
mins = Time.minute();
secs = Time.second();
Coreinfo(); // Called once to get local connection data
}
void loop()
{
//int x = 0;
// if(IWDG_SYSTEM_RESET == 1)
// x = 1;
static int lastdata = millis();
if(CheckTime() == 1) // Update time and check to see if new hour
{
GetData();
Table();
}
if (millis() - lastdata > 2*MINUTE_MILLIS) // every minute
{
if (!Spark.connected())
Spark.connect();
else
Spark.disconnect();
GetData(); // Read analog and digitalinputs
lastdata = millis();
}
TCPClientCall();
}
// Checks to see if it is a new hour and
int CheckTime()
{
hours = Time.hour();
mins = Time.minute();
secs = Time.second();
static int lasthour;
if(mins == 0) // ensure once per hour
{
if((hours == 0 || hours ==12) && sleepflag == 1) // ensure once at midnight and midday
{
Spark.syncTime();
year = Time.year();
month = Time.month();
date = Time.day();
//Spark.disconnect();
WiFi.off();
sleepflag = 0;
}
else if (hours == 8 || hours == 20) // ensure once at midday
{
WiFi.on(); // Wake up!!
while(WiFi.status() != WIFI_ON)
SPARK_WLAN_Loop(); // run backgound task so wifi can turn off
Spark.connect();
delay(1000);
sleepflag = 1;
}
if(lasthour != hours )
{
lasthour = hours;
return 1;
}
else
return -1;;
}
else return -1;
}
// This function to read data from inputs
void GetData()
{
float tempread;
float tempvolts;
static short solarmApoint[5];
static int i;
short tempmA = 0;
int j;
tempread = analogRead(tempPin);
tempvolts = tempread* 3.3; // Reference voltage supplied by Spark Core
tempvolts /= 4096; // Approx 8mV per integer unit
tempC = (tempvolts - 0.5)*100; // TMP36 gives 10mV per C with 500mV offset at 0C
tempC += tempoffset; // temperature correction for sensor location and intrinsic error
delay(300); // Delay to compensate for ADC sampling rate
tempread = analogRead(loadmAPin);
tempvolts = tempread*3.3; // Reference voltage supplied by Spark Core
tempvolts /= 4096; // Approx 8mV per integer unit
tempvolts = tempvolts*loagain; // Converting mvolts to amps through resistor
tempvolts += loaoffset;
tempvolts *= mAfactor;
loadmA = (1000 * tempvolts) + 0.5; //Conversion and rounding of positive amps to milliamps
delay(300); //Delay to compensate for ADC sampling rate
tempread = analogRead(solarmAPin);
tempvolts = tempread*3.3; // Reference voltage supplied by Spark Core
tempvolts /= 4096; // Approx 8mV per integer unit
if (mVB == 0)
tempvolts -= (mVA*soabiasfactor/1000); // Allowance for reference offset due to 17k resistor etc.
else
tempvolts -= ((mVA+mVB)*soabiasfactor/1000); // Battery B connected then refrence voltage double to about 13v
tempvolts = - tempvolts;
tempvolts = tempvolts*soagain; // converting mvolts to mamps
tempvolts *= mAfactor;
tempmA = (1000 * tempvolts) + soaoffset+0.5; //conversion and rounding of positive amps to milliamps and offset correction
if (tempmA < 0)
tempmA = 0;
if(i>=0 && i <4)
i++;
else
i = 0;
solarmApoint[i] = tempmA;
tempmA = 0; // initialise to zero before calculating moving average
for(j = 0; j <=4; j++) // moving average of 5 points
tempmA += solarmApoint[j];
solarmA = tempmA/5;
delay(300); //Delay to compensate for ADC sampling rate
ReadBat(); // Read which battery is connected and get its voltage
datetimestamp = ((year-2000)*100000000) + (month*1000000) + (date*10000) + (hours*100) + mins;
sprintf(Battdata,"%10lu,%.1fC,A: %4dmV,B: %4dmV,L: %4dmA,S: %4dmA",datetimestamp,tempC,mVA,mVB,loadmA,solarmA);
Battdata[59] = '\0'; // ensure no corruption when wake up from WiFi off.
}
// This function to write data to two dimensional array with datetimstamp
void Table()
{
EEPROM.write(1,tableindex%256); // store current tableindex every hour
EEPROM.write(2,tableindex/256);
delay(50);
flash->writeString(Battdata,tableindex*DATA_BLOCK_SIZE);
delay(50);
if(tableindex < (MAX_DATA_BLOCK-1)) // barrel log resets to the beginning
tableindex++;
else
tableindex = 0;
}
void ReadBat()
{
float tempread;
float tempvolts;
tempread = analogRead(batPin);
tempvolts = tempread*3.3; // Reference voltage supplied by Spark Core
tempvolts /= 4096; // Approx 8mV per integer unit
tempvolts = Vfactor*tempvolts*(tempvolts - 1); // Voltage increased by factor of potential divider
tempvolts = (1000 * tempvolts) +mVoffset + (mAmVfactor*loadmA) +0.5; //conversion and rounding of positive volts to millivolts
if (digitalRead(batAorBPin) == LOW)
mVA = tempvolts;
else
mVB = tempvolts;
}
int Latch(String command) // Allows devices to be turned on or off through 1A latch relay
{
if(command == "ON")
{
digitalWrite(latchAPin, LOW); // ensure digital otput is low before pulse
digitalWrite (latchAPin, HIGH);
delay(20); // 10ms square wave pulse low-high-low
digitalWrite(latchAPin, LOW);
return 1;
}
else if(command == "OFF")
{
digitalWrite(latchBPin, LOW); // ensure digital otput is low before pulse
digitalWrite (latchBPin, HIGH);
delay(20); // 10ms square wave pulse low-high-low
digitalWrite(latchBPin, LOW);
return 1;
}
else
return -1;
}
// Create client connection through DNS server
void TCPClientCall()
{
int tempindex;
char tempbuf[7];
int count = 1;
char nnbuf[20] = "-01 days";
int readbuf = 0;
// listen for incoming clients
TCPClient client = server.available();
if (client)
{
// Spark.disconnect();
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected())
{
if (client.available())
{
char c = client.read();
if ( c == '=' )
readbuf = 1;
else if (readbuf ==1 || readbuf == 2)
{
nnbuf[readbuf] = c;
if (c > '9')
readbuf =3;
else if (readbuf ==1)
count = (c - '0')*10;
else
count += c -'0';
readbuf++;
}
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank)
{
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print(Coredata);
client.println("<br />");
client.print(Battdata);
client.println("<br />");
client.println("<br />");
client.print("NV MEMORY DATA");
if (readbuf == 4)
client.println("-command error - value between 00 and 99 please");
else
client.print(nnbuf);
client.println("<br />");
sprintf(tempbuf,"I:%4d",tableindex);
client.println(tempbuf);
client.println("<br />");
for (int i = count*24; i > 0; i--)
{
tempindex = tableindex - i;
if(tempindex >=0)
{
// flash->read(NVdata,(tableindex-1)*60,60);
flash->read(NVdata,tempindex*DATA_BLOCK_SIZE,DATA_BLOCK_SIZE);
NVdata[59] = '\0'; //Ensure any sring corruption is restricted
client.print(NVdata);
client.println("<br />");
}
// else
// break;
}
client.println("</html>");
break;
}
if (c == '\n')
{
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r')
{
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// close the connection:
client.stop();
Serial.println("client disconnected");
client.flush();
// Spark.connect();
}
}
void Coreinfo() // Called in setup to pull netwok connection details
{ // One or more of function calls prevented WiFi.off/on and Spark.sleep from functioning when in main loop
char macstr[24];
byte mac[6];
Network.macAddress(mac); //get MAC address
sprintf (macstr,"MAC %2x:%2x:%2x:%2x:%2x:%2x,",mac[5],mac[4],mac[3],mac[2],mac[1],mac[0]);
// for (int i =0; i<12;i++)
// SerialID[i] = EEPROM.read(i);
// SerialID[12] = '\0';
// for (int i = 0; i < 6; i++)
// BuildDate[i] = EEPROM.read(i+12);
// BuildDate[6] = '\0';
// Version[0] = EEPROM.read(18);
// Version[1] = EEPROM.read(19);
// Version[2] = '\0';
sprintf(Coredata,"MAC:%s,SN0123456789,140722,5.1",macstr);
}