Home Tutorials Tutorial on the bytearray Data Type in MicroPython

Tutorial on the bytearray Data Type in MicroPython

by shedboy71

The bytearray data type in MicroPython is a mutable sequence of bytes. It is particularly useful when dealing with binary data, such as reading and writing data to sensors, serial communication, file handling, and network programming.

Since bytearray objects are mutable, you can modify the data in place, which can be more memory-efficient for embedded systems.

This tutorial will cover the basics of using the bytearray data type in MicroPython, including creating, modifying, slicing, and practical use cases.

Table of Contents:

1. What is a bytearray?

A bytearray is a mutable sequence of integers in the range of 0 to 255, representing bytes. It can be used to store binary data and allows modification of the data in place.

bytearray is ideal for operations where you need to modify data buffers efficiently.

2. Creating a bytearray

You can create a bytearray in several ways: from a list of integers, a bytes object, or by specifying a size filled with zeros.

Example 1: Creating a bytearray from a List of Integers

data = bytearray([65, 66, 67, 68])  # ASCII values for 'A', 'B', 'C', 'D'
print(data)  # Output: bytearray(b'ABCD')

Example 2: Creating a bytearray from a String

data = bytearray(b'Hello, MicroPython!')
print(data)  # Output: bytearray(b'Hello, MicroPython!')

Example 3: Creating an Empty bytearray of a Specific Size

data = bytearray(5)  # Creates a bytearray of length 5, filled with zeros
print(data)  # Output: bytearray(b'\x00\x00\x00\x00\x00')

Explanation:

bytearray([65, 66, 67, 68]) creates a bytearray from a list of integers representing ASCII values.
bytearray(b’Hello, MicroPython!’) creates a bytearray from a bytes literal.
bytearray(5) creates a bytearray of size 5, initialized with zeros.

3. Modifying a bytearray

Since bytearray is mutable, you can change its contents by assigning new values to specific positions.

Example: Modifying Elements in a bytearray

data = bytearray(b'Hello')
data[0] = ord('h')  # Modify the first element to 'h'
print(data)  # Output: bytearray(b'hello')

# Modifying a range of elements
data[1:4] = b'ey'
print(data)  # Output: bytearray(b'heylo')

Explanation:

data[0] = ord(‘h’) modifies the first byte to the ASCII value of ‘h’.
data[1:4] = b’ey’ replaces elements at indices 1, 2, and 3 with ‘e’ and ‘y’.

4. Accessing Elements

You can access individual elements in a bytearray just like you would in a list, using indexing. Elements in a bytearray are integers representing byte values (0–255).

Example: Accessing Elements

data = bytearray(b'ABC')

# Accessing elements
print(data[0])  # Output: 65 (ASCII for 'A')
print(data[1])  # Output: 66 (ASCII for 'B')

# Iterating through the bytearray
for byte in data:
    print(byte)  # Output: 65, 66, 67

5. Slicing a bytearray

Slicing a bytearray allows you to create sub-sequences of bytes. The result of slicing a bytearray is a new bytearray containing the specified range of elements.

Example: Slicing a bytearray

data = bytearray(b'Hello, World!')

# Extracting a slice
greeting = data[:5]
print(greeting)  # Output: bytearray(b'Hello')

# Modifying a slice
data[7:] = b'MicroPython'
print(data)  # Output: bytearray(b'Hello, MicroPython')

Explanation:

data[:5] extracts the first 5 bytes from the bytearray.
data[7:] = b’MicroPython’ replaces the bytes starting from index 7 with ‘MicroPython’.

6. Common Methods for bytearray

bytearray supports several useful methods, such as append(), extend(), and insert() for modifying the contents.

Example: Using append(), extend(), and insert()

data = bytearray(b'ABC')

# Append a single byte
data.append(68)  # ASCII for 'D'
print(data)  # Output: bytearray(b'ABCD')

# Extend the bytearray with more bytes
data.extend(b'EFG')
print(data)  # Output: bytearray(b'ABCDEFG')

# Insert a byte at a specific position
data.insert(0, 90)  # ASCII for 'Z'
print(data)  # Output: bytearray(b'ZABCDEFG')

7. Practical Examples

Example 1: Serial Communication Buffer

In embedded systems, bytearray is often used as a buffer for serial communication. Here’s a simple example of handling incoming data using a bytearray.

buffer = bytearray(10)  # Create a buffer of size 10

# Simulate receiving data into the buffer
buffer[0:5] = b'Hello'
buffer[5:] = b'12345'

print(buffer)  # Output: bytearray(b'Hello12345')

# Extract data using slicing
message = buffer[:5]
print(message)  # Output: bytearray(b'Hello')

Explanation:

A bytearray buffer of size 10 is created to hold incoming data.
The buffer is then filled with data, simulating serial data reception.

Example 2: Byte-Level Data Processing

bytearray is useful when processing binary data, such as parsing a data packet received from a sensor.

packet = bytearray(b'\x01\x02\x03\x04\x05')

# Process packet data
header = packet[0]  # First byte as header
payload = packet[1:]  # Remaining bytes as payload

print(header)  # Output: 1
print(payload)  # Output: bytearray(b'\x02\x03\x04\x05')

# Modify payload
packet[1] = 100
print(packet)  # Output: bytearray(b'\x01d\x03\x04\x05')

Explanation:

The packet is split into a header (packet[0]) and payload (packet[1:]).
The payload is then modified by changing the value at index 1.

Example 3: Creating and Modifying a Bitmap

You can use bytearray to represent binary data, such as a bitmap or an image in raw byte form.

# Create a simple 8x1 monochrome bitmap using a bytearray
bitmap = bytearray([0b11110000])  # 8 pixels, first 4 are 'on', last 4 are 'off'

# Toggle the 5th pixel
bitmap[0] ^= 0b00001000  # XOR to toggle the 5th bit

print(bin(bitmap[0]))  # Output: 0b11111000

Explanation:

An 8-pixel-wide bitmap is represented using a single byte.
The ^= operator is used to toggle the state of the 5th pixel (from off to on).

Conclusion

The bytearray data type in MicroPython is a powerful tool for working with binary data, particularly in memory-constrained environments such as microcontrollers. Key points to remember:

Mutable: You can modify a bytearray in place.
Efficient: Useful for handling data in low-level communication, sensors, and other embedded system tasks.
Flexible: You can create, access, modify, and slice bytearray objects to suit various applications.

By mastering bytearray, you can efficiently handle binary data in your MicroPython projects, making it a versatile choice for a wide range of embedded programming tasks.

You may also like

Leave a Comment