Skip to content

Embedded programming | Binary to decimal using buttons

This fifth week I worked on getting used to Embedded programming.

Since we are going to study Inputs and Outputs devices more widely during the following two weeks, we just need to make something very simple for this assignment; then this time I went for something less creative.

I made a quick program that converts binary numbers (entered with two buttons) to decimal. Actually, the code works for numbers from 0 to 31 due to the amount of bits that can be entered (5) , it can be easily changed to accept higher quantities.

I will consider adding this property as a variable to make it easier.

Softwares and hardwares

- For this practice we programmed an Arduino UNO with its Arduino IDE.
- For Circuit diagramming I used TinkerCad.

Components:

For this assignment I used:

Quantity Description
1 x Arduino UNO
2 x Momentary push button
2 x Resistor 10K
1 x Small breadboard
a few Jumper cables

Circuit

It’s useful to make a digital circuit diagram first, it will make the wiring easier(specially when we work with more devices), and the capability of replicating our project in the future. Although for professional projects we must use more technical diagrams

I used the Pull-down resistor configuration for the buttons.

- Circuit on TinkerCad:
Circuit

- Physical circuit:
Circuit

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const int led = LED_BUILTIN; //the build-in LED on the Board
const int Button0 = 2; //Button in pin 2 -> number 0
const int Button1 = 3; //Button in pin 3 -> number 1

void setup()
{
  //Declare pinModes (inputs and outputs)
  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);
  pinMode(Button0, INPUT);
  pinMode(Button1, INPUT);

  //Initialize Serial communication
  Serial.begin (9600);
}

void loop()
{
  char message[5];
  int n=0;
  Serial.print("Binario: ");
    while (n<5)

    {
      if(digitalRead(Button0) == HIGH)
      {
      Serial.print("0");
      delay(500);
      message[n]='0';
      n++;
      }
      else if(digitalRead(Button1) == HIGH)
        {
        Serial.print("1");
        delay(500);
        message[n]='1';
        n++;
        }
    }
    Convert(message);
}

void Convert (String message){

  char bin[6];
  message.toCharArray(bin, 6);

  int i = 0;
  int dec = 0;

  while ( bin[i] == '0' || bin[i] == '1' ) {
    if ( bin[i] == '0' )
      dec <<= 1;
    else {
      dec ^= 1;
      dec <<= 1;}
    ++i;  }

  dec >>= 1;

  Serial.print(" = Decimal: ");
  Serial.println(dec);
}

Demonstration

Download files

- Code: BinaryButtons.ino


Last update: February 12, 2021