Answer the question
In order to leave comments, you need to log in
Switch case statement in Arduino for data range?
#include "Ultrasonic.h"
Ultrasonic ultrasonic(4, 7);
const int led1 = 9;
const int led2 = 10;
const int led3 = 11;
const int led4 = 12;
const int led5 = 13;
void setup()
{
pinMode (led1, OUTPUT);
pinMode (led2, OUTPUT);
pinMode (led3, OUTPUT);
pinMode (led4, OUTPUT);
pinMode (led5, OUTPUT);
Serial.begin(9600);
}
void loop()
{
float dist = ultrasonic.Ranging(CM);
Serial.println(dist);
if (dist > 40) {digitalWrite(led1, 1); digitalWrite(led2, 0); digitalWrite(led3, 0); digitalWrite(led4, 0); digitalWrite(led5, 0); }
if (dist <= 40 && dist > 30) {digitalWrite(led1, 1); digitalWrite(led2, 1); digitalWrite(led3, 0); digitalWrite(led4, 0); digitalWrite(led5, 0); }
if (dist <= 30 && dist > 20) {digitalWrite(led1, 1); digitalWrite(led2, 1); digitalWrite(led3, 1); digitalWrite(led4, 0); digitalWrite(led5, 0); }
if (dist <= 20 && dist > 10) {digitalWrite(led1, 1); digitalWrite(led2, 1); digitalWrite(led3, 1); digitalWrite(led4, 1); digitalWrite(led5, 0); }
if (dist <= 10) {digitalWrite(led1, 1); digitalWrite(led2, 1); digitalWrite(led3, 1); digitalWrite(led4, 1); digitalWrite(led5, 1); }
delay(100);
}
Answer the question
In order to leave comments, you need to log in
I don't like the abundance of if. How can you shorten a construction using a switch case?
digitalWrite(led1, 1);
digitalWrite(led2, dist <= 40);
digitalWrite(led3, dist <= 30);
digitalWrite(led4, dist <= 20);
digitalWrite(led5, dist <= 10);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question