Lesson 22: Binary counter
Halaman ini memerlukan browser terbaru (dengan dukungan SharedArrayBuffer). Silakan perbarui Chrome, Edge, Firefox, atau Safari ke versi terbaru.
English
Numbers made of lights
- Inside a computer every number is stored in binary: only 0s and 1s, off and on.
- Four LEDs can show a binary number: each LED is one bit. On is 1, off is 0.
- First the Arduino counts from 0 to 15 by itself. Then you build a counter with a button.
Words for this lesson
| Word | Meaning |
|---|---|
| binary | numbers written with only 0 and 1 |
| bit | one binary digit: 0 or 1 |
| place value | what a digit is worth because of where it is: 1, 2, 4, 8 … |
| bitRead(n, i) | gives bit number i of n (bit 0 is worth 1) |
English
Place values
| LED | pin 5 | pin 4 | pin 3 | pin 2 |
|---|---|---|---|---|
| worth | 8 | 4 | 2 | 1 |
| 5 = 4 + 1 | 0 | 1 | 0 | 1 |
| 11 = 8 + 2 + 1 | 1 | 0 | 1 | 1 |
| 15 = 8 + 4 + 2 + 1 | 1 | 1 | 1 | 1 |
- The number is 8 × (pin 5) + 4 × (pin 4) + 2 × (pin 3) + 1 × (pin 2).
- We write the biggest place value on the left, like in denary: 11 is 1011.
English
Read the bits
void setup() {
Serial.begin(9600);
int n = 11;
for (int i = 3; i >= 0; i--) {
Serial.print(bitRead(n, i));
}
Serial.println();
}
void loop() {
}
- The loop goes from bit 3 down to bit 0, so the Serial Monitor shows
1011, biggest place value first.
Kesulitan 3/5 · 200 koin + bonus kecil pada penyelesaian pertama hari ini
Four LEDs show a number in binary. The LED on pin 2 is worth 1, pin 3 is worth 2, pin 4 is worth 4 and pin 5 is worth 8. Finish show(n): LED i (0 to 3) is on when bitRead(n, i) is 1. The loop counts 0, 1, 2 … 15, a quarter second for each number.
Klik Jalankan untuk melihat output di sini.
Kesulitan 4/5 · 280 koin + bonus kecil pada penyelesaian pertama hari ini
Make a counter for people coming into a room. Each press of the button on pin 8 adds 1 to count and shows it on the LEDs. After 15 it goes back to 0. Print Count: and the number after each press.
Klik Jalankan untuk melihat output di sini.