European Robotic LABoratory EURLAB European Robotic LABoratory Basic knowledge x.x: How to decide with Arduino EURLAB Basic knowledge x.x – How to decide with Arduino
How to decide with Arduino of course, when you want to solve a problem by a program for Arduino, you must have the ability to implement a decision. This is possible by mean the 'IF‘ statement. EURLAB Basic knowledge x.x - How to decide with Arduino
The ‘IF’ statement ………………….. if (‘condition’) { // here you can put First possibility: to do or not an ‘action’. In this case, when condition is ‘false’ nothing is done! ………………….. if (‘condition’) { // here you can put // statements // to realize if // condition is // true } …………………… Example: int buttonState = 0; // variable for reading the button 4 status void setup() { pinMode(13, OUTPUT); // initialize the LED pin 13 as an output: pinMode(4, INPUT); // initialize the pin 4 as an input: } void loop() { buttonState = digitalRead(4); // read the state of the button 4 // check if the pushbutton is pressed. if (buttonState == HIGH) { // if it is pressed…… digitalWrite(13, HIGH); // ……turn LED on: } EURLAB Basic knowledge x.x - How to decide with Arduino
// if condition is false The ‘IF’ statement Second possibility: Do ‘action 1’ if condition ‘true’. Do ‘action 2’ if condition ‘false’ if (‘condition’) { // here you can put // statements // if condition is true } else // if condition is false Example: int buttonState = 0; // variable for reading the button 4 status void setup() { pinMode(13, OUTPUT); // initialize the LED pin 13 as an output: pinMode(4, INPUT); // initialize the pin 4 as an input: } void loop() { buttonState = digitalRead(4); // read the state of the button 4 // check if the pushbutton is pressed. if (buttonState == HIGH) { // if it is true…… digitalWrite(13, HIGH); // ……turn LED on: } else digitalWrite(13, LOW); // ……turn LED off: EURLAB Basic knowledge x.x - How to decide with Arduino
The ‘SWITCH-CASE’ statement Sometimes you have to choose between more than two situations: In this situation is useful to use the ‘SWITCH-CASE’ instuctions EURLAB Basic knowledge x.x - How to decide with Arduino
The ‘SWITCH-CASE’ statement Example: int sensorValue = 0; // variable to store the value coming from the sensor void setup() { pinMode(13, OUTPUT); // set Pin 13 as an OUTPUT pinMode(12, OUTPUT); // set Pin 12 as an OUTPUT } void loop() { sensorValue = analogRead(A0); // read the value from sensor attached to input A0: switch (sensorValue) { case 50: digitalWrite(13,LOW); digitalWrite(12,LOW); break; // exit from ‘case’ structure without evaluating other cases case 100: digitalWrite(13,HIGH); digitalWrite(12,LOW); case 150: digitalWrite(13,LOW); digitalWrite(12,HIGH); case 200: digitalWrite(13,HIGH); digitalWrite(12,HIGH);} } EURLAB Basic knowledge x.x - How to decide with Arduino