from machine import Pin, I2C
import ssd1306
import time
# Initialize I2C and OLED
i2c = I2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
TEXT_SIZE = 1 # Adjust this value to change text size (1 for normal, 2 for double, etc.)
# Constants for display dimensions
WIDTH = 128
HEIGHT = 64
def draw_text(oled, text, x, y, size=1):
if size == 1:
oled.text(text, x, y)
else:
scale = size
for i, char in enumerate(text):
oled.text(char, x + (i * 8 * scale), y, 1)
if scale > 1:
oled.text(char, x + (i * 8 * scale), y + 8, 1)
oled.text(char, x + (i * 8 * scale), y + 16, 1)
def draw_rectangle(x, y, width, height, color):
for i in range(width):
for j in range(height):
oled.pixel(x + i, y + j, color)
def draw_array(arr, low, high, mid, target, text_size):
oled.fill(0)
for i, num in enumerate(arr):
x = i * 12
y = 30
if i == mid:
draw_rectangle(x, y - 10, 10, 10, 1)
draw_text(oled, str(num), x, y, text_size)
if num == target:
draw_text(oled, '*', x, y + 10, text_size)
oled.show()
def binary_search_recursive(arr, target, low, high, text_size):
if low > high:
return -1 # Target is not in the list
mid = (low + high) // 2
draw_array(arr, low, high, mid, target, text_size)
time.sleep(1) # Pause to visualize
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search_recursive(arr, target, low, mid - 1, text_size)
else:
return binary_search_recursive(arr, target, mid + 1, high, text_size)
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Example unsorted list
unsorted_arr = [9, 3, 1, 7, 5, 11, 15, 13, 19, 17]
# Sorting the list
bubble_sort(unsorted_arr)
print("Sorted array:", unsorted_arr)
# Clear the OLED display before starting
oled.fill(0)
oled.show()
# Searching for a target in the sorted list
target = 9
result = binary_search_recursive(unsorted_arr, target, 0, len(unsorted_arr) - 1, TEXT_SIZE)
# Display the final result
oled.fill(0)
if result != -1:
draw_text(oled, "Element found at", 0, 0, TEXT_SIZE)
draw_text(oled, "index {}".format(result), 0, 10, TEXT_SIZE)
else:
draw_text(oled, "Element not found", 0, 0, TEXT_SIZE)
oled.show()
equations = ['(x * y) & 24', '(x * y) & 47', '(x * y) & 64', 'x & y', 'x % y', '(x % y) % 4', '40 % (x % y + 1)']
def display_equation(eqn, oled):
start = time.time()
oled.fill(0) # clear display
oled.text('calculating', 0, 0, 1)
oled.text(equations[eqn], 0, 10, 1)
oled.show()
for x in range(WIDTH):
for y in range(1, HEIGHT):
try:
result = eval(equations[eqn])
if result:
oled.pixel(x, y, 0)
else:
oled.pixel(x, y, 1)
except ZeroDivisionError:
oled.pixel(x, y, 1)
except Exception as e:
oled.text('Error', 0, 20, 1)
break
oled.show()
time.sleep(5)
end = time.time()
duration = str(end - start)
print(equations[eqn])
print(duration, ' seconds')
for eqn in range(len(equations)):
display_equation(eqn, oled)
oled.fill(0)
oled.text('done', 0, 0, 1)
oled.show()
print('done')