H
H
Heinrich Schulz2014-08-17 13:31:33
Arduino
Heinrich Schulz, 2014-08-17 13:31:33

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);                                  
}

I get the distance to the nearest obstacle in centimeters and, based on this, I light the LEDs.
I don't like the abundance of if. How can you shorten a construction using a switch case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2014-08-17
@gkoh90

I don't like the abundance of if. How can you shorten a construction using a switch case?

Following the C / C ++ standard - no way. In addition, your dist is a float, and only integer labels can be specified in switch statement cases.
But you can replace the if bunch with the following:
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 question

Ask a Question

731 491 924 answers to any question