AdaCore Blog

Ada for micro:bit Part 4: Pin Input

by Fabien Chouteau

Welcome to the Ada for micro:bit series where we look at simple examples to learn how to program the BBC micro:bit with Ada.

If you haven't already, please follow the instructions in Part 1 to setup your development environment.

In this fourth part we will see how to read the digital state of a pin. This means reading if the pin is at 0 volts (low) or 3.3 volts (high).

Wiring Diagram

For this example we will need a couple of extra parts:

  • A breadboard
  • An LED
  • A 470 ohm resistor
  • A push button
  • A couple of wires to connect them all

We start from the same circuit as the part three example, and we add a push button.

Interface

To control the IO pin we are going to use the function Set of the package MicroBit.IOs.

function Set (Pin : Pin_Id) return Boolean
     with Pre => Supports (Pin, Digital);

Arguments:

  • Pin : The id of the pin that we want to read as digital input

Precondition:

  • The procedure Set has a precondition that the pin must support digital IO.

As you can see, the function Set to read the pin has the same name as the procedure set that we used to control the pin in the output example. It is called overloading, two subprograms with the same name that provide different services.

In the code, we are going to write an infinite loop that reads the state of pin 1. If it is high, it means the button is not pressed so we turn off the LED on pin 0. It if it is low, it means the button is pressed so we turn on the LED on pin 0.

Here is the full code of the example:

with MicroBit.IOs;

procedure Main is
begin

   --  Loop forever
   loop

      --  Check if pin 1 is high
      if MicroBit.IOs.Set (1) then

         --  Turn off the LED connected to pin 0
         MicroBit.IOs.Set (0, False);
      else

         --  Turn on the LED connected to pin 0
         MicroBit.IOs.Set (0, True);
      end if;
   end loop;
end Main;

Following the instructions of Part 1 you can open this example (Ada_Drivers_Library-master\examples\MicroBit\digital_in\digital_in.gpr), compile and program it on your micro:bit.

See you next week for another Ada project on the micro:bit.

Don't miss out on the opportunity to use Ada in action by taking part in the fifth annual Make with Ada competition! We're calling on developers across the globe to build cool embedded applications using the Ada and SPARK programming languages and are offering over $9,000 in total prizes. Find out more and register today!

Posted in

About Fabien Chouteau

Fabien Chouteau

Fabien joined AdaCore in 2010 after his engineering degree at the EPITA (Paris). He is involved in real-time, embedded and hardware simulation technology. Maker/DIYer in his spare time, his projects include electronics, music and woodworking.