Go Down

Topic: Basic digitalRead question (Read 759 times) previous topic - next topic


Hello all, I apologize for the dumb question but... I just got my arduino Uno today (hi everybody!) and am familiarizing myself with the language. I actually have quite a bit of experience programming in python, c and c++, but I'm not a programmer by trade. I just wanted to modify the example DigitalReadSerial code. It works just fine with the original code (see the Examples section), but I tried to modify it so that it wouldn't display all those 0s when the switch is not depressed, I only want it to display the 1s when I press the switch, so here is what I changed:

void setup() {
  pinMode(2, INPUT);

void loop() {
  int sensorValue;
  sensorValue = digitalRead(2);
  if ( sensorValue = HIGH) {
    Serial.println(sensorValue, DEC);

Problem is: I was expecting the serial monitor to display nothing until I pressed the switch, and then I thought it'd start outputting 1s; instead, all it does is only display 1s, all the time, even when the switch is not depressed. I'm sure it's something very simple, I'm just not sure what I'm doing wrong....

Coding Badly

 if ( sensorValue == HIGH) {


The be specific the '=' operator always assigns a value to a variable  and returns that same value as its result.  It has nothing to do with 'equals' comparison at all.  The '==' operator does comparison and returns true or false.  Its very easy to be caught out by this, mainly because you are allowed to use '=' in an expression.

The plus side is that you can write:
Code: [Select]

  a = b = c = 0 ;

Which is interpreted as if it were:
Code: [Select]

  a = (b = (c = 0)) ;

So your code that did if ( sensorValue = HIGH) was setting sensorValue to HIGH then returning HIGH (which is equivalent to true) as the if-test.
[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]


Apr 05, 2011, 03:57 am Last Edit: Apr 05, 2011, 04:14 am by OlivierG Reason: 1
Dang. Just like Python.  :smiley-red: I'll go sit in a corner and write "I will not ask stupid questions" 1,000 times. Thanks!

OK, so the digitalRead function returns either 0/1 or LOW/HIGH then? One could use either, and even if you declare it as an integer, you can still manipulate it as high or low as opposed to 1 or 0?

Coding Badly

OK, so the digitalRead function returns either 0/1


or LOW/HIGH then?


One could use either


and even if you declare it as an integer, you can still manipulate it as high or low as opposed to 1 or 0?


Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131