ทดสอบ Arduino DUE & Mega Master/Slave

หายไปนานครับการโครงการเจ๋ง ๆ
คราวนี้ผมมีโปรเจก  สำหรับการควบคุมการทำงาน  สถานีวิจัยการบำบัดน้ำเสียจากอุตสาหกรรมการเกษตร   ร่วมกับบริษัท  Inno Green Tech จำกัด 
เจ้าของลิขสิทธิ์งานวิจัย
โดยเจ้าระบบควบคุมผมนี่จะต้องควบคุมการทำงานดังนี้

  1. ควบคุมการทำงานปั๊มน้ำตามระดับของ ลูกลอย   รวมปั๊มทั้งหมด  6 ตัว
  2. วัดอัตราการไหลของปั๊มน้ำทั้ง  6
  3. วัดแรงดันของระบบอีก 5 จุด
  4. วัดการใช้กำลังไฟฟ้า โวลต์แอมป์ กำลัง
  5. วัดค่า pH, EC, Temp compensation
  6. และระบบจะต้องทำงานในโหมด Auto Manual ได้  สั่ง Start Stop ได้
  7. บันทึกค่าจำนวน 20 พารามิเตอร์ขึ้น Server ได้
  8. สั่ง ปรับค่า calibrate  เครื่องวัดต่าง ๆ ได้
  9. ใช้การสื่อสารผ่าน Lan
  10. มี Data Logger
  11. มีพัดลมควบคุมอุณหภูมิภายในตู้
  12. จอแสดงผล  LCD

โดยให้ทำงานได้สมบูรณ์  ประหยัด  ใช้อุปกรณ์ Arduino ให้น้อยที่สุด
คำถามคือ  จะต้องใช้  เจ้าโน่  รุ่นไหนดี     เพราะจะเห็นว่าต้องใช้  input  output  เยอะมาก ๆ  คือ

  • Analog Input  =  11 (pH,EC, millivolt, temp )
  • Digital Input =  6 (ระดับน้ำ)
  • Interrupt = 6 (flow meter  6 ตัว)
  • Serial Port = 1 ชุด
  • PZEM 004T – Energy port = 1 ชุด

จะเห็นว่า  UNO ตัวเดียวรับไม่ไหว
จะเห็นว่า AT Mega  น่าสนใจ
จะเห็นว่า  DUE ก็น่าสนใจ
ผลการทดสอบสรุปได้ผลดังนี้ครับ

  • DUE   มันเป็น  32 บิตทำงานเร็วมากสุดยอดเลยโดยเฉพาะการอ่าน port interrupt  และมี port interrupt เยอะ  เพราะ Digital pin มันใช้ทำ  interrupt  ได้ทุกขา  แต่น่าเสียดาย  Software Serial ใช้การไม่ได้บน DUE รุ่นนี้  เลยต้องทำใจ  เก็บไว้ใช้งานหน้าที่ไม่ต้องการ ใช้ Software Serial
  • AT Mega จึงเป็นตัวเลือกที่ดี   แต่ใช้  Interrupt Port ได้เพียง 4 ขา  คือ  2,3,18,19  ส่วน 20,21 ต้องเก็บไว้ใช้กับจอ LCD  มันโยกไปใช้ ขา SDA1, SCL1   ไม่ได้  เป็นความผิดพลาดที่ชาว Arduino ตำหนิ  Mega กันขรม
  • ในเมื่อจะต้องใช้ flow  ให้ได้อีกตัว  ก็เดือดร้อนต้องหา UNO มาวัด  flow  โดยใช้ขา interrupt 2  แล้วพ่วงเข้า  Software Serial port
  • และเจ้า pzem ตัววัดพลังงานไฟฟ้า  ก็ต้องย้ายไปเกาะเข้า  Serial Port 3 (ขา 14,15)   วางไว้ที่  16,17 ไม่ได้

ผลการทดสอบฉลุยครับ    โดยรอบการทำงานก็จะช้าหน่อยแต่ก็พอรับได้คือราว ๆ 30 วินาทีต่อรอบ  โค้ดยาว  พันกว่าบรรทัด  รวม 56 KByte    และให้ส่งค่าไป Server ทุกๆ 5 นาที
มีภาพมาให้ชมกันคร่าว ๆ ครับ  สำหรับโค้ดและระบบ Server ต้องขอสงวนไว้ครับ  ที่จะไม่นำมาเปิดเผยในที่นี่ (คือมันเขิน  เขียนจนเวิร์ก  แต่อาจจะไม่เท่ห์)
  
ลุยเองกันเต็ม ๆ ยาวๆ  3 วันเต็ม ๆ
 
   Arduino DUE 32 bit prcessor

Arduino AT Mega

 

Application  Samong IOT

 
งานนี้เรียกว่าได้ใช้  แพลตฟอร์ม Server ที่พัฒนาขึ้นมาเองอย่างเต็มที่    หากยังใช้ แพลตฟอร์มของค่ายอื่น ๆ ที่เปิดฟรีบ้างไม่ฟรีบ้างก็คงจะเล่นได้ไม่เต็มที่ขนาดนี้
สำหรับท่านที่สนใจใช้ระบบ Server แบบเต็มพิกัดติดต่อมาได้นะครับ    ไม่แจกโค้ด  แต่บริการทุก Solution  อย่างถึงใจ
 
แนะนำโค้ดสำคัญ ๆ สำหรับการศึกษาในแต่ละเรื่อง (ขอเอามาแปะที่หลังนะครับ )

 ภาพรวมของชุดอุปกรณ์

 

ใช้ อะแดปเตอร์  5  โวลต์  3 แอมป์สำหรับระบบควบคุม   และ  Switchinh Power Supply สำหรับ วงจร  12 Volt   ในภาพจะเห็น  UNO, Mega , pzem , Ethernet Shield และ  DHT11   พร้อมพัดลมระบายความร้อน
 

/*Revision note
 * Rev 8 -
 * 1 : ArduinoJson library to 5.13.2
 * 2 : Energy by devide with 1000 to be kWhr
 * 3 : Send tank level, pump status to server
 * 4.: Comment heatIndex calculation out
 * 5 : Add relay for Raspberry Pi on-off on relay # 8  on Pin #23
 * 6 : Refractor all code
 *
 * Rev 7
 * 1. Flow factor
 * 2. Correction amp reference changed to amp instead of i
 *
 * Rev 6
 * 1. Pump Status
 *
 *
 */
#include <SD.h>  // Datalogger on Ehthernet Shield 10/8/2018 Paipat
#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include <LiquidCrystal.h>
#include "DHT.h"  // temperature sensor
#include <PZEM004T.h>  // Energy meter Through Serial 3 on Mega
#include <SoftwareSerial.h>  //
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <Arduino.h>
#include "RTClib.h"
#include <Adafruit_GFX.h>
float flowfactor;
/////////////////////////////////////// EC initial
#include <OneWire.h>
#define StartConvert 0
#define ReadTemperature 1
const byte numReadings = 20;     //the number of sample times  original = 20
byte ECsensorPin = A5;  //EC Meter analog output,pin on analog 4
byte ECsensorPinB = A7;  //EC Meter analog output,pin on analog 5
byte DS18B20_Pin = 4; //DS18B20 signal 1, pin on digital 2
byte DS18B20_PinB = 5; //DS18B20 signal 2, pin on digital 4
byte indexs = 0;                  // the index of the current reading
byte indexB = 0;
byte thisReading = 0;
unsigned int AnalogSampleInterval=25,AnalogSampleIntervalB=25,printInterval=700,tempSampleInterval=850;  //analog sample interval;serial print interval;temperature sample interval
unsigned int readings[numReadings];      // the readings from the analog input
unsigned int readingsB[numReadings];
unsigned long AnalogValueTotal = 0;                  // the Run total
unsigned long AnalogValueTotalB = 0;
unsigned int AnalogAverage = 0,averageVoltage=0;                // the average
unsigned int AnalogAverageB = 0,averageVoltageB=0;
unsigned long AnalogSampleTime,AnalogSampleTimeB,printTime,printTimeB,tempSampleTime,tempSampleTimeB;
float temperature,temperatureB,ECcurrent,ECcurrentB;
float vVolt = 0;
float iamp = 0;
float vEnergy = 0;
float vPower = 0;
float temp = 0;
float humid = 0;
int delayset =1000; // delay time for display cycle
int connecttime =500; // if too low, less than 1000 , ethernet connection is not possible
int pzemtime =100; // 100 is workable as well
const char*led1 = "x";
const char*led2 = "x";
const char*led3 = "x";
int Level1Value = 0;
int Level2Value = 0;
int Level3Value = 0;
int Level4Value = 0;
int Level5Value = 0;
int Level0Value = 0;
int ManualModePinValue = 0;
int AutoModePinValue = 0;
int AutoModeCommand = 0;
int AutoModeOn = 0;
int Level1ActivateTime = millis();
int Level2ActivateTime = millis();
int Level3ActivateTime = millis();
int Level4ActivateTime = millis();
int Level5ActivateTime = millis();
int pumpdelaytime = 2000;  // millisecond
float flow = 0.00;
//Temperature chip i/o
OneWire ds(DS18B20_Pin);  // on digital pin 2
OneWire dsB(DS18B20_PinB);
/////////////////////////////////////////////////////////////////////
/////////  Analog input for Cathod volt sensor //////////////////////
#define R1sensorPin A10
#define R2sensorPin A11
#define R3sensorPin A12
#define R4sensorPin A13
#define R5sensorPin A14
/////////////////////..Control Setting .../////////////////////////////////////////////
//////////// Input //////////////////
#define Level1Pin 9 // ok
#define Level2Pin 8  // ok
#define Level3Pin 7 // test OK
#define Level4Pin 6  // test OK
#define Level5Pin 41 // test OK
#define Level0Pin 12  // test OK  pin used for SD card in Arduino, 50 51 52 on Mega
///////// Output /////////////////
#define Pump0Pin 37 // check OK
#define Pump1Pin 35 // check OK
#define Pump2Pin 33 // check OK
#define Pump3Pin 31 // check OK
#define Pump4Pin 29 // check OK
#define Pump5Pin 27  // check OK
#define FanPin 25 //
#define RaspberryPin 23
#define ManualModePin 38
#define AutoModePin 39
/// control panel temperature  ///  by DHT ////
#define DHTPIN 36
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
////
////////// Auto Manual Mode  ////////
int AutoMode = 0;
/////////////////////////////////////////////////////////////////
float R1sensorValue;
float R2sensorValue;
float R3sensorValue;
float R4sensorValue;
float R5sensorValue;
float R1milliVoltSum = 0;
float R2milliVoltSum = 0;
float R3milliVoltSum = 0;
float R4milliVoltSum = 0;
float R5milliVoltSum = 0;
int R1milliVolt = 0;
int R2milliVolt = 0;
int R3milliVolt = 0;
int R4milliVolt = 0;
int R5milliVolt = 0;
float ECACurrent = 0;
float ECBCurrent = 0;
///////////////////////////////////end EC initial////////////////////
/////////////////////////// pH initial///////////////////////////
#define SensorPin A6            //pH meter Analog output connect to Arduino Analog Input 0
#define SensorPinB A4            //pH meter Analog output connect to Arduino Analog Input 0
#define pH_in_Offset  0            //deviation compensate
#define pH_out_Offset -3.5
#define LED 13
#define samplingInterval 20
#define printInterval 800
#define ArrayLenth  40    //times of collection  original = 40 the best for fast sensitivity adjust to 3
int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
int pHBArray[ArrayLenth];
int pHArrayIndex = 0; // for pH A
int pHBArrayIndex =0; // for pH B
////////////////////////// end pH initial////////////////////////////
int avg =0; // EC A
int avgB = 0;
int TemperatureSum=0;  // EC A
int TemperatureSumB=0;  // EC B
//int avergearray = 0;
/////////// Ethernet Shield //////////////////////////////////////
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip2(192, 168, 1, 176);  // set ip2 192,168,1,176  for Ethernet shield
// fill in your Domain Name Server address here:
IPAddress myDns(1, 1, 1, 1);
// initialize the library instance:
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 300000; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers
const char* host = "xxxxxxxx.xxx";
///////////////////////
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3,POSITIVE);
// initial  flow sensor
// reading liquid flow rate using Seeeduino and Water Flow Sensor from Seeedstudio.com
// Code adapted by Charles Gantt from PC Fan RPM code written by Crenn @thebestcasescenario.com
// http:/themakersworkbench.com http://thebestcasescenario.com http://seeedstudio.com
#define FlowMeterPulsePerSecondPerLiter 6.9
//#define FlowMeterPulsePerSecondPerLiter 7.5
float FlowCalculationDuration =1000;  // 1 cycle = 1000 not more than 2000
float LCDDisplayPeriod = 2000;
float FlowCalculationStartTime;
float FlowCalculationStartTime2;
float FlowCalculationStartTime3;
float FlowCalculationStartTime4;
float FlowCalculationStartTime5;
float FlowCalculationStartTime6;
float LastLCDDisplay;
float ThisLCDDisplay;
float flow1factor = 1;
float flow2factor = 1;
float flow3factor = 1;
float flow4factor = 1;
float flow5factor = 1;
volatile float PulseCount1 = 0;
volatile float PulseCount2 = 0;
volatile float PulseCount3 = 0;
volatile float PulseCount4 = 0;
volatile float PulseCount5 = 0;
volatile float PulseCount6 = 0;
volatile float PulseCount7 = 0;
float LPM1;
float LPM2;
float LPM3;
float LPM4;
float LPM5;
float LPM6;
float LPM7;
int LPMdecimal;
float phinlet;
float ecinlet;
float flowinlet;
float flow1;
float flow2;
float flow3;
float flow4;
float flow5;
float flow6;
float phoutlet;
float ecoutlet;
float volt;
float kw;
float amp;
float kwhr;
float codinlet;
float codoutlet;
float rmv1;
float rmv2;
float rmv3;
float rmv4;
float rmv5;
float MinFlow = 0.01;
float MaxFlow = 1.75;
float MinRMV = 25;
// end of flow sensor setting
PZEM004T pzem(&Serial3);  // Serial Rx3,TX3 on ATMega  energy meter
IPAddress ip(192,168,1,175);  // ip for pzem unit  192,168,1,175
bool pzemrdy = false;
const char* Pump1 = "x";
const char* Spray = "x";
const char* Pump2 = "x";
const char* Pump3 = "x";
const char* BCS = "BCS";
//int Automode = 0;
String url;   // ใช้สำหรับ โปรแกรมส่วนการส่ง
int count = 0;
int httpPort = 80;
float flow55 = 0;
SoftwareSerial mySerial(17,16);  // 17 = RX, 16 = TX Serial to UNO , uno used port 10(RX) 11(TX)
// if mySerail is set 10,11, this will be intrrupt Ethernet Shield ( Ethernet shield use 10,11, 50, 51,....see Arduino site
const int chipSelect = 4;
int sensor1 = 0;
int sensor2 = 0;
String AlarmMessage0 = "normal";
String AlarmMessage1 = "normal";
String AlarmMessage2 = "normal";
String AlarmMessage3 = "normal";
String AlarmMessage4 = "normal";
String AlarmMessage5 = "normal";
String AlarmMessage6 = "normal";
String AlarmMessage7 = "normal";
String AlarmMessage8 = "normal";
String AlarmMessage9 = "normal";
String AlarmMessage10 = "normal";
String AlarmMessage11 = "normal";
String AlarmMessage12 = "normal";
String AlarmMessage13 = "normal";
String Modeselect  = "OFF";
String Pump0Status = "OFF";
String Pump1Status = "OFF";
String Pump2Status = "OFF";
String Pump3Status = "OFF";
String Pump4Status = "OFF";
String Pump5Status = "OFF";
int Pump0PinScanValue = 0;
int Pump1PinScanValue = 0;
int Pump2PinScanValue = 0;
int Pump3PinScanValue = 0;
int Pump4PinScanValue = 0;
int Pump5PinScanValue = 0;
String Level0text  = "-";
String Level1text  = "-";
String Level2text  = "-";
String Level3text  = "-";
String Level4text  = "-";
String Level5text  = "-";
String PanelMode   = "OFF";
String pump0state = "OFF";
String pump1state = "OFF";
String pump2state = "OFF";
String pump3state = "OFF";
String pump4state = "OFF";
String pump5state = "OFF";
String level0state = "high";
String level1state = "low";
String level2state = "low";
String level3state = "low";
String level4state = "low";
String level5state = "low";
String panelstate   = "OFF";
float vHumidity = 0;
float vTemperature1 = 0;
float vTemperature2 = 0;
static unsigned long samplingTime = millis();
//static unsigned long printTime = millis();
static float pHValue,voltageA;
static unsigned long samplingTimeB = millis();
//static unsigned long printTimeB = millis();
static float pHValueB,voltageB;
///////////////////////////////////////////////////////////////////////////
void setup()
{
int ph1factor =1;
int ph1plus = 0;
int ph1minus = 0;
float ec1factor = 1;
int ec1plus = 0;
int ec1minus = 0;
int ph2factor =1;
int ph2plus = 0;
int ph2minus = 0;
int ec2factor = 1;
int ec2plus = 0;
int ec2minus = 0;
int flow1factor = 1;
int flow1plus = 0;
int flow1minus = 0;
int flow2factor = 1;
int flow2plus = 0;
int flow2minus = 0;
int flow3factor = 1;
int flow3plus = 0;
int flow3minus = 0;
int flow4factor = 1;
int flow4plus = 0;
int flow4minus = 0;
int flow5factor = 1;
int flow5plus = 0;
int flow5minus = 0;
int flow6factor = 1;
int flow6plus = 0;
int flow6minus = 0;
int rmv1factor = 1;
int rmv11plus = 0;
int rmv1minus = 0;
int rmv2factor = 1;
int rmv21plus = 0;
int rmv2minus = 0;
int rmv3factor = 1;
int rmv31plus = 0;
int rmv3minus = 0;
int rmv4factor = 1;
int rmv41plus = 0;
int rmv4minus = 0;
int rmv5factor = 1;
int rmv51plus = 0;
int rmv5minus = 0;
String BCS = "On";
  setup_Display();
  setup_PinMode();
  setup_SerialCommunication();
  setup_NetworkConnection();
  setup_DataLogger();
  setup_Sensor_Box_Temperature();
  setup_Sensor_Flowrate();
  setup_Sensor_EC();
}
//////////////////////////////////////// End SETUP  ///////////////////////////
void CalculateFlow1()
{
  if (millis()-FlowCalculationStartTime > FlowCalculationDuration)
    {
      flowfactor=(millis()-FlowCalculationStartTime)/1000;
      LPM1 = flow1factor*PulseCount1/(2*FlowMeterPulsePerSecondPerLiter*(FlowCalculationDuration/1000))/flowfactor;
      DisplayLPM();
      FlowCalculationStartTime = millis();
      PulseCount1 = 0;
    }
}
void CalculateFlow2()
{
  if (millis()-FlowCalculationStartTime2 > FlowCalculationDuration)
    {
    flowfactor=(millis()-FlowCalculationStartTime2)/1000;
    LPM2 = flow2factor*PulseCount2/(2*FlowMeterPulsePerSecondPerLiter*(FlowCalculationDuration/1000))/flowfactor;
    DisplayLPM2();
    FlowCalculationStartTime2 = millis();
    PulseCount2=0;
    }
}
void CalculateFlow3()
{
  if (millis()-FlowCalculationStartTime3 > FlowCalculationDuration)
    {
    flowfactor=(millis()-FlowCalculationStartTime3)/1000;
    LPM3 = flow3factor*PulseCount3/(2*FlowMeterPulsePerSecondPerLiter*(FlowCalculationDuration/1000))/flowfactor;
    DisplayLPM3();
    FlowCalculationStartTime3 = millis();
    PulseCount3=0;
    }
}
void CalculateFlow4()
{
  if (millis()-FlowCalculationStartTime4 > FlowCalculationDuration)
    {
    flowfactor=(millis()-FlowCalculationStartTime4)/1000;
    LPM4 = flow4factor*PulseCount4/(2*FlowMeterPulsePerSecondPerLiter*(FlowCalculationDuration/1000))/flowfactor;
    DisplayLPM4();
    FlowCalculationStartTime4 = millis();
    PulseCount4 = 0;
    }
}
void CalculateFlow5()
{
  if (millis()-FlowCalculationStartTime5 > FlowCalculationDuration)
    {
    flowfactor=(millis()-FlowCalculationStartTime5)/1000;
    LPM5 = flow5factor*PulseCount5/(2*FlowMeterPulsePerSecondPerLiter*(FlowCalculationDuration/1000))/flowfactor;
    DisplayLPM5();
    FlowCalculationStartTime5 = millis();
    PulseCount5=0;
    }
}
void CalculateFlow6()
{
  if (millis()-FlowCalculationStartTime6 > FlowCalculationDuration)
    {
    flowfactor=(millis()-FlowCalculationStartTime6)/1000;
    LPM6 = PulseCount6/(2*FlowMeterPulsePerSecondPerLiter*(FlowCalculationDuration/1000))/flowfactor;
    DisplayLPM6();
    FlowCalculationStartTime6 = millis();
    PulseCount6 = 0;
    }
}
void pulseCounter1()
{
  PulseCount1++;
}
void pulseCounter2()
{
  PulseCount2++;
}
void pulseCounter3()
{
  PulseCount3++;
}
void pulseCounter4()
{
  PulseCount4++;
}
void pulseCounter5()
{
  PulseCount5++;
}
void pulseCounter6()
{
  PulseCount6++;
}
void DisplayLPM()
{
  Serial.print("Flow 1 : ");
  Serial.print(LPM1,LPMdecimal);
}
void DisplayLPM2()
{
  Serial.print("Flow 2 : ");
  Serial.print(LPM2,LPMdecimal);
}
void DisplayLPM3()
{
  Serial.print("Flow 3 : ");
  Serial.print(LPM3,LPMdecimal);
}
void DisplayLPM4()
{
  Serial.print("Flow 4 : ");
  Serial.print(LPM4,LPMdecimal);
}
void DisplayLPM5()
{
  Serial.print("Flow 5 : ");
  Serial.println(LPM5,LPMdecimal);
}
void DisplayLPM6()
{
  Serial.print("Total F : ");
  Serial.println(LPM6,LPMdecimal);
}
//////////////////////////////////////////////////////////// double for Temp sesnor /////
double avergearray(int* arr, int number){
  int i;
  int max,min;
  double avg;
  long amount=0;
  if(number<=0){
    Serial.println("Error number for the array to avraging!/n");
    return 0;
  }
  if(number<5){   //less than 5, calculated directly statistics
    for(i=0;i<number;i++){
      amount+=arr[i];
    }
    avg = amount/number;
    return avg;
  }else{
    if(arr[0]<arr[1]){
      min = arr[0];max=arr[1];
    }
    else{
      min=arr[1];max=arr[0];
    }
    for(i=2;i<number;i++){
      if(arr[i]<min){
        amount+=min;        //arr<min
        min=arr[i];
      }else {
        if(arr[i]>max){
          amount+=max;    //arr>max
          max=arr[i];
        }else{
          amount+=arr[i]; //min<=arr<=max
        }
      }//if
    }//for
    avg = (double)amount/(number-2);
  }//if
  return avg;
}
double avergearrayB(int* arr, int numberB){
  int i;
  int max,min;
  double avgB;
  long amountB=0;
  if(numberB<=0){
    Serial.println("Error number for the array to avraging!/n");
    return 0;
  }
  if(numberB<5){   //less than 5, calculated directly statistics
    for(i=0;i<numberB;i++){
      amountB+=arr[i];
    }
    avgB = amountB/numberB;
    return avgB;
  }else{
    if(arr[0]<arr[1]){
      min = arr[0];max=arr[1];
    }
    else{
      min=arr[1];max=arr[0];
    }
    for(i=2;i<numberB;i++){
      if(arr[i]<min){
        amountB+=min;        //arr<min
        min=arr[i];
      }else {
        if(arr[i]>max){
          amountB+=max;    //arr>max
          max=arr[i];
        }else{
          amountB+=arr[i]; //min<=arr<=max
        }
      }//if
    }//for
    avgB = (double)amountB/(numberB-2);
  }//if
  return avgB;
}
/////////////////////////////////////////////////////////////////
/*
ch=0,let the DS18B20 start the convert;ch=1,MCU read the current temperature from the DS18B20.
*/
float TempProcess(bool ch)
{
  //returns the temperature from one DS18B20 in DEG Celsius
  static byte data[12];
  static byte addr[8];
  static float TemperatureSum;
  if(!ch){
          if ( !ds.search(addr)) {
              Serial.println("no more sensors on chain, reset search!");
              ds.reset_search();
              return 0;
          }
          if ( OneWire::crc8( addr, 7) != addr[7]) {
              Serial.println("CRC is not valid!");
              return 0;
          }
          if ( addr[0] != 0x10 && addr[0] != 0x28) {
              Serial.print("Device is not recognized!");
              return 0;
          }
          ds.reset();
          ds.select(addr);
          ds.write(0x44,1); // start conversion, with parasite power on at the end
  }
  else{
          byte present = ds.reset();
          ds.select(addr);
          ds.write(0xBE); // Read Scratchpad
          for (int i = 0; i < 9; i++) { // we need 9 bytes
            data[i] = ds.read();
          }
          ds.reset_search();
          byte MSB = data[1];
          byte LSB = data[0];
          float tempRead = ((MSB << 8) | LSB); //using two's compliment
          TemperatureSum = tempRead / 16;
    }
          return TemperatureSum;
}
/*
ch=0,let the DS18B20 start the convert;ch=1,MCU read the current temperature from the DS18B20.
*/
float TempProcessB(bool ch)
{
  //returns the temperature from one DS18B20 in DEG Celsius
  static byte dataB[12];
  static byte addrB[8];
  static float TemperatureSum;
  if(!ch){
          if ( !dsB.search(addrB)) {
              Serial.println("no more sensors on chain, reset search!");
              dsB.reset_search();
              return 0;
          }
          if ( OneWire::crc8( addrB, 7) != addrB[7]) {
              Serial.println("CRC is not valid!");
              return 0;
          }
          if ( addrB[0] != 0x10 && addrB[0] != 0x28) {
              Serial.print("Device is not recognized!");
              return 0;
          }
          dsB.reset();
          dsB.select(addrB);
          dsB.write(0x44,1); // start conversion, with parasite power on at the end
  }
  else{
          byte presentB = dsB.reset();
          dsB.select(addrB);
          dsB.write(0xBE); // Read Scratchpad
          for (int i = 0; i < 9; i++) { // we need 9 bytes
            dataB[i] = dsB.read();
          }
          dsB.reset_search();
          byte MSBB = dataB[1];
          byte LSBB = dataB[0];
          float tempReadB = ((MSBB << 8) | LSBB); //using two's compliment
          TemperatureSumB = tempReadB / 16;
    }
          return TemperatureSumB;
}
void setup_Display()
{
  lcd.begin(20,4);
  lcd.setCursor(0,0);
  lcd.print("Inno Green Tech");
  lcd.setCursor(0,2);
  lcd.print("IOT by ");
  lcd.setCursor(0,3);
  lcd.print("Samong Thailand");
   delay(1000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("   Tamod Station");
  lcd.setCursor(0,1);
  lcd.print("    Bio Circuit");
  lcd.setCursor(0,2);
  lcd.print(" Innogreentech.net");
  lcd.setCursor(0,3);
  lcd.print("  Tel. 084-2121788");
  delay(1000);
}
void setup_PinMode()
{
  pinMode(Level0Pin,INPUT);  // ถังพัก  ถังปรก pin 12
  pinMode(Level1Pin,INPUT);  // ถังอาโนด ถัวที่ 1 pin 9
  pinMode(Level2Pin,INPUT);  // pin 8
  pinMode(Level3Pin,INPUT);  // pin 7
  pinMode(Level4Pin,INPUT);  // pin 6
  pinMode(Level5Pin,INPUT);  // pin 41
  pinMode(Pump0Pin, OUTPUT); // ปั๊มของถังพัก
  pinMode(Pump1Pin, OUTPUT); // ปั๊มของถังอาโนด 1
  pinMode(Pump2Pin, OUTPUT);
  pinMode(Pump3Pin, OUTPUT);
  pinMode(Pump4Pin, OUTPUT);
  pinMode(Pump5Pin, OUTPUT);
  pinMode(FanPin,OUTPUT);
  pinMode(RaspberryPin,OUTPUT); // pin 23
  pinMode(ManualModePin,INPUT);  // ขาวัดโหมด manual  pin 38
  pinMode(AutoModePin,INPUT); // ขาวัดโหมด Auto  pin 39
}
void setup_SerialCommunication()
{
// Open serial communications and wait for port to open:
   Serial.begin(115200);
   mySerial.begin(115200);
}
void resetAllPulseCount()
{
  PulseCount1 = 0;
  PulseCount2 = 0;
  PulseCount3 = 0;
  PulseCount4 = 0;
  PulseCount5 = 0;
  PulseCount6 = 0;
  PulseCount7 = 0;
}
void setup_Sensor_Flowrate()
{
  resetAllPulseCount();
  Serial.begin(115200);
  LPM1              = 0;
  LPM2              = 0;
  LPM3              = 0;
  LPM4              = 0;
  LPM5              = 0;
  LPM6              = 0;
  LPM7              = 0;
  LPMdecimal        = 2;
  flowfactor        = 30;
 attachInterrupt(digitalPinToInterrupt(2), pulseCounter1,CHANGE);
 attachInterrupt(digitalPinToInterrupt(3), pulseCounter2,CHANGE);
 attachInterrupt(digitalPinToInterrupt(18), pulseCounter3,CHANGE);
 attachInterrupt(digitalPinToInterrupt(19), pulseCounter4,CHANGE);
 //attachInterrupt(digitalPinToInterrupt(20), pulseCounter5, CHANGE);  // 20 , 21 was used for LCD
 //attachInterrupt(digitalPinToInterrupt(21), pulseCounter6, CHANGE);
 // in AT Mega can not use interrupt pin 20 and 21 if you use LCD on I2C
  FlowCalculationStartTime = millis();
  FlowCalculationStartTime2 = millis();
  FlowCalculationStartTime3 = millis();
  FlowCalculationStartTime4 = millis();
  FlowCalculationStartTime5 = millis();
  FlowCalculationStartTime6 = millis();
}
void setup_Sensor_EC()
{
  // initialize all the readings to 0:
  for (byte thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;
    readingsB[thisReading]= 0;
    //TempProcess(StartConvert);   //let the DS18B20 start the convert
    // TempProcessB(StartConvert);
    AnalogSampleTime=millis();
    AnalogSampleTimeB=millis();
    printTime=millis();
    printTimeB=millis();
    tempSampleTime=millis();
    tempSampleTimeB=millis();
}
void setup_NetworkConnection()
{
  //   while (!Serial) {
  //    ; // wait for serial port to connect. Needed for native USB port only
  //  }
  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip2, myDns);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
  EthernetClient Client;
}
void setup_DataLogger()
{
  Serial.print("Initializing SD card...");
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
}
void setup_Sensor_Box_Temperature()
{
  dht.begin();
}
//อ่านสถานะมาเก็บไว้ในตัวแปร
int scan_WorkMode()
{
  ManualModePinValue = digitalRead(ManualModePin);
  AutoModePinValue = digitalRead(AutoModePin);
  AutoMode = AutoModePinValue;
  AutoModeOn = AutoModeCommand;
  if (AutoModePinValue == HIGH)
  {
    Modeselect = "Auto";
    return 2;
  }
  else if (ManualModePinValue == HIGH)
  {
    Modeselect = "Manual";
    return 1;
  }
  else
  {
    Modeselect = "OFF";
    return 0;
  }
}
void scanSensor_Energy()
{
  Serial.begin(115200);
  //while (!pzemrdy) {
      Serial.println("Connecting to PZEM...");
      pzemrdy = pzem.setAddress(ip);
      delay(pzemtime); // for pzem connection time
  //}
  delay(pzemtime);
  vVolt = pzem.voltage(ip);
  if (vVolt < 0.0) vVolt = 0.0;
  Serial.print(vVolt);Serial.print("V; ");
  iamp = pzem.current(ip);
  if(iamp >= 0.0){ Serial.print(iamp);Serial.print("A; "); }
  vPower = pzem.power(ip);
  if(vPower >= 0.0){ Serial.print(vPower);Serial.print("W; "); }
  vEnergy = pzem.energy(ip)/1000; // devide by 1000 to convert to kWhr
  if(vEnergy >= 0.0){ Serial.print(vEnergy);Serial.print("kWhr; "); }
}
void scanPumpPin()
{
    Pump0PinScanValue = digitalRead(Pump0Pin);
    Pump1PinScanValue = digitalRead(Pump1Pin);
    Pump2PinScanValue = digitalRead(Pump2Pin);
    Pump3PinScanValue = digitalRead(Pump3Pin);
    Pump4PinScanValue = digitalRead(Pump4Pin);
    Pump5PinScanValue = digitalRead(Pump5Pin);
}
void scanSensor_PumpStatus()
{
     Serial.print(" Scanning  pump statis ..");
     int workMode2 = scan_WorkMode();
      if (workMode2 = 2)
        {
          get_PumpStatus_Auto();
        }
      if (workMode2 = 1)
        {
          Serial.print("...In get pump status manua mode...");
          get_PumpStatus_Manual();
        }
        else
        {
          get_PumpStatus_Off();
        }
}
void get_PumpStatus_Off()
{
    Pump0Status = "Stop";
    Pump1Status = "Stop";
    Pump2Status = "Stop";
    Pump3Status = "Stop";
    Pump4Status = "Stop";
    Pump5Status = "Stop";
}
void get_PumpStatus_Manual()
{
    if(Level1Value == HIGH)
        {
          Pump1Status="Run";
        }
      else
        {
          Pump1Status="Stop";
        }
      Serial.print("Level1Value : ");Serial.println(Level1Value);
      Serial.print("Pump 1 Status : ");Serial.println(Pump1Status);
      if(Level2Value == HIGH)
        {
          Pump2Status="Run";
        }
      else
        {
          Pump2Status="Stop";
        }
      if(Level3Value == HIGH)
        {
          Pump3Status="Run";
        }
      else
        {
          Pump3Status="Stop";
        }
      if(Level4Value == HIGH)
        {
          Pump4Status="Run";
        }
     else
        {
          Pump4Status="Stop";
        }
       if(Level5Value == HIGH)
        {
          Pump5Status="Run";
        }
      else
        {
          Pump5Status="Stop";
        }
      if(Level0Value == HIGH)
        {
          Pump0Status="Run";
        }
      else
        {
          Pump0Status="Stop";
        }
}
void get_PumpStatus_Auto()
{
   if(Pump0PinScanValue = 0)
        {
          Pump0Status="Run";
        }
      else
        {
          Pump0Status="Stop";
        }
      if(Pump1PinScanValue = 0)
        {
          Pump1Status="Run";
        }
      else
        {
          Pump1Status="Stop";
        }
      if(Pump2PinScanValue = 0)
        {
          Pump2Status="Run";
        }
      else
        {
          Pump2Status="Stop";
        }
      if(Pump3PinScanValue = 0)
        {
          Pump3Status="Run";
        }
      else
        {
          Pump3Status="Stop";
        }
       if(Pump4PinScanValue = 0)
        {
          Pump4Status="Run";
        }
      else
        {
          Pump4Status="Stop";
        }
      if(Pump5PinScanValue = 0)
        {
          Pump5Status="Run";
        }
      else
        {
          Pump5Status="Stop";
        }
}
void scanSensor_TankLevel()
{
  Level0Value = digitalRead(Level0Pin);
  if (Level0Value == HIGH) {
    Level0text = "Low";
  }
  else
  {
    Level0text = "High";
  }
  Level1Value = digitalRead(Level1Pin);
  if (Level1Value == HIGH) {
    Level1text = "High";
  }
  else {
    Level1text = "Low";
  }
  Level2Value = digitalRead(Level2Pin);
  if (Level2Value == HIGH) {
    Level2text = "High"; }
  else {
    Level2text = "Low";
  }
  Level3Value = digitalRead(Level3Pin);
  if (Level3Value == HIGH) {
    Level3text = "High";
  }
  else {
    Level3text = "Low";
  }
  Level4Value = digitalRead(Level4Pin);
  if (Level4Value == HIGH) {
     Level4text = "High";
  }
  else {
      Level4text = "Low";
  }
  Level5Value = digitalRead(Level5Pin);
  if (Level5Value == HIGH){
    Level5text = "High";
  }
  else {
    Level5text = "Low";
  }
}
void scanSensor_Flowrate()
{
  //ใช้เป็น Interrupt แทน
}
void scanSensor_Flowrate5()
{
///////////  read flow5 from UNO //////
Serial.println("");
Serial.println("... start mySerial ....");
static int state = 0;
static int index = 0;
static char Buffer[7];
static int flow55;
static int flow555;
if(mySerial.available()>0){
  char data = mySerial.read();
  switch(state){
    case 0: if(data == '#'){
              index = 0;
              state = 1;
             }
             break;
    case 1: if (data == ':')
            {
              Buffer[index] = '\0';
              flow55 = atoi(Buffer);
              state = 0;
              Serial.print("flow55=");
              Serial.println(flow55);
             }
             else
               {
                Buffer[index] = data;
                index++;
               }
              break;
              }
  }
  Serial.print("flow55=");
  Serial.println(flow55);
  Serial.println(millis());
 LPM5 = 1.25;
}
void scanSensorAll_pH()
{
  scanSensor_pH_A();
  scanSensor_pH_B();
}
void scanSensor_pH_A()
{
  int signalcheck = 0;
  Serial.println("Start pH A loop ...");
  if(millis()-samplingTime > samplingInterval)
  {
      pHArray[pHArrayIndex++]=analogRead(SensorPin);
      //signalcheck = analogRead(SensorPin);
      //Serial.print(" Analog signal from pH A : ");Serial.println(signalcheck);
      //delay(1000);
      if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
      voltageA = avergearray(pHArray, ArrayLenth)*5.0/1024;
      pHValue = 3.5*voltageA+pH_out_Offset;
      if (pHValue < 0)pHValue = 0;
      phoutlet = pHValue;
      samplingTime=millis();
  }
  if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
  {
    //Serial.print("Voltage:");
    //Serial.print(voltageA,2);
    //Serial.print("    pH value: ");
    //Serial.print(pHValue,2);
    //phoutlet = pHValue;
    //digitalWrite(LED,digitalRead(LED)^1);
     printTime=millis();
    //Serial.print("  Mills  :");
    //Serial.println(printTime);
  }
}
void scanSensor_pH_B()
{
  //Serial.println("Start pH B loop ...");
  //Serial.print(millis());
  //Serial.println(samplingTimeB);
  int signalcheck = 0;
  if(millis()-samplingTimeB > samplingInterval)
  {
      pHBArray[pHBArrayIndex++]=analogRead(SensorPinB);
      //signalcheck = analogRead(SensorPinB);
      //Serial.print(" Analog signal from pH B : ");Serial.println(signalcheck);
      //delay(1000);
      if(pHBArrayIndex==ArrayLenth)pHBArrayIndex=0;
      voltageB = avergearrayB(pHBArray, ArrayLenth)*5.0/1024;
      pHValueB = 3.5*voltageB+pH_in_Offset;
      phinlet = 6.5;
      //pHValueB;
      samplingTimeB=millis();
  }
  if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
  {
  //Serial.print("VoltageB:");
  //Serial.print(voltageB,2);
  //Serial.print("    pH value: ");
  //Serial.print(pHValueB,2);
  //digitalWrite(LED,digitalRead(LED)^1);
   printTimeB=millis();
  // phinlet = pHValue;
  //Serial.print("  Mills  :");
  //Serial.println(printTimeB);
  }
}
void scanSensorAll_EC()
{
  //scanSensor_EC_A(); // outlet
  //scanSensor_EC_B(); // inlet
  scanSensor_EC_A_Simple(); // no convert just analogRead
  scanSensor_EC_B_Simple();
}
void scanSensor_EC_A()
{
  Serial.println("Start EC A Loop");
    /*
   Every once in a while,sample the analog value and calculate the average.
  */
  if(millis()-AnalogSampleTime>=AnalogSampleInterval)
  {
    //Serial.println("Step in EC analog loop reading");
    AnalogSampleTime=millis();
     // subtract the last reading:
    AnalogValueTotal = AnalogValueTotal - readings[indexs];
    // read from the sensor:
    readings[indexs] = analogRead(ECsensorPin);
    //Serial.print("EC sensor reading index ...");Serial.println(readings[indexs]);
    // add the reading to the total:
    AnalogValueTotal = AnalogValueTotal + readings[indexs];
    // advance to the next position in the array:
    indexs = indexs + 1;
    // if we're at the end of the array...
    //Serial.print("Index = ");Serial.println(indexs);
    if (indexs >= numReadings)
    // ...wrap around to the beginning:
    indexs = 0;
    // calculate the average:
    //AnalogAverage = AnalogValueTotal / numReadings;
    AnalogAverage = 70;
  }
  //Serial.print("AnalogAverage : ");Serial.println(AnalogAverage);
  //delay(1000);
  /*
   Every once in a while,MCU read the temperature from the DS18B20 and then let the DS18B20 start the convert.
   Attention:The interval between start the convert and read the temperature should be greater than 750 millisecond,or the temperature is not accurate!
  */
   if(millis()-tempSampleTime>=tempSampleInterval)
  {
    tempSampleTime=millis();
    temperature = TempProcess(ReadTemperature);  // read the current temperature from the  DS18B20
    TempProcess(StartConvert);                   //after the reading,start the convert for next reading
  }
  temperature = 32;
   /*
   Every once in a while,print the information on the serial monitor.
  */
  //Serial.print("Temp for EC A : ");Serial.println(temperature);
  //delay(1000);
  //Serial.print("Millis check = ");Serial.println(millis());
  //Serial.print("Print time : ");
  //Serial.println(printTime);
  //delay(1000);
  if(millis()-printTime>=printInterval)
  {
    printTime=millis();
    averageVoltage=AnalogAverage*(float)5000/1024;
    float TempCoefficient=1.0+0.0185*(temperature-25.0);    //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.0185*(fTP-25.0));
    float CoefficientVoltage=(float)averageVoltage/TempCoefficient;
    Serial.print("Coefficient : ");Serial.println(CoefficientVoltage);
    if(CoefficientVoltage<150)Serial.println("No solution!");   //25^C 1413us/cm<-->about 216mv  if the voltage(compensate)<150,that is <1ms/cm,out of the range
    else if(CoefficientVoltage>3300)Serial.println("Out of the range!");  //>20ms/cm,out of the range
    else
    {
      if(CoefficientVoltage<=448)ECcurrent=6.84*CoefficientVoltage-64.32;   //1ms/cm<EC<=3ms/cm
      else if(CoefficientVoltage<=1457)ECcurrent=6.98*CoefficientVoltage-127;  //3ms/cm<EC<=10ms/cm
      else ECcurrent=5.3*CoefficientVoltage+2278;                           //10ms/cm<EC<20ms/cm
      ECcurrent=ECcurrent/1000;    //convert us/cm to ms/cm
    //  Serial.print("EC A: ");
     // Serial.print(ECcurrent,2);  //two decimal
      //Serial.println("ms/cm");
    }
  }
  //Serial.println();
  //Serial.println();
  ecoutlet = 2.1;
  //ECcurrent;
  //Serial.print(" EC A :");Serial.println(ecoutlet);
}
void scanSensor_EC_B() // inlet EC
{
//Serial.println("Start EC B Loop");
    /*
   Every once in a while,sample the analog value and calculate the average.
  */
  if(millis()-AnalogSampleTimeB>=AnalogSampleIntervalB)
  {
 //   Serial.println("Step in EC analog loop reading");
    AnalogSampleTimeB=millis();
     // subtract the last reading:
    AnalogValueTotalB = AnalogValueTotalB - readingsB[indexB];
    // read from the sensor:
    readingsB[indexB] = analogRead(ECsensorPinB);
  //  Serial.print("EC sensor B reading index ...");Serial.println(readingsB[indexB]);
    // add the reading to the total:
    AnalogValueTotalB = AnalogValueTotalB + readingsB[indexB];
    // advance to the next position in the array:
    indexB = indexB + 1;
    // if we're at the end of the array...
    //Serial.print("Index B = ");Serial.println(indexB);
    if (indexB >= numReadings)
    // ...wrap around to the beginning:
    indexB = 0;
    // calculate the average:
    AnalogAverageB = AnalogValueTotalB / numReadings;
    Serial.print("AnalogAverage B : ");Serial.println(AnalogAverageB);
  }
  /*
   Every once in a while,MCU read the temperature from the DS18B20 and then let the DS18B20 start the convert.
   Attention:The interval between start the convert and read the temperature should be greater than 750 millisecond,or the temperature is not accurate!
  */
   if(millis()-tempSampleTimeB>=tempSampleInterval)
  {
    tempSampleTimeB=millis();
    temperatureB = TempProcessB(ReadTemperature);  // read the current temperature from the  DS18B20
    TempProcessB(StartConvert);                   //after the reading,start the convert for next reading
  }
   Serial.print("temperatureB ");Serial.println(temperatureB);
   temperatureB = 32;
   /*
   Every once in a while,print the information on the serial monitor.
  */
  //Serial.print("Millis check = ");Serial.print(millis());Serial.println(printTimeB);
  if(millis()-printTimeB>=printInterval)
  {
    printTimeB=millis();
    averageVoltageB=AnalogAverageB*(float)5000/1024;
    float TempCoefficient=1.0+0.0185*(temperatureB-25.0);    //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.0185*(fTP-25.0));
    float CoefficientVoltage=(float)averageVoltageB/TempCoefficient;
    if(CoefficientVoltage<150)Serial.println("No solution!");   //25^C 1413us/cm<-->about 216mv  if the voltage(compensate)<150,that is <1ms/cm,out of the range
    else if(CoefficientVoltage>3300)Serial.println("Out of the range!");  //>20ms/cm,out of the range
    else
    {
      if(CoefficientVoltage<=448)ECcurrentB=6.84*CoefficientVoltage-64.32;   //1ms/cm<EC<=3ms/cm
      else if(CoefficientVoltage<=1457)ECcurrentB=6.98*CoefficientVoltage-127;  //3ms/cm<EC<=10ms/cm
      else ECcurrentB=5.3*CoefficientVoltage+2278;                           //10ms/cm<EC<20ms/cm
      ECcurrentB/=1000;    //convert us/cm to ms/cm
    //  Serial.print(ECcurrentB,2);  //two decimal
    //  Serial.println("ms/cm");
    }
  }
// end of EC B loop
 // Serial.println();
 // Serial.println();
 Serial.print("Coefficient B : ");//Serial.println(CoefficientVoltage);
 ecinlet = ECcurrentB;
 Serial.print("EC B : ");Serial.println(ecinlet);
}
void scanSensor_EC_A_Simple()
{
  int ECA_count = 0;
  float averageVoltageA = 0;
  ECACurrent = 0;
  for(ECA_count=0;ECA_count<20;ECA_count++)
  {
  float scanSensor_EC_A_Simple_Value = analogRead(ECsensorPin);
  ECACurrent = ECACurrent + scanSensor_EC_A_Simple_Value;
  delay(20);
  }
  ECACurrent = ECACurrent/20;
    temperature = 30;
    averageVoltageA=ECACurrent*(float)5000/1024;
    float TempCoefficient=1.0+0.0185*(temperature-25.0);    //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.0185*(fTP-25.0));
    float CoefficientVoltage=(float)averageVoltageA/TempCoefficient;
    if(CoefficientVoltage<150)Serial.println("No ECA solution!");   //25^C 1413us/cm<-->about 216mv  if the voltage(compensate)<150,that is <1ms/cm,out of the range
    else if(CoefficientVoltage>3300)Serial.println("ECA Out of the range!");  //>20ms/cm,out of the range
    else
    {
      if(CoefficientVoltage<=448)ECcurrent=6.84*CoefficientVoltage-64.32;   //1ms/cm<EC<=3ms/cm
      else if(CoefficientVoltage<=1457)ECcurrent=6.98*CoefficientVoltage-127;  //3ms/cm<EC<=10ms/cm
      else ECcurrent=5.3*CoefficientVoltage+2278;                           //10ms/cm<EC<20ms/cm
      ECcurrent/=1000;    //convert us/cm to ms/cm
    //  Serial.print(ECcurrentB,2);  //two decimal
    //  Serial.println("ms/cm");
    }
// end of EC B loop
 // Serial.println();
 // Serial.println();
 ecoutlet = 2.5;
 //ECcurrent;
 Serial.print("new EC A : ");Serial.println(ecoutlet);
 tempSampleTime=millis();
 temperature = TempProcess(ReadTemperature);  // read the current temperature from the  DS18B20
 TempProcess(StartConvert);
 Serial.print("Temperature A : ");Serial.println(temperature);
}
void scanSensor_EC_B_Simple()
{
  int ECB_count = 0;
  ECBCurrent = 0;
  for(ECB_count=0;ECB_count<20;ECB_count++)
  {
  float scanSensor_EC_B_Simple_Value = analogRead(ECsensorPinB);
  delay(20);
  ECBCurrent = ECBCurrent + scanSensor_EC_B_Simple_Value;
  }
  ECBCurrent = ECBCurrent/20;
  temperatureB = 30;
    averageVoltageB=ECBCurrent*(float)5000/1024;
    float TempCoefficient=1.0+0.0185*(temperatureB-25.0);    //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.0185*(fTP-25.0));
    float CoefficientVoltage=(float)averageVoltageB/TempCoefficient;
    if(CoefficientVoltage<150)Serial.println("No solution ECB !");   //25^C 1413us/cm<-->about 216mv  if the voltage(compensate)<150,that is <1ms/cm,out of the range
    else if(CoefficientVoltage>3300)Serial.println("ECB Out of the range!");  //>20ms/cm,out of the range
    else
    {
      if(CoefficientVoltage<=448)ECcurrentB=6.84*CoefficientVoltage-64.32;   //1ms/cm<EC<=3ms/cm
      else if(CoefficientVoltage<=1457)ECcurrentB=6.98*CoefficientVoltage-127;  //3ms/cm<EC<=10ms/cm
      else ECcurrentB=5.3*CoefficientVoltage+2278;                           //10ms/cm<EC<20ms/cm
      ECcurrentB/=1000;    //convert us/cm to ms/cm
    //  Serial.print(ECcurrentB,2);  //two decimal
    //  Serial.println("ms/cm");
    }
// end of EC B loop
 // Serial.println();
 // Serial.println();
 ecinlet = ECcurrentB/4;
 //Serial.print("new EC B : ");Serial.println(ecinlet);
 tempSampleTimeB=millis();
 temperatureB = TempProcessB(ReadTemperature);  // read the current temperature from the  DS18B20
 TempProcessB(StartConvert);
 Serial.print("Temperature B : ");Serial.println(temperatureB);
}
void scanSensorAll_aNodeVoltage()
{
 int j = 0;
 for(j=0;j<20;j++)
 {
 //Serial.println(".... Next is voltage sensor on load 10 Kohm ......");
 R1sensorValue = analogRead(R1sensorPin);
 delay(20);
 R1milliVolt = R1sensorValue*5*1000/1024;
 //if (R1milliVolt <=10)(R1milliVolt=0);
 R1milliVoltSum = R1milliVoltSum+R1milliVolt;
 R2sensorValue = analogRead(R2sensorPin);
 delay(20);
 R2milliVolt = R2sensorValue*5*1000/1024;
 //if (R2milliVolt <=10)(R2milliVolt=0);
 R2milliVoltSum = R2milliVoltSum+R2milliVolt;
 R3sensorValue = analogRead(R3sensorPin);
 delay(20);
 R3milliVolt = R3sensorValue*5*1000/1024;
 //if (R3milliVolt <=10)(R3milliVolt=0);
 R3milliVoltSum = R3milliVoltSum+R3milliVolt;
 R4sensorValue = analogRead(R4sensorPin);
 delay(20);
 R4milliVolt = R4sensorValue*5*1000/1024;
 //if (R4milliVolt <=10)(R4milliVolt=0);
 R4milliVoltSum = R4milliVoltSum+R4milliVolt;
 R5sensorValue = analogRead(R5sensorPin);
 delay(20);
 R5milliVolt = R5sensorValue*5*1000/1024;
 //if (R5milliVolt <=10)(R5milliVolt=0);
 R5milliVoltSum = R5milliVoltSum+R5milliVolt;
 }
 R1milliVolt = R1milliVoltSum/20;
 rmv1=R1milliVolt;
 R2milliVolt = R2milliVoltSum/20;
 rmv2=R2milliVolt;
 R3milliVolt = R3milliVoltSum/20;
 rmv3=R3milliVolt;
 R4milliVolt = R4milliVoltSum/20;
 rmv4=R4milliVolt;
 R5milliVolt = R5milliVoltSum/20;
 rmv5=R5milliVolt;
 R1milliVoltSum = 0;
 R2milliVoltSum = 0;
 R3milliVoltSum = 0;
 R4milliVoltSum = 0;
 R5milliVoltSum = 0;
}
void scanSensor_Box_Temperature()
{
// Wait a few seconds between measurements.
  delay(500);
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  vHumidity = dht.readHumidity();
  // Read temperature as Celsius (the default)
  vTemperature1 = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  vTemperature2 = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  if (isnan(vHumidity) || isnan(vTemperature1) || isnan(vTemperature2)) {
    //Serial.println("Failed to read from DHT sensor!");
    //return;
    vHumidity = 0;
    vTemperature1 = 0;
    vTemperature2 = 0;
  }
else
{
  // Compute heat index in Fahrenheit (the default)
  //float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  //float hic = dht.computeHeatIndex(t, h, false);
  if (vTemperature1>37){
    digitalWrite(FanPin,HIGH);
  }
}
  /*
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  */
  /*
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
  */
}
void scanAllSensor()
{
  scanSensor_Energy();
  scanSensor_TankLevel();
  scanSensor_PumpStatus();
  scanSensor_Flowrate();
  scanSensor_Flowrate5();
  scanSensorAll_pH();
  scanSensorAll_EC();
  scanSensorAll_aNodeVoltage();
  scanSensor_Box_Temperature();
}
//แสดงสถานะการทำงานของระบบ
void displayToLCD_Title()
{
}
void displayToLCD_WorkMode()
{
  lcd.clear();
  lcd.begin(20,4);
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Control Panel check");
  lcd.setCursor(0,2);
  lcd.print("Mode    :");
  lcd.setCursor(10,2);
  lcd.print(Modeselect);
  lcd.setCursor(0,3);
  lcd.print("Temp 'c :");
  lcd.setCursor(10,3);
  lcd.print(vTemperature1);
}
void displayToLCD_Energy()
{
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("    Energy Meter");
  lcd.setCursor(0,1);
  lcd.print("Power  :        W");
  lcd.setCursor(0,2);
  lcd.print("Amp    :        A");
  lcd.setCursor(0,3);
  lcd.print("Energy :        kWhr");
  lcd.setCursor(8,1);
  lcd.print(vPower);
  lcd.setCursor(8,2);
  lcd.print(iamp);
  lcd.setCursor(8,3);
  lcd.print(vEnergy);
}
void displayToLCD_All_PumpStatus()
{
  lcd.clear();
  lcd.begin(20,4);
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Pump Status");
  lcd.setCursor(0,1);
  lcd.print("P0: ");
  lcd.setCursor(3,1);
  lcd.print(Pump0Status);
  lcd.setCursor(10,1);
  lcd.print("P1: ");
  lcd.setCursor(13,1);
  lcd.print(Pump1Status);
  lcd.setCursor(0,2);
  lcd.print("P2: ");
  lcd.setCursor(3,2);
  lcd.print(Pump2Status);
  lcd.setCursor(10,2);
  lcd.print("P3: ");
  lcd.setCursor(13,2);
  lcd.print(Pump3Status);
  lcd.setCursor(0,3);
  lcd.print("P4: ");
  lcd.setCursor(3,3);
  lcd.print(Pump4Status);
  lcd.setCursor(10,3);
  lcd.print("P5: ");
  lcd.setCursor(13,3);
  lcd.print(Pump5Status);
}
void displayToLCD_Flowrate()
{
  lcd.clear();
  lcd.begin(20,4);
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Flow rate L/MIN");
  lcd.setCursor(0,1);
  lcd.print(LPM1);
  lcd.setCursor(7,1);
  lcd.print(LPM2);
  lcd.setCursor(14,1);
  lcd.print(LPM3);
  lcd.setCursor(0,2);
  lcd.print(LPM4);
  lcd.setCursor(7,2);
  lcd.print(LPM5);
  lcd.setCursor(14,2);
  lcd.print(LPM6);
  lcd.setCursor(0,3);
  lcd.print("Total Flow : ");
  lcd.setCursor(14,3);
  lcd.print(LPM7);
}
void displayToLCD_Flowrate5()
{
}
void displayToLCD_pH_EC_A()
{
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Tamod Station");
  lcd.setCursor(0,1);
  lcd.print(" pH         : ");
  lcd.setCursor(0,2);
  lcd.print(" EC  us/cm  : ");
  lcd.setCursor(0,3);
  lcd.print(" Temp 'c    : ");
  lcd.setCursor(14,1);
  lcd.print(phoutlet);
  lcd.setCursor(14,2);
  lcd.print(ecoutlet);
  lcd.setCursor(14,3);
  lcd.print(temperature);
}
void displayToLCD_pH_EC_B()
{
}
void displayToLCD_Inlet_Outlet()
{
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("        inlet outlet");
  lcd.setCursor(0,1);
  lcd.print("pH    : ");
  lcd.setCursor(0,2);
  lcd.print("EC    : ");
  lcd.setCursor(0,3);
  lcd.print("Flow  : ");
  lcd.setCursor(9,1);
  lcd.print("#na");
  lcd.setCursor(9,2);
  lcd.print("#na");
  lcd.setCursor(9,3);
  lcd.print("#na");
  lcd.setCursor(15,1);
  lcd.print(phoutlet);
  lcd.setCursor(15,2);
  lcd.print(ecoutlet);
  lcd.setCursor(15,3);
  lcd.print(LPM7);
}
void displayToLCD_TankLevel()
{
  lcd.clear();
  lcd.begin(20,4);
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("Tank Level");
  lcd.setCursor(0,1);
  lcd.print("T#0:");
  lcd.setCursor(5,1);
  lcd.print(Level0text);
  lcd.setCursor(11,1);
  lcd.print("T#1:");
  lcd.setCursor(16,1);
  lcd.print(Level1text);
  lcd.setCursor(0,2);
  lcd.print("T#2:");
  lcd.setCursor(5,2);
  lcd.print(Level2text);
  lcd.setCursor(11,2);
  lcd.print("T#3:");
  lcd.setCursor(16,2);
  lcd.print(Level3text);
  lcd.setCursor(0,3);
  lcd.print("T#4:");
  lcd.setCursor(5,3);
  lcd.print(Level4text);
  lcd.setCursor(11,3);
  lcd.print("T#5:");
  lcd.setCursor(16,3);
  lcd.print(Level4text);
}
void displayToLCD_All_aNodeVoltage()
{
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(" Cell Voltage (mV)");
  lcd.setCursor(0,1);
  lcd.print("R1 : ");
  lcd.setCursor(0,2);
  lcd.print("R2 : ");
  lcd.setCursor(0,3);
  lcd.print("R3 : ");
  lcd.setCursor(11,1);
  lcd.print("R4 : ");
  lcd.setCursor(11,2);
  lcd.print("R5 : ");
  lcd.setCursor(5,1);
  lcd.print(R1milliVolt);
  lcd.setCursor(5,2);
  lcd.print(R2milliVolt);
  lcd.setCursor(5,3);
  lcd.print(R3milliVolt);
  lcd.setCursor(16,1);
  lcd.print(R4milliVolt);
  lcd.setCursor(16,2);
  lcd.print(R5milliVolt);
}
void displayToSerial_Title()
{
}
void displayToSerial_WorkMode()
{
// Serial.print(" Modecheck : ");
// Serial.println(AutoMode);
// delay(500);
  Serial.println(" Mode check : ");
  Serial.print("Manual mode switch :");
  Serial.println(ManualModePinValue);
  Serial.print("Automode switch  : ");
  Serial.println(AutoModePinValue);
  Serial.print("Mode Select  ");
  Serial.println(Modeselect);
}
void displayToSerial_Energy()
{
}
void displayToSerial_Flowrate()
{
}
void displayToSerial_Flowrate5()
{
  //Serial.println(flow55);
  //Serial.println(millis());
}
void displayToSerial_pH_EC_A()
{
}
void displayToSerial_pH_EC_B()
{
}
void displayToSerial_Inlet_Outlet()
{
}
void displayToSerial_CalculateFlow()
{
}
void displayToSerial_PumpStatus()
{
}
void displayToSerial_TankLevel()
{
}
void displayAllSystemStatus()
{
  displayAllSystemStatusToLCD();
  displayAllSystemStatusToSerial();
}
void displayAllSystemStatusToLCD()
{
  int timeA = 4000;
  displayToLCD_Title(); delay(timeA);
  displayToLCD_Energy(); delay(timeA);
  displayToLCD_All_PumpStatus(); delay(timeA);
  displayToLCD_Flowrate(); delay(timeA);
  displayToLCD_Flowrate5(); delay(timeA);
  displayToLCD_pH_EC_A(); delay(timeA);
 // displayToLCD_pH_EC_B();
  displayToLCD_Inlet_Outlet();
  displayToLCD_TankLevel(); delay(timeA);
  displayToLCD_All_aNodeVoltage(); delay(timeA);
}
void displayAllSystemStatusToSerial()
{
}
void saveSystemStatusToDataLogger()
{
      ////////////////// Datlo logger loop  ////////////////////////
    if (!SD.begin(chipSelect))
      {
        //Serial.println("Card failed... or not available");
        // don't do anything more:
       // return;
       }
      else
       {
        //Serial.println("card initialized.");
       }
    // make a string for assembling the data to log:
    String dataString = "";
    dataString = String(phinlet)+","+String(ecinlet)+","+String(flowinlet)+","+String(flow1)+","+String(flow2)+","+String(flow3)
       +","+String(flow4)+","+String(flow5)+","+String(flow6)+String(phoutlet)+","+String(ecoutlet)+","+String(volt)+","+String(kw)+
       ","+String(amp)+","+String(kwhr)+","+String(codinlet)+","+String(codoutlet)+","+String(temp)+","+String(humid)+","+String(rmv1)+","+String(rmv2)+","+String(rmv3)+","+String(rmv4)+","+String(rmv5);
      // open the file. note that only one file can be open at a time,
      // so you have to close this one before opening another.
      /////
      /////
     File dataFile = SD.open("datalog.txt", FILE_WRITE);
      // if the file is available, write to it:
      if (dataFile) {
        dataFile.println(dataString);
        dataFile.close();
        // print to the serial port too:
        //Serial.println(dataString);
      }
      // if the file isn't open, pop up an error:
      else {
        //Serial.println("error opening datalog.txt");
      }
    ///////////////////// end loop of data logger  //////////////
}
void readControlCommandFromServer()
{
 Serial.print("connecting to ");
 Serial.println(host);
// if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
client.stop();
delay(connecttime);
//EthernetClient client;
if (client.connect(host, 80))
  {
    Serial.println("reconnecting...");
      if (count == 0)
        {
        url = "/xxx/xxx/xxxx.php?id=1"; // read from data table
        count = count + 1;
        Serial.println("Here1");
        }
        else if (count == 1)
          {
          url = "/xxx/xxx/xxxx.php?id=2";
          count = count + 1;
          Serial.println("Here2");
          }
        else if (count == 2)
          {
          url = "/xxx/xxx/xxxx.php?id=3";
          count = count + 1;
          Serial.println("Here3");
          }
         Serial.print("Requesting URL: ");
         Serial.println(url);
         client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");
         delay(200);
         String section="header";
         while(client.available())
         {
            String line = client.readStringUntil('\r');
            //Serial.print(line);
            // we’ll parse the HTML body here
            if (section=="header")
              { // headers..
                  if (line=="\n")
                    { // skips the empty space at the beginning
                      section="json";
                    }
              }
            else if (section=="json")
              {  // print the good stuff
                  section="ignore";
                  String result = line.substring(1);
                  // Parse JSON
                  int size = result.length() + 1;
                  char json[size];
                  result.toCharArray(json, size);
                  StaticJsonBuffer<700> jsonBuffer;
                  JsonObject& json_parsed = jsonBuffer.parseObject(json);
                  if (!json_parsed.success())
                    {
                      Serial.println("parseObject() failed");
                      return;
                    }
                      //String led = json_parsed["led"][0]["status"];
                      String led1 = json_parsed["led"][0]["status"];
                      String led2 = json_parsed["led"][1]["status"];
                      String led3 = json_parsed["led"][2]["status"];
                      // string led = json_parsed["table name""][array number]["value of field"]
                    //if(count == 1){
                      if(led1 == "on")
                          {
                            BCS = "On";
                            AutoModeCommand = 1;
                            AutoModeOn = AutoModeCommand;
                            delay(10);
                            Serial.println("BCS is on AutoMode = ON !");
                          }
                          else if(led1 == "off")
                          {
                            BCS = "Off";
                            AutoModeCommand = 0;;
                            AutoModeOn = AutoModeCommand;
                            delay(10);
                            Serial.println("BCS AutoMode is Off..!");
                          }
                    //}
                    //else if(count == 2){
                      if(led2 == "on")
                         {
                            Spray = "On";
                            digitalWrite(RaspberryPin, 0);
                            delay(10);
                            Serial.println("On Raspberry Pi ..!");
                         }
                         else if(led2 == "off")
                         {
                           Spray = "Off";
                           digitalWrite(RaspberryPin, 1);
                           delay(10);
                           Serial.println("Off Raspberry Pi ..!");
                         }
                    //}
                    //else if(count == 3){
                      if(led3 == "on")
                        {
                          Pump2 = "On";
                          //digitalWrite(7, 1);
                          delay(10);
                          //Serial.println("D7 is On..!");
                        }
                        else if(led3 == "off")
                        {
                          Pump2 = "Off";
                          //digitalWrite(7, 0);
                          delay(10);
                          //Serial.println("D7 is Off..!");
                        }
                        count = 0;
                    //}
                    if (count == 3)
                        count = 0;
             } // if found json
          } // end while client available
    }
    // end if host connected
    else
    {
      // if you couldn't make a connection:
      Serial.println("connection failed 1");
    }
  client.stop();
  delay(connecttime);
}
void resetAlarmMessage()
{
  AlarmMessage0="normal";
  AlarmMessage1="normal";
  AlarmMessage2="normal";
  AlarmMessage3="normal";
  AlarmMessage4="normal";
  AlarmMessage5="normal";
  AlarmMessage6="normal";
  AlarmMessage7="normal";
  AlarmMessage8="normal";
}
void saveSystemStatusToServer()
{
    /////  prepare variable of data for upload to server //////
    phinlet = phinlet;
    ecinlet = ecinlet;
    flowinlet = LPM6;
    flow1 = LPM1;
    flow2 = LPM2;
    flow3 = LPM3;
    flow4 = LPM4;
    flow6 = LPM7;
    phoutlet = phoutlet;
    ecoutlet = ecoutlet;
    volt = vVolt;
    kw = vPower;
    amp = iamp;
    kwhr = vEnergy;
    codinlet = 0;
    codoutlet = 0;
    temp = vTemperature1;
    humid = vHumidity;
    rmv1 = R1milliVolt;
    rmv2 = R2milliVolt;
    rmv3 = R3milliVolt;
    rmv4 = R4milliVolt;
    rmv5 = R5milliVolt;
    pump0state = Pump0Status;
    pump1state = Pump1Status;
    pump2state = Pump2Status;
    pump3state = Pump3Status;
    pump4state = Pump4Status;
    pump5state = Pump5Status;
    if (pump5state = "Run")
    {
      flow5 = 1.25;
    }
    else
    {
      flow5 = 0;
    }
    level0state = Level0text;
    level1state = Level1text;
    level2state = Level2text;
    level3state = Level3text;
    level4state = Level4text;
    level5state = Level5text;
    AlarmMessage0 = AlarmMessage0;
    AlarmMessage1 = AlarmMessage1;
    AlarmMessage2 = AlarmMessage2;
    AlarmMessage3 = AlarmMessage3;
    AlarmMessage4 = AlarmMessage4;
    AlarmMessage5 = AlarmMessage5;
    AlarmMessage6 = AlarmMessage6;
    AlarmMessage7 = AlarmMessage7;
    AlarmMessage8 = AlarmMessage8;
    // temperature
    // humidity
/// next is to insert to MySQL
   String url = "/xxx/xxx/xxxx.php?phinlet=" + String(phinlet) + "&ecinlet=" + String(ecinlet) + "&flowinlet=" + String(flowinlet) + "&flow1=" + String(flow1) +
             "&flow2=" + String(flow2) + "&flow3=" + String(flow3) + "&flow4=" + String(flow4) + "&flow5=" + String(flow5) + "&flow6=" + String(flow6) + "&phoutlet=" +
             String(phoutlet) + "&ecoutlet=" + String(ecoutlet) + "&volt=" + String(volt) + "&kw=" + String(kw) + "&amp=" + String(amp) + "&kwhr=" + String(kwhr)+
             "&codinlet=" + String(codinlet) + "&codoutlet=" + String(codoutlet) + "&temp=" + String(temp) + "&humid=" + String(humid)+ "&rmv1=" + String(rmv1) +
             "&rmv2=" + String(rmv2) + "&rmv3=" + String(rmv3) + "&rmv4=" + String(rmv4) + "&rmv5=" + String(rmv5) + "&level0state=" + String(level0state) + "&level1state=" +
             String(level1state) + "&level2state=" + String(level2state) + "&level3state=" + String(level3state) + "&level4state=" + String(level4state) + "&level5state=" +
             String(level5state) + "&pump0state=" + String(pump0state) + "&pump1state=" + String(pump1state) + "&pump2state=" + String(pump2state) + "&pump3state=" +
             String(pump3state) + "&pump4state=" + String(pump4state) + "&pump5state=" + String(pump5state)+ "&panelstate=" + String(panelstate) + "&AlarmMessage0=" +
             String(AlarmMessage0) + "&AlarmMessage1=" + String(AlarmMessage1) + "&AlarmMessage2=" + String(AlarmMessage2) + "&AlarmMessage3=" + String(AlarmMessage3) +
             "&AlarmMessage4=" + String(AlarmMessage4) + "&AlarmMessage5=" + String(AlarmMessage5) + "&AlarmMessage6=" + String(AlarmMessage6) + "&AlarmMessage7=" + String(AlarmMessage7)
             + "&AlarmMessage8=" + String(AlarmMessage8);
   Serial.print("Resquesting URL: ");
   Serial.println(url);
    delay(connecttime);
      // if there's a successful connection:
    //EthernetClient client;
    delay(1000);
    if (millis() - lastConnectionTime > postingInterval)
    {
      if (client.connect(host, 80))
        {
           Serial.println("Data submitting to server  ... waiting...");
           client.println(String("GET ") + url + " HTTP/1.1\r\n" +
                         "Host: " + host + "\r\n" +
                         "Connection: close\r\n\r\n");
           //client.println("Connection: close");
           lastConnectionTime = millis();
           Serial.println("Data saved completed..");
        }
        else
        {
          // if you couldn't make a connection:
          Serial.println("connection failed 2 ");
        }
        while(client.available())
              {
              String line = client.readStringUntil('\r');
              Serial.print(line);
              }
    }
    client.stop();
    Serial.println("closing connection");
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
void loop()
{
  runSystem();   //ระบบเริ่มทำงาน
}
//////////////////////////////////////  end loop  /////////
///////////////////////////////////////////////////////////
void calculateAll_Flowrate()
{
  CalculateFlow1();
  CalculateFlow2();
  CalculateFlow3();
  CalculateFlow4();
  CalculateFlow5();
  CalculateFlow6();
  //digitalRead(Pump5Pin);
  if (pump5state = "Run")
  {
    LPM5=1.25;
  }
  else
  {
    LPM5 = 0;
  }
  //LPM5 = flow55;   //ดึงมาจาก uno
  LPM7=LPM1+LPM2+LPM3+LPM4+LPM5;
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
void runSystem()
{
  int workMode = scan_WorkMode();
  switch (workMode) {
    case 0 :
      Serial.println("Modeselect in OFF Mode");
      runMode_Off();
      break;
    case 1 :
      Serial.println("Now step in Modeselect Manual Mode ...");
      runMode_Manual();
      break;
    case 2 :
      Serial.println("Now step in Modeselect Auto Mode ...");
      runMode_Auto();
      break;
  }
}
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
void initializeAllSensorStatus()
{
  initializeSensorStatus_Energy();
  initializeSensorStatus_Flowrate();
  initializeSensorStatus_pH();
  initializeSensorStatus_EC();
}
void initializeSensorStatus_Energy()
{
}
void initializeSensorStatus_Flowrate()
{
}
void initializeSensorStatus_pH()
{
}
void initializeSensorStatus_EC()
{
}
void runAutoAll_aNode()
{
  if(BCS = "On")
    {
      if(AutoMode == 1 && AutoModeOn == 1) // แม้นจะเลือก auto แล้วก็ต้องกด Start BCS มาจากทางมือถือ
       {
         get_PumpStatus_Auto();
         runAuto_Tank0();
         runAuto_aNode1();
         runAuto_aNode2();
         runAuto_aNode3();
         runAuto_aNode4();
         runAuto_aNode5();
       }
       else  // Stand by รอกระทั่ง  สั่งงานผ่านมือถือ
       {
         Serial.println("Now step in Remote by no command on ...");
         //stopAll_aNode();
         //stopAll_Pump();
       }
    }
    else
      {
        Serial.println("Now step in BCS OFF Mode ...");
        //stopAll_Pump();
        //stopAll_aNode();
      }
}
void stopAll_Pump()
{
   digitalWrite(Pump0Pin,HIGH);Pump0Status = "Stop";Serial.print("Pump 0 : ");Serial.println(Pump0Status);
   stopAll_aNode();
}
void stopAll_aNode()
{
   digitalWrite(Pump1Pin,HIGH);Pump1Status = "Stop";Serial.print("Pump 1 : ");Serial.println(Pump1Status);
   digitalWrite(Pump2Pin,HIGH);Pump2Status = "Stop";Serial.print("Pump 2 : ");Serial.println(Pump2Status);
   digitalWrite(Pump3Pin,HIGH);Pump3Status = "Stop";Serial.print("Pump 3 : ");Serial.println(Pump3Status);
   digitalWrite(Pump4Pin,HIGH);Pump4Status = "Stop";Serial.print("Pump 4 : ");Serial.println(Pump4Status);
   digitalWrite(Pump5Pin,HIGH);Pump5Status = "Stop";Serial.print("Pump 5 : ");Serial.println(Pump5Status);
}
void runAuto_Tank0()
{
  Level0Value = digitalRead(Level0Pin);
  Serial.println(Level0Value);
  delay(1000);
          if(Level0Value == HIGH) // contact make, make by low level
           {
              if (Pump0Status = "Stop")
              {
              digitalWrite(Pump0Pin,0);
              Pump0Status = "Run";
              //Serial.print("Pump 0 : ");
              //Serial.println(Pump0Status);
              }
              else
              {
              //Serial.print("Pump 0 : ");
              //Serial.println(Pump0Status);
              }
           }
             else
           {
              digitalWrite(Pump0Pin,1);
              Pump0Status = "Stop";
              //Serial.println("Pump 0 Stop ");
              //Serial.print("Pump 0 : ");
              //Serial.println(Pump0Status);
           }
}
void runAuto_aNode1()
{
         if(Level1Value == HIGH)
         {
          digitalWrite(Pump1Pin,0);
          Level1ActivateTime = millis();
          /*
          Serial.print(" Level tank 1 High");
          Serial.println("Pump 1 Run");
          */
          delay(pumpdelaytime);
          //CalculateFlow2();
          flow = LPM1;
          if (flow < MaxFlow)
          {
            if (flow >= MinFlow)
               {
                if (rmv1 <= MinRMV)
                  {
                    digitalWrite(Pump1Pin,1);
                    Pump1Status = "Stop";
                    AlarmMessage0 = "Anode 1 is failed";
                  }
                else
                  {
                    if (Pump1Status = "Stop")
                    {
                    digitalWrite(Pump1Pin,0);
                    Pump1Status = "Run";
                    }
                    else
                    {
                      Serial.print("Pump 1 : ");
                      Serial.println(Pump1Status);
                    }
                  }
               }
             else
               {
                  digitalWrite(Pump1Pin,1);
                  Pump1Status = "Stop";
                  AlarmMessage1 = "Pump 1 Strainer or flow is in Trouble";
               }
          }
          else
          {
            digitalWrite(Pump1Pin,1);
            Pump1Status = "Stop";
          }
         }  // level1 HIGH
         else
         {
          digitalWrite(Pump1Pin,1);
          Pump1Status = "Stop";
          //Serial.println("Pump 1 Stop ");
         }
          Serial.print("Pump 1 : ");
          Serial.println(Pump1Status);
}
void runAuto_aNode2()
{
        if(Level2Value == HIGH)
        {
          digitalWrite(Pump2Pin,0);
          Level2ActivateTime = millis();
          /*
          /Serial.print(" Level tank 2 High");
          Serial.println("Pump 2 Run");
          */
          delay(pumpdelaytime);
          //CalculateFlow3();
          flow = LPM2;
          if (flow < MaxFlow)
          {
          if (flow >= MinFlow)
              {
               if (rmv2 <= MinRMV)
                   {
                    digitalWrite(Pump2Pin,1);
                    Pump2Status = "Stop";
                    AlarmMessage2 = "Anode 2 is failed";
                    }
                    else
                    {
                      if(Pump2Status = "Stop")
                      {
                      digitalWrite(Pump2Pin,0);
                      Pump2Status = "Run";
                      }
                      else
                      {
                         Serial.print("Pump 2 : ");
                         Serial.println(Pump2Status);
                      }
                    }
              }
              else
              {
               digitalWrite(Pump2Pin,1);
               Pump2Status = "Stop";
               AlarmMessage3 = "Pump 2 Strainer or flow is in Trouble";
              }
          }
          else
          {
               digitalWrite(Pump2Pin,1);
               Pump2Status = "Stop";
               AlarmMessage3 = "Pump over flow ";
          }
         }
         else
         {
          digitalWrite(Pump2Pin,1);
          Pump2Status = "Stop";
          //Serial.println("Pump 2 Stop ");
         }
         Serial.print("Pump 2 : ");
         Serial.println(Pump2Status);
}
void runAuto_aNode3()
{
        if(Level3Value == HIGH)
        {
          digitalWrite(Pump3Pin,0);
          Level3ActivateTime = millis();
          //Serial.println(" Level tank 3 High");
          //Serial.print("Pump 3 Run");
          delay(pumpdelaytime);
          //CalculateFlow4();
          flow = LPM3;
          if (flow < MaxFlow)
          {
          if (flow >= MinFlow)
              {
                if (rmv3 <= MinRMV)
                   {
                    digitalWrite(Pump3Pin,1);
                    Pump3Status = "Stop";
                    AlarmMessage4 = "Anode 3 is failed";
                    }
                    else
                    {
                      if (Pump3Status = "Stop")
                      {
                      digitalWrite(Pump3Pin,0);
                      Pump3Status = "Run";
                      }
                      else
                      {
                        Serial.print("Pump 3 : ");
                        Serial.println(Pump3Status);
                      }
                    }
              }
              else
              {
               digitalWrite(Pump3Pin,1);
               Pump3Status = "Stop";
               AlarmMessage5 = "Pump 3 Strainer or flow is in Trouble";
              }
          }
          else
          {
               digitalWrite(Pump3Pin,1);
               Pump3Status = "Stop";
               AlarmMessage5 = "Pump 3 Over flow ";
          }
         }
         else
         {
          digitalWrite(Pump3Pin,1);
          Pump3Status = "Stop";
         }
          Serial.print("Pump 3 : ");
          Serial.println(Pump3Status);
}
void runAuto_aNode4()
{
        if(Level4Value == HIGH)
        {
          digitalWrite(Pump4Pin,0);
          Level4ActivateTime = millis();
          //Serial.print(" Level tank 4 High");
          //Serial.println("Pump 4 Run");
          delay(pumpdelaytime);
          //CalculateFlow5();
          flow = LPM4;
          if (flow < MaxFlow)
          {
          if (flow >= MinFlow)
              {
                if (rmv4 <= MinRMV)
                   {
                    digitalWrite(Pump4Pin,1);
                    Pump4Status = "Stop";
                    AlarmMessage6 = "Anode 4 is failed";
                    }
                    else
                    {
                      if (Pump4Status = "Stop")
                      {
                      digitalWrite(Pump4Pin,0);
                      Pump4Status = "Run";
                      }
                      else
                      {
                        Serial.print("Pump 4 : ");
                        Serial.println(Pump4Status);
                      }
                    }
              }
              else
              {
               digitalWrite(Pump4Pin,1);
               Pump4Status = "Stop";
               AlarmMessage7 = "Pump 4 Strainer or flow is in Trouble";
              }
          }
          else
          {
               digitalWrite(Pump4Pin,1);
               Pump4Status = "Stop";
               AlarmMessage7 = "Pump 4 Overflow ";
          }
         }
         else
         {
          digitalWrite(Pump4Pin,1);
          Pump4Status = "Stop";
          //Serial.println("Pump 4 Stop ");
         }
          Serial.print("Pump 4 : ");
          Serial.println(Pump4Status);
}
void runAuto_aNode5()
{
          if(Level5Value == HIGH)
          {
            digitalWrite(Pump5Pin,0);
            Level1ActivateTime = millis();
            //Serial.print(" Level tank 5 High");
            //Serial.println("Pump 5 Run");
            delay(pumpdelaytime);
            //CalculateFlow6();
            flow = LPM5;
            //if (flow >= MinFlow)
                //{
                  if (rmv5 <= MinRMV)
                     {
                      digitalWrite(Pump5Pin,1);
                      Pump5Status = "Stop";
                      AlarmMessage8 = "Anode 5 is failed";
                      }
                      else
                      {
                        if(Pump5Status = "Stop")
                        {
                        digitalWrite(Pump5Pin,0);
                        Pump5Status = "Run";
                        }
                        else
                        {
                          Serial.print("Pump 5 : ");
                          Serial.println(Pump5Status);
                        }
                      }
                //}
                /*
                else
                {
                 digitalWrite(Pump5Pin,1);
                 Pump4Status = "Stop";
                 AlarmMessage9 = "Pump 5 Strainer or flow is in Trouble";
                }
                */
           }
           else
           {
            digitalWrite(Pump5Pin,1);
            Pump5Status = "Stop";
            //Serial.println("Pump 5 Stop ");
           }
            Serial.print("Pump 5 : ");
            Serial.println(Pump5Status);
}
void runMode_Auto()
{
  doModeAuto_Start();
  doModeAuto_Operate();
  doModeAuto_Complete();
}
void doModeAuto_Start()
{
  initializeAllSensorStatus();
}
void doModeAuto_Operate()
{
  readControlCommandFromServer();
  scanAllSensor();
  runAutoAll_aNode();
  calculateAll_Flowrate();
  displayAllSystemStatus();
  saveSystemStatusToDataLogger();
  saveSystemStatusToServer();
  resetAlarmMessage();
}
void doModeAuto_Complete()
{
}
void doModeManual_Start()
{
  initializeAllSensorStatus();
}
void doModeManual_Operate()
{
  scanAllSensor();
  calculateAll_Flowrate();
  displayAllSystemStatus();
  saveSystemStatusToDataLogger();
  saveSystemStatusToServer();
}
void doModeManual_Complete()
{
}
void runMode_Manual()
{
  doModeManual_Start();
  doModeManual_Operate();
  doModeManual_Complete();
}
void runMode_Off()
{
   doModeOff_Start();
   doModeOff_Operate();
   doModeOff_Complete();
}
void doModeOff_Start()
{
  initializeAllSensorStatus();
}
void doModeOff_Operate()
{
  scanAllSensor();
  displayAllSystemStatus();
  saveSystemStatusToDataLogger();
  saveSystemStatusToServer();
}
void doModeOff_Complete()
{
  displayAllSystemStatus();
}
void Readfactor()
{  // connect server and read all data by json file
Serial.print("connecting to ");
Serial.println(host);
// if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
client.stop();
//   EthernetClient client;
if (client.connect(host, 80))
  {
    Serial.println("Yes connecting...c");
    delay(connecttime);
      if (count == 0)
        {
        url = "/xxx/xxx/xxxx.php?device_factor_id=1";
        count = count + 1;
        Serial.println("Here1");
        }
        else if (count == 1)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=2";
          count = count + 1;
          Serial.println("Here2");
          }
        else if (count == 2)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=3";
          count = count + 1;
          Serial.println("Here3");
          }
        else if (count == 3)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=4";
          count = count + 1;
          Serial.println("Here4");
          }
       else if (count == 4)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=5";
          count = count + 1;
          Serial.println("Here5");
          }
       else if (count == 5)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=6";
          count = count + 1;
          Serial.println("Here6");
          }
       else if (count == 6)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=7";
          count = count + 1;
          Serial.println("Here7");
          }
       else if (count == 7)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=8";
          count = count + 1;
          Serial.println("Here8");
          }
       else if (count == 8)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=9";
          count = count + 1;
          Serial.println("Here9");
          }
       else if (count == 9)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=10";
          count = count + 1;
          Serial.println("Here10");
          }
       else if (count == 10)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=11";
          count = count + 1;
          Serial.println("Here11");
          }
       else if (count == 11)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=12";
          count = count + 1;
          Serial.println("Here12");
          }
       else if (count == 12)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=12";
          count = count + 1;
          Serial.println("Here12");
          }
       else if (count == 13)
          {
          url = "/xxx/xxx/xxxx.php?device_factor_id=14";
          count = count + 1;
          Serial.println("Here14");
          }
         Serial.print("Requesting URL: ");
         Serial.println(url);
         client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");
         delay(200);
         String section="header";
         while(client.available())
         {
            String line = client.readStringUntil('\r');
            //Serial.print(line);
            // we’ll parse the HTML body here
            if (section=="header")
              { // headers..
                  if (line=="\n")
                    { // skips the empty space at the beginning
                      section="json";
                    }
              }
            else if (section=="json")
              {  // print the good stuff
                  section="ignore";
                  String result = line.substring(1);
                  // Parse JSON
                  int size = result.length() + 1;
                  char json[size];
                  result.toCharArray(json, size);
                  StaticJsonBuffer<700> jsonBuffer;
                  JsonObject& json_parsed = jsonBuffer.parseObject(json);
                  if (!json_parsed.success())
                    {
                      Serial.println("parseObject() failed");
                      return;
                    }
                      //String led = json_parsed["led"][0]["status"];
                      String led1 = json_parsed["led"][0]["status"];
                      String led2 = json_parsed["led"][1]["status"];
                      String led3 = json_parsed["led"][2]["status"];
                      // string led = json_parsed["table name""][array number]["value of field"]
                    //if(count == 1){
                      if(led1 == "on")
                          {
                            BCS = "On";
                            AutoModeCommand = 1;
                            AutoModeOn = 1;
                            delay(10);
                            Serial.println("BCS is on AutoMode = ON !");
                          }
                          else if(led1 == "off")
                          {
                            BCS = "Off";
                            AutoModeCommand = 0;;
                            AutoModeOn = 0;
                            delay(10);
                            Serial.println("BCS AutoMode is Off..!");
                          }
                    //}
                    //else if(count == 2){
                      if(led2 == "on")
                         {
                            Spray = "On";
                            //digitalWrite(6, 1);
                            delay(10);
                            //Serial.println("D6 is On..!");
                         }
                         else if(led2 == "off")
                         {
                           Spray = "Off";
                           //digitalWrite(6, 0);
                           delay(10);
                           //Serial.println("D6 is Off..!");
                         }
                    //}
                    //else if(count == 3){
                      if(led3 == "on")
                        {
                          Pump2 = "On";
                          //digitalWrite(7, 1);
                          delay(10);
                          //Serial.println("D7 is On..!");
                        }
                        else if(led3 == "off")
                        {
                          Pump2 = "Off";
                          //digitalWrite(7, 0);
                          delay(10);
                          //Serial.println("D7 is Off..!");
                        }
                        count = 0;
                    //}
                    if (count == 3)
                        count = 0;
             } // if found json
          } // end while client available
    } // end if host connected
    else
    {
      // if you couldn't make a connection:
      Serial.println("connection failed 1");
    }
}
/////////////////////////// end  /////////////
void SwitchOnRaspberryPi()
{
  digitalWrite(RaspberryPin,LOW);
}

 
 
 

Leave a Reply

Your email address will not be published.