Go Down

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

crooveck

Hi guys
This is very basic question, but I'm stuck on it, so please help just a little :)

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?

Thanks in advance :)
Pablo

lloyddean

#1
Apr 21, 2012, 01:40 am Last 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

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

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!

Arduino
via Egeo 16
Torino, 10131
Italy