In: Computer Science
this is for those who did Arduino projects
this code is supposed to work this way, there is a temperature sensor in the Arduino Uno along with a motor. the motor should turn on only when the temperature in the sensor exceeds 23 degrees Celcius. Here is the code
float AnalogToVolts(int reading);
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop()
{
int reading;
float volts;
float temperature_in_celsius;
reading = analogRead(A1);
volts = AnalogToVolts(reading); //Function call
if ( temperature_in_celsius > 23)
{
digitalWrite(13, HIGH);
}
else
{
digitalWrite(13, LOW);
}
Serial.println(temperature_in_celsius);
Serial.println(volts);
}
// Function Definition
float AnalogToVolts(int reading)
{
float temperature_in_celsius;
float volts;
volts = reading/1023.0 * 5.0; //Perform conversion
temperature_in_celsius = volts * 100 - 50;
return temperature_in_celsius;
return volts; //Return result
}
but it does not work. it properly shows the temperature and all, but the motor do not respond correctly with the temperature. Please fix this. Thank you
Hey below are some errors that I noticed:
No other function has access to them unless you pass them those variables.
It is not like , if we update temperature_in_celsius inside function AnalogToVolts , it doesn't mean that the temperature_in_celsius inside void loop( ) gets updated.
______________________________________________________________________________________________________________________________________________________________________________
float AnalogToVolts(int reading);
void setup()
{
Serial.begin(9600);
// setting A1 analog pin to read input from the sensor.
pinMode(A1, INPUT);
pinMode(13, OUTPUT);
}
void loop()
{
int reading;
float volts;
float temperature_in_celsius;
reading = analogRead(A1);
volts = AnalogToVolts(reading); //Function call
// updating
temperature_in_celsius
temperature_in_celsius = volts*100 ;
if ( temperature_in_celsius > 23)
{
digitalWrite(13, HIGH);
}
else
{
digitalWrite(13, LOW);
}
Serial.println(temperature_in_celsius);
Serial.println(volts);
}
// Function Definition
float AnalogToVolts(int reading)
{
// the temperature_in_celsius variable
, we don't need to declare one here
// float temperature_in_celsius;
float volts;
// MODIFICATION 1
// I also found that the conversion has some small error,
// Most of the standards say that.
// volts = 5*reading/1023
// multiplying the above with 100 gives the temperature in
celsius
// volts = reading/1023.0 * 5.0; //Perform conversion
// temperature_in_celsius = volts * 100 - 50;
volts = 5.0*reading/1023.0;
// No need to update this local
variable here
// return temperature_in_celsius;
// only returning volts
// there in the loop() we update temperature_in_celsius
value
return volts; //Return result
}
____________________________________________________________________________________________________
THANK YOU!!