I have a situation where I read values from sensors (attached to an arduino) which gets stored in a mysql database, which is then displayed on a webpage. At the same time relay values are read from a webpage, stored on mysql and then written to the arduino. I can do each separately but not at the same time. I've attached some code to show what Im trying to accomplish. I think it has something to do with Serial availability
/*----( SETUP: RUNS ONCE )----*/
void setup() {
Serial.begin(115200);
sensors.begin(); //Get DS18B20 temperatures
sensors.setResolution(probe1, 10); //set resolution to 10bit
sensors.setResolution(probe2, 10); //set resolution to 10bit
Wire.begin(); // Start the Wire (I2C communications)
RTC.begin(); // Start the RTC Chip
digitalWrite(Relay_1, RELAY_OFF); //Relays
digitalWrite(Relay_2, RELAY_OFF);
pinMode(Relay_1, OUTPUT); //Set relays as outputs
pinMode(Relay_2, OUTPUT);
}
/*--(end setup )---*/
/****** LOOP: RUNS CONSTANTLY ******/
void loop() {
ReadSensors();
delay(1000);
ReadRelays();
}
/****** Read Sensors ******/
void ReadSensors()
{
DateTime now = RTC.now(); //Get time from RTC
photolevel = analogRead(photopin); //Read light level
sensors.requestTemperatures();
dallas1 = sensors.getTempC(probe1);
dallas2 = sensors.getTempC(probe2);
dtostrf(photolevel, 1, 0, photo1);
dtostrf(dallas1, 1, 2, temp1);
dtostrf(dallas2, 1, 2, temp2);
String tempAsString1 = String(photo1);
String tempAsString2 = String(temp1);
String tempAsString3 = String(temp2);
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(" ");
Serial.println(tempAsString1 + " " + tempAsString2 + " " + tempAsString3);
Serial.flush();
}
void ReadRelays()
{
Serial.flush();
// Read all serial data available, as fast as possible
while(Serial.available() > 0)
{
char inChar = Serial.read();
if(inChar == SOP)
{
index = 0;
inData[index] = '\0';
started = true;
ended = false;
}
else if(inChar == EOP)
{
ended = true;
break;
}
else
{
if(index < 79)
{
inData[index] = inChar;
index++;
inData[index] = '\0';
}
}
}
if(started && ended)
{
// The end of packet marker arrived. Process the packet
if (strlen(inData) > 0)
{
char *token = strtok(inData, ",");
if(token)
{
index = 0;
array[index] = atoi(token);
while (token = strtok(NULL, ","))
{
array[index++] = atoi(token);
}
}
}
Serial.println(array[0]);
Serial.println(array[1]);
// Reset for the next packet
started = false;
ended = false;
index = 0;
inData[index] = '\0';
}
}
Any suggestions would be well appreciated??