Pages: [1]   Go Down
Author Topic: How to convert several digitalRead() to one decimal number?  (Read 485 times)
0 Members and 1 Guest are viewing this topic.
Warsaw, Poland
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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 smiley
Pablo
Logged

Des Moines, WA - USA
Offline Offline
God Member
*****
Karma: 25
Posts: 779
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
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); }
« Last Edit: April 21, 2012, 01:13:01 am by lloyddean » Logged

Fort Lauderdale, FL
Offline Offline
Faraday Member
**
Karma: 71
Posts: 6144
Baldengineer
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

http://arduino.cc/en/Reference/BitWrite
Logged

Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.c

Pages: [1]   Go Up
Jump to: