Byte Variables
One way we can store binary numbers is by using a byte variable. For example, we can create the byte variable outputs using the following code:
The B in front of the number tells Arduino to read the number as a binary number (in this case, 11111111) instead of its base-10 equivalent of 255. Listing 6-2 demonstrates this further.
// Listing 6-2 byte a;
void setup()
{
Serial.begin(9600);
}
void loop()
{
for ( int count = 0 ; count < 256 ; count++ )
{ a = count;
Serial.print("Base-10 = "); Serial.print(a, DEC);
Serial.print(" Binary = "); Serial.println(a, BIN); delay(1000);
}
}
Listing 6-2: Binary number demonstration
We display byte variables as base-10 numbers using DEC or as binary numbers using BIN as part of the Serial.print() function. After uploading the sketch, you should see output in the Serial Monitor similar to that shown in Figure 6-3.
Figure 6-3: Output from Listing 6-2
increasing digital outputs with shift registers
The Arduino board has 13 digital pins that we can use as outputs—but sometimes 13 just isn’t enough. To add outputs, we can use a shift register and still have plenty of room left on the Arduino for outputs. A shift register is an integrated circuit (IC) with eight digital output pins that can be controlled by sending a byte of data to the IC. For our projects, we will be using the 74HC595 shift register shown in Figure 6-4.
Figure 6-4: The 74HC595 shift register IC
The 74HC595 shift register has eight digital outputs that can operate like the Arduino digital output pins. The shift register itself takes up three Arduino digital output pins, so the net gain is five output pins.
The principle behind the shift register is simple: We send 1 byte of data (8 bits) to the shift register, and it turns on or off the matching eight outputs based on the 1 byte of data. The bits representing the byte of data match the output pins in order from highest to lowest. So the leftmost bit of the data represents output pin 7 of the shift register, and the rightmost bit of the data represents output pin 0. For example, if we send B10000110 to the shift register, then it will turn on outputs 7, 2, and 1 and will turn off outputs 0 and 3–6 until the next byte of data is received or the power is turned off.
More than one shift register can also be connected together to provide an extra eight digital output pins for every shift register attached to the same three Arduino pins; this makes shift registers very convenient when you want to control lots of LEDs. Let’s do that now by creating a binary number display.
Do'stlaringiz bilan baham: |