Python - OLED 128x64 Bricklet

This is the description of the Python API bindings for the OLED 128x64 Bricklet. General information and technical specifications for the OLED 128x64 Bricklet are summarized in its hardware description.

An installation guide for the Python API bindings is part of their general description.

Examples

The example code below is Public Domain (CC0 1.0).

Hello World

Download (example_hello_world.py)

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4HOST = "localhost"
 5PORT = 4223
 6UID = "XYZ" # Change XYZ to the UID of your OLED 128x64 Bricklet
 7
 8from tinkerforge.ip_connection import IPConnection
 9from tinkerforge.bricklet_oled_128x64 import BrickletOLED128x64
10
11if __name__ == "__main__":
12    ipcon = IPConnection() # Create IP connection
13    oled = BrickletOLED128x64(UID, ipcon) # Create device object
14
15    ipcon.connect(HOST, PORT) # Connect to brickd
16    # Don't use device before ipcon is connected
17
18    # Clear display
19    oled.clear_display()
20
21    # Write "Hello World" starting from upper left corner of the screen
22    oled.write_line(0, 0, "Hello World")
23
24    input("Press key to exit\n") # Use raw_input() in Python 2
25    ipcon.disconnect()

Pixel Matrix

Download (example_pixel_matrix.py)

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4HOST = "localhost"
 5PORT = 4223
 6UID = "XYZ" # Change XYZ to the UID of your OLED 128x64 Bricklet
 7WIDTH = 128 # Columns (each 1 pixel wide)
 8HEIGHT = 8 # Rows (each 8 pixels high)
 9
10from tinkerforge.ip_connection import IPConnection
11from tinkerforge.bricklet_oled_128x64 import BrickletOLED128x64
12
13def draw_matrix(oled, start_column, start_row, column_count, row_count, pixels):
14    pages = []
15
16    # Convert pixel matrix into 8bit pages
17    for row in range(row_count):
18        pages.append([])
19
20        for column in range(column_count):
21            page = 0
22
23            for bit in range(8):
24                if pixels[(row * 8) + bit][column]:
25                    page |= 1 << bit
26
27            pages[row].append(page)
28
29    # Merge page matrix into single page array
30    data = []
31
32    for row in range(row_count):
33        for column in range(column_count):
34            data.append(pages[row][column])
35
36    # Set new window
37    oled.new_window(start_column, start_column + column_count - 1,
38                    start_row, start_row + row_count - 1)
39
40    # Write page data in 64 byte blocks
41    for i in range(0, len(data), 64):
42        block = data[i:i + 64]
43        oled.write(block + [0] * (64 - len(block)))
44
45if __name__ == "__main__":
46    ipcon = IPConnection() # Create IP connection
47    oled = BrickletOLED128x64(UID, ipcon) # Create device object
48
49    ipcon.connect(HOST, PORT) # Connect to brickd
50    # Don't use device before ipcon is connected
51
52    # Clear display
53    oled.clear_display()
54
55    # Draw checkerboard pattern
56    pixels = []
57
58    for row in range(HEIGHT * 8):
59        pixels.append([])
60
61        for column in range(WIDTH):
62            pixels[row].append((row // 8) % 2 == (column // 8) % 2)
63
64    draw_matrix(oled, 0, 0, WIDTH, HEIGHT, pixels)
65
66    input("Press key to exit\n") # Use raw_input() in Python 2
67    ipcon.disconnect()

Load Image

Download (example_load_image.py)

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4HOST = "localhost"
 5PORT = 4223
 6UID = "XYZ" # Change XYZ to the UID of your OLED 128x64 Bricklet
 7WIDTH = 128 # Columns (each 1 pixel wide)
 8HEIGHT = 8 # Rows (each 8 pixels high)
 9
10import sys
11from PIL import Image
12from tinkerforge.ip_connection import IPConnection
13from tinkerforge.bricklet_oled_128x64 import BrickletOLED128x64
14
15def draw_matrix(oled, start_column, start_row, column_count, row_count, pixels):
16    pages = []
17
18    # Convert pixel matrix into 8bit pages
19    for row in range(row_count):
20        pages.append([])
21
22        for column in range(column_count):
23            page = 0
24
25            for bit in range(8):
26                if pixels[(row * 8) + bit][column]:
27                    page |= 1 << bit
28
29            pages[row].append(page)
30
31    # Merge page matrix into single page array
32    data = []
33
34    for row in range(row_count):
35        for column in range(column_count):
36            data.append(pages[row][column])
37
38    # Set new window
39    oled.new_window(start_column, start_column + column_count - 1,
40                    start_row, start_row + row_count - 1)
41
42    # Write page data in 64 byte blocks
43    for i in range(0, len(data), 64):
44        block = data[i:i + 64]
45        oled.write(block + [0] * (64 - len(block)))
46
47if __name__ == "__main__":
48    ipcon = IPConnection() # Create IP connection
49    oled = BrickletOLED128x64(UID, ipcon) # Create device object
50
51    ipcon.connect(HOST, PORT) # Connect to brickd
52    # Don't use device before ipcon is connected
53
54    # Clear display
55    oled.clear_display()
56
57    # Convert image to black/white pixels
58    image = Image.open(sys.argv[1])
59    image_data = image.load()
60    pixels = []
61
62    for row in range(HEIGHT * 8):
63        pixels.append([])
64
65        for column in range(WIDTH):
66            if column < image.size[0] and row < image.size[1]:
67                pixel = image_data[column, row] > 0
68            else:
69                pixel = False
70
71            pixels[row].append(pixel)
72
73    draw_matrix(oled, 0, 0, WIDTH, HEIGHT, pixels)
74
75    input("Press key to exit\n") # Use raw_input() in Python 2
76    ipcon.disconnect()

Scribble

Download (example_scribble.py)

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4HOST = "localhost"
 5PORT = 4223
 6UID = "XYZ" # Change XYZ to the UID of your OLED 128x64 Bricklet
 7WIDTH = 128 # Columns (each 1 pixel wide)
 8HEIGHT = 8 # Rows (each 8 pixels high)
 9
10import math
11import time
12from PIL import Image, ImageDraw
13from tinkerforge.ip_connection import IPConnection
14from tinkerforge.bricklet_oled_128x64 import BrickletOLED128x64
15
16def draw_image(oled, start_column, start_row, column_count, row_count, image):
17    image_data = image.load()
18    pages = []
19
20    # Convert image pixels into 8bit pages
21    for row in range(row_count):
22        pages.append([])
23
24        for column in range(column_count):
25            page = 0
26
27            for bit in range(8):
28                if image_data[column, (row * 8) + bit]:
29                    page |= 1 << bit
30
31            pages[row].append(page)
32
33    # Merge page matrix into single page array
34    data = []
35
36    for row in range(row_count):
37        for column in range(column_count):
38            data.append(pages[row][column])
39
40    # Set new window
41    oled.new_window(start_column, start_column + column_count - 1,
42                    start_row, start_row + row_count - 1)
43
44    # Write page data in 64 byte blocks
45    for i in range(0, len(data), 64):
46        block = data[i:i + 64]
47        oled.write(block + [0] * (64 - len(block)))
48
49if __name__ == "__main__":
50    ipcon = IPConnection() # Create IP connection
51    oled = BrickletOLED128x64(UID, ipcon) # Create device object
52
53    ipcon.connect(HOST, PORT) # Connect to brickd
54    # Don't use device before ipcon is connected
55
56    # Clear display
57    oled.clear_display()
58
59    # Draw rotating line
60    image = Image.new("1", (WIDTH, HEIGHT * 8), 0)
61    draw = ImageDraw.Draw(image)
62    origin_x = WIDTH // 2
63    origin_y = HEIGHT * 8 // 2
64    length = HEIGHT * 8 // 2 - 2
65    angle = 0
66
67    print("Press ctrl+c to exit")
68
69    try:
70        while True:
71            radians = math.pi * angle / 180.0
72            x = (int)(origin_x + length * math.cos(radians))
73            y = (int)(origin_y + length * math.sin(radians))
74
75            draw.rectangle((0, 0, WIDTH, HEIGHT * 8), 0, 0)
76            draw.line((origin_x, origin_y, x, y), 1, 1)
77
78            draw_image(oled, 0, 0, WIDTH, HEIGHT, image)
79            time.sleep(0.025)
80
81            angle += 1
82    except KeyboardInterrupt:
83        pass
84
85    ipcon.disconnect()

Draw Servo Poti

Download (example_draw_servo_poti.py)

  1#!/usr/bin/env python
  2# -*- coding: utf-8 -*-
  3
  4#
  5# This example uses a Servo Brick, a Rotary Poti Bricklet and
  6# a OLED 128x64 Bricklet.
  7#
  8# The position of the Rotary Poti Bricklet is drawn on the OLED
  9# display (as text, as a bar graph and as a dial indicator).
 10# At the same time the servo moves to an angle that is equivalent
 11# of the position of the Rotary Poti Bricklet.
 12#
 13
 14HOST = "localhost"
 15PORT = 4223
 16SCREEN_WIDTH = 128
 17SCREEN_HEIGHT = 64
 18
 19from tinkerforge.ip_connection import IPConnection
 20from tinkerforge.bricklet_oled_128x64 import BrickletOLED128x64
 21from tinkerforge.bricklet_rotary_poti import BrickletRotaryPoti
 22from tinkerforge.brick_servo import BrickServo
 23
 24from PIL import Image, ImageDraw, ImageFont
 25
 26import sys
 27import math
 28import time
 29
 30def draw_matrix(pixels):
 31    column_index = 0
 32    column = []
 33
 34    for i in range(SCREEN_HEIGHT//8 - 1): # We use last 8 pixels for text
 35        for j in range(SCREEN_WIDTH):
 36            page = 0
 37            for k in range(8):
 38                if pixels[i*8 + k][j] == 1:
 39                    page |= 1 << k
 40
 41            if len(column) <= column_index:
 42                column.append([])
 43
 44            column[column_index].append(page)
 45            if len(column[column_index]) == SCREEN_HEIGHT:
 46                column_index += 1
 47
 48        oled.new_window(0, SCREEN_WIDTH-1, 0, 6)
 49
 50    for i in range(len(column)):
 51        oled.write(column[i])
 52
 53def line_at_angle(startx, starty, angle, length):
 54   radian_angle = math.pi * angle / 180.0
 55   x = startx + length * math.cos(radian_angle)
 56   y = starty + length * math.sin(radian_angle)
 57   return (startx, starty, x, y)
 58
 59if __name__ == "__main__":
 60    # Create Brick/Bricklet objects
 61    ipcon = IPConnection()
 62    oled = BrickletOLED128x64('x5U', ipcon)
 63    poti = BrickletRotaryPoti('8Co', ipcon)
 64    servo = BrickServo('6e8MF1', ipcon)
 65
 66    # Connect to brickd
 67    ipcon.connect(HOST, PORT)
 68
 69    # Configure Servo so that it rotates 180°
 70    servo.set_pulse_width(6, 650, 2350)
 71    servo.enable(6)
 72
 73    # Clear display
 74    oled.clear_display()
 75
 76    # Draw text once at beginning, the window in draw_matrix does not overwrite
 77    # the last line of the display
 78    oled.write_line(7, 5, "tinkerforge.com")
 79
 80    # We just use an endless loop here, press ctrl + c to abort the script
 81    while True:
 82        # With position 110 poti is at 90°
 83        angle = poti.get_position()*90//110
 84        if angle > 90:
 85            angle = 90
 86        elif angle < -90:
 87            angle = -90
 88
 89        # Set servo position according to angle
 90        servo.set_position(6, angle*100)
 91
 92        # Create angle text
 93        angle_str = str(angle) + u'°'
 94        if angle >= 0:
 95            angle_str = ' ' + angle_str
 96
 97        # Draw servo position line
 98        img = Image.new('1', (128, 64), 0)
 99        draw = ImageDraw.Draw(img)
100        draw.line(line_at_angle(32, 32, angle - 90, 32), 1, 6)
101
102        # Draw bar graph
103        draw.line((90, 4, 90 + angle*30//90, 4), 1, 6)
104
105        # Draw angle text
106        font = ImageFont.truetype("./share/fonts/truetype/dejavu/DejaVuSans.ttf", 25)
107        draw.text((70, 22), angle_str, font=font, fill=1)
108
109        # Move data from PIL image into matrix of bools
110        data = img.load()
111        pixel_matrix = [[False]*SCREEN_WIDTH for i in range(SCREEN_HEIGHT)]
112        for x in range(SCREEN_WIDTH):
113            for y in range(SCREEN_HEIGHT):
114                pixel_matrix[y][x] = data[x, y] == 1
115
116        # Draw everything to display
117        draw_matrix(pixel_matrix)
118
119        # Framerate of ~40 FPS
120        time.sleep(0.04)
121
122    ipcon.disconnect()

API

Generally, every function of the Python bindings can throw an tinkerforge.ip_connection.Error exception that has a value and a description property. value can have different values:

  • Error.TIMEOUT = -1

  • Error.NOT_ADDED = -6 (unused since Python bindings version 2.0.0)

  • Error.ALREADY_CONNECTED = -7

  • Error.NOT_CONNECTED = -8

  • Error.INVALID_PARAMETER = -9

  • Error.NOT_SUPPORTED = -10

  • Error.UNKNOWN_ERROR_CODE = -11

  • Error.STREAM_OUT_OF_SYNC = -12

  • Error.INVALID_UID = -13

  • Error.NON_ASCII_CHAR_IN_SECRET = -14

  • Error.WRONG_DEVICE_TYPE = -15

  • Error.DEVICE_REPLACED = -16

  • Error.WRONG_RESPONSE_LENGTH = -17

All functions listed below are thread-safe.

Basic Functions

BrickletOLED128x64(uid, ipcon)
Parameters:
  • uid – Type: str
  • ipcon – Type: IPConnection
Returns:
  • oled_128x64 – Type: BrickletOLED128x64

Creates an object with the unique device ID uid:

oled_128x64 = BrickletOLED128x64("YOUR_DEVICE_UID", ipcon)

This object can then be used after the IP Connection is connected.

BrickletOLED128x64.write(data)
Parameters:
  • data – Type: [int, ...], Length: 64, Range: [0 to 255]
Returns:
  • None

Appends 64 byte of data to the window as set by new_window().

Each row has a height of 8 pixels which corresponds to one byte of data.

Example: if you call new_window() with column from 0 to 127 and row from 0 to 7 (the whole display) each call of write() (red arrow) will write half of a row.

Display pixel order

The LSB (D0) of each data byte is at the top and the MSB (D7) is at the bottom of the row.

The next call of write() will write the second half of the row and the next two the second row and so on. To fill the whole display you need to call write() 16 times.

BrickletOLED128x64.new_window(column_from, column_to, row_from, row_to)
Parameters:
  • column_from – Type: int, Range: [0 to 127]
  • column_to – Type: int, Range: [0 to 127]
  • row_from – Type: int, Range: [0 to 7]
  • row_to – Type: int, Range: [0 to 7]
Returns:
  • None

Sets the window in which you can write with write(). One row has a height of 8 pixels.

BrickletOLED128x64.clear_display()
Returns:
  • None

Clears the current content of the window as set by new_window().

BrickletOLED128x64.write_line(line, position, text)
Parameters:
  • line – Type: int, Range: [0 to 7]
  • position – Type: int, Range: [0 to 25]
  • text – Type: str, Length: up to 26
Returns:
  • None

Writes text to a specific line with a specific position. The text can have a maximum of 26 characters.

For example: (1, 10, "Hello") will write Hello in the middle of the second line of the display.

You can draw to the display with write() and then add text to it afterwards.

The display uses a special 5x7 pixel charset. You can view the characters of the charset in Brick Viewer.

The font conforms to code page 437.

Advanced Functions

BrickletOLED128x64.set_display_configuration(contrast, invert)
Parameters:
  • contrast – Type: int, Range: [0 to 255], Default: 143
  • invert – Type: bool, Default: False
Returns:
  • None

Sets the configuration of the display.

You can set a contrast value from 0 to 255 and you can invert the color (black/white) of the display.

BrickletOLED128x64.get_display_configuration()
Return Object:
  • contrast – Type: int, Range: [0 to 255], Default: 143
  • invert – Type: bool, Default: False

Returns the configuration as set by set_display_configuration().

BrickletOLED128x64.get_identity()
Return Object:
  • uid – Type: str, Length: up to 8
  • connected_uid – Type: str, Length: up to 8
  • position – Type: chr, Range: ["a" to "h", "z"]
  • hardware_version – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]
  • firmware_version – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]
  • device_identifier – Type: int, Range: [0 to 216 - 1]

Returns the UID, the UID where the Bricklet is connected to, the position, the hardware and firmware version as well as the device identifier.

The position can be 'a', 'b', 'c', 'd', 'e', 'f', 'g' or 'h' (Bricklet Port). A Bricklet connected to an Isolator Bricklet is always at position 'z'.

The device identifier numbers can be found here. There is also a constant for the device identifier of this Bricklet.

Virtual Functions

Virtual functions don't communicate with the device itself, but operate only on the API bindings device object. They can be called without the corresponding IP Connection object being connected.

BrickletOLED128x64.get_api_version()
Return Object:
  • api_version – Type: [int, ...], Length: 3
    • 0: major – Type: int, Range: [0 to 255]
    • 1: minor – Type: int, Range: [0 to 255]
    • 2: revision – Type: int, Range: [0 to 255]

Returns the version of the API definition implemented by this API bindings. This is neither the release version of this API bindings nor does it tell you anything about the represented Brick or Bricklet.

BrickletOLED128x64.get_response_expected(function_id)
Parameters:
  • function_id – Type: int, Range: See constants
Returns:
  • response_expected – Type: bool

Returns the response expected flag for the function specified by the function ID parameter. It is true if the function is expected to send a response, false otherwise.

For getter functions this is enabled by default and cannot be disabled, because those functions will always send a response. For callback configuration functions it is enabled by default too, but can be disabled by set_response_expected(). For setter functions it is disabled by default and can be enabled.

Enabling the response expected flag for a setter function allows to detect timeouts and other error conditions calls of this setter as well. The device will then send a response for this purpose. If this flag is disabled for a setter function then no response is sent and errors are silently ignored, because they cannot be detected.

The following constants are available for this function:

For function_id:

  • BrickletOLED128x64.FUNCTION_WRITE = 1

  • BrickletOLED128x64.FUNCTION_NEW_WINDOW = 2

  • BrickletOLED128x64.FUNCTION_CLEAR_DISPLAY = 3

  • BrickletOLED128x64.FUNCTION_SET_DISPLAY_CONFIGURATION = 4

  • BrickletOLED128x64.FUNCTION_WRITE_LINE = 6

BrickletOLED128x64.set_response_expected(function_id, response_expected)
Parameters:
  • function_id – Type: int, Range: See constants
  • response_expected – Type: bool
Returns:
  • None

Changes the response expected flag of the function specified by the function ID parameter. This flag can only be changed for setter (default value: false) and callback configuration functions (default value: true). For getter functions it is always enabled.

Enabling the response expected flag for a setter function allows to detect timeouts and other error conditions calls of this setter as well. The device will then send a response for this purpose. If this flag is disabled for a setter function then no response is sent and errors are silently ignored, because they cannot be detected.

The following constants are available for this function:

For function_id:

  • BrickletOLED128x64.FUNCTION_WRITE = 1

  • BrickletOLED128x64.FUNCTION_NEW_WINDOW = 2

  • BrickletOLED128x64.FUNCTION_CLEAR_DISPLAY = 3

  • BrickletOLED128x64.FUNCTION_SET_DISPLAY_CONFIGURATION = 4

  • BrickletOLED128x64.FUNCTION_WRITE_LINE = 6

BrickletOLED128x64.set_response_expected_all(response_expected)
Parameters:
  • response_expected – Type: bool
Returns:
  • None

Changes the response expected flag for all setter and callback configuration functions of this device at once.

Constants

BrickletOLED128x64.DEVICE_IDENTIFIER

This constant is used to identify a OLED 128x64 Bricklet.

The get_identity() function and the IPConnection.CALLBACK_ENUMERATE callback of the IP Connection have a device_identifier parameter to specify the Brick's or Bricklet's type.

BrickletOLED128x64.DEVICE_DISPLAY_NAME

This constant represents the human readable name of a OLED 128x64 Bricklet.