Go Down

### Topic: How to convert several digitalRead() to one decimal number? (Read 722 times)previous topic - next topic

#### crooveck

##### Apr 21, 2012, 01:17 am
Hi guys

I have four pins connected to four switches (one switch - one pin). Each represents one bit in my four bits number. I need to read a state of those pins and convert the binary value to decimal number.

For example on pin following pins I have: 15 == HIGH, 16 == HIGH, 17 == HIGH and 18 == LOW, that is equal to B00001110 which is qual to 14 in decimal.

Is there any nice trick for doing this?

Pablo

#### lloyddean

#1
##### Apr 21, 2012, 01:40 amLast Edit: Apr 21, 2012, 08:13 am by lloyddean Reason: 1
Code: [Select]
`const uint8_t       pinBUTTON_BIT0  = 18;const uint8_t       pinBUTTON_BIT1  = 17;const uint8_t       pinBUTTON_BIT2  = 16;const uint8_t       pinBUTTON_BIT3  = 15;const uint8_t       BUTTON_UP       =  LOW;const uint8_t       BUTTON_DOWN     = HIGH;int     value =  0;if ( BUTTON_DOWN == digitalRead(pinBUTTON_BIT0) ) { value |= (1 << 0); }if ( BUTTON_DOWN == digitalRead(pinBUTTON_BIT1) ) { value |= (1 << 1); }if ( BUTTON_DOWN == digitalRead(pinBUTTON_BIT2) ) { value |= (1 << 2); }if ( BUTTON_DOWN == digitalRead(pinBUTTON_BIT3) ) { value |= (1 << 3); }`

#### James C4S

#2
##### Apr 21, 2012, 04:32 am
http://arduino.cc/en/Reference/BitWrite
Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com

Go Up

Please enter a valid email to subscribe