Project tutorial
Temperature Control

Temperature Control © GPL3+

Temperature control of heating with Arduino Uno Wifi, Arduino Uno, SD Shield, and Google Chart and perhaps an Alexa Interface.

  • 5,770 views
  • 1 comment
  • 29 respects

Components and supplies

Arduino Microcontroller board, Uno Wi-Fi, A000133, ATmega328P, A000133, Arduino
×1
A000066 iso both
Arduino UNO & Genuino UNO
×1
SD-Karten-Shield, 103030005, Seeed Studio
×1
NTC-Widerstand Perle 30 kOhm, B57551G1303F005, EPCOS
×1
1434509556 android phone color
Android device
×1

Apps and online services

About this project

The story

It started when I saw the ArduinoUnoWifi on the Arduino side. So you can "simply" create a temperature recorder with an SD shield, which is accessible via a website. That was the idea and after several days and more hardware the result is visible below.

The Arduino Uno Wifi board comes with the ESP-link firmware. This does not allow communication via the User Datagram Protocol. Thus, the time can not be queried via the Network Time Protocol. Thus, the firmware must be replaced with the "WiFi Link" firmware.

About Alexa

Alexa is not supported in Switzerland. The devices do not work. So I had to search for a wokaround. In the Android there is a function speech to text and text to speech. With it I have a sister of Alexa, the Annunziata called to life. It runs on Android smartphones.

Video DEMO

project idea

principle

use case

Code

arduino uno wifiArduino
arduino uno wifi
#include <WiFiLink.h>
#include <WiFiUdp.h>
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[50]; //buffer to hold incoming and outgoing packets
char ssid[] = "xxxxT";      //  your network SSID (name)
char pass[] = "xxxx";   // your network passwo
int keyIndex = 0;                 // your network key Index number (needed only for WEP)
String url = "";
unsigned long timeOut = 0;
unsigned long sTime = 0;
long timeSendData = -60000;

int status = WL_IDLE_STATUS;
WiFiUDP Udp;
WiFiServer server(80);
WiFiClient client;



void setup() {
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
  delay(2000);
  Serial.begin(38400);      // initialize serial communication
  delay(1000);


  //Check if communication with the wifi module has been established
  if (WiFi.status() == WL_NO_WIFI_MODULE_COMM) {
    Serial.println("Communication with WiFi module not established.");
    while (true); // don't continue:
  }

  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Connect to Network : ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 10 seconds for connection:
    delay(5000);
  }
  Serial.print("UnixTime  :");
  sTime = setTime();
  while (sTime < 1504716686) {
    Serial.println(getTime());
    delay(1000);
    sTime = setTime();
  }
  Serial.println(getTime());
  Udp.stop();
  digitalWrite(2, LOW);
  delay(1000);
  digitalWrite(2, HIGH);
  server.begin();                           // start the web server on port 80
  printWifiStatus();                        // you're connected now, so print out the status
  timeOut = millis();
}


void loop() {
  dooWeb();
  doSendData();
}

void doSendData() {
  if ((millis() - timeSendData) > 60000) {
    timeSendData = millis() ;
    Serial.print("DATA,");
    Serial.print(getTime());
    Serial.print(",");
    for (int analogPin = 0; analogPin < 4; analogPin++) {
      int sensor = analogRead(analogPin);
      Serial.print(intToTemp(sensor));
      Serial.print(",");
    }
    Serial.print("#");
  }
}

void dooWeb() {
  WiFiClient client = server.available();   // listen for incoming clients
  if (client) {                             // if you get a client,
    Serial.println("new client");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        // Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Connection: close");
            client.println("Accept-Ranges: bytes");
            client.print("Content-type:");
            if (url.endsWith("jpg") ) client.println("image/jpg");
            else if (url.endsWith("ico") ) client.println("image/ico");
            else if (url.endsWith("png") ) client.println("image/png");
            else if (url.endsWith("svg") ) client.println("image/svg+xml");
            else client.println("text/html");
            client.println();
            if (url.endsWith("/?")) {
              for (int analogPin = 0; analogPin < 4; analogPin++) {
                int sensor = analogRead(analogPin);
                client.print(String(intToTemp(sensor), 1));
                client.print(",");
              }
            }
            // the content of the HTTP response follows the header:
            while (Serial.available() > 0) Serial.read();
            Serial.println(url + "#");
            timeOut = millis();
            String buffer = "";
            size_t cnt = 50;
            while ((millis() - timeOut) < 10000) {
              if (Serial.available() > 0) {
                timeOut = millis();
                char c = Serial.read();
                buffer.concat(c);
                if (buffer.length() > 8)buffer.remove(0, 1);
                if (buffer.endsWith("PUT")) {
                  buffer.replace("PUT", "");
                  buffer.remove(0, buffer.indexOf("#") + 1);
                  cnt = buffer.toInt();
                  size_t i = 0;
                  while ((millis() - timeOut) < 10000) {
                    if (Serial.available() >= cnt) {
                      i = Serial.readBytes(packetBuffer, cnt);
                      int clst = client.status();
                      if (clst == 4) {
                        client.write(packetBuffer, i);
                        if (i == 50) {
                          Serial.print("NEXT");
                          timeOut = millis();
                        }
                        break;
                      } else {
                        Serial.println("client.status :" + String(clst));
                        while (Serial.available() > 0) {
                          Serial.read();
                        }
                        client.stop();
                        client = false;
                        delay(100);
                        return;
                      }
                    }
                  }
                }
              }
              if (cnt != 50) break;
            }

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          }
          else {      // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        }
        else if (c != '\r') {    // if you got anything else but a carriage return character,
          if (currentLine.startsWith("GET") or currentLine.length() < 4 ) {
            currentLine += c;      // add it to the end of the currentLine
          }
        }

        if (currentLine.endsWith("HTTP/1.1")) {
          url =  currentLine;
          url.replace(" HTTP/1.1", "");
        }

      }
    }
    client.stop();
    Serial.println("client disonnected");
    delay(10);
  }
}


void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
}

unsigned long getTime() {
  if (sTime == 0) {
    sTime = getTime();
  }
  return sTime + millis() / 1000;
}

float intToTemp(int x) {
  x = 1023 - x;
  float result;
  result = -9.01865E-13 * x * x * x * x * x + 2.47090E-09 * x * x * x * x - 2.74511E-6 * x * x * x + 1.55555E-3 * x * x - 5.40551E-1 * x + 1.22271E2;
  return result;
}

unsigned long setTime() {
  unsigned int localPort = 2390;      // local port to listen for UDP packets

  Udp.begin(localPort);

  sendNTPpacket( packetBuffer, NTP_PACKET_SIZE); // send an NTP packet to a time server
  delay(500);
  if ( Udp.parsePacket() ) {
    // We've received a packet, read the data from it
    Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
    Serial.write(packetBuffer, NTP_PACKET_SIZE);
    Serial.println();

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;

    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    return (epoch );
  }
}
unsigned long sendNTPpacket(  uint8_t *packetBuffer, const int NTP_PACKET_SIZE) {


  //Serial.println("1");
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  //Serial.println("2");
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  //Serial.println("3");

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  char adr[] = "ch.pool.ntp.org";
  Udp.beginPacket(adr, 123); //NTP requests are to port 123
  //Serial.println("4");
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  //Serial.println("5");
  Udp.endPacket();
  //Serial.println("6");
}
arduino uno mit SD CardArduino
arduino uno mit SD Card
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;
const char ETX = '#'; // Char(3);
byte packetBuffer[50];
float temper[10];
String temperStr;
String inputStr = "";
boolean isData = false;
boolean isGet = false;
boolean isFilename = false;
String filename = "";
char empfaenger = "";
File file;
char input ;
String in;
uint32_t timeOut = 0;
int index = 0;
long quad = -738000;
uint32_t aTime = 0;
String more = "";
File ff;
File root;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(38400);
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    // don't do anything more:
    return;
  }

  timeOut = millis();
}

String unixtToString(uint32_t t, bool sommer = false) {
  uint32_t tt = t;
  uint32_t wochentag = ((t + 345600) % (604800)) / 86400;
  t += 3600;
  int data [6] = {0, 0, 0, 0, 0, 0};
  data[5] = t % 60; //sek
  t = t / 60;
  data[4] = t % 60; //min
  t = t / 60;
  data[3] = t % 24; //h
  t = t / 24;
  data[0] = t / 365 + 1970; // Year
  data[2] = t % 365;
  uint32_t  ly;
  for (ly = 1972; ly < data[0]; ly += 4) {
    if (!(ly % 100) && (ly % 400)) continue;
    --data[2];
  }
  if (data[2] < 0) data[2] += 365, --data[0];
  static int const dm[2][12] = {
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  };
  ly = (data[0] == ly) ? 1 : 0;
  while (data[2] >= dm[ly][data[1]]) data[2] -= dm[ly][data[1]++];
  if (!sommer) {
    if (data[1] > 2 && data[1] < 9) sommer = true;
    if ((data[1] == 2) && (31 - data[2] + wochentag < 7) && (wochentag > 0))sommer = true;
    if ((data[1] == 2) && (31 - data[2] + wochentag < 7) && (wochentag == 0) && (data[3] > 1))sommer = true;
    if ((data[1] == 9) && (31 - data[2] + wochentag > 7))sommer = true;
    if ((data[1] == 9) && (31 - data[2] + wochentag < 7) && (wochentag == 0) && (data[3] < 2)) sommer = true;
    if (sommer) {
      tt += 3600;
      return unixtToString(tt, true);
    }
  }
  ++data[2]; //day
  ++data[1]; //mont
  return
    String(data[0]) + "-"
    + (data[1] <= 9 ? "0" + String(data[1]) : String(data[1])) + "-"
    + (data[2] <= 9 ? "0" + String(data[2]) : String(data[2])) + "T"
    + (data[3] <= 9 ? "0" + String(data[3]) : String(data[3])) + ":"
    + (data[4] <= 9 ? "0" + String(data[4]) : String(data[4])) + ":"
    + (data[5] <= 9 ? "0" + String(data[5]) : String(data[5]));
}

void safeQuadData() {
  if ((millis() - quad) > 900000) {
    String d = unixtToString(aTime);
    d = d.substring(0, 10);
    d.replace("-", "");
    String f = "/dat/" + String(d) + ".TXT";
    file = SD.open(f, FILE_WRITE);
    file.print(unixtToString(aTime));
    file.print(",");
    for (int i = 0; i < 10; i++) {
      if (i < 9) {
        file.print( String(temper[i], 1) + ",");
      } else {
        file.println(  String(temper[i], 1) );
      }
    }
    quad = millis();
    timeOut = millis();
    file.close();
  }
}

boolean doSendData() {
  boolean fileclose = false;
  long sizeToSend = 0;
  if (more.length() > 0) {
    sizeToSend = more.length();
  } else {
    sizeToSend = file.size() - file.position();
    if (sizeToSend >= 50) {
      sizeToSend = 50;
    } else {
      fileclose = true;
    }
  }
  Serial.print("#" + String(sizeToSend) + "PUT");
  timeOut = millis();
  int i = 0;
  if (more.length() > 0) {
    Serial.print(more);
    more = "";
  } else {
    while (millis() - timeOut < 10000) {
      i = file.read(packetBuffer, sizeToSend);
      Serial.write(packetBuffer, i);
      sizeToSend = sizeToSend - i;
      if (sizeToSend == 0) {
        break;
      }
    }
    if (fileclose) {
      file.close();
    }
  }
  return   false;
}

float intToTemp(int x) {
  x = 1023 - x;
  float result;
  result = -9.01865E-13 * x * x * x * x * x + 2.47090E-09 * x * x * x * x - 2.74511E-6 * x * x * x + 1.55555E-3 * x * x - 5.40551E-1 * x + 1.22271E2;
  return result;
}

boolean doGet(char in) {
  if (in != ETX ) {
    filename = filename + in;
  } else  if (SD.exists(filename)) {
    file = SD.open(filename, FILE_READ);
    doSendData();
    filename = "";
  }  else if (filename.endsWith( "/" ) ) {
    file = SD.open("/index.htm", FILE_READ);
    doSendData();
    filename = "";
  } else if (filename.endsWith( "/?" ) ) {
    String send = "";
    for (int i = 0; i < 6; i++) {
      if (i < 5) {
        send = send + String(intToTemp(analogRead(i)), 1) + ",";
      } else {
        send = send + String(intToTemp(analogRead(i)), 1)  ;
      }
    }
    Serial.print("#" + String(send.length()) + "PUT");
    Serial.print(send);
    filename = "";
  }  else if (filename.endsWith( "?" ) ) {
    String pin = filename.substring(filename.length() - 2, filename.length() - 1);
    String temp = String(intToTemp(analogRead(pin.toInt())));
    String send = String(temp);
    Serial.print("#" + String(send.length()) + "PUT");
    Serial.print(send.substring(0, 50));
    filename = "";
  } else if (filename.endsWith( "DIR" ) ) {
    if (SD.exists("LIST.TXT")) {
      SD.remove("LIST.TXT");
    }
    ff = SD.open("LIST.TXT", FILE_WRITE);
    root = SD.open("DAT/");
    while (true) {
      File entry =  root.openNextFile();
      if (! entry) {
        // no more files
        break;
      }
      ff.print(entry.name());
      ff.print(",");
      entry.close();
    }
    ff.close();
    delay(10);
    file = SD.open("LIST.TXT", FILE_READ);
    doSendData();
    filename = "";
  }
  return (in != ETX );
}

boolean doData(char in) {
  if (in != ETX) {
    if (isFilename ) {
      file.write(in);
      temperStr.concat(in);
      if (temperStr.length() > 8) {
        temperStr.remove(0, 1);
      }
      if (temperStr.endsWith(",")) {
        temperStr.remove(",");
        temper[index] = temperStr.toFloat();
        temperStr = "";
        index++;
      }
    } else {
      if (in == ',') {
        aTime = filename.toInt();
        String d = unixtToString(aTime);
        d = d.substring(0, 10);
        d.replace("-", "");
        String f = "/data/" + String(d) + ".TXT";
        file = SD.open(f, FILE_WRITE);
        isFilename = true;
        file.print(unixtToString(aTime ) +  in);
      }
      filename = filename + in;
    }
  } else {
    for (int analogPin = 0; analogPin < 6; analogPin++) {
      int sensor = analogRead(analogPin);
      file.print(intToTemp(sensor));
      if (analogPin < 5) {
        file.print(",");
      } else {
        file.println("");
      }
      temper[index] = intToTemp(sensor);
      index++;
    }
    index = 0;
    isFilename = false;
    filename = "";
    file.close();
  }
  return  in != ETX;
}


void serialEvent() {
  timeOut = millis();
  if (Serial.available() > 0 ) {
    input = Serial.read();
    if ( !(isGet or isData )) {
      inputStr.concat(input);
      if (inputStr.length() > 6) {
        inputStr.remove(0, 1);
      }
      if (inputStr.endsWith("GET ") ) {
        isGet = true;
      }
      if (inputStr.endsWith("DATA,") ) {
        isData = true;
      }
      if (inputStr.endsWith("NEXT") ) {
        doSendData();
      }
    } else {
      if (isGet )isGet = doGet(input);
      if (isData)isData = doData(input);
    }
  }
}
void loop() {
  if (millis() - timeOut > 10000) {
    isGet = false;
    isData = false;
    isFilename = false;
    filename = "";
    timeOut = millis();
  }
  safeQuadData();
}
SD Card File with html ChartJavaScript
<html>
    <head>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script type="text/javascript">

            google.charts.load('current', {'packages': ['corechart', "calendar"]});
            google.charts.setOnLoadCallback(drawChartLine);
            google.charts.setOnLoadCallback(drawChart);



            var d = new Date();
            var dat = "dat/" + d.getFullYear() + ((d.getMonth() < 9) ? "0" : "") + (d.getMonth() + 1) + ((d.getDate() < 10) ? "0" : "") + (d.getDate()) + ".TXT";
            var app = angular.module('myApp', []);


            function drawChartLine() {
                var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

                var data = new google.visualization.DataTable();
                data.addColumn('datetime', 'Day Time');
                data.addColumn('number', "Heiz. Vorl");
                data.addColumn('number', "Heiz. Rueckl");
                data.addColumn('number', "Brauch Wasser");
                data.addColumn('number', "Boiler Wasser");
                data.addColumn('number', "Wasser vor WP");
                data.addColumn('number', "Wasser nach WP");
                data.addColumn('number', "E. Sond. Vorl");
                data.addColumn('number', "E. Sond. Rueckl");
                data.addColumn('number', "Wohnung");
                data.addColumn('number', "Aussen");

                var options = {'title': 'Heizungstemperaturen vom ' + ((d.getDate() < 10) ? "0" : "") + d.getDate() + "." + ((d.getMonth() < 9) ? "0" : "") + (d.getMonth() + 1) + "." + d.getFullYear(),
                    vAxis: {title: "Temperatur in Grad C",
                    },
                    hAxis: {
                        title: "Zeit in Stunden",
                        viewWindow: {
                            min: new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0),
                            max: new Date(d.getFullYear(), d.getMonth(), d.getDate(), 24, 00)
                        },
                    },
                    'width': "100%",
                    'height': 600};
                $.get(dat, function (csvString) {
                    var array = csvString.split("\n");
                    data.addRows(array.length);
                    for (i = 0; i < array.length; i++) {
                        var row = array[i].split(",");
                        var da = new Date();
                        da = new Date(row[0]);
                        data.setCell(i, 0, da);
                        for (x = 1; x < 11; x++) {
                            data.setCell(i, x, row[x]);
                        }
                    }
                    chart.draw(data, options);
                });
            }

            function drawChart() {
                var chart = new google.visualization.Calendar(document.getElementById('calendar_basic'));
                var array2 = [""];
                var datArray = [[new Date(), 1]];
                var dataTable = new google.visualization.DataTable();
                dataTable.addColumn({type: 'date', id: 'Date'});
                dataTable.addColumn({type: 'number', id: 'Day'});

                datArray[0] = [new Date(), 1];
                dataTable.addRows(datArray);

                var options = {
                    title: "Daten vorhanden",
                    height: 350
                };

                google.visualization.events.addListener(chart, 'select', function () {
                    var selection = chart.getSelection();
                    if (selection.length) {
                        var row = selection[0].row;
                        if (row) {
                            d = new Date(selection[0].date);
                            dat = "dat/" + d.getFullYear() + ((d.getMonth() < 9) ? "0" : "") + (d.getMonth() + 1) + ((d.getDate() < 10) ? "0" : "") + (d.getDate()) + ".TXT";
                            $.get(dat, function (csvString) {
                                drawChartLine();
                            });
                        }
                    }
                });

                $.get("DIR", function (csvString) {
                    csvString = csvString.substr(0, csvString.length - 2);

                    csvString = csvString.replace("2017119.TXT,", "20171109.TXT,");
                    array2 = csvString.split(",");
                    for (i = 0; i < array2.length; i++) {
                        array2[i] = array2[i].replace(".TXT", "");
                    }
                    dataTable = new google.visualization.DataTable();
                    dataTable.addColumn({type: 'date', id: 'Date'});
                    dataTable.addColumn({type: 'number', id: 'Day'});
                    lauf = 0;
                    for (i = 0; i < array2.length; i++) {
                        try {
                            var datums = new Date(array2[i].substr(0, 4), array2[i].substr(4, 2) - 1, array2[i].substr(6, 2));
                            if (datums.getFullYear() > 2016) {
                                datArray[lauf] = [datums, ((i % 2) === 0) ? 1 : -1];
                                lauf++;
                            }
                        } catch (err) {

                        }
                    }
                    dataTable.addRows(datArray);
                    chart.draw(dataTable, options);
                    $scope.names = array2;
                });
            }
        </script>
    </head>
    <body>  
        <H1><a href="/">Heizung</a></H1>

        <div id="chart_div"></div>

        <div id="calendar_basic"></div>

    </body>
</html>
SD Card File with html indexJavaScript
SD Card File with html index
<html>
    <head>
        <style>
            .imgBG {
                position: absolute;
                z-index: -1;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                width: 100%;
                height: 100%;
            }
        </style>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <script type="text/javascript">
            google.charts.load('current', {'packages': ['gauge']});
            google.charts.setOnLoadCallback(drawChart);
            var dat = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,0.0,0.0];

            function drawChart() {
                var data = [];
                var chart = [];
                loadXMLDoc()
                for (i = 0; i < 10; i++) {
                    data[i] = google.visualization.arrayToDataTable([['Label', 'Value'], ['C', dat[i]]]);
                }
                var options = {
                    width: 120, height: 120,
                    redFrom: 22, redTo: 100,
                    greenFrom: 10, greenTo: 22,
                    yellowFrom: 0, yellowTo: 10,
                    max: 100
                };
                for (i = 0; i < 10; i++) {
                    chart[i] = new google.visualization.Gauge(document.getElementById("chart_div" + (i + 1)));
                }
                for (i = 0; i < 10; i++) {
                    chart[i].draw(data[i], options);
                }
                setInterval(function () {
                    loadXMLDoc();
                }, 50000);


                function loadXMLDoc() {
                    var xhttp = new XMLHttpRequest();
                    xhttp.onreadystatechange = function () {
                        if (this.readyState === 4 && this.status === 200) {
                            var xx = this.responseText.split(",");
                            for (i = 0; i < 12; i++) {
                                dat[i] = parseFloat(xx[i]);
                            }
                            for (i = 0; i < 10; i++) {
                                data[i].setValue(0, 1, dat[i]);
                                chart[i].draw(data[i], options);
                            }
                        }
                    };
                    var a = "?";
                    xhttp.open("GET", a, true);
                    xhttp.send();
                }
            }
        </script>
    </head>
    <body>  
   
    <H1><a href="tes.htm">Heizung</a>	</H1>
    <div style="width: 100%; height: 100%; "  
        </div>
        <table style="background:url('Bild.svg') ; background-size: 100%;">
             <tr>
                <td>  </td>
                <td height="200"></div></td> 
                <td><div id="chart_div1" style="width: 120px; height: 120px;"></div></td> 
                <td></td> 
                <td><div id="chart_div2" style="width: 120px; height: 120px;"></div></td> 
            </tr>
            <tr>
                <td>  </td>
                <td height="200"><div id="chart_div3" style="width: 120px; height: 120px;"></div></td> 
                <td><div id="chart_div4" style="width: 120px; height: 120px;"></div></td> 
                <td></td> 
                <td><div id="chart_div5" style="width: 120px; height: 120px;"></div></td> 
            </tr>
            <tr>
                <td height="200"><div id="chart_div6" style="width: 120px; height: 120px;"></div></td> 
                <td></td> 
                <td></td> 
                <td></td> 
                <td><div id="chart_div7" style="width: 120px; height: 120px;"></div></td> 
            </tr>
            <tr>
                <td height="200"> </td> 
                <td><div id="chart_div8" style="width: 120px; height: 120px;"></div></td> 
                <td><div id="chart_div9" style="width: 120px; height: 120px;"></div></td> 
                <td><div id="chart_div10" style="width: 120px; height: 120px;"></div></td> 
                <td></td> 
        </table> 

    </body>
</html>
AnnunziataJava
Code for a Android Application
package com.example.relleum.speechtotext;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    String text;
    EditText editText = null;
    TextToSpeech t1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();
        editText = findViewById(R.id.editText);
        final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);

        final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
                Locale.getDefault());

        mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle bundle) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float v) {

            }

            @Override
            public void onBufferReceived(byte[] bytes) {

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onError(int i) {

            }

            @Override
            public void onResults(Bundle bundle) {
                //getting all the matches
                ArrayList<String> matches = bundle
                        .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

                //displaying the first match
                if (matches != null) {
                    text = matches.get(0);
                    editText.setText(text);
                    new RetrieveFeedTask().execute(text);
                }


            }

            @Override
            public void onPartialResults(Bundle bundle) {

            }

            @Override
            public void onEvent(int i, Bundle bundle) {

            }
        });

        t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    t1.setLanguage(Locale.GERMAN);
                }
            }
        });

        findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mSpeechRecognizer.stopListening();
                        editText.setHint("Hier siehst du den Input");

                        break;

                    case MotionEvent.ACTION_DOWN:
                        mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
                        editText.setText("");
                        editText.setHint("Hören...");
                        break;
                }
                return false;
            }
        });
    }


    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                        Uri.parse("package:" + getPackageName()));
                startActivity(intent);
                finish();
            }
        }
    }


    class RetrieveFeedTask extends AsyncTask<String, Void, String> {

        private Exception exception;


        protected String doInBackground(String... dataA) {
            String data = dataA[0];
            String fullString = "";
            if (data.contains("Annunziata")) {
                URL url = null;
                try {
                    url = new URL("http", "192.168.1.110", "?");
                    InputStreamReader inputStreamReader = new InputStreamReader(url.openStream());
                    BufferedReader reader = new BufferedReader(inputStreamReader);
                    String line;
                    while ((line = reader.readLine()) != null) {
                        fullString += line;
                    }
                    reader.close();

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (data.contains("null")) {
                    fullString = fullString.split(",")[0];
                    return fullString;

                }
                if (data.contains("1")) {
                    fullString = fullString.split(",")[1];
                    return fullString;

                }
                if (data.contains("2")) {
                    fullString = fullString.split(",")[2];
                    return fullString;

                }
                if (data.contains("3")) {
                    fullString = fullString.split(",")[3];
                    return fullString;

                }
                if (data.contains("4")) {
                    fullString = fullString.split(",")[4];
                    return fullString;

                }
                if (data.contains("5")) {
                    fullString = fullString.split(",")[5];
                    return fullString;

                }
                if (data.contains("6")) {
                    fullString = fullString.split(",")[6];
                    return fullString;

                }
                if (data.contains("7")) {
                    fullString = fullString.split(",")[7];
                    return fullString;

                }
                if (data.contains("8") || data.contains("Wohnung")) {
                    fullString = fullString.split(",")[8];
                    return " in der Wohnung " + fullString;

                }
                if (data.contains("9") || data.contains("außen")) {
                    fullString = fullString.split(",")[9];
                    return " im freien " + fullString;

                }
                return data + "#";
            }
            if (data.contains("spieglein")){

                data="Frau Königin, Ihr seid die Schönste hier, Aber Schneewittchen ist tausendmal schöner als Ihr.";
                return data;
            }
            if (data.contains("Anlage")){
                data= "Der Potovoltaikertrag beträgt "+Modbus.getGesammtertrag()+ "Wattstunden";
                return data;
            }
            return data + "#";
        }

        protected void onPostExecute(String feed) {
            if (feed.contains("Königin") || feed.contains("Potovoltaikertrag") ){
                t1.speak(feed, TextToSpeech.QUEUE_FLUSH, null);
                return;
            }
            if (feed.endsWith("#")) {
                editText.setText(feed.replace('#', ' '));
                feed = antworttext2();
                t1.speak(feed, TextToSpeech.QUEUE_FLUSH, null);
                return;
            }
            editText.setText(feed);

            if (feed.length() > 0) {
                feed = "Die Temperatur beträgt" + feed + " Grad Celsius," + antworttext();
                t1.speak(feed, TextToSpeech.QUEUE_FLUSH, null);

            }
        }

        private String antworttext() {
            Random rnd = new Random();

            String ret = "";
            switch ((int) (rnd.nextFloat() * 4)) {
                case 0:
                    ret = " besten Dank für Ihre Nachfrage";
                    break;
                case 1:
                    ret = " es hat mich gefreut dir Auskunft zu geben";
                    break;
                case 2:
                    ret = " für weitere Fragen stehe ich gerne zur Verfügung";
                    break;
                case 3:
                    ret = " Es macht spass dir Auskunft zu geben";
                    break;
            }
            return ret;
        }

        private String antworttext2() {
            Random rnd = new Random();

            String ret = "";
            switch ((int) (rnd.nextFloat() * 5)) {
                case 0:
                    ret = " habe Frage nicht verstanden, Frage Annunziata";
                    break;
                case 1:
                    ret = " Bitte Frage wiederholen";
                    break;
                case 2:
                    ret = " Weiss leider keine Antwort auf deine Frage";
                    break;
                case 3:
                    ret = " das muoosch selber beantworta";
                    break;
                case 4:
                    ret = " Warum soll ich das wissen?";
                    break;
            }
            return ret;
        }


    }
}
ModbusJava
Modbusanwendung für Sunny PV Portal
package com.example.relleum.speechtotext;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Created by relleum on 10.12.17.
 */

public class Modbus {
    private InetAddress inetAddress;
    private  int port;
    private int transactionIdentifier=10;
    private int protocolIdentifier;
    private int messageLength;
    private int theUnitIdentifier=126;//126
    private int theFunctionCode;
    private int dataAddress;
    private int numberOfRegisters;

    Modbus(String aInetAdress, int aPort){
        try {
            inetAddress= InetAddress.getByName(aInetAdress);
            port=aPort;

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static String getGesammtertrag(){
        Modbus modbus= new Modbus("192.168.1.101",502);
        byte[] b=modbus.readData(40210,4);
        ByteBuffer byteBuffer= ByteBuffer.wrap(b);
        byteBuffer.asIntBuffer();
        byteBuffer.order(ByteOrder.BIG_ENDIAN);
        return Integer.toString(byteBuffer.getInt()*10);
    }

    public static void main(String [] args){


         System.out.println("Res read Data: "+ getGesammtertrag());

    }

    byte[] readData(int aStartingAddress,int aQuantityOfRegisters){
        aStartingAddress=aStartingAddress-1;
        ModbusRequest modbusRequest= new ModbusRequest();
        try {
            Socket socket= new Socket(inetAddress,port);
            DataInputStream dataInputStream= new DataInputStream(socket.getInputStream());
            DataOutputStream dataOutputStream= new DataOutputStream(socket.getOutputStream());
            byte[] bytes=new byte[12];
            // Transaction Identifier Hi
            bytes[0] = (byte) (0xff & (transactionIdentifier >> 8));
            //Transaction Identifier Lo
            bytes[1] = (byte) (0xff & transactionIdentifier);
            transactionIdentifier = transactionIdentifier > 127 ? 1 : transactionIdentifier + 1;
            transactionIdentifier++;
            //Protocol Identifier
            bytes[2] = 0;
            bytes[3] = 0;
            // Length
            short l = (short) (bytes.length - 7);
            bytes[4] = (byte) (0xff & (l >> 8));
            bytes[5] = (byte) (0xff & l);

            bytes[6] = (byte) (0xff & theUnitIdentifier);
            // Function Code
            bytes[7] = (byte) (0xff & 3);
            //Starting Address
            bytes[8] = (byte) (0xff & (aStartingAddress >> 8));
            bytes[9] = (byte) (0xff & aStartingAddress);
            //Quantity of Registers
            bytes[10] = (byte) (0xff & (aQuantityOfRegisters >> 8));
            bytes[11] = (byte) (0xff & aQuantityOfRegisters);
            dataOutputStream.write(bytes);
            System.out.println(bytes);
            for (int i = 0; i < bytes.length; i++) {
                System.out.print(bytes[i]);
                System.out.print(" ");

            }
            System.out.println();
            byte[] buffer=new byte[9];

            dataInputStream.readFully(buffer);
            System.out.println("TransactionIdentifier: "+modbusRequest.getTransactionIdentifier(buffer));
            System.out.println("ProtocolIdentifier:    "+modbusRequest.getProtocolIdentifier(buffer));
            System.out.println("Lenght:                "+modbusRequest.getLenght(buffer));
            System.out.println("Adress:                "+modbusRequest.getAdress( buffer));
            System.out.println("Funktion:                "+modbusRequest.getFunktion( buffer));
            System.out.println("Grösse:                "+modbusRequest.getGroesse( buffer));

            System.out.println();
            byte[] buf=new byte[modbusRequest.getGroesse(buffer)];
            dataInputStream.readFully(buf);
            for (int i = 0; i < buf.length; i++) {
                System.out.print(buf[i]);
                System.out.print(" ");

            }

            return buf;
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] buffer=new byte[8];
        return buffer;
    }


    public class ModbusRequest {

        public  int getTransactionIdentifier(byte[] b) {
            return ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);
        }

        public  int getProtocolIdentifier(byte[] b) {
            return ((b[2] & 0xFF) << 8) | (b[3] & 0xFF);
        }

        public  int getLenght(byte[] b) {

            return ((b[4] & 0xFF) << 8) | (b[5] & 0xFF);
        }

        public  int getAdress(byte[] b) {

            return (b[6] & 0xFF);
        }
        public  int getFunktion(byte[] b) {

            return (b[7] & 0xFF);
        }
        public  int getGroesse(byte[] b) {

            return (b[8] & 0xFF);
        }


    }

}

Schematics

Schema
Schema
Zeichnung iirm281xda

Comments

Similar projects you might like

Health Kit: Humidity and Temperature Control

Project tutorial by Diana Khalipina

  • 7,699 views
  • 2 comments
  • 48 respects

Arduino Control AC Water Heater temperature

Project tutorial by Mohannad Rawashdeh

  • 13,460 views
  • 0 comments
  • 9 respects

Control an LED with the Remote Control

Project showcase by Nicholas_N

  • 9,836 views
  • 3 comments
  • 16 respects

Arduino Temperature Control

Project tutorial by pandhoit

  • 28,944 views
  • 13 comments
  • 44 respects

Temperature Sensor To control Servo Motor

by Jasleen

  • 13,428 views
  • 2 comments
  • 17 respects
Add projectSign up / Login