2

I'm working on a simple ADC project, the goal is to adjust the on/off of the LEDs according to the binary reading (1-on,0-off). I've tried this with 8 bit, and it works as intended. But on 10 bit, two of the LEDs with representation of 2^8 and 2^9 won't turn on even though the reading on the serial monitor is 1023 (should be 1111111111 -all LEDs on). I wonder if there's anything wrong with my code or circuit? (I'm totally new to arduino, sorry for the noobness) -I'm using Arduino UNO R3, the details are shown in the imageenter image description here

void setup(){
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  
  Serial.begin(9600);
}

void loop(){
  int sensorValue = analogRead(A0);
  Serial.print("Decimal=");
  Serial.print(sensorValue);
  Serial.print("\tBinary=");
  Serial.println(sensorValue,BIN);
  
  if(sensorValue>=0&&sensorValue<=1023){
    digitalWrite(4,(sensorValue&1));
    digitalWrite(5,(sensorValue&2));
    digitalWrite(6,(sensorValue&4));
    digitalWrite(7,(sensorValue&8));
    digitalWrite(8,(sensorValue&16));
    digitalWrite(9,(sensorValue&32));
    digitalWrite(10,(sensorValue&64));
    digitalWrite(11,(sensorValue&128));
    digitalWrite(12,(sensorValue&256));
    digitalWrite(13,(sensorValue&512));
  }
  delay(20); 
}
1
  • write a debug sketch ... turn on all of the LEDs ... does that work?
    – jsotola
    Oct 8 '20 at 16:23
3

According to the official documentation, the second parameter of digitalWrite() should be either HIGH or LOW. Thus, in order to be compliant with the published API, you are supposed to write:

digitalWrite(12, sensorValue&256 ? HIGH : LOW);

In practice, digitalWrite() interprets any non-zero value as HIGH. However, its prototype is:

void digitalWrite(uint8_t pin, uint8_t val);

Both parameters have the type uint8_t, which means “8-bit unsigned integer”. If you provide a value that doesn't fit in 8 bits, the implicit cast to uint8_t will reduce it modulo 28. Thus, both 256 and 512 become zero through the implicit cast.

2
  • Your trinary operator trick would fix the 8 bit truncation problem AND send the documented values to the function. Personally, I'd write a function that took bit index and a value and returned HIGH or LOW, and call that. D.R.Y.
    – Duncan C
    Oct 8 '20 at 19:10
  • I know OP is new, but fancy not writing to ports for ganged output.
    – mckenzm
    Oct 9 '20 at 1:24
1

Seems, digitalWrite does not take any int != 0 as HIGH

Rather consider supplying a boolean (one byte value)

   digitalWrite(12,(sensorValue&256)==256);
   digitalWrite(12,(sensorValue>>8)&1);

or similar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.