wazawoo:
But I was actually looking for a way to input an integer with the keyboard and see the binary result. When a new integer is inputted, the LEDs are reset and the new binary result is displayed.
What's the best way to do this?
Ah. The way I read the post, I thought that the value to be displayed was already in a variable. Like many things, there is probably no "best" way, so how about a crude way instead
There is no error checking etc. Basically it accumulates three characters from the serial monitor, converts them to an integer, and displays it on the LEDs. Exactly three characters must always be entered, e.g. 001 or 042 or 255. If more than three characters are entered, they are ignored. (Actually, if the line ending option in the serial monitor is set to "Both NL & CR", it will give the appearance of accepting 1, 2 or 3 character inputs. A bit of a sloppy approach but you get what you pay for!)
int ledPins[] = {9, 8, 7, 6, 5, 4, 3, 2}; //least-significant to most-significant bit
byte nChar; //number of characters read
char c; //incoming character
char input[8]; //accumulates the incoming characters
int n; //the converted value of the input characters
#define nBits sizeof(ledPins)/sizeof(ledPins[0]) //number of bits
void setup(void)
{
for (byte i=0; i<nBits; i++) {
pinMode(ledPins[i], OUTPUT);
}
Serial.begin(9600);
}
void loop(void)
{
if (nChar < 3) { //accumulate three characters
if (Serial.available()) {
c = Serial.read();
input[nChar++] = c;
}
}
else {
input[3] = 0; //atoi() expects string terminator
n = atoi(input); //convert the input characters to integer
dispBinary(n);
delay(100); //wait for any additional characters
while (Serial.available()) { //ignore them
c = Serial.read();
}
nChar = 0;
}
}
void dispBinary(int n)
{
if (n >= 0 && n <= 255) { //only display values between 0 and 255
for (byte i=0; i<nBits; i++) {
digitalWrite(ledPins[i], n & 1);
n /= 2;
}
}
}
As for the code below, this is what is called direct port manipulation. If you are new to Arduino, I might come back to that at a later point. Some study of the datasheet is in order to understand the registers (e.g. DDRD, PORTD), etc.
Magician:
DDRD = 0xFF; // Declare pins 0..7 as outputs;
PORTD = decimal_integer; // Light them up!