-3

I'm working on an Arduino project for multiple switches to be turned on in a sequence (4,3,1,2). I've been able to find a code that would work but I am struggling to understand what is happening.

Its a return function that makes sense, however the "?" and ":0" is where I get lost

Here is the code

uint8_t readSwitches()
{
  return (analogRead(A1) > 500 ? (1<<1) : 0)
       | (analogRead(A2) > 500 ? (1<<2) : 0)
       | (analogRead(A3) > 500 ? (1<<3) : 0)
       | (analogRead(A4) > 500 ? (1<<4) : 0);
}

Can someone explain what is happening

user438383
  • 5,716
  • 8
  • 28
  • 43
Riamd
  • 3
  • Does this answer your question? [Return type of '?:' (ternary conditional operator)](https://stackoverflow.com/questions/8535226/return-type-of-ternary-conditional-operator) – user438383 Oct 31 '21 at 11:38

1 Answers1

1

it's a so called ternary operator and is of the form A ? B : C and is a shortened if-else

If(A) then B else C

https://www.cprogramming.com/reference/operators/ternary-operator.html

So what this return statement does is

checking if the Ax variables are > 500and if they are, setting a certain bit and bitwise OR them together

Raildex
  • 3,406
  • 1
  • 18
  • 42