So what I'm trying to do is hook up my temperature sensor and using an if/ else statement to control a basic LED light (if the temp goes above 75 turn the light on) but I seem to be having trouble with my coding. Is there a simple mistake I'm making or is it more complex?
int const tempPin = A0;
int const LEDPin = 5;
int value = analogRead(tempPin);
int tempLevel = 0;
int tempLevel2 = 255;
int constraint = 0;
void setup()
{
Serial.begin(9600);
analogReference(DEFAULT);
pinMode(LEDPin, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
digitalWrite(8, HIGH);
}
void loop(){
{
int value = analogRead(tempPin);
value = (5.0*value*100.0)/1024.0;
Serial.println("Temperature: ");
Serial.println((byte)value);
delay(1000);
}
if(value > 75){
analogWrite(LEDPin, tempLevel);
}
else{
analogWrite(LEDPin, tempLevel2);
}
}
I tried quite a bit of other options before I came to this one. It does work but I wanted to know if you saw any problems with it?
Most of all I tried fixing that integer overflow with the new equation down below
void loop() {
float temperature = 0.0; // stores the calculated temperature
int sample; // counts through ADC samples
float ten_samples = 0.0; // stores sum of 10 samples
// take 10 samples from the MCP9700
for (sample = 0; sample < 10; sample++) {
// convert A0 value to temperature
temperature = ((float)analogRead(A0) * 5.0 / 1024.0) - 0.5;
temperature = temperature / 0.01;
// sample every 0.1 seconds
delay(100);
// sum of all samples
ten_samples = ten_samples + temperature;
}
// get the average value of 10 temperatures
temperature = ten_samples / 10.0;
// send temperature out of serial port
Serial.print(temperature);
Serial.println(" deg. C");
ten_samples = 0.0;
{
if (temperature > 26){
digitalWrite(LEDPin, HIGH);
digitalWrite(LEDPin2, LOW);
}
else {
digitalWrite(LEDPin, LOW);
digitalWrite(LEDPin2, HIGH);
}
}
}
temperature = ((float)analogRead(A0) * 5.0 / 1024.0) - 0.5;
temperature = temperature / 0.01;
You are now using floats, and multiplication is faster than division, I would express the temperature this way
temperature = 100*(((float)analogRead(A0) * .004883) - 0.5);
Sampling every 100 ms seems very fast and a bit of overkill to get 10 readings per second. How fast is your temperature changing? But, if its working....