Home Tutorials MicroPython uarray Module Tutorial with Examples

MicroPython uarray Module Tutorial with Examples

by shedboy71

The uarray module in MicroPython is a lightweight version of Python’s array module, designed to handle arrays of numeric data efficiently.

Since MicroPython is designed for microcontrollers and devices with limited memory, the uarray module allows you to store and manipulate arrays of numbers using minimal memory compared to standard lists.

In this tutorial, we will cover:

Let’s dive into each topic with examples.

1. What is the uarray Module?

The uarray module in MicroPython is used to create arrays of primitive data types, such as integers or floating-point numbers. Unlike lists, arrays in uarray are much more memory-efficient because they store data in a compact form, optimized for the specific type.

Key Characteristics:

  • Arrays created using uarray are fixed in type (e.g., all elements must be integers or floating-point numbers).
  • Arrays are more memory-efficient compared to lists, making them ideal for microcontroller environments with limited RAM.

You can import the uarray module like this:

import uarray as array

2. Why Use uarray?

Arrays in uarray are particularly useful when:

  • Memory efficiency is crucial: Arrays use less memory compared to lists by storing data in a compact form.
  • You need to handle large datasets of numerical data on a microcontroller.
  • You want to reduce memory overhead while storing homogeneous data types (e.g., all integers or all floats).

3. Creating Arrays with uarray

You can create an array in the uarray module by specifying the typecode and initial values.

Syntax:

array.array(typecode, [initial_values])
  • typecode: Defines the type of data that will be stored in the array. Common typecodes include:
    • ‘b’: signed char (8-bit)
    • ‘B’: unsigned char (8-bit)
    • ‘h’: signed short (16-bit)
    • ‘H’: unsigned short (16-bit)
    • ‘i’: signed int (32-bit)
    • ‘f’: float (32-bit)

Example 1: Creating an Integer Array

import uarray as array

# Creating an array of signed integers ('i') with initial values
int_array = array.array('i', [1, 2, 3, 4, 5])
print(int_array)

Output:

array('i', [1, 2, 3, 4, 5])

Example 2: Creating a Floating-Point Array

import uarray as array

# Creating an array of floats ('f') with initial values
float_array = array.array('f', [1.1, 2.2, 3.3])
print(float_array)

Output:

array('f', [1.100000023841858, 2.200000047683716, 3.299999952316284])
  • In this example, we create an array of floats using the typecode ‘f’. The precision of floating-point numbers may vary slightly due to the limited precision of floats.

4. Accessing and Modifying Array Elements

Just like lists, you can access and modify individual elements in an array using indexing.

Example: Accessing and Modifying Array Elements

import uarray as array

# Creating an array of signed integers
int_array = array.array('i', [10, 20, 30, 40, 50])

# Accessing elements by index
print("First element:", int_array[0])  # Output: 10
print("Last element:", int_array[-1])  # Output: 50

# Modifying elements
int_array[2] = 100
print("Modified array:", int_array)  # Output: array('i', [10, 20, 100, 40, 50])

Output:

First element: 10
Last element: 50
Modified array: array('i', [10, 20, 100, 40, 50])
  • In this example, we access elements using their index and modify an element at index 2.

5. Adding and Removing Elements in uarray

Unlike lists, arrays in uarray have limited options for adding and removing elements. Arrays do not have dynamic resizing as lists do, but you can append and extend arrays.

Example 1: Appending Elements

import uarray as array

# Creating an integer array
int_array = array.array('i', [1, 2, 3])

# Appending an element to the array
int_array.append(4)
print("After appending 4:", int_array)  # Output: array('i', [1, 2, 3, 4])

Example 2: Extending Arrays

You can extend an array by adding multiple elements from another iterable (e.g., a list or array).

import uarray as array

# Extending an array with another list of integers
int_array.extend([5, 6])
print("After extending:", int_array)  # Output: array('i', [1, 2, 3, 4, 5, 6])

Output:

After appending 4: array('i', [1, 2, 3, 4])
After extending: array('i', [1, 2, 3, 4, 5, 6])
  • In this example, we first append a single element to the array, and then we extend the array with multiple elements using extend().

6. Iterating Over Arrays

You can iterate over an array just like you would with a list, using a for loop.

Example: Iterating Over an Array

import uarray as array

# Creating an array of integers
int_array = array.array('i', [10, 20, 30, 40])

# Iterating over the array
for value in int_array:
    print(value)

Output:

10
20
30
40
  • In this example, we loop through the int_array and print each value.

7. Examples and Use Cases of uarray

Example 1: Storing Sensor Data Efficiently

Arrays are often used in embedded systems for storing sensor data because of their memory efficiency.

import uarray as array

# Storing temperature readings as a float array
temperature_readings = array.array('f', [22.5, 23.0, 22.8, 23.1])

# Adding a new reading
temperature_readings.append(22.9)

# Displaying all readings
for reading in temperature_readings:
    print(f"Temperature: {reading}°C")

Output:

Temperature: 22.5°C
Temperature: 23.0°C
Temperature: 22.799999237060547°C
Temperature: 23.100000381469727°C
Temperature: 22.899999618530273°C
  • In this example, we store temperature readings as a float array and append new readings as they come in.

Example 2: Efficiently Handling Large Arrays

Arrays are particularly useful when you need to work with large datasets on memory-constrained devices.

import uarray as array

# Creating a large array of integers
large_int_array = array.array('i', range(100))

# Summing all the values in the array
total = sum(large_int_array)
print(f"Sum of all elements: {total}")

Output:

Sum of all elements: 4950
  • In this example, we create a large integer array and compute the sum of all its elements.

8. Array Types and Size

Different typecodes in uarray represent different types of data and determine the amount of memory each element occupies.

Typecode Type Size (bytes)
‘b’ signed char 1
‘B’ unsigned char 1
‘h’ signed short 2
‘H’ unsigned short 2
‘i’ signed int 4
‘I’ unsigned int 4
‘f’ float 4
‘d’ double (not supported in MicroPython) 8

Choosing the appropriate typecode can help save memory. For example, using ‘B’ for unsigned 8-bit data will use less memory than using `’i’` for 32-bit integers.

Summary of array Functions

 
Function Description
len(array) Returns the number of elements in an array

len(uarray.array(‘i’, [21 , 1, 2])) ⇒ 3

max(array) Returns the maximum value in an array.

max(uarray.array(‘i’, [21, 1, 2])) ⇒ 21

min(array) Returns the minimum value in an array.

min(uarray.array(‘i’, [21, 1, 2])) ⇒ 1

sorted(array
[, reverse =
True|False])
Returns a sorted copy of the array as a list

A = (uarray.array(‘i’, [21, 1, 2]))

Conclusion

The uarray module in MicroPython provides an efficient way to handle arrays of numeric data, especially in memory-constrained environments like microcontrollers. In this tutorial, we covered:

  • Creating arrays with different typecodes.
  • Accessing and modifying elements in an array.
  • Appending, extending, and iterating over arrays.
  • Practical examples of using uarray for sensor data and large datasets.

You may also like

Leave a Comment