user119o
user119o

Reputation: 387

How switch case statement works in Arduino/C++

I have written below function and check it using Arduino MEGA. This code is simply read PORTC and filter it's 4bit and according to that bit values, function returns -2 to 13.

#define PDL_1_BRN 37 //PC0
#define PDL_2_GRN 36 //PC1
#define PDL_3_WHT 35 //PC2
#define PDL_4_YEL 34 //PC3

void setup() {
  Serial.begin(9600);
  pinMode(PDL_1_BRN, INPUT); //use external pullup
  pinMode(PDL_2_GRN, INPUT);
  pinMode(PDL_3_WHT, INPUT);
  pinMode(PDL_4_YEL, INPUT);

}
uint32_t t = 0;
void loop() {

  t = micros();
  getPedalState();
  Serial.println(micros() - t);


}

int8_t getPedalState() {
  uint8_t val = 0;
  val = PINC & 0x0F;
  switch (val) {
    case 0x0F:
      return 0;
      break;
    case 0x0B:
      return 1;
      break;
    case 0x09:
      return 2;
      break;
    case 0x01:
      return 3;
      break;
    case 0x05:
      return 4;
      break;
    case 0x0D:
      return 5;
      break;
    case 0x0C:
      return 6;
      break;
    case 0x04:
      return 7;
      break;
    case 0x00:
      return 8;
      break;
    case 0x08:
      return 9;
      break;
    case 0x0A:
      return 10;
      break;
    case 0x02:
      return 11;
      break;
    case 0x06:
      return 12;
      break;
    case 0x0E:
      return 13;
      break;
    case 0x07:
      return -1;
      break;
    case 0x03:
      return -2;
      break;

  }
}

Using separate code I measured PORTC read execution time using micros(). It takes 4uS as I measured.

This code also read the PORTC and then used a switch case to identify port value.

But, this entire function also gets only 4uS to execute all instructions (port reading, masking, switch case).

That means, switch case didn't take at least 1uS to execute. As I know, swich case start to compare one by one top of the code to bottom of the code. (That means switch case gets more time to return value in bottom of the code.) But, this code gets only 4uS for any value of the PORTC. Please explain how switch case works in Arduino/C++.

Upvotes: 0

Views: 670

Answers (1)

Delta_G
Delta_G

Reputation: 3243

The resolution of the micros function is 4uS. That's why you're seeing the same values. Toggle a pin instead and watch it with an oscilloscope and you'll get a better idea of the actual timing.

Upvotes: 2

Related Questions