So I have plugged in two soil moisture sensors to measure moisture at two different depths. The code I have is below:
int val = 0; //Variable to store soil value
int soil = A0; //Declare a variable for the soil moisture sensor at 25cm soil depth
int soilPower = D6; //Variable for Soil moisture Power
int soil2 = A1;// Declare a variable for the second soil moisture sensor at 50cm soil depth
int soilPower2 = D5; //Variable for the second Soil moisture sensor Power
//Rather than powering the sensor through the V-USB or 3.3V pins,
//we'll use a digital pin to power the sensor. This will
//prevent oxidation of the sensor as it sits in the corrosive soil.
void setup()
{
Serial.begin(9600); // open serial over USB
pinMode(soilPower, OUTPUT); //Set D6 as an OUTPUT
digitalWrite(soilPower, LOW); //Set to LOW so no power is flowing through the sensor
pinMode(soilPower2, OUTPUT); //Set D5 as an OUTPUT
digitalWrite(soilPower2, LOW); //Set to LOW so no power is flowing through the sensor
//This line creates a variable that is exposed through the cloud.
//You can request its value using a variety of methods
Particle.variable("soil", &val, INT);
Particle.variable("soil2", &val, INT);
}
void loop()
{
Serial.print("Soil Moisture Sensor = ");
//get soil moisture value from the function below and print it
Serial.println(readSoil());
delay(1000);//take a reading every second
}
//This is a function used to get the soil moisture content
int readSoil()
{
digitalWrite(soilPower, HIGH); //turn D6 "On"
delay(10); //wait 10 milliseconds
val = analogRead(soil);
digitalWrite(soilPower, LOW); //turn D6 "Off"
return val;
digitalWrite(soilPower2, HIGH); //turn D5 "On"
delay(10); //wait 10 milliseconds
val = analogRead(soil2);
digitalWrite(soilPower2, LOW); //turn D5 "Off"
return val;
}
So I have power running through the first sensor module but not the second? Any help would be greatly appreciated!
First, it would be good for you to state what your actual problem is. What result does this code give you vs. what you expect? One problem I see right off is that you’re returning val for soil, which causes that function to end; the part of that function that reads the second sensor is never executed. A second problem is that you’ve assigned the same variable, val, to both Particle.variables; you need to have two variables, one for each sensor (also, you should read the docs on Particle.variable, and update your code to the current syntax).
@jrbierring, as @Ric pointed out, your code does a return val1; which ENDS THE FUNCTION. The code following the return statement NEVER GETS EXECUTED. I am putting text in caps because you seem to have missed this.
Since you declare val1 and val2 as globals, there is no need to declare your readSoil() function as returning an int. Instead, make it void and remove the return statements from the function. Then in loop() call the function and (as a separate command), Serial.print() both val1 and val2 since you know they were both updated.