Question: Can somebody help fix this code, I want to read temp and light then both of them. but i don't to repeat if else if
Can somebody help fix this code, I want to read temp and light then both of them. but i don't to repeat if else if else. I am trying to call function instead of repeating the code.
int tempPin = A0; // Analog input pin for temperature sensor
int lightPin = A1; // Analog input pin for light sensor
ReadTemp(){
// If the command is to read temperature
float temp = (5.0 * analogRead(tempPin) * 100.0) / 1024.0; // Calculate the temperature in Celsius(check if this formula is correct
Serial.print("Temperature is: ");
Serial.print(temp);
Serial.println("C");
}
ReadLight(){
// If the command is to read light intensity
int lightValue = analogRead(lightPin); // Read the analog value from the photoresistor
Serial.print("Light intensity is: ");
Serial.println(lightValue);
}
void setup() {
Serial.begin(9600); // Start serial communication at 9600 bits per second
}
void loop() {
if (Serial.available()) {
String command = Serial.readStringUntil(' '); // Read the incoming command from serial monitor
if (command == "Read Temp") {
ReadTemp();
}
else if (command == "Read Light") {
ReadLight();
}
else if (command == "Read all sensors") {
ReadTemp();
ReadLight();
}
else { // If the command is not correct
Serial.println("Invalid command please try again.");
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
