Example

Here are some examples of how to use mraa, common convention is to import mraa as mraa to keep it short but feel free to import it globally! As a general rule the API is very similar to the C++ API so there are only basic examples to show quick usage. The mraa module can be built with python3 or python2. All examples may not run on python3 as this is not tested.

Hello GPIO

Here is the simplest Gpio program in mraa.

import mraa
import time

# initialise gpio 23
gpio_1 = mraa.Gpio(23)

# initialise gpio 24
gpio_2 = mraa.Gpio(24)

# set gpio 23 to output
gpio_1.dir(mraa.DIR_OUT)

# set gpio 24 to output
gpio_2.dir(mraa.DIR_OUT)

# toggle both gpio's
while True:
    gpio_1.write(1)
    gpio_2.write(0)

    time.sleep(1)

    gpio_1.write(0)
    gpio_2.write(1)

    time.sleep(1)

GPIO Interrupt (isr)

The GPIO module allows you to set an interrupt on a GPIO. This interrupt is controlled by the mode that the ‘edge’ is in. Before setting another isr please remove the first one, multiple isrs on one pin are not supported. Some platforms will not support interrupts on all pins so please check your return values.

Note: Galileo Gen1 only supports EDGE_BOTH

import mraa
import time
import sys

class Counter:
    count = 0

c = Counter()

# inside a python interrupt you cannot use 'basic' types so you'll need to use
# objects
def isr_routine(gpio):
    print("pin " + repr(gpio.getPin(True)) + " = " + repr(gpio.read()))
    c.count += 1

# GPIO
pin = 6;

try:
    # initialise GPIO
    x = mraa.Gpio(pin)

    print("Starting ISR for pin " + repr(pin))

    # set direction and edge types for interrupt
    x.dir(mraa.DIR_IN)
    x.isr(mraa.EDGE_BOTH, isr_routine, x)

    # wait until ENTER is pressed
    var = raw_input("Press ENTER to stop")
    x.isrExit()
except ValueError as e:
    print(e)

Note: If the python script is ended the destructors will run meaning that the ISR will not run. The sleep call is there for that function.

Note: The python isr module treats only objects. This means that int counters will not work inside your isr. Please use the different edge modes.

I2c

The I2c module module has a number of different ways of interacting with the i2c bus, including a number of overloaded read() calls and the writeReg() helper function.

x = m.I2c(0)
x.address(0x77)

# initialise device
if x.readReg(0xd0) != 0x55:
    print("error")

# we want to read temperature so write 0x2e into control reg
x.writeReg(0xf4, 0x2e)

# read a 16bit reg, obviously it's uncalibrated so mostly a useless value :)
print(str(x.readWordReg(0xf6)))

# and we can do the same thing with the read()/write() calls if we wished
# thought I'd really not recommend it!

x.write(bytearray(b'0xf40x2e'))

x.writeByte(0xf6)
d = x.read(2)

# WARNING: python 3.2+ call
print(str(d))
print(int.from_bytes(d, byteorder='little'))
It is considered best practice to make sure the address is correct before doing
any calls on i2c, in case another application or even thread changed the addres
on that bus. Multiple instances of the same bus can exist.

Pwm

The PWM module is rather simple, note that different hardware support PWM generation is various different ways so results may vary.

import mraa
import time

# initialise PWM
x = mraa.Pwm(3)

# set PWM period
x.period_us(700)

# enable PWM
x.enable(True)

value= 0.0

while True:
    # write PWM value
    x.write(value)

    time.sleep(0.05)

    value = value + 0.01
    if value >= 1:
        value = 0.0

Aio

The ADC is typically provided on a dedicated or shared SPI bus, this is abstracted by the Linux kernel as spidev and abstracted again by mraa. It is fairly simple in use.

import mraa

print(mraa.getVersion())

try:
    # initialise AIO
    x = mraa.Aio(0)

    # read integer value
    print(x.read())

    # read float value
    print("%.5f" % x.readFloat())
except:
    print("Are you sure you have an ADC?")

Uart

Uart is the Universal asynchronous receiver/transmitter interface in mraa. It allows the exposure of UART pins on supported boards, with basic configuration operations supported.

Here’s a simple pair of programs comprising a sender and receiver pair.

Sender:

import mraa
import sys

sys.stdout.write("Initializing UART...")
u = mraa.Uart(0)
print("...done")

print("Setting UART parameters: baudrate 115200, 8N1, no flow control")
u.setBaudRate(115200)
u.setMode(8, mraa.UART_PARITY_NONE, 1)
u.setFlowcontrol(False, False)

msg_b = bytearray("Hello, mraa byte array!", "ascii")
print("Sending message as a byte array: '{0}'".format(msg_b))
u.write(msg_b)
# Make sure the message gets out to the line.
# It's generally unnecessary (and performance-degrading) to do this explicitly,
# UART driver normally takes care of that, but it may be useful with specific
# half-duplex endpoints, like Dynamixel servos.
u.flush()

msg_s = "Hello, mraa string!"
print("Sending message as a string: '{0}'".format(msg_s))
u.writeStr(msg_s)

sys.stdout.write("Two-way, half-duplex communication, sending a flag...")
u.writeStr("X")
print("...sent, awaiting response...")
# Checking for data in the RX buffer, giving it a 100ms timeout
if u.dataAvailable(100):
    print("We've got a response: '{0}', says the other side".format(u.readStr(20)))
else:
    print("No data received, do you have anything at the other end?")

Receiver:

import mraa

# Initialise UART
u = mraa.Uart(0)

# Set UART parameters
u.setBaudRate(115200)
u.setMode(8, mraa.UART_PARITY_NONE, 1)
u.setFlowcontrol(False, False)

# Start a neverending loop waiting for data to arrive.
# Press Ctrl+C to get out of it.
while True:
    if u.dataAvailable():
        # We are doing 1-byte reads here
        data_byte = u.readStr(1)
        print(data_byte)

        # Just a two-way half-duplex communication example, "X" is a flag
        if data_byte == "X":
            u.writeStr("Yes, master!")

LED

LED module is used for controlling the on-board LEDs. With the help of this module, we can control the brightness, trigger etc…

import mraa
import time

# initialise user1 led
led_1 = mraa.Led("user1")

# read maximum brightness
val = led_1.readMaxBrightness()

print("maximum brightness value for user1 led is: %d" % val);

# turn led on/off depending on read max_brightness value
if (val >= 1):
    val = 0
# never reached mostly
else:
    val = 1

# set LED brightness
led_1.setBrightness(val)

# sleep for 5 seconds
time.sleep(5)

led_1.trigger("heartbeat")

print("led trigger set to: heartbeat")