Go Down

Topic: Problem with pulling sensor data without using delay() (Read 567 times) previous topic - next topic

cbodor

Hello, Like many others I want to poll a sensor every few seconds, but do not want to use the delay() function and tie up my whole arduino. For some reason the following code does not seem to work for me, when I run it the oled display is updating the sensor reading as fast as it can, IE its not waiting 1000ms, instead just going at it as fast as it can. Please excuse my HORRIBLE code and my ignorance. Many thanks. If it matters I am also calling this temp() function via a case:
Code: [Select]

case 4:
 

    temp();
   
    break;


Code: [Select]

void temp()
{
uoled.Text(0,0, 2, 150, "Temperature",1);
uoled.Line(0, 15, 96, 15, 65000);
   
long previousMillis = 0;   // will store last time DS was updated
long interval = 1000;      // interval at which to read temp (milliseconds)
   
if (millis() - previousMillis > interval) {
   previousMillis = millis();

   int reading = analogRead(sensorPin); 

   float voltage = reading * 5.0;  // converting that reading to voltage, for 3.3v arduino use 3.3
   voltage /= 1024.0;

   float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
                                               //to degrees ((volatge - 500mV) times 100)

   float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;  // now convert to Fahrenheight

   char tempC[4];
   char tempF[4];
   char volts[4];

   itoa(temperatureC, tempC, 10);
   //dtostrf(temperatureC, 2, 2, tempC);
   itoa(temperatureF, tempF, 10);
   //dtostrf(temperatureF, 2, 2, tempF);
   dtostrf(voltage, 2, 2, volts);

   uoled.Text(0,2, 2, 150, tempC,1);
   uoled.Text(6,2, 2, slow_color, "C",1);

   uoled.Text(0,3, 2, 150, tempF,1);
   uoled.Text(6,3, 2, slow_color, "F",1);

   uoled.Text(0,4, 2, 150, volts,1);
   uoled.Text(6,4, 2, slow_color, "V",1);

}

}


wildbill

previousMillis is a local variable to function temp. It is initialized to zero every time temp is called and after the first second of run time, it will always be less than millis() - interval.

Make it global, or better, static.

cbodor

Well don't I feel sheepish. Put those two vars at the top of the project and bang works like a charm. Thanks!

Go Up