This is all about "If Statements" in the Arduino world.
These are only executed , based on a condition
The
if
statement checks for a condition and executes the following statement or set of statements if the condition is 'true'.Check out this old circuit about pots:
I'll be modifying this with a if statement.
The code:
----------------
// if statement exercise
// if voltage is above 4V, the LED lights
// if voltage is above 4V, the LED lights
// set up variables
int myPin=A2;
int readVal;
float V2;
int dT=250;
int redPin=9;
void setup()
{
Serial.begin(9600);
pinMode(myPin,INPUT);
pinMode(redPin,OUTPUT);
}
void loop()
{
readVal=analogRead(myPin);
V2=(5./1023.)*readVal;
// converts to a voltage -- remember to place the decimal
// points after the 5 & 1023 ... these may be floating points
Serial.print("Potentiometer Voltage is ");
Serial.println(V2);
if(V2>4.0){
digitalWrite(redPin, HIGH);
}
if (V2<4.0) {
digitalWrite(redPin, LOW);
}
delay(dT);
}
------------------------------------
Here is a variation of the if statement using equal (==)
and not equal(!=)
if(V2==5.0){
digitalWrite(redPin, HIGH);
// "==" is equal
}
if (V2!=5.0) {
digitalWrite(redPin, LOW);
// != is not equal
----------------------------------------------------------------------
Compound Conditionals
You can also use AND , OR
if(V2>2.0 && V2<3.0){
digitalWrite(redPin, HIGH);
// "&&" is and
}
if (V2<2 || V2>3) {
digitalWrite(redPin, LOW);
// "||" is OR
}
delay(dT);
digitalWrite(redPin, HIGH);
// "&&" is and
}
if (V2<2 || V2>3) {
digitalWrite(redPin, LOW);
// "||" is OR
}
delay(dT);
----------------------
if you are combining great than and equal, you don't use "=="
eg:
if(V2>=2.0 && V2<=3.0){
digitalWrite(redPin, HIGH);
// "&&" is and
}
if (V2<=2 || V2>=3) {
digitalWrite(redPin, LOW);
// "||" is OR
digitalWrite(redPin, HIGH);
// "&&" is and
}
if (V2<=2 || V2>=3) {
digitalWrite(redPin, LOW);
// "||" is OR
--------------------------------------------
Thanks to Paul McWhorter for the great video.
---------------------------------
-------------------------------------
No comments:
Post a Comment