EcoRenovator  

Go Back   EcoRenovator > Improvements > Geothermal & Heat Pumps
Advanced Search
 


Blog Register 60+ Home Energy Saving Tips Recent Posts Search Today's Posts Mark Forums Read


Reply
 
Thread Tools Display Modes
Old 01-03-16, 03:25 PM   #21
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

7. DS18B20.ino - you will need to put in your own addresses for your sensors
#include <OneWire.h>
#include <DallasTemperature.h>

// Initialize OneWire
OneWire one_wire(DS18B20);
DallasTemperature sensors(&one_wire);

// OneWire Sensor addresses
//28 71 94 2B 06 00 00 2C
//28 81 15 31 04 00 00 34
DeviceAddress compressor = { 0x28, 0x71, 0x94, 0x2B, 0x6, 0x0, 0x0, 0x2C };
DeviceAddress evaporator = { 0x28, 0x81, 0x15, 0x31, 0x4, 0x0, 0x0, 0x34 };

NIL_THREAD(threadReadSensors, arg) {
while (TRUE) {
//Serial.println("Read DS18B20 sensors");
sensors.requestTemperatures();
tempCompressor = sensors.getTempC(compressor);
tempEvaporator = sensors.getTempC(evaporator);
//Serial.println(tempCompressor);
//Serial.println(tempEvaporator);
if (tempCompressor != lastTempCompressor) {
lastTempCompressor = tempCompressor;
}
if (tempEvaporator != lastTempEvaporator) {
lastTempEvaporator = tempEvaporator;
}
// Sleep for 10 seconds.
nilThdSleepSeconds(10);
}
}

Acuario is offline   Reply With Quote
Old 01-03-16, 03:25 PM   #22
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

8. DS1307.ino
#include <Time.h>
#include <DS1307RTC.h>

const char *monthName[12] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

uint64_t makeTimeMilli(tmElements_t tm) {
return ((uint64_t)makeTime(tm) * 1000);
}

void writeTime(tmElements_t tmw) {

// Configure the RTC
RTC.write(tmw);
}

void readTime() {

if (RTC.read(tm)) {
//Serial.print("Ok, Time = ");
//print2digits(tm.Hour);
//Serial.write(':');
//print2digits(tm.Minute);
//Serial.write(':');
//print2digits(tm.Second);
//Serial.print(", Date (D/M/Y) = ");
//Serial.print(tm.Day);
//Serial.write('/');
//Serial.print(tm.Month);
//Serial.write('/');
//Serial.print(tmYearToCalendar(tm.Year));
//Serial.println();
}
else {
if (RTC.chipPresent()) {
Serial.println("The DS1307 is stopped. Please run the SetTime");
Serial.println("example to initialize the time and begin running.");
Serial.println();
// get the date and time the compiler was run
if (getDate(__DATE__) && getTime(__TIME__)) {
// and configure the RTC with this info
RTC.write(tm);
}
}
else {
Serial.println("DS1307 read error! Please check the circuitry.");
Serial.println();
}
}
}


void print2digits(int number) {
if (number >= 0 && number < 10) {
Serial.write('0');
}
Serial.print(number);
}

bool getTime(const char *str)
{
int Hour, Min, Sec;

if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
tm.Hour = Hour;
tm.Minute = Min;
tm.Second = Sec;
return true;
}


bool getDate(const char *str)
{
char Month[12];
int Day, Year;
uint8_t monthIndex;

if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
for (monthIndex = 0; monthIndex < 12; monthIndex++) {
if (strcmp(Month, monthName[monthIndex]) == 0) break;
}
if (monthIndex >= 12) return false;
tm.Day = Day;
tm.Month = monthIndex + 1;
tm.Year = CalendarYrToTm(Year);
return true;
}
Acuario is offline   Reply With Quote
Old 01-03-16, 03:27 PM   #23
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

9. Ethernet.ino (part 1)
//For ethernet
#include <SPI.h>
#include <Ethernet.h>
#include "HeatpumpController.h"

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0x00, 0xAD, 0xBE, 0xEF, 0xFD, 0x13 };
byte ip[] = { 192, 168, 0, 190 }; // ip in lan (that's what you need to use in your browser.
byte gateway[] = { 192, 168, 0, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
#define ETHPORT 8081
EthernetServer server(ETHPORT); // Initialize the Ethernet server library

void returnSetupPage(EthernetClient cl, bool save);
void saveSettings(char * buf);
void returnWebPage(EthernetClient cl);
void XML_response(EthernetClient cl);
void StrClear(char *str, char length);
char StrContains(char *str, char *sfind);

void setupEthernet(void) {
Ethernet.begin(mac, ip);
server.begin();

DEBUG_PRINT("server is at ");
DEBUG_PRINTLN(Ethernet.localIP());
}

NIL_THREAD(threadEthernet, arg) { // listen for incoming clients
#define REQ_BUF_SZ 120 // size of buffer used to capture HTTP requests
char HTTP_req[REQ_BUF_SZ] = { 0 }; // buffered HTTP request stored as null terminated string
char req_index = 0; // index into HTTP_req buffer

while (TRUE) {
EthernetClient client = server.available(); // try to get client

if (client) { // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client buffer first part of HTTP request in HTTP_req array (string)
// leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
if (req_index < (REQ_BUF_SZ - 1)) {
HTTP_req[req_index] = c; // save HTTP request character
req_index++;
}
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
// display received HTTP request on serial port
//DEBUG_PRINTST("Received HTTP:-%s", HTTP_req);

// send a standard http response header
client.println("HTTP/1.1 200 OK");
// remainder of header follows below, depending on if web page or XML page is requested
// Ajax request - send XML file
if (StrContains(HTTP_req, "ajax_inputs")) {
// send rest of HTTP header
client.println("Content-Type: text/xml");
client.println("Connection: keep-alive");
client.println();
// send XML file containing input states
XML_response(client);
}
else if (StrContains(HTTP_req, "setup")) {
returnSetupPage(client, FALSE);
}
else if (StrContains(HTTP_req, "savesettings")) {
saveSettings(HTTP_req);
returnSetupPage(client, TRUE);
}
else if (StrContains(HTTP_req, "settime")) {
setTime(HTTP_req);
returnSetupPage(client, TRUE);
}
else if (StrContains(HTTP_req, "defrostOn")) {
Serial.println("START defrost forced");
defrostFlag = TRUE;
returnSetupPage(client, FALSE);
}
else if (StrContains(HTTP_req, "defrostOff")) {
Serial.println("STOP defrost forced");
defrostFlag = FALSE;
returnSetupPage(client, FALSE);
}
else { // web page request send rest of HTTP header
returnWebPage(client);
}
// reset buffer index and all buffer elements to 0
req_index = 0;
StrClear(HTTP_req, REQ_BUF_SZ);
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
nilThdSleepSeconds(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)

// Sleep
nilThdSleepSeconds(10);
}
}
Acuario is offline   Reply With Quote
Old 01-03-16, 03:29 PM   #24
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

10. Ethernet.ino (part 2)
//Save settings received from web page
//GET /savesettings?defTime=5&defTemp=-2 HTTP/1.1
void saveSettings(char * buf) {
char str1[150];
char *s = str1, *t = NULL;
char sbuf[50];
char keyname[10];
int val;
bool res;

str1[0] = '\0';
const char *start = strchr(buf, '?') + 1;
strncat(str1, start, strcspn(start, " "));
DEBUG_PRINTST("Extracted %s\n", str1);

while ((t = strtok(s, "&")) != NULL) {
s = NULL;
sprintf(sbuf, "%s", t);

sscanf(sbuf, "%32[^=]=%d", keyname, &val);
SerialPrint2("Name=%s, value=%d\n", keyname, val);

//Running time of defrost cycle
if (StrContains(keyname, "defTime")) {
if (defTime != val)
EEPROM_write_byte(DEFROSTTIME, val);
defTime = val;
}

//Temperature of condensor to start defrost cycle
else if (StrContains(keyname, "defStartT")) {
if (defTemp != val)
EEPROM_write_byte(DEFROSTTEMP, val + DEFROST_OFFSET);
defTemp = val;
}
else if (StrContains(keyname, "hys")) {
if (hysterisis != val)
EEPROM_write_byte(HYSTERISIS, val);
hysterisis = val;
}

//Temperature to stop defrost. Overrides timer
else if (StrContains(keyname, "defStopT")) {
if (defUpperTemp != val)
EEPROM_write_byte(DEFROSTMAXTEMP, val);
defUpperTemp = val;
}

//Desired room temperature
else if (StrContains(keyname, "roomTemp")) {
if (desiredRoomTemp != val)
{
res = sendBAC1000Command(TEMPSETTING, 0, 1, 0, 0, val * 2, 0);
bacSetTemp = val;
desiredRoomTemp = val;
EEPROM_write_byte(DESIREDROOMTEMP, desiredRoomTemp);
}
}

//Maximum water temperature
else if (StrContains(keyname, "waterTemp")) {
if (maxWaterTemp != val)
EEPROM_write_byte(MAXWATERTEMP, val);
maxWaterTemp = val;
}

//Min time between defrost cycles
else if (StrContains(keyname, "defCycle")) {
if (timeBetweenDefrost != val)
EEPROM_write_byte(TIMEBETWEENDEFROST, val);
timeBetweenDefrost = val;
}

//System power state - on or off
else if (StrContains(keyname, "sysState")) {
if (operatingState != val)
{
res = sendBAC1000Command(POWERONOFF, 0, 1, (val << 4), 0, 0, 0);
operatingState = val;
powerStateBAC = val;
EEPROM_write_byte(LASTSYSTEMSTATE, operatingState);
}
}

//System operating mode heat/cool
else if (StrContains(keyname, "sysMode")) {
if (operatingMode != val)
{
res = sendBAC1000Command(MODESETTING, 0, 1, (val << 5), 0, 0, 0);
operatingMode = val;
operatingModeBAC = val;
EEPROM_write_byte(LASTSYSTEMMODE, operatingState);
}
}
}
}

//Set RTC time
void setTime(char * buf) {
tmElements_t tm;
char str1[150];
char *s = str1, *t = NULL;
char sbuf[50];
char keyname[10];
int val;
bool res;

str1[0] = '\0';
const char *start = strchr(buf, '?') + 1;
strncat(str1, start, strcspn(start, " "));
DEBUG_PRINTST("Extracted %s\n", str1);

while ((t = strtok(s, "&")) != NULL) {
s = NULL;
sprintf(sbuf, "%s", t);

sscanf(sbuf, "%32[^=]=%d", keyname, &val);
DEBUG_PRINTST("Name=%s, value=%d\n", keyname, val);

if (StrContains(keyname, "hour")) {
tm.Hour = val;
}
else if (StrContains(keyname, "minute")) {
tm.Minute = val;
}
else if (StrContains(keyname, "day")) {
tm.Day = val;
}
else if (StrContains(keyname, "month")) {
tm.Month = val;
}
else if (StrContains(keyname, "year")) {
tm.Year = val;
}
RTC.write(tm);
}
}

void returnSetupPage(EthernetClient cl, bool save) {
DEBUG_PRINTLN("Setup page");

// send a standard http response header
cl.println(F("Content-Type: text/html"));
cl.println(F("Connection: close")); // the connection will be closed after completion of the response
cl.println();
cl.println(F("<!DOCTYPE HTML>"));
cl.println(F("<html>"));
cl.println(F("<!DOCTYPE HTML><html><head>"));
cl.println(F("<link rel='stylesheet' type='text/css' href='http://www.tortosaforum.com/heatpump/heatpumpcss.css' />"));
cl.println(F("<title>Heat pump - SETUP</title></head><body>"));

cl.println(F("<H1>Heat Pump Controller - SETUP</H1>"));
//cl.println(F("<form action='savesettings' method='post'><table border='1' width='50%'>"));
cl.println(F("<form action='savesettings'><table border='1' width='30%'>"));
cl.println(F("<tr><th>Setting</th><th>Value</th></tr>"));
cl.print(F("<tr><td>Defrost run time</td><td><input type='number' name='defTime' min='1' max='10' value='"));
cl.print(defTime);
cl.println(F("'></td></tr>"));
cl.print(F("<tr><td>Defrost start temperature</td><td><input type='number' name='defStartT' min='-15' max='5' value='"));
cl.print(defTemp);
cl.println(F("'></td></tr>"));
cl.print(F("<tr><td>Defrost stop temperature</td><td><input type='number' name='defStopT' min='0' max='15' value='"));
cl.print(defUpperTemp);
cl.println(F("'></td></tr>"));
cl.print(F("<tr><td>Time between defrost cycles</td><td><input type='number' name='defCycle' min='15' max='60' value='"));
cl.print(timeBetweenDefrost);
cl.println(F("'></td></tr>"));
cl.print(F("<tr><td>Max water temperature</td><td><input type='number' name='waterTemp' min='1' max='40' value='"));
cl.print(maxWaterTemp);
cl.println(F("'></td></tr>"));
cl.print(F("<tr><td>Hysterisis</td><td><input type='number' name='hys' min='1' max='15' value='"));
cl.print(hysterisis);
cl.println(F("'></td></tr>"));

cl.print(F("<tr><td>Desired room temperature</td><td><input type='number' name='roomTemp' min='1' max='40' value='"));
cl.print(bacSetTemp);
cl.println(F("'></td></tr>"));

cl.print(F("<tr><td>System state</td><td><input type='radio' name='sysState' value='1'"));
if (operatingState == TRUE)
cl.println(F(" checked>ON<input type='radio' name='sysState' value='0'>Off</td></tr>"));
else
cl.println(F(">On<input type='radio' name='sysState' value='0' checked>Off</td></tr>"));

cl.println(F("<tr><td>Mode</td><td><input type='radio' name='sysMode' value='0'"));
if (operatingModeBAC == 0)
cl.println(F(" checked>Cool<input type='radio' name='sysMode' value='1'>Heat</td></tr>"));
else
cl.println(F(">Cool<input type='radio' name='sysMode' value='1' checked>Heat</td></tr>"));
cl.println(F("</table><br><input type='submit' value='Save'></form>"));
cl.println(F("<BR><BR>"));

//Table to set time/date
cl.println(F("<form action='settime'><table border='1' width='30%'>"));
cl.println(F("<tr><th>Setting</th><th>Value</th></tr>"));
cl.print(F("<tr><td>Hour</td><td><input type='number' name='hour' id='hour' min='1' max='23'></td></tr>"));
cl.print(F("<tr><td>Minute</td><td><input type='number' name='minute' id='minute' min='1' max='59'></td></tr>"));
cl.print(F("<tr><td>Day</td><td><input type='number' name='day' id='day' min='1' max='31'></td></tr>"));
cl.print(F("<tr><td>Month</td><td><input type='number' name='month' id='month' min='1' max='12'></td></tr>"));
cl.print(F("<tr><td>Year</td><td><input type='number' name='year' id='year' min='2015' max='2030'></td></tr>"));
cl.println(F("</table><br><input type='submit' value='Set'></form>"));
cl.println(F("<BR><BR>"));
cl.println(F("<script>"));
cl.println(F("var d = new Date();"));
cl.println(F("document.getElementById('hour').valu e = d.getHours();"));
cl.println(F("document.getElementById('minute').va lue = d.getMinutes();"));
cl.println(F("document.getElementById('day').value = d.getDate();"));
cl.println(F("var month = d.getMonth() + 1;"));
cl.println(F("document.getElementById('month').val ue = month;"));
cl.println(F("document.getElementById('year').valu e = d.getFullYear();"));
cl.println(F("</script>"));

cl.println(F("<a href=\"/?defrostOn\"\">Start Defrost</a>"));
cl.println(F("<a href=\"/?defrostOff\"\">Stop Defrost</a>"));

if (save == TRUE)
cl.println(F("<script>alert('Settings saved');</script>"));
if(defrostFlag == TRUE)
cl.println(F("<p>Defrost running..</p>"));
else
cl.println(F("<p>Defrost not running..</p>"));
cl.println(F("</body></html>"));
}
Acuario is offline   Reply With Quote
Old 01-03-16, 03:30 PM   #25
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

11. Ethernet.ino (part 3)
//Return initial web page - then updated by AJAX XML
void returnWebPage(EthernetClient cl) {

cl.println(F("Content-Type: text/html"));
cl.println(F("Connection: keep-alive"));
cl.println();
cl.println(F("<!DOCTYPE html>"));
cl.println(F("<html><head>"));
cl.println(F("<link rel='stylesheet' type='text/css' href='http://www.tortosaforum.com/heatpump/heatpumpcss.css' />"));
cl.println(F("<title>Heat Pump Controller status</title>"));
cl.println(F("<script>"));
cl.println(F("function GetArduinoInputs(){"));
cl.println(F("nocache = '&nocache=' + Math.random() * 1000000;"));
cl.println(F("var request = new XMLHttpRequest();"));
cl.println(F("request.onreadystatechange = function(){"));
cl.println(F("if (this.readyState == 4) {"));
cl.println(F("if (this.status == 200) {"));
cl.println(F("if (this.responseXML != null) {"));

cl.println(F("document.getElementById('roomTemp'). innerHTML=this.responseXML.getElementsByTagName('r oomTemp')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('bacSetTemp' ).innerHTML=this.responseXML.getElementsByTagName( 'bacSetTemp')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('compressor' ).innerHTML=this.responseXML.getElementsByTagName( 'compressor')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('evaporator' ).innerHTML=this.responseXML.getElementsByTagName( 'evaporator')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('flow').inne rHTML=this.responseXML.getElementsByTagName('flow' )[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('return').in nerHTML=this.responseXML.getElementsByTagName('ret urn')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('humidity'). innerHTML=this.responseXML.getElementsByTagName('h umidity')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('dewpoint'). innerHTML=this.responseXML.getElementsByTagName('d ewpoint')[0].childNodes[0].nodeValue;"));

cl.println(F("document.getElementById('bacMode').i nnerHTML=this.responseXML.getElementsByTagName('ba cMode')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('bacPowerSta te').innerHTML=this.responseXML.getElementsByTagNa me('bacPowerState')[0].childNodes[0].nodeValue;"));

cl.println(F("document.getElementById('defrost').i nnerHTML=this.responseXML.getElementsByTagName('de frost')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('systemTime' ).innerHTML=this.responseXML.getElementsByTagName( 'systemTime')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('defrostStep ').innerHTML=this.responseXML.getElementsByTagName ('defrostStep')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('hysterisis' ).innerHTML=this.responseXML.getElementsByTagName( 'hysterisis')[0].childNodes[0].nodeValue;"));

cl.println(F("document.getElementById('compStat'). innerHTML=this.responseXML.getElementsByTagName('c ompStat')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('fanLow').in nerHTML=this.responseXML.getElementsByTagName('fan Low')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('fanHigh').i nnerHTML=this.responseXML.getElementsByTagName('fa nHigh')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('valve').inn erHTML=this.responseXML.getElementsByTagName('valv e')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('pump').inne rHTML=this.responseXML.getElementsByTagName('pump' )[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('state').inn erHTML=this.responseXML.getElementsByTagName('stat e')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('maxWaterTem p').innerHTML=this.responseXML.getElementsByTagNam e('maxWaterTemp')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('ambient').i nnerHTML=this.responseXML.getElementsByTagName('am bient')[0].childNodes[0].nodeValue;"));
cl.println(F("document.getElementById('s4').innerH TML=this.responseXML.getElementsByTagName('s4')[0].childNodes[0].nodeValue;"));

cl.println(F("}}}}"));
cl.println(F("request.open('GET', 'ajax_inputs' + nocache, true);"));
cl.println(F("request.send(null);"));
cl.println(F("setTimeout('GetArduinoInputs()', 5000);}"));
cl.println(F("</script></head>"));
cl.println(F("<body onload='GetArduinoInputs()'>"));
cl.println(F("<h1>Heat Pump Controller status</h1>"));

//////////////////////////////////////////////////////////////////////////////////////////////
cl.println(F("<table border = '1' width = '30%'>"));
cl.println(F("<tr><th>Parameter</th><th>Reading</th><th>Setting</th></tr>"));
cl.print(F("<tr><td>Room temperature</td><td><span id='roomTemp'>...</span></td><td><span id='bacSetTemp'>...</span></td></tr>"));
cl.print(F("<tr><td>Flow temperature</td><td><span id='flow'>...</span></td><td><span id='maxWaterTemp'>...</span></td></tr>"));
cl.print(F("<tr><td>Return temperature</td><td><span id='return'>...</span></td><td>&nbsp;</td></tr>"));
cl.print(F("<tr><td>Evaporator</td><td><span id='evaporator'>...</span></td><td>"));
cl.print(defTemp);
cl.print(F("</td></tr>"));
cl.print(F("<tr><td>Compressor</td><td><span id='compressor'>...</span></td><td>&nbsp;</td></tr>"));
cl.println(F("</table>"));

//////////////////////////////////////////////////////////////////////////////////////////////
cl.println(F("<table border = '1' width = '30%'>"));
cl.println(F("<tr><th>Relay</th><th>Status</th></tr>"));
cl.print(F("<tr><td>Compressor</td><td><span id='compStat'>...</span></td></tr>"));
cl.print(F("<tr><td>Fan low</td><td><span id='fanLow'>...</span></td></tr>"));
cl.print(F("<tr><td>Fan high</td><td><span id='fanHigh'>...</span></td></tr>"));
cl.print(F("<tr><td>3W valve</td><td><span id='valve'>...</span></td></tr>"));
cl.print(F("<tr><td>Circulating</td><td><span id='pump'>...</span></td></tr>"));
cl.println(F("</table>"));

cl.println(F("<p>State: <span id='state'>...</span></p>"));

cl.println(F("<p>Ambient: <span id='ambient'>...</span></p>"));
cl.println(F("<p>S4: <span id='s4'>...</span></p>"));
cl.println(F("<p>Humidity: <span id='humidity'>...</span></p>"));
cl.println(F("<p>Dew point: <span id='dewpoint'>...</span></p>"));
cl.println(F("<p>Hysterisis: <span id='hysterisis'>...</span></p>"));

cl.println(F("<p>BAC Mode: <span id='bacMode'>...</span></p>"));
cl.println(F("<p>BAC Power: <span id='bacPowerState'>...</span></p>"));
cl.println(F("<p>Defrost running: <span id='defrost'>...</span></p>"));
cl.println(F("<p>Defrost step: <span id='defrostStep'>...</span></p>"));
cl.println(F("<p></p><p>System time: <span id='systemTime'>...</span></p>"));
cl.println(F("</body></html>"));
}
Acuario is offline   Reply With Quote
Old 01-03-16, 03:30 PM   #26
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

12. Ethernet.ino (part 4)

// send the XML file with status
void XML_response(EthernetClient cl)
{
char buf[20];

cl.print(F("<?xml version = \"1.0\" ?>"));
cl.print(F("<inputs>"));
cl.print(F("<systemTime>"));
sprintf(buf, "%02d:%02d:%02d %02d/%02d", tm.Hour, tm.Minute, tm.Second, tm.Day, tm.Month);
cl.print(buf);
cl.print(F("</systemTime>"));
cl.print(F("<bacSetTemp>"));
cl.print(bacSetTemp);
cl.print(F("</bacSetTemp>"));
cl.print(F("<maxWaterTemp>"));
cl.print(maxWaterTemp);
cl.print(F("</maxWaterTemp>"));
cl.print(F("<roomTemp>"));
cl.print(bacRoomTemp);
cl.print(F("</roomTemp>"));
cl.print(F("<compressor>"));
cl.print(tempCompressor);
cl.print(F("</compressor>"));
cl.print(F("<flow>"));
cl.print(flowTemp);
cl.print(F("</flow>"));
cl.print(F("<return>"));
cl.print(returnTemp);
cl.print(F("</return>"));
cl.print(F("<evaporator>"));
cl.print(tempEvaporator);
cl.print(F("</evaporator>"));
cl.print(F("<humidity>"));
cl.print(humidity);
cl.print(F("</humidity>"));
cl.print(F("<dewpoint>"));
cl.print(dewPointTemp);
cl.print(F("</dewpoint>"));
cl.print(F("<bacPowerState>"));
sprintf(buf, "%s", powerStateBAC == FALSE ? sOff : sOn);
cl.print(buf);
cl.print(F("</bacPowerState>"));
cl.print(F("<bacMode>"));
sprintf(buf, "%s", mode[operatingModeBAC]);
cl.print(buf);
cl.print(F("</bacMode>"));
cl.print(F("<defrost>"));
sprintf(buf, "%s", defrostFlag == TRUE ? "YES" : "NO");
cl.print(buf);
cl.print(F("</defrost>"));

cl.print(F("<defrostStep>"));
cl.print(defStep);
cl.print(F("</defrostStep>"));
cl.print(F("<hysterisis>"));
cl.print(hysterisis);
cl.print(F("</hysterisis>"));
cl.print(F("<defCycle>"));
cl.print(timeBetweenDefrost);
cl.print(F("</defCycle>"));
cl.print(F("<state>"));
cl.print(systemState);
cl.print(F("</state>"));
cl.print(F("<ambient>"));
cl.print(ambientTemp);
cl.print(F("</ambient>"));
cl.print(F("<s4>"));
cl.print(ambientTemp);
cl.print(F("</s4>"));

cl.print(F("<compStat>"));
sprintf(buf, "%s", compStat == OFF ? sOff : sOn);
cl.print(buf);
cl.print(F("</compStat>"));
cl.print(F("<fanLow>"));
sprintf(buf, "%s", fanLow == OFF ? sOff : sOn);
cl.print(buf);
cl.print(F("</fanLow>"));
cl.print(F("<fanHigh>"));
sprintf(buf, "%s", fanHigh == OFF ? sOff : sOn);
cl.print(buf);
cl.print(F("</fanHigh>"));
cl.print(F("<valve>"));
sprintf(buf, "%s", valve == OFF ? sOff : sOn);
cl.print(buf);
cl.print(F("</valve>"));
cl.print(F("<pump>"));
sprintf(buf, "%s", pump == OFF ? sOff : sOn);
cl.print(buf);
cl.print(F("</pump>"));

cl.println(F("</inputs>"));
}


// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
for (int i = 0; i < length; i++) {
str[i] = 0;
}
}

// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
char found = 0;
char index = 0;
char len;

len = strlen(str);

if (strlen(sfind) > len) {
return 0;
}
while (index < len) {
if (str[index] == sfind[found]) {
found++;
if (strlen(sfind) == found) {
return 1;
}
}
else {
found = 0;
}
index++;
}
return 0;
}
Acuario is offline   Reply With Quote
Old 01-03-16, 03:32 PM   #27
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

13. NTCThermistor.ino (still sort of in development/test)

///////////////////////////////////////////////////////////////////////////////////////////////////
// NTC Thermistor
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <math.h>




// enumerating 3 major temperature scales
enum {
T_KELVIN = 0,
T_CELSIUS,
T_FAHRENHEIT
};

// manufacturer data for episco k164 10k thermistor
// simply delete this if you don't need it
// or use this idea to define your own thermistors
#define EPISCO_K164_10k 4300.0f,298.15f,10000.0f // B,T0,R0
#define NTCRES 3380.0f,298.15f,10000.0f

NIL_THREAD(threadReadNTC, arg) {
while (TRUE) {

//while (readAnalog == TRUE) {
// nilThdSleepMilliseconds(100);
//}
for (int s = 2; s < 6; s++) {
ntcSensor[s - 2] = int(Thermistor(analogRead(s)));
nilThdSleepMilliseconds(200);
// DEBUG_PRINTST("Sensor %d: %d\n", s, ntcSensor[s - 2]);
}
//for (int s = 0; s < 4; s++) {
// ntcSensor[s] = int(Thermistor(analogRead(s)));
// //ntcSensor[s] = int(Temperature(s, T_CELSIUS, NTCRES, 9850));
// //ntcSensor[s] = thermNTC(s);
// //ntcSensor[s] = tempTable(s);
// nilThdSleepMilliseconds(200);
//}

// Sleep for 10 seconds.
nilThdSleepSeconds(10);
}
}

// resistance at 25 degrees C
#define THERMISTORNOMINAL 10000
// temp. for nominal resistance (almost always 25 C)
#define TEMPERATURENOMINAL 25
// how many samples to take and average, more takes longer but is more 'smooth'
#define NUMSAMPLES 5
// The beta coefficient of the thermistor (usually 3000-4000)
#define BCOEFFICIENT 3950
// the value of the 'other' resistor
#define SERIESRESISTOR 10500

int samples[NUMSAMPLES];

float thermNTC(int pin) {
uint8_t i;
float average;

// take N samples in a row, with a slight delay
for (i = 0; i < NUMSAMPLES; i++) {
samples[i] = analogRead(pin);
delay(10);
}

// average all the samples out
average = 0;
for (i = 0; i < NUMSAMPLES; i++) {
average += samples[i];
}
average /= NUMSAMPLES;
Serial.println(average);
// convert the value to resistance
average = 1023 / average - 1;
average = SERIESRESISTOR / average;

float steinhart;
steinhart = average / THERMISTORNOMINAL; // (R/Ro)
steinhart = log(steinhart); // ln(R/Ro)
steinhart /= BCOEFFICIENT; // 1/B * ln(R/Ro)
steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
steinhart = 1.0 / steinhart; // Invert
steinhart -= 273.15; // convert to C
return(steinhart);
}


// Temperature function outputs float , the actual
// temperature
// Temperature function inputs
// 1.AnalogInputNumber - analog input to read from
// 2.OuputUnit - output in celsius, kelvin or fahrenheit
// 3.Thermistor B parameter - found in datasheet
// 4.Manufacturer T0 parameter - found in datasheet (kelvin)
// 5. Manufacturer R0 parameter - found in datasheet (ohms)
// 6. Your balance resistor resistance in ohms

float Temperature(int AnalogInputNumber, int OutputUnit, float B, float T0, float R0, float R_Balance)
{
float R, T;

// R=1024.0f*R_Balance/float(analogRead(AnalogInputNumber)))-R_Balance;
R = R_Balance*(1024.0f / float(analogRead(AnalogInputNumber)) - 1);

T = 1.0f / (1.0f / T0 + (1.0f / B)*log(R / R0));

switch (OutputUnit) {
case T_CELSIUS:
T -= 273.15f;
break;
case T_FAHRENHEIT:
T = 9.0f*(T - 273.15f) / 5.0f + 32.0f;
break;
default:
break;
};

return T;
}


///////////////////////////
// Stuff for NTC thermistor
///////////////////////////
// 666 ohms = 100C
//double Thermistor(int RawADC) {
// double Temp;
// Temp = log(9850.0*((1024.0 / RawADC - 1)));
// Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp))* Temp);
// Temp = Temp - 273.15; // Convert Kelvin to Celcius
// return Temp - 18;
//}

double Thermistor(int RawADC) {
double Temp;
Temp = log(10000.0*((1024.0 / RawADC - 1)));
//Temp = log(10000.0 / (1024.0 / RawADC - 1)); // for pull-up configuration
Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp))* Temp);
Temp = Temp - 273.15; // Convert Kelvin to Celcius
return Temp;
}
Acuario is offline   Reply With Quote
Old 01-03-16, 03:33 PM   #28
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

14. OLED.ino
/*
Universal 8 bit Graphics Library, u8glib - Universal Graphics Library for 8 Bit Embedded Systems - Google Project Hosting
*/
#include <Wire.h> // Comes with Arduino IDE
#include <U8glib.h>

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_DEV_0 | U8G_I2C_OPT_NO_ACK | U8G_I2C_OPT_FAST); // Fast I2C / TWI


void failureBAC1000(void) {
u8g.setFont(u8g_font_unifont);
u8g.drawStr(0, 10, "Fail to read BAC1000");
}

// graphic commands to redraw the complete screen should be placed here
void draw(void) {
char line1[20]; // used to store strings

u8g.setFont(u8g_font_unifont);

readTime(); //Get the time from the DS1307
if (lcd_page == LCD_PAGE0) {
sprintf(line1, "%02d:%02d:%02d %02d/%02d", tm.Hour, tm.Minute, tm.Second, tm.Day, tm.Month);
u8g.drawStr(0, 10, line1);

char t[3];
char u[3];
dtostrf(tempCompressor, 2, 0, t);
dtostrf(tempEvaporator, 2, 0, u);
sprintf(line1, "Cp:%s Ev:%s", t, u);
u8g.drawStr(0, 22, line1);

//Dewpoint
dtostrf(dewPointTemp, 5, 2, t);
sprintf(line1, "Dp:%s", t);
//u8g.drawBitmapP(0, 25, 1, 8, dropletIco);
u8g.drawStr(0, 34, line1);

if (defrostFlag == FALSE)
sprintf(line1, "Machine:%s", operatingState == FALSE ? "OFF" : "ON");
else
sprintf(line1, "Machine:%s Def:%d", operatingState == FALSE ? "OFF" : "ON", defrostStartTime - (int)(defrostRunTime / 1000));
u8g.drawStr(0, 46, line1);
sprintf(line1, "%s", systemState);
u8g.drawStr(0, 58, line1);
}
}

NIL_THREAD(threadDisplayOLED, arg) {
while (TRUE) {

wdt_reset(); //Reset watchdog timer

u8g.firstPage(); // picture loop
do {
draw();
nilThdSleepMilliseconds(50);

} while (u8g.nextPage());

// rebuild the picture after some delay
nilThdSleepMilliseconds(100);
}
}
Acuario is offline   Reply With Quote
Old 01-03-16, 03:36 PM   #29
Acuario
Apprentice EcoRenovator
 
Join Date: May 2011
Location: Tortosa, Spain
Posts: 217
Thanks: 2
Thanked 70 Times in 42 Posts
Default

And that's it for the moment.
It still lacks control of the heatpump in cooling mode when the temperature reaches the dewpoint that's to come later (when the summer approaches!)

Hope this helps or inspires someone.

By the way, as a development environment I use Visual Studio 2015 and Visual Micro extension for Arduino.

Acuario

Acuario is offline   Reply With Quote
The Following 3 Users Say Thank You to Acuario For This Useful Post:
ameliaamelia (01-04-17), h2oo2h (10-25-16), jeff5may (01-04-16)
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -5. The time now is 06:29 AM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2021, vBulletin Solutions Inc.
Ad Management by RedTyger
Inactive Reminders By Icora Web Design