AdaCore Blog

Ada for micro:bit Part 6: Analog 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 sixth part we will see how to read the analog value of a pin. This means reading a value between 0 and 1023 that tells the voltage applied to the pin. 0 means 0 volts, 1023 means 3.3 volts.

Wiring Diagram

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

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

For this example we start from the same circuit as the pin output example, and we add a potentiometer. The center pin of the potentiometer is connected to pin 1 of the micro:bit the other two pins are respectively connected to GND and 3V.

Interface

To read the analog value of the IO pin we are going to use the function Analogof the package MicroBit.IOs.

function Analog (Pin : Pin_Id) return Analog_Value
     with Pre => Supports (Pin, Analog);
   --  Read the voltagle applied to the pin. 0 means 0V 1023 means 3.3V

Arguments:

  • Pin : The id of the pin that we want read the analog value from

Precondition:

  • The function Analog has a precondition that the pin must support analog IO.

In the code, we are going to write an infinite loop that reads the value of pin 1, and set pin 0 to the same value.

This means that you can control the brightness of the LED using the potentiometer.

Here is the full code of the example:

with MicroBit.IOs;

procedure Main is

   Value : MicroBit.IOs.Analog_Value;
begin

   --  Loop forever
   loop

      --  Read analog value of pin
      Value := MicroBit.IOs.Analog (1);

      --  Write analog value of pin 0
      MicroBit.IOs.Write (0, Value);
   end loop;
end Main;

Following the instructions of Part 1 you can open this example (Ada_Drivers_Library-master\examples\MicroBit\analog_in\analog_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.