Micro:bit MicroPython: Connecting the UART OBLOQ to WiFi network

In this tutorial we will learn how to connect the UART OBLOQ to a WiFi network, using the micro:bit board and MicroPython to send the commands to the device, using a serial connection.

Introduction

In this tutorial we will learn how to connect the UART OBLOQ to a WiFi network, using the micro:bit board and MicroPython to send the commands to the device, using a serial connection.

Please check this previous tutorial for the schematic diagram and explanation on how to connect the micro:bit board to the UART OBLOQ.

For this tutorial I’m using version 1.7.0 of MicroPython for the micro:bit board which, at the time of writing, is the version used by the uPyCraft IDE when flashing the device.

As already mentioned in some previous posts, after opening a serial connection using this MicroPytho version, it sends a dummy byte to the serial port. Because of that, the UART OBLOQ starts building a command that doesn’t exist, which we need to flush.

If you are using a more recent version of MicroPython that already has this problem fixed, then you can skip that part of the code.

The code

As usual, we will start by importing the uart object and the sleep function from the micro:bit module.

from microbit import uart, sleep

Since, for this tutorial, the answer from the UART OBLOQ to the WiFi connection command is not trivial to obtain with a single read from the serial interface, we will first define a helper function that allows to read content from the serial port until a specified termination character.

This function will then return as output all the content read until that character (also included in the output).

So, as parameters, our function will receive a uart object and the termination character that we want to look for. Note that, for simplicity, we will assume that this termination character will always exist in the received message and thus we will not define any timeout.

So, be careful when using this function since, if you pass a termination character that will never be available in the serial port, then the function will be locked in an infinite loop. Naturally, in a real application, you should account for this scenario.

def readUntil(uartObject, termination):
# implementation

In the implementation of the function, we will start by declaring an empty string, since we will build our output by appending the content returned by each serial port read method call.

result = ''

Then, we will start an infinite loop. Inside that loop, the first thing we will do is checking if there’s any byte available for reading by calling the any method on our uart object. This method, which receives no arguments, returns True if there are bytes available to read and False otherwise.

In case there are bytes available, we will read the next one by calling the uart object read method, passing as input the value 1. This method call will return as output a bytes object with length 1.

Then, we will convert that byte to a character by using the chr function, passing as input the value of our byte. Although our bytes object only contains one byte, it’s still a bytes data structure, so we need to access to index 0 in order to obtain the first (and only) byte.

We will append the obtained character to our previously declared result string, so we build the final result.

After that, we will compare the obtained byte, also as a character, with the termination character passed as input of our function. If they match, we will break the loop.

Between each iteration of the loop, we will do a small 100 milliseconds delay. You can check below the mentioned loop.

while True:
  if uartObject.any():

      byte = uartObject.read(1)

      result = result + chr(byte[0])

      if chr(byte[0]) == termination:
        break

  sleep(100)

Finally, we will return the result that we have built in the loop.

return result

The complete function code can be seen below.

def readUntil(uartObject, termination):
  result = ''

  while True:
    if uartObject.any():

        byte = uartObject.read(1)

        result = result + chr(byte[0])

        if chr(byte[0]) == termination:
          break

    sleep(100)

  return result

Now that we have our helping function, we can move on and start the serial interface using the micro:bit pins 0 and 1.

After that, we need to flush the garbage byte sent by the micro:bit after we start the serial connection. Recall that this is only needed if you are using a MicroPython version that still has this bug, since it was corrected in more recent versions.

Since the expected result is |1|-1| plus the answer termination character ‘\r‘, we can already leverage our readUntil function.

Note that, in this case, we don’t need to store the output of the function since we simply want to clean the serial port.

uart.init(baudrate=9600, tx = pin0, rx = pin1)

uart.write("\r")
readUntil(uart, '\r')

Next, we can send the command to connect the UART OBLOQ to a WiFi network. The command has the format indicated below, as covered in more detail on this post.

Please note that, in the command, the credentials are separated by a comma but kept inside the same pair of “| characters.

|2|1|yourNetworkName,yourNetworkPassword|

The MicroPython command to be used is the following:

uart.write("|2|1|yourNetworkName,yourNetworkPass|\r")

After we send the command, the UART OBLOQ should return |2|1| to indicate its reception. After that, it will periodically print |2|2| during the connection procedure, which may take a while.

When the connection procedure finishes, the UART OBLOQ will return an answer in the following format, where ipAddress is the local IP assigned to the UART OBLOQ on the network:

|2|3|ipAddress|

So, to process this sequence, we can simply use our readUntil function to keep reading content until it obtains a ‘3’ character. We don’t need to store the result of the function call at this step since basically what we want to do is waiting until the connection occurs.

After that, we can call the readUntil function again, but this time waiting for the ‘\r‘ character, which marks the end of the answer. In this case, we will store the result, which should contain the IP address, so we can later print it.

readUntil(uart, '3')
result = readUntil(uart, '\r')

To finalize, we will re-initialize the serial interface with a baud rate of 115200 and leaving the defaults for the remaining parameters, so the MicroPython prompt becomes available again. After that, we print the result with the IP address.

uart.init(baudrate=115200)
print(result)

The final code can be seen below.

from microbit import uart, sleep

def readUntil(uartObject, termination):
  result = ''

  while True:
    if uartObject.any():

        byte = uartObject.read(1)

        result = result + chr(byte[0])

        if chr(byte[0]) == termination:
          break

    sleep(100)

  return result

uart.init(baudrate=9600, tx = pin0, rx = pin1)

uart.write("\r")
readUntil(uart, '\r')

uart.write("|2|1|yourNetworkName,yourNetworkPass|\r")

readUntil(uart, '3')
result = readUntil(uart, '\r')

uart.init(baudrate=115200)
print(result)

Testing the code

To test the code, simply upload the previous script to your micro:bit board, assuming all the connections to the UART OBLOQ are already performed. You can use some tool such as the uPyCraft IDE to make the process easier.

During the commands execution, your UART OBLOQ LED should change from red to blue during the connection procedure. After it is able to connect to the WiFi network with success, the LED should turn green.

In the MicroPython prompt, you should get an output similar to figure 1, which shows the IP address assigned to my UART OBLOQ device.

Using micro:bit and uPython to connect the UART OBLOQ to a WiFi network

Figure 1 – Output of the program, on the uPyCraft IDE.

Related Posts

Advertisements

2 Replies to “Micro:bit MicroPython: Connecting the UART OBLOQ to WiFi network”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s