FONA Library fails to send SMS or get signal quality in the LOOP

Hi all,

i have an Mduino 57R+ , which has a GSM module on board that works with the Adafruit FONA library .When i install the testcode all seems to work fine, i can send text messages, read them , get the signal quality and so on.

Now, getting the code i need (SMS and signal quality) in my code seems to be a pain. I can't seem to send text messages (FAIL) and when i put a signal quality in my loop, it doesnt work.
I get an OK to unlock my SIM so that's not really the problem, but in the Fona test code, after the unlock i get 'Call ready -- SMS ready'. I don't get that in my code..?

I posted my complete code, as this is mandatory i learned.

Thanks !

#include <OneWire.h>
#include <DallasTemperature.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <ModbusRTUMaster.h>
#include <RS485.h>
#include "Adafruit_FONA.h"

#define FONA_RST 2

char replybuffer[255];
HardwareSerial *fonaSerial = &Serial1;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

ModbusRTUMaster master(RS485);

#define UDP_TX_PACKET_MAX_SIZE  1024

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 200);

unsigned int localPort = 8001;      // local port to listen on

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];  // buffer to hold incoming packet,
char ReplyBuffer[] = "";        // a string to send back

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp; 

#define MasterModbusAdd  0
#define SlaveModbusAdd   1
#define FanModbusAdd     5
#define RS485Serial      3

const uint32_t baudrate = 19200UL; 

// Declare variables : 
int Cel1Active,Cel1Running,Cel1Prior;
String result,tmp,ch;
char caracter;
uint16_t au16data[16];
uint16_t au16dataw[16];
uint8_t u8state,func;
int TVOCTemp,NewTVOCTemp, TVOCHum,SetTemp,SetHum,SetFan,SetTDiff,SetHDiff,SetHeatDelay,SetVatTemp,SetVatTempDiff,SetEvaporatorDiff,MaxVatT,MinVatT,PressDelay,slave,AlarmCount,LowTemp,HighTemp,LowHum,HighHum;;
String SetTempSTR,SetHumSTR,SetFanSTR,SetTempDiff,SetHumDiff,SetHeatDelaySTR,VatTempSTR,VatTempDiffSTR,EvaporatorDiffSTR,MaxVatTSTR,MinVatTSTR,PressDelaySTR,LowTempSTR,HighTempSTR,LowHumSTR,HighHumSTR;
int  temp1,temp2,temp3,temp4;
bool R01,R02,R03,R04,R05,R06,R07,R08,R11,R27,AlarmActive; // relay override statusses
bool TOk, ColdQ, HotQ,HeatDelayActive,DeHumidActive,HumidActive, Heating,Cooling,MagValve;
unsigned long HeatDelayTime, PressTime;
unsigned long u32wait;
unsigned long target_time = 0L ;
const unsigned long PERIOD = 10*1000UL;
int numReadings = 5;
int currentReading = 0;
int Deviation = 2; // 4 = 40% deviation readings are ignored
unsigned long AvgTemp1,AvgTemp2,AvgTemp3,AvgTemp4;
unsigned long AlarmDelayTime = 0; // in mS 
unsigned long AlarmInterval = 10000; // in mS 
int ActiveAlarmCode =0;
char ReceiveString[UDP_TX_PACKET_MAX_SIZE];  // buffer to hold incoming packet,
char SendString[] ="";
String SendStr ;

long previousMillis = 0;        

long interval = 10000;           


//millisDelay AlarmDelay;
 
OneWire oneWire(2); // pin D6
DallasTemperature sensors(&oneWire);
DeviceAddress DST1 = {0x28, 0x1A, 0x6F, 0xA5, 0x13, 0x21, 0x01, 0x29};  // Warm water vat
DeviceAddress DST2 = {0x28, 0x7E, 0x65, 0x8E, 0x13, 0x21, 0x01, 0x6F};  // Koud water vat
DeviceAddress DST3 = {0x28, 0x99, 0x09, 0xD5, 0x13, 0x21, 0x01, 0xBF};  // Batterij IN 
DeviceAddress DST4 = {0x28, 0x07, 0xBF, 0x99, 0x13, 0x21, 0x01, 0x3C};  // Batterij UIT

//Backup sensor :  {0x28, 0xE0, 0x4E, 0xB9, 0x13, 0x21, 0x01, 0xB8};  
 
void setup() {
  Serial.begin(9600);
  // start the Ethernet
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start UDP
  Udp.begin(localPort);
  
  Serial.println("Connecting to RS485 ");
  RS485.begin(baudrate, HALFDUPLEX, SERIAL_8E1);
  master.begin(baudrate);

  u32wait = millis() + 2000;
  u8state = 0; 
  slave=1;
  func=0;
  AlarmCount =0;
  HeatDelayActive = false;
  DeHumidActive = false;
  HumidActive = false;
  Heating = false;
  Cooling = false;
  MagValve = false;
  Cel1Active = 0;
  Cel1Running = false;

  pinMode(I0_1, INPUT);   // Pressostaat
  pinMode(R0_1, OUTPUT);  // Magneetventiel 
  pinMode(R0_2, OUTPUT);  // Compressor
  pinMode(R0_3, OUTPUT);  // Pomp Koud Water
  pinMode(R0_4, OUTPUT);  // Pomp Warm Water
  pinMode(R0_5, OUTPUT);  // Ventiel Koud Water
  pinMode(R0_6, OUTPUT);  // Ventiel Warm Water
  pinMode(R0_7, OUTPUT);  // Weerstand Vat
  pinMode(R0_8, OUTPUT);  // Stoombevochtiger
  pinMode(R1_1, OUTPUT);  // Weerstand Batterij
  pinMode(R2_7, OUTPUT);  // Alarm

  R01 = false;
  R02 = false;
  R03 = false;
  R04 = false;
  R05 = false;
  R06 = false;
  R07 = false;
  R08 = false;
  R11 = false;
  R27 = false;  

  // Start Temp Sensors
  sensors.begin();
  sensors.setResolution(11);

  //  Start GSM Module 
  fonaSerial->begin(4800);    // baudrate correct? 
  if (! fona.begin(*fonaSerial)) {
    Serial.println(F("Couldn't find FONA Module"));  
     while (1);
  }

const char* pinchar="****";
  if (! fona.unlockSIM(pinchar)) {
          Serial.println(F("SIM Unlock Failed"));
        } else {
          Serial.println(F("SIM Unlock OK!"));
        }
  delay(2000);
  
   while (1) {
    uint8_t n = fona.getNetworkStatus();
    if (n == 1) break;
  }

  Serial.println(F("Registered to the network"));
   
  // Print module IMEI number.  -- WORKS !
  char imei[16] = {0}; // MUST use a 16 character buffer for IMEI!
  uint8_t imeiLen = fona.getIMEI(imei);
  if (imeiLen > 0) {
    Serial.print("Module IMEI: "); Serial.println(imei);
  }

  const char* sendto="0032***********";   // My number hardcoded
  String  message="System started";              // Demo text

  char txt[message.length() + 1];
  message.toCharArray(txt, message.length()+1);

       
  if (!fona.sendSMS(sendto, txt)) {
          Serial.println(F("SMS Failed"));      // Gives me a FAIL
        } else {
          Serial.println(F("SMS Sent!"));
        }
}

 
void loop() {

   unsigned long currentMillis = millis();
 
  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED 
    previousMillis = currentMillis;   
        uint8_t n = fona.getRSSI();
        int8_t r;

        Serial.print(F("RSSI = ")); Serial.print(n); Serial.print(": ");
        if (n == 0) r = -115;
        if (n == 1) r = -111;
        if (n == 31) r = -52;
        if ((n >= 2) && (n <= 30)) {
          r = map(n, 2, 30, -110, -54);
        }
        Serial.print(r); Serial.println(F(" dBm"));
  }
   
  }
    

 SendStr="";
 SendStr = SendStr + digitalRead(R0_1)+"/";
 SendStr = SendStr + digitalRead(R0_2)+"/";
 SendStr = SendStr + digitalRead(R0_3)+"/";
 SendStr = SendStr + digitalRead(R0_4)+"/";
 SendStr = SendStr + digitalRead(R0_5)+"/";
 SendStr = SendStr + digitalRead(R0_6)+"/";
 SendStr = SendStr + digitalRead(R0_7)+"/";
 SendStr = SendStr + digitalRead(R0_8)+"/";
 SendStr = SendStr + digitalRead(R1_1)+"/";
 SendStr = SendStr + digitalRead(R2_7)+"/";
 SendStr = SendStr + digitalRead(I0_1)+"/";
 SendStr = SendStr + TVOCTemp  + "/";
 SendStr = SendStr + TVOCHum   + "/";
 SendStr = SendStr + temp1+ "/";
 SendStr = SendStr + temp2+ "/";
 SendStr = SendStr + temp3+ "/";
 SendStr = SendStr + temp4+ "/";
 SendStr = SendStr + Cel1Active+ "/";   
 SendStr = SendStr + Cel1Prior +"/" ;    
 SendStr = SendStr + ActiveAlarmCode ;    
 
 //Serial.println(SendStr);
 char SendString[SendStr.length()+1];
 SendStr.toCharArray(SendString, SendStr.length()+1);
  
 int packetSize = Udp.parsePacket();
 
  if (packetSize) {
    //Serial.print("Received packet of size ");
    //Serial.println(packetSize);
    //Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i=0; i < 4; i++) {
     // Serial.print(remote[i], DEC);
      if (i < 3) {
       // Serial.print(".");
      }
    }
  //  Serial.print(", port ");
   // Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    Udp.read(ReceiveString, UDP_TX_PACKET_MAX_SIZE);
  //  Serial.println("Contents:");
   // Serial.println(ReceiveString);

    // send a reply to the IP address and port that sent us the packet we received
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    Udp.write(SendString);
    Udp.endPacket();
  }
  delay(100);
  
 ConvertReceivedData(ReceiveString);       

 ControlCel1();

}
// END LOOP


void ConvertReceivedData(String inputdata)
{
      // R0_1 : Magneetventiel
      // R0_2 : Compressor
      // R0_3 : Pomp Koud Water
      // R0_4 : Pomp Warm Water
      // R0_5 : Koud Water Ventiel
      // R0_6 : Warm Water Ventiel
      // R0_7 : Weerstand Warm Water
      // R0_8 : Stoom
      // R1_1 : Weerstand batterij
      // R2_7 : Alarm
      
      
      //Serial.println(inputdata);
      if(inputdata.indexOf("E") > 0) // check if we have complete data 
      {
      inputdata.replace("ST","");
      inputdata.replace("E","");

      // Set Vars
      
      if (getIntValue(inputdata, ':', 10)!=0){
         SetTemp        = getIntValue(inputdata, ':', 10);
      }
      if (getIntValue(inputdata, ':', 11)!=0){
         SetHum        = getIntValue(inputdata, ':', 11);
      }
      if (getIntValue(inputdata, ':', 12)!=0){
         SetFan        = getIntValue(inputdata, ':', 12);
      }
      if (getIntValue(inputdata, ':', 13)!=0){
         SetTDiff        = getIntValue(inputdata, ':', 13);
      }
      if (getIntValue(inputdata, ':', 14)!=0){
         SetHDiff        = getIntValue(inputdata, ':', 14);
      }
      if (getIntValue(inputdata, ':', 15)!=0){
         SetHeatDelay    = getIntValue(inputdata, ':', 15);
      }
      if (getIntValue(inputdata, ':', 16)!=0){
         SetVatTemp        = getIntValue(inputdata, ':', 16);
      }
        if (getIntValue(inputdata, ':', 17)!=0){
         SetVatTempDiff        = getIntValue(inputdata, ':', 17);
      }
        if (getIntValue(inputdata, ':', 18)!=0){
         SetEvaporatorDiff        = getIntValue(inputdata, ':', 18);
      }
        if (getIntValue(inputdata, ':', 19)!=0){
         MaxVatT        = getIntValue(inputdata, ':', 19);
      }
        if (getIntValue(inputdata, ':', 20)!=0){
         MinVatT        = getIntValue(inputdata, ':', 20);
      }
        if (getIntValue(inputdata, ':', 21)!=0){
         PressDelay        = getIntValue(inputdata, ':', 21);
      }
        if (getIntValue(inputdata, ':', 22)!=0){
         LowTemp        = getIntValue(inputdata, ':', 22);
      }
        if (getIntValue(inputdata, ':', 23)!=0){
         HighTemp        = getIntValue(inputdata, ':', 23);
      }
        if (getIntValue(inputdata, ':', 24)!=0){
         LowHum        = getIntValue(inputdata, ':', 24);
      }
        if (getIntValue(inputdata, ':', 25)>0){
         HighHum        = getIntValue(inputdata, ':', 25);
      }
      if (getIntValue(inputdata, ':', 26)==0){
         Cel1Active = 0;
      }   
      else{
        Cel1Active = 1;
      }
      if (getIntValue(inputdata, ':', 27)>0){
         Cel1Prior = 1;  // PRIOR HUM
      }   
      else{
         Cel1Prior = 0;  // PRIOR TEMP
      }

        // Set Relays : 
      if ( Cel1Active==0) // enkel manuele bediening bij besturing niet actief
      {
        
    
      // Relay 1 , Magneetventiel
      if (getValue(inputdata, ':', 0).equals("1"))
      {
         digitalWrite(R0_1, HIGH); 
         R01 = true;
      }
      else
      {
        digitalWrite(R0_1, LOW); 
        R01= false;
      }
      // Relay 2 : Compressor
       if (getValue(inputdata, ':', 1).equals("1"))
      {
      
        digitalWrite(R0_2, HIGH); 
        R02 = true;
      }
      else
      {
        digitalWrite(R0_2, LOW); 
        R02 = false;
      }
      // Relay 3 :
      if (getValue(inputdata, ':', 2).equals("1"))
      {
        digitalWrite(R0_3, HIGH); 
        R03 = true;
      }
      else
      {
        digitalWrite(R0_3, LOW); 
        R03 = false;
      }
      // Relay 4 :
      if (getValue(inputdata, ':', 3).equals("1"))
      {
        digitalWrite(R0_4, HIGH); 
        R04 = true;
      }
      else
      {
        digitalWrite(R0_4, LOW); 
        R04 = false;
      }
      // Relay 5 :
      if (getValue(inputdata, ':', 4).equals("1"))
      {
        digitalWrite(R0_5, HIGH); 
        R05 = true;
      }
      else
      {
        digitalWrite(R0_5, LOW); 
        R05 = false;
      }
      // Relay 6 :
      if (getValue(inputdata, ':',5).equals("1"))
      {
        digitalWrite(R0_6, HIGH); 
        R06 = true;
      }
      else
      {
        digitalWrite(R0_6, LOW); 
        R06 = false;
      }
      // Relay 7 :
      if (getValue(inputdata, ':',6 ).equals("1"))
      {
        digitalWrite(R0_7, HIGH); 
        R07 = true;
      }
      else
      {
        digitalWrite(R0_7, LOW); 
        R07 = false;
      }
      // Relay 8 :
      if (getValue(inputdata, ':', 7).equals("1"))
      {
        digitalWrite(R0_8, HIGH); 
        R08 = true;
      }
      else
      {
        digitalWrite(R0_8, LOW); 
        R08 = false;
      }
      // Relay 9 :
      if (getValue(inputdata, ':', 8).equals("1"))
      {
        digitalWrite(R1_1, HIGH); 
        R11 = true;
      }
      else
      {
        digitalWrite(R1_1, LOW); 
        R11 = false;
      }
      // Relay 9 , ALARM :
      if (getValue(inputdata, ':', 27).equals("1"))
      {
        digitalWrite(R2_7, HIGH); 
        R27 = true;
      }
      else
      {
        digitalWrite(R2_7, LOW); 
        R27 = false;
      }
    
    }
/*
      Serial.print("TVOCTemp:");
      Serial.println(TVOCTemp);
      Serial.print("TVOCHum:");
      Serial.println(TVOCHum);
      Serial.print("SetTemp:");
      Serial.println(SetTemp);
      Serial.print("SetHum:");
      Serial.println(SetHum);
      Serial.print("SetFan:");
      Serial.println(SetFan);
      Serial.print("SetTempDiff:");
      Serial.println(SetTDiff);
      Serial.print("SetHumDiff:");
      Serial.println(SetHDiff);
      Serial.print("HeatDelay:");
      Serial.println(SetHeatDelay);
      Serial.print("SetVatTemp:");
      Serial.println(SetVatTemp);
      Serial.print("VatTemp:");
      Serial.println(temp2*10);
      Serial.print("SetVatTempDiff:");
      Serial.println(SetVatTempDiff);
      Serial.print("Koud water vat :");
      Serial.println(temp2);*/
   }
}


void ControlCel1()
{

  //Check Temp Every 10s
  if (millis () - target_time >= PERIOD)
  {
    target_time += PERIOD ;   // change scheduled time exactly, no slippage will happen
    sensors.setWaitForConversion(false);  // makes it async

    delay(100);
    
  
    sensors.requestTemperatures();
    
    sensors.setWaitForConversion(false);
    int ttemp1 =  sensors.getTempC(DST1)*10;
    int ttemp2 =  sensors.getTempC(DST2)*10;
    int ttemp3 =  sensors.getTempC(DST3)*10;
    int ttemp4 =  sensors.getTempC(DST4)*10;

    if (ttemp1>-1000) 
    {
      temp1 = ttemp1;
    }
    if (ttemp2>-1000) 
    {
      temp2 = ttemp2;
    }
    if (ttemp3>-1000) 
    {
      temp3 = ttemp3;
      TVOCTemp = temp3;
    }
    if (ttemp4>-1000) 
    {
      temp4 = ttemp4;
    }
    
  

    sensors.setWaitForConversion(true);
    //temporary changes : use Batterij IN as cel temp and use Fancom Hum sensor 0-5v, conversion 0-1024 
    
    //TVOCHum = analogRead(CONTROLLINO_A2)+130; too much?
    
//    TVOCHum = analogRead(CONTROLLINO_A2);
    
    if (TVOCHum>1000)
    {
      TVOCHum = 1000;
    } 
 
   //}
}
   
   // All relais UIT
   if (Cel1Active==0 && Cel1Running==true)
   {
       if (R01 == false) {
          digitalWrite(R0_1, LOW); 
       }
       if (R02 == false) {
          digitalWrite(R0_2, LOW); 
       }
       if (R03 == false) {
          digitalWrite(R0_3, LOW); 
       }
       // Pomp warm water uit
       if (R04 == false) {
          digitalWrite(R0_4, LOW); 
       }
        // Ventiel koud water dicht
       if (R05 == false) {
          digitalWrite(R0_5, LOW); 
       }
       // Ventiel warm water dicht
       if (R06 == false) {
          digitalWrite(R0_6, LOW); 
       }
       // Weerstand vat uit
       if (R07 == false) {
          digitalWrite(R0_7, LOW); 
       }
        // Stoombevochtiger uit
       if (R08 == false) {
          digitalWrite(R0_8, LOW); 
       }
       if (R11 == false) {
          digitalWrite(R1_1, LOW); 
       }
       if (R27 == false) {
          digitalWrite(R2_7, LOW); 
       }
       delay (250);
       Cel1Running = false;
  }       
    
      
      
  if (TVOCTemp>0 && SetTemp>0 && TVOCHum>0 && SetHum>0 && SetHDiff>0 and SetTDiff>0 && Cel1Active>0) // Make sure we have a reading
  {
 
    Cel1Running=true;
    
    //  Temperature Controlling : 
    //  1. Stop Cooling :
   
    if (TVOCTemp<SetTemp && Cooling==true)
    {
      Cooling = false;
       //pomp koud water uit , enkel indien compressor niet draait.
       if (R03 == false && digitalRead(R0_2) == LOW && DeHumidActive==false  ) 
       {
          digitalWrite(R0_3, LOW); 
       }
        // Ventiel koud water dicht
       if (R05 == false && DeHumidActive==false) {
          digitalWrite(R0_5, LOW); 
       }
     }
     
    //  Temperature Controlling : 
    // 2:  Stop Heating 
    if (TVOCTemp>SetTemp && Heating==true)
    {
      Serial.println("--Stop Heating");
       HeatDelayActive = false;
       Heating = false;
       // Pomp warm water uit, enkel indien compressor uit
       if (R04 == false && digitalRead(R0_2) == LOW && DeHumidActive==false) {
          digitalWrite(R0_4, LOW); 
       }
       // Ventiel warm water dicht
       if (R06 == false && DeHumidActive==false) {
          digitalWrite(R0_6, LOW); 
       }
       // Weerstand batterij uit
       if (R11 == false && DeHumidActive==false) {
          digitalWrite(R1_1, LOW); 
       }
     }
   //  Temperature Controlling : 
   // 3 :  Start Cooling , only when Temperature is Prior OR Humididity is OK
   
    if ((TVOCTemp>(SetTemp+SetTDiff)) && ( Cel1Prior == 0 || (Cel1Prior == 1 && HumidActive == false && DeHumidActive == false)))
    {
       if (Cel1Prior == 0 && HumidActive==true) 
       {
          digitalWrite(R0_8, LOW); 
       }
       if (Cel1Prior == 0 && DeHumidActive==true) 
       {
          digitalWrite(R0_6, LOW); // warm water ventiel dicht
       }
       Serial.println("--Start Cooling");
       Cooling = true;
       // Pomp koud water aan
       digitalWrite(R0_3, HIGH); 
       // Koud water ventiel open
       digitalWrite(R0_5, HIGH); 
   }

   //  Temperature Controlling : 
   // 4: Start Heating , only when Temperature is Prior OR Humididity is OK
    
    if ((TVOCTemp<(SetTemp-SetTDiff))  && ( Cel1Prior == 0 || (Cel1Prior == 1 && HumidActive == false && HumidActive == false)))
    {
       if (Cel1Prior == 0 && HumidActive==true) 
       {
          // Stoombevochtiger UIT
          digitalWrite(R0_8, LOW); 
       }
       if (Cel1Prior == 0 && DeHumidActive==true) 
       {
          // koud water ventiel UIT
          digitalWrite(R0_5, LOW); 
       }
       
       Serial.println("--Start Heating");
       Heating = true;
       
       if (HeatDelayActive == false)
       {
          HeatDelayTime = millis();
          HeatDelayActive = true;
       }
      
       if (((millis() - HeatDelayTime) >= (SetHeatDelay*60000)) && HeatDelayActive == true)
       {
           // Activeer weerstand batterij
           digitalWrite(R1_1, HIGH);    // tijdelijk uit
       }
      
       // Pomp warm water aan
       digitalWrite(R0_4, HIGH); 
       
       // Warm water ventiel open
       digitalWrite(R0_6, HIGH); 
       
    }
    
    //  Humidity Controlling : 
    //  1: Stop Drying :

    if (TVOCHum<SetHum && DeHumidActive==true)
    {
       Serial.println("--Drying Stopped");
       DeHumidActive = false ;
       HeatDelayActive = false;

       //pomp koud water uit , enkel indien compressor niet draait.
       if (R03 == false && digitalRead(R0_2) == LOW ) {
          digitalWrite(R0_3, LOW); 
       }
       // Pomp warm water uit
       if (R04 == false && digitalRead(R0_2) == LOW ) {
          digitalWrite(R0_4, LOW); 
       }
        // Ventiel koud water dicht
       if (R05 == false) {
          digitalWrite(R0_5, LOW); 
       }
       // Ventiel warm water dicht
       if (R06 == false) {
          digitalWrite(R0_6, LOW); 
       }
       // Weerstand batterij uit
       if (R11 == false) {
          digitalWrite(R1_1, LOW); 
       }
    }

    // 2: Stop Humiding
    
    if (TVOCHum>SetHum && HumidActive==true)
    {
       HumidActive = false;
       // Stoombevochtiger uit
       if (R08 == false) {
          digitalWrite(R0_8, LOW); 
       }
    }

    // 3: Start Drying 
    if  ((TVOCHum>(SetHum+SetHDiff)) && ( Cel1Prior == 1 || (Cel1Prior == 0 && Heating ==false && Cooling== false)))
    {
      Serial.println("--Ontvochtigen");
      DeHumidActive = true;

      if (temp4>temp3) // Uitgaande temperatuur van de batterij word te hoog, stop bijwarmen
      {
         // Pomp warm water UIT, enkel indien compressor uit
         if (digitalRead(R0_2) == LOW) {
            digitalWrite(R0_4, LOW); 
         }
         // Ventiel warm water DICHT
         digitalWrite(R0_6, LOW); 
         // Weerstand Batterij UIT
         digitalWrite(R1_1, LOW);     
      }
      if (temp4<temp3-10) 
      {
          // Pomp warm water AAN
          digitalWrite(R0_4, HIGH); 
          // Ventiel warm water OPEN
          digitalWrite(R0_6, HIGH); 
   
          if (HeatDelayActive == false)
          {
              HeatDelayTime = millis();
              HeatDelayActive = true;
          }
          if (((millis() - HeatDelayTime) >= (SetHeatDelay*60000)) && HeatDelayActive == true)
          {
           // Weerstand Batterij AAN
           digitalWrite(R1_1, HIGH);  
          }
      }
      
      // pomp Koud Water AAN
      digitalWrite(R0_3, HIGH); 
      // Ventiel Koud Water OPEN
      digitalWrite(R0_5, HIGH); 
      // Pomp en ventiel warm water worden hierboven geregeld.
           
      // bevochtigen uit
      digitalWrite(R0_8, LOW); 
     
    }

    // 4 : Start Humiding

    if ( (TVOCHum<(SetHum-SetHDiff)) && ( Cel1Prior == 1 || (Cel1Prior == 0 && Heating ==false && Cooling== false)) )
    {
    Serial.println("--Bevochtigen");
      HumidActive = true;
      digitalWrite(R0_8, HIGH); 
     
    }


   
   
    //Compressor sturing
    // 1: Als temperatuur in vat te hoog komt, start compressor
    if ((temp2 - SetVatTempDiff)>SetVatTemp)
    {
       Serial.println("--Chiller sturing AAN");
       // Magneetventiel AAN
       Serial.println("--Magneetventiel AAN");
       digitalWrite(R0_1, HIGH); 
       if (MagValve == false)
       {
        MagValve = true;
        PressTime = millis();
       }


     if  ( (millis() - PressTime) >= (PressDelay*1000))
     {
      if (digitalRead(R0_1) == HIGH && digitalRead(I0_1) == LOW )
      {
      
           // Alarm motor start niet 
        //   SendAlarm(10);
        //   AlarmCount++;
           
       }
     }

       
       // Als Pressostaat HOOG is , start compressor , start pompen 
       if (digitalRead(I0_1)==HIGH)
       {
          Serial.println("--Pressostaat HOOG = Compressor AAN , pompen AAN");
          digitalWrite(R0_2, HIGH); 
          digitalWrite(R0_3, HIGH); 
          digitalWrite(R0_4, HIGH); 
       }

      // Als Pressostaat LAAG is , stop compressor :
       if (digitalRead(I0_1)==LOW)
       {
          Serial.println("--Pressostaat LAAG = Compressor UIT , pompen UIT");
          //Compressor uit
          digitalWrite(R0_2, LOW); 
         
   
       }
   

       
    }

    // stopcompressor van zodra temp bereikt.
    if (temp2<=SetVatTemp)    
    {
       //magneetventiel uit     
       MagValve = false;
       Serial.println("--Magneetventiel UIT");
       digitalWrite(R0_1, LOW); 
       digitalWrite(R0_2, LOW);  
       if (Cooling==false && Heating==false && HumidActive==false && DeHumidActive==false)
       {
          digitalWrite(R0_3, LOW); 
          digitalWrite(R0_4, LOW); 
       }
       
       // Als Pressostaat LAAG is , compressor uit :
       if (digitalRead(I0_1)==LOW) 
       {
          Serial.println("--Pressostaat LAAG = Compressor UIT");
          if (R02 == false) {
             // Compressor UIT
             digitalWrite(R0_2, LOW); 
           
          }
       }
    }
    

    AlarmCount = 0;
    // Set Alarms :
    if ((LowTemp>0) && (LowTemp>TVOCTemp))  // Temp te laag
    {
       SendAlarm(20);
       AlarmCount++;
    }
    if (HighTemp>0 && HighTemp<TVOCTemp) // Temp te hoog
    {
       SendAlarm(21);
        AlarmCount++;
    }
    if (LowHum>0 && LowHum>TVOCHum) // Hum te laag
    {
       SendAlarm(22);
        AlarmCount++;
    }
    if (HighHum>0 && HighHum<TVOCHum/10) // Hum te hoog
    {
       SendAlarm(23);
       AlarmCount++;
    }

    // Als koud water vat te koud is 
    if (temp2< MinVatT)
    {
       SendAlarm(24);
         AlarmCount++;
    }

    // Als warm water vat te warm is 
    if (temp2> MaxVatT)
    {
       SendAlarm(25);
         AlarmCount++;
    }


    if ( AlarmCount == 0 )
    {
    //    AlarmDelay.stop(); 
        ActiveAlarmCode = 0;
    }
  } // End IF TVOC>0

          
 

}

void SendAlarm(int AlarmCode)
{
 /*   if (AlarmDelay.justFinished()) {
        /*Serial.println("Just Finshed");
        delay(100);
        AlarmActive = true;
        ActiveAlarmCode = AlarmCode;
        AlarmDelay.repeat();
     }
/*     if (AlarmDelay.isRunning()==false && AlarmActive == false) {
        AlarmDelayTime = AlarmInterval;  // Wait x minutes between alarms.
        AlarmDelay.start(AlarmDelayTime); 
        ActiveAlarmCode = AlarmCode;
     }*/

//      if (AlarmDelay.isRunning()==true && AlarmActive == true) {
   
     //  
  //   }

     
  }


String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;

    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

int getIntValue(String data, char separator, int index)
{  
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;
    String result;
    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    result = found > index ? data.substring(strIndex[0], strIndex[1]) : "";
    return result.toInt();
}



void ResetAlarm()
{
     if (R27 == false) {
          digitalWrite(R2_7, LOW); 
     }
     AlarmActive = false;
  
     AlarmDelayTime = 0; // Set it to 0 to make the next alarm trigger immediatly
}

void flushSerial() {
   while (Serial.available())
   Serial.read();
}

char readBlocking() {
 while (!Serial.available());
 return Serial.read();
}