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

print (mraa.getVersion())
x = mraa.Gpio(13)
x.dir(mraa.DIR_OUT)
x.write(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 test(gpio):
  print("pin " + repr(gpio.getPin(True)) + " = " + repr(gpio.read()))
  c.count+=1

pin = 6;
if (len(sys.argv) == 2):
  try:
    pin = int(sys.argv[1], 10)
  except ValueError:
    printf("Invalid pin " + sys.argv[1])
try:
	x = mraa.Gpio(pin)
	print("Starting ISR for pin " + repr(pin))
	x.dir(mraa.DIR_IN)
	x.isr(mraa.EDGE_BOTH, test, x)
	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

x = mraa.Pwm(3)
x.period_us(700)
x.enable(True)
value= 0.0

while True:
    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:
    x = mraa.Aio(0)
    print (x.read())
    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

# Initialize 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!")