I am new to Arduino. I am working through the projects book in the Arduino Starter Kit, and currently working on an example to build a setup that uses input from a temperature sensor to control LEDs - the higher the temperature is abover the base value, the more LEDs light up. The program also produces a readout of each value generated.
The base value in the tutorial is to be set by the user at the start as a global variable. However, I wanted to try and set a baseline value using the sensor itself to detect the ambient temperature. Based on this official Arduino tutorial, it seems that global variables can be altered within the setup loop, and these values can then carry over to the main loop. However, mine does not appear to be doing so.
The variable I am trying to get a baseline value for is baselineTemp. It seems that whatever example I declare the global value to be at the start, this appears to be the value that the main loop uses. I set up a printout to check if the value was being calculated and assigned correctly within the setup loop, and it was, but it was still not working when carried over to the main loop, and it was reverting back to the originally declared global variable. Where am I going wrong?
const int sensorPin = A0;
int sensorVal = 0;
float baselineTemp = 20.0;
void setup () {
int runningtotal = 0;
int average = 0;
Serial.begin(9600);
for(int pinNumber = 2; pinNumber<5; pinNumber++){
pinMode(pinNumber, OUTPUT);
digitalWrite(pinNumber, LOW);
}
while (millis() < 5000) {
sensorVal = analogRead(sensorPin);
for (int i = 1; i <= 6; i++){
runningtotal = runningtotal + sensorVal;
Serial.print("Value: ");
Serial.println(sensorVal);
delay (1000);
}
}
Serial.print("Running Total: ");
Serial.println(runningtotal);
average = runningtotal/6;
float avvoltage = (average/1024.0) * 5.0;
float baselineTemp = (avvoltage - .5)* 100;
Serial.print("Average: ");
Serial.print(average);
Serial.print(" , Volts: ");
Serial.print(avvoltage);
Serial.print(" , Baseline Temp - degrees C: ");
Serial.println(baselineTemp);
}
void loop(){
int sensorVal = analogRead(sensorPin);
Serial.print("SensorValue: ");
Serial.print(sensorVal);
float voltage = (sensorVal/1024.0) * 5.0;
Serial.print(" , Volts: ");
Serial.print(voltage);
Serial.print (" , degrees C: ");
float temperature = (voltage - .5)* 100;
Serial.println(temperature);
if(temperature <baselineTemp+2) {
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
}else if(temperature >= baselineTemp+2 && temperature < baselineTemp+4){
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
}else if(temperature >= baselineTemp+4 && temperature < baselineTemp+6){
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
}else if(temperature >= baselineTemp+6){
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
}
delay(5000);
}