Tag Archives: python

Machine Learning Waveforms

I’ve used machine learning before, this is my waveform classifier.

(Next to do, more classes)

Class0 – Train data

Class1 – Train data

Running train script

Test data

Prediction

Code ( generates a h5 classifier )

import tensorflow as tf

from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input
import os


# Define dataset path
DATASET_PATH = "data/"

# Load images using ImageDataGenerator
datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)

train_data = datagen.flow_from_directory(
    DATASET_PATH,
    target_size=(128, 128),
    batch_size=32,
    class_mode='categorical',
    subset="training"
)

val_data = datagen.flow_from_directory(
    DATASET_PATH,
    target_size=(128, 128),
    batch_size=32,
    class_mode='categorical',
    subset="validation"
)

# Define CNN model
model = Sequential([
    Input(shape=(128, 128, 3)),
    Conv2D(32, (3,3), activation='relu'),
    MaxPooling2D(2,2),
    
    Conv2D(64, (3,3), activation='relu'),
    MaxPooling2D(2,2),
    
    Flatten(),
    Dense(128, activation='relu'),
    Dropout(0.5),
    Dense(train_data.num_classes, activation='softmax')
])

# Compile model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Train the CNN
model.fit(train_data, validation_data=val_data, epochs=10)

# Save model
model.save("waveform_classifier.h5")
print("Model saved as waveform_classifier.h5")

Code to predict class

import numpy as np
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import load_model

# Load trained model
model = load_model("waveform_classifier.h5")

# Load and preprocess image
def predict_waveform(image_path):
    img = image.load_img(image_path, target_size=(128, 128))
    img_array = image.img_to_array(img) / 255.0
    img_array = np.expand_dims(img_array, axis=0)

    # Predict class
    prediction = model.predict(img_array)
    predicted_class = np.argmax(prediction)
    
    print(f"Predicted Class: {predicted_class}")

for f in range(1,5):
    predict_waveform("testdata/" + str(f) + ".png")

Generate images from CSV

import pandas as pd
import matplotlib.pyplot as plt

def waveform_to_image(csv_file, signal_column="amplitude", save_path="waveform.png"):
    # Load CSV
    df = pd.read_csv(csv_file)

    # Extract signal (time,amplitude)
    signal = df[signal_column]

    # Plot waveform
    plt.figure(figsize=(4, 4))
    plt.ylim(0, 20)

    plt.plot(signal, color='black', linewidth=2)
    # Hide axes
    plt.axis('off')  

    # Save as an image
    plt.savefig(save_path, bbox_inches='tight', pad_inches=0)
    plt.close()
    print(f"Saved waveform image as {save_path}")

# Loop through files 1.csv to 32.csv and generate images
for i in range(1, 31):
    csv_filename = f"{i}.csv"
    png_filename = f"{i}.png"
    waveform_to_image(csv_filename, save_path=png_filename)

First tests with 360 Lidar

In the past, I’ve played with a standard lidar device.

Now it is time to check out a 360 version.

This one is very small (40mm x 40mm x 35mm)

Provided examples didn’t work. (People with same error on the Github issues tracker page had the same)

I changed the python script so it worked also with this YDLidar T-mini Plus version.

Next to-do, put this on my robot car.

Code:

import os
import ydlidar
import time
import sys
from matplotlib.patches import Arc
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

RMAX = 32.0

fig = plt.figure()
lidar_polar = plt.subplot(polar=True)
lidar_polar.autoscale_view(True,True,True)
lidar_polar.set_rmax(RMAX)
lidar_polar.grid(True)
ports = ydlidar.lidarPortList();
port = "/dev/ttyUSB0";
for key, value in ports.items():
    port = value;
    
laser = ydlidar.CYdLidar();

laser.setlidaropt(ydlidar.LidarPropSerialPort, port);
laser.setlidaropt(ydlidar.LidarPropSerialBaudrate, 230400);
laser.setlidaropt(ydlidar.LidarPropLidarType, ydlidar.TYPE_TRIANGLE);
laser.setlidaropt(ydlidar.LidarPropDeviceType, ydlidar.YDLIDAR_TYPE_SERIAL);
laser.setlidaropt(ydlidar.LidarPropScanFrequency, 10.0);
laser.setlidaropt(ydlidar.LidarPropSampleRate, 4);
laser.setlidaropt(ydlidar.LidarPropSingleChannel, False);
laser.setlidaropt(ydlidar.LidarPropMaxAngle, 180.0);
laser.setlidaropt(ydlidar.LidarPropMinAngle, -180.0);
laser.setlidaropt(ydlidar.LidarPropMaxRange, 16.0);
laser.setlidaropt(ydlidar.LidarPropMinRange, 0.02);
laser.setlidaropt(ydlidar.LidarPropIntenstiy, True);

scan = ydlidar.LaserScan()

def animate(num):
    
    r = laser.doProcessSimple(scan);
    if r:
        angle = []
        ran = []
        intensity = []
        for point in scan.points:
            angle.append(point.angle);
            ran.append(point.range);
            intensity.append(point.intensity);
        lidar_polar.clear()
        lidar_polar.scatter(angle, ran, c=intensity, cmap='hsv', alpha=0.95, marker=".")

ret = laser.initialize();
if ret:
    ret = laser.turnOn();
    if ret:
        ani = animation.FuncAnimation(fig, animate, interval=50)
        plt.show()
    laser.turnOff();
laser.disconnecting();
plt.close();

Reverse engineering Epaper Arduino for own image pusher

To display quotes, changing once per hour.

There is not much to be found for Waveshare 4.2 Epaper.
Except for an Arduino web example.
( see https://www.waveshare.com/wiki/E-Paper_ESP32_Driver_Board )

I reversed engineered the workings, and created a python upload script to push images.

Original workings are a mess.
Per 4 bit of color, high-low switched in a byte.
Black and red separated.
Using a till p encoding over curl commands.

My implementation uses a python script called as:

python3 epaper-pusher.py ~/Downloads/Untitled.png
http://10.1.0.99/EPDI_
30 times something like 
http://10.1.0.99/ppppppppppppppppppppppppppppppppppppppppppppppppppppppaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppiodaLOAD_
http://10.1.0.99/NEXT_
30 times something like
http://10.1.0.99/pbcdefghijjjjjjffffffoooooooaaabbbbbbeeeedddppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppiodaLOAD_
http://10.1.0.99/SHOW_
NOTES:
a = 0000
-
-
-
p = 1111 = 15

30 lines with 1000 bytes ( ending with iodaLOAD_ )

black pixels
first block 1
second block 0

red pixels
first block 0
second block 1

white pixels
first block 1
second block 1

PIXEL Example
RBRB
BWBW

First block 
1010 - letter K
0101 - Letter F - second nibble = white

Second block
0101 - Letter F
1111 - Letter P - second nibble white

Code

from PIL import Image
import numpy
import requests

url="http://10.1.0.99/" 

black_pixels = numpy.zeros((400,300))
red_pixels = numpy.zeros((400,300))



def classify_pixel_color(pixel):
    """
    Classify a pixel as black, white, or red.
    """
    r, g, b = pixel[:3]  # Ignore alpha if present

    # Define thresholds for classification
    if r < 128 and g < 128 and b < 128:
        return 'black'
    elif r > 200 and g > 200 and b > 200:
        return 'white'
    elif r > 128 and g < 100 and b < 100:
        return 'red'
    else:
        return None

def process_image(image_path):
    """
    Process the image and classify its pixels into black, white, or red.
    """
    image = Image.open(image_path)
    image = image.convert("RGB")  # Ensure the image is in RGB mode

    width, height = image.size
    pixel_data = image.load()

    color_counts = {'black': 0, 'white': 0, 'red': 0}

    for y in range (0, 299):
        for x in range (0, 399):
            black_pixels[x][y] = 0
            red_pixels[x][y] = 0

    for y in range(299):
        for x in range(399):
            color = classify_pixel_color(pixel_data[x, y])
            if color:
                color_counts[color] += 1
                if color == 'black':
                    black_pixels[x][y] = 1;
                if color == 'red':
                    red_pixels[x][y] = 1;
                if color == 'white':
                    black_pixels[x][y] = 1;
                    red_pixels[x][y] = 1;

    return color_counts, black_pixels, red_pixels

def number_to_letter(num):
    """
    Translates a number from 0 to 15 into a corresponding letter (a-p).

    Args:
        num (int): The number to translate.

    Returns:
        str: The corresponding letter (a-p).
    """
    if 0 <= num <= 15:
        return chr(ord('a') + num)
    else:
        raise ValueError("Number must be between 0 and 15, inclusive.")

def print_array_in_chunks(array, chunk_size=1001):
    current_chunk = ""
    for item in array:
        # Convert item to string and add to the current chunk
        item_str = str(item)
        if len(current_chunk) + len(item_str) + 1 > chunk_size:
            # Print the current chunk and reset it
            current_chunk += "iodaLOAD_"
            try:
                requests.get(url + current_chunk, verify=False)
                if not response.content:  # Equivalent to expecting an empty reply
                    pass
            except requests.exceptions.RequestException as e:
                # Catch any request-related errors
                pass
            current_chunk = item_str
        else:
            # Append the item to the current chunk
            current_chunk += (item_str)
    current_chunk += "iodaLOAD_"
    # Print any remaining items in the chunk
    if current_chunk:
        try:
            requests.get(url + current_chunk, verify=False)
            if not response.content:  # Equivalent to expecting an empty reply
                pass
        except requests.exceptions.RequestException as e:
            # Catch any request-related errors
            pass
        

def switch_in_pairs(arr):
    # Loop through the array with a step of 2
    for i in range(0, len(arr) - 1, 2):
        # Swap values at index i and i+1
        arr[i], arr[i + 1] = arr[i + 1], arr[i]
    return arr

if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print("Usage: python3 script.py <image_path>")
        sys.exit(1)

    image_path = sys.argv[1]
    try:
        color_counts, black_pixels, red_pixels = process_image(image_path)
        try:
            requests.get(url + "EPDI_" , verify=False)
            if not response.content:  # Equivalent to expecting an empty reply
                pass
        except requests.exceptions.RequestException as e:
            # Catch any request-related errors
            pass

        
        lines=[]
        for y in range(300):
            for x in range(0,399,4):
                first = red_pixels[x][y]
                second = red_pixels[x+1][y]
                thirth = red_pixels[x+2][y]
                fourth = red_pixels[x+3][y]
                nibble = 0
                if (first ==  1):
                        nibble = nibble + 8
                if (second ==  1):
                        nibble = nibble + 4
                if (thirth ==  1):
                        nibble = nibble + 2
                if (fourth ==  1):
                        nibble = nibble + 1
                lines.append(number_to_letter(nibble))
        switched_array = switch_in_pairs(lines)
        print_array_in_chunks(switched_array)
        try:
            requests.get(url + "NEXT_" , verify=False)
            if not response.content:  # Equivalent to expecting an empty reply
                pass
        except requests.exceptions.RequestException as e:
            # Catch any request-related errors
            pass
        lines=[]
        for y in range(300):
            for x in range(0,399,4):
                first = black_pixels[x][y]
                second = black_pixels[x+1][y]
                thirth = black_pixels[x+2][y]
                fourth = black_pixels[x+3][y]
                nibble = 0
                if (first ==  1):
                        nibble = nibble + 8
                if (second ==  1):
                        nibble = nibble + 4
                if (thirth ==  1):
                        nibble = nibble + 2
                if (fourth ==  1):
                        nibble = nibble + 1
                lines.append(number_to_letter(nibble))
        switched_array = switch_in_pairs(lines)
        print_array_in_chunks(switched_array)

        try:
            requests.get(url + "SHOW_" , verify=False)
            if not response.content:  # Equivalent to expecting an empty reply
                pass
        except requests.exceptions.RequestException as e:
            # Catch any request-related errors
            pass

    except Exception as e:
        pass

2D on a 3D printer, moving lab and designing

Not a lot to tell, but much going on.

Having my own business means having a more professional electronics lab is a must.
So I’m moving from the attic to our outside workshop. That also means I have to make our Music Studio smaller.

So moving, printing a lot on my new 3D printer and designing EuroCards.

Part of the Address decoding eurocard with din41612.

Above card will hold two address decodes parts, selectable using jumpers. ( Old skool TTL using 74xx and a new solution using ATF22V10.

We like Low Poly models, so I printed one using marble PLA.

In the back my 100yr old highhat from my Grandfather (moleskin)

I’ve cleaned my old 3D printer, and I am planning to convert this printer to a 2D plotter and a CNC machine.

I’ve already printed a pen holder and a dremel holder.
(The filament head will be removed)

I’m working on a Gcode writer to plot drawings using a pen, or using a Gyro-cut knife to cut paper.
And the biggest project using this old 3D printer, a CNC machine!

Test Code:

import time
import serial

arduino = serial.Serial('/dev/ttyUSB0', 115200, timeout=.1)

# Motor stuff
arduino.write(str.encode("M84 X Y Z S12000\r\n"))
arduino.write(str.encode("M92 X160 Y160 Z800\r\n"))
# Extrude fix
arduino.write(str.encode("G92 E0\r\n"))
# Go home
arduino.write(str.encode("G28\r\n"))
# Move to x,y,z
arduino.write(str.encode("G1 Z90 X50 Y50\r\n"))
# Wait
arduino.write(str.encode("M400\r\n"))

Sin wave fun:

import time
import serial
import math
from time import sleep

arduino = serial.Serial('/dev/ttyUSB0', 115200, timeout=.1)

arduino.write(str.encode("M84 X Y Z S12000\r\n")) 
arduino.write(str.encode("M92 X160 Y160 Z800\r\n")) 
arduino.write(str.encode("G92 E0\r\n")) 
arduino.write(str.encode("G28\r\n")) 
arduino.write(str.encode("M220 S100\r\n")) 
arduino.write(str.encode("G1 Z10 X60 Y60\r\n"))
arduino.write(str.encode("M400\r\n"))
sleep(10)
count = 0
while True:
	newx=(math.sin(math.radians(count))*50)+60
	newy=(math.cos(math.radians(count))*50)+60
	newz=(math.cos(math.radians(count))*10)+20
	count = count + 1
	mystring="G1 Z" + str(newz) + " X" + str(newx) + " Y" + str(newy) + "\r\n" 
	print(mystring) 
	arduino.write(str.encode(mystring)) 
	arduino.write(str.encode("M400\r\n")) 
        # Not waiting for answer yet
	print(newx) 
	sleep(0.1)	
X,Y and Z movement (4x speed)

Minimal socket test server, client and arduino

Socket connect to server, enter number and get reply test.

server.py

import socket
import threading

# Define the host and port
HOST = '0.0.0.0'  # Localhost (change as needed)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

# Function to handle each client connection
def handle_client(conn, addr):
    print(f"Connected by {addr}")
    
    # Send a thank you message to the client upon connection
    thank_you_message = "Thank you for connecting! Please enter a number:\n"
    conn.sendall(thank_you_message.encode('utf-8'))
    
    while True:
        try:
            data = conn.recv(1024)
            if not data:
                break
            
            # Decode the received data
            received_number = data.decode('utf-8').strip()
            print(f"Received from {addr}: {received_number}")
            
            # Try to convert the received data to an integer
            try:
                number = int(received_number)
                response = f"The double of {number} is {number * 2}\n"
            except ValueError:
                response = "Please enter a valid number.\n"
            
            # Send the response back to the client
            conn.sendall(response.encode('utf-8'))
        except ConnectionResetError:
            print(f"Connection with {addr} lost.")
            break

    conn.close()
    print(f"Connection with {addr} closed.")

# Function to start the server and listen for connections
def start_server():
    # Create a socket object
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # Bind the socket to the host and port
    server.bind((HOST, PORT))
    
    # Start listening with a maximum backlog of 5 connections
    server.listen(5)
    print(f"Server listening on {HOST}:{PORT}")
    
    while True:
        # Accept a new connection
        conn, addr = server.accept()
        
        # Create a new thread to handle the client connection
        client_thread = threading.Thread(target=handle_client, args=(conn, addr))
        client_thread.start()

# Run the server
if __name__ == "__main__":
    start_server()

python-client.py

import socket

# Define the server host and port
HOST = 'IPNUMBERSERVER'  # The server's hostname or IP address
PORT = 65432        # The port used by the server

def start_client():
    # Create a socket object
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # Connect to the server
    client.connect((HOST, PORT))
    
    # Receive and print the welcome message from the server
    welcome_message = client.recv(1024).decode('utf-8')
    print(welcome_message)
    
    while True:
        # Enter a number and send it to the server
        number = input("Enter a number (or type 'exit' to quit): ")
        
        if number.lower() == 'exit':
            print("Closing connection...")
            break
        
        client.sendall(number.encode('utf-8'))
        
        # Receive the response from the server and print it
        response = client.recv(1024).decode('utf-8')
        print(response)
    
    # Close the connection after the loop ends
    client.close()

# Run the client
if __name__ == "__main__":
    start_client()

arduino-client.ino

#include <ESP8266WiFi.h> // For ESP8266
//#include <WiFi.h>       // For ESP32

// Replace with your network credentials
const char* ssid     = "your_SSID";     // Replace with your network SSID (name)
const char* password = "your_PASSWORD"; // Replace with your network password

// Define the server's IP address and port
const char* host = "192.168.1.100"; // Replace with your server's IP address
const int port = 65432;             // Server port

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(10);

  // Connect to WiFi
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Connect to the server
  Serial.print("Connecting to server at ");
  Serial.print(host);
  Serial.print(":");
  Serial.println(port);

  if (client.connect(host, port)) {
    Serial.println("Connected to server!");
    
    // Wait for the welcome message from the server
    while (client.available() == 0);

    // Read and print the welcome message
    while (client.available()) {
      char c = client.read();
      Serial.print(c);
    }
  } else {
    Serial.println("Connection failed.");
  }
}
void loop() {
  // Check if connected to the server
  if (client.connected()) {
    // Check if there is any serial input from the user
    if (Serial.available() > 0) {
      String input = Serial.readStringUntil('\n');
      input.trim(); 

      if (input.equalsIgnoreCase("exit")) {
        Serial.println("Closing connection...");
        client.stop(); // Disconnect from the server
        while (true);  // Stop the loop
      }

      // Send the number to the server
      client.println(input);

      // Wait for the server's response
      while (client.available() == 0);

      // Read and print the server's response
      while (client.available()) {
        char c = client.read();
        Serial.print(c);
      }
    }
  } else {
    Serial.println("Disconnected from server.");
    while (true); // Stop the loop
  }
}

Bornhack 2023 NFC Badge Display hack

Last week I bought an old Bornhack Badge. I thought it needed a display.

Using a SSD1306 display, and Circuitpython I made this.

( Wooded thingy contains an RFID chip ( Part of my player ))

Library and files needed:

  • font5x8.bin in root of filesystem ( just google for this file )
  • copy of adafruit_framebuf.mpy in /lib
  • copy of adafruit_ssd1306.mpy in /lib

Code: (midway some pixel examples, just uncomment)

import board
from time import sleep
import busio 
from PN7150 import PN7150
import adafruit_ssd1306
import math
import adafruit_framebuf


if True:
    # Fast 400KHz I2C
    i2c = busio.I2C(board.SCL, board.SDA, frequency = 400000)
else:
    # Regular 100kHz I2C
    i2c = board.I2C()


WIDTH = 32
HEIGHT = 8

buffer = bytearray(round(WIDTH * math.ceil(HEIGHT / 8)))
fb = adafruit_framebuf.FrameBuffer(
    buffer, WIDTH, HEIGHT, buf_format=adafruit_framebuf.MVLSB
)


nfc = PN7150(i2c, board.IRQ, board.VEN)

display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c,addr=0x3c)

assert nfc.connect()
print("Connected.")

assert nfc.modeRW()
print("Switched to read/write mode.")

display.fill(0)

display.show()

#display.fill(0)
#display.text('Hello', 0, 0, 1 )
#display.text('World', 0, 10, 1)
#display.show()
# Set a pixel in the origin 0,0 position.
#display.pixel(0, 0, 1)
# Set a pixel in the middle 64, 16 position.
#display.pixel(64, 16, 1)
# Set a pixel in the opposite 127, 31 position.
#display.pixel(127, 31, 1)
#display.show()

while True:
    display.fill(0)
    display.text('Waiting for card', 0, 0, 1 )
    display.show()

    assert nfc.startDiscoveryRW()

    print("Waiting for card..")
    card = nfc.waitForCard()
    assert nfc.stopDiscovery()

    print("ID: {}".format(card.nfcid1()))
    id = card.nfcid1()
    display.text(id, 0, 10, 1 )
    display.show()

    sleep(0.5)

Not sure about display i2c address? Use below code

import time
import board
import busio

# List of potential I2C busses
ALL_I2C = ("board.I2C()",)

# Determine which busses are valid
found_i2c = []
for name in ALL_I2C:
    try:
        print("Checking {}...".format(name), end="")
        bus = eval(name)
        bus.unlock()
        found_i2c.append((name, bus))
        print("ADDED.")
    except Exception as e:
        print("SKIPPED:", e)

# Scan valid busses
if len(found_i2c):
    print("-" * 40)
    print("I2C SCAN")
    print("-" * 40)
    while True:
        for bus_info in found_i2c:
            name = bus_info[0]
            bus = bus_info[1]

            while not bus.try_lock():
                pass

            print(
                name,
                "addresses found:",
                [hex(device_address) for device_address in bus.scan()],
            )

            bus.unlock()

        time.sleep(2)
else:
    print("No valid I2C bus found.")

Keyboard switch part 1

Testing the first keyboard. It is the 8085-SDK hex matrix keyboard.

It is running on a Raspberry Pi Zero 2, without X server.
So the images are displayed using the framebuffer.
Also the touch data is read using evdev and the raw devices.

Todo:

  • HID part
  • Add a rotary button for the selection of the different Keyboard Layouts
  • Improvement keyboard matrix calculation to find out which key is being pressed.
  • Code to control AT/PS2 computers directly using GPIO pins
  • Add a controller to use Raw controlling of matrix pins ( 6502 C64 hardware for example )

Bash test and configuring the OS for testing.

cat <<EOF >> /boot/config.txt
hdmi_group=2
hdmi_mode=87
hdmi_timings=400 0 100 10 140 1280 10 20 20 2 0 0 0 60 0 43000000 3
display_rotate=3
EOF

# Image testing
apt-get install fbi
sudo fbi -d /dev/fb0 -T 1 8085.png  -a --noverbose

apt-get install python3-evdev python3-uinput evtest
evtest

First simple python test

import select
from math import floor
import sys
slot = 0

keysname=[["F","E","D","C","vect-int","reset"],
          ["B","A","9","8","GO","Single-Step"],
          ["7","6","5","4","Exam-reg","Subst-mem"],
          ["3","2","1","0","Exec","Next"],
          ]
keysnames=[["F","E","D","C","vect-int","reset"],
          ["B","A","L","H","GO","Single-Step"],
          ["PCL","PCH","SPL","SPH","Exam-reg","Subst-mem"],
          ["3","2","1","0",".",","],
          ]

for path in evdev.list_devices():
    device = evdev.InputDevice(path)
    if evdev.ecodes.EV_ABS in device.capabilities():
        break
else:
    sys.stderr.write('Failed to find the touchscreen.\n')
    sys.exit(1)

while True:
    r, w, x = select.select([device.fd], [], [])

    id_ = -1
    x = y = 0

    for event in device.read():

        if event.code == event.value == 0:
           if id_ != -1:
                yy = floor(( x - 600 ) / 700)
                xx = floor(( y - 1377 ) / 226)
                if yy < 4 and yy >=0 and xx < 6 and xx >= 00:
                     if slot == 1:
                         print(keysnames[yy][xx])
                     else:
                         print(keysname[yy][xx])

        elif event.code == ABS_MT_TRACKING_ID:
            id_ = event.value
        elif event.code == ABS_MT_SLOT:
            slot = event.value
        elif event.code == ABS_MT_POSITION_X:
            x = event.value
        elif event.code == ABS_MT_POSITION_Y:
            y = event.value

I came up with a simple matrix calculation

Pressing the 4 corner keys gave me x and y.
I took averages for min and max reading.
I don’t need pixel-perfect reading, and I noticed values between 960 and 3080 vertically.
We want 960 – 3080 into 4 blocks, but the middle should start @ 960.

So 3080/3 = about 700
700 / 2 = 350
block 1 starts 350 sooner than 960 is ~ 600
Upper key y coords = 600-> + 700
Next is 1300 -> + 700
converting to whole numbers using floor gives me:
floor(( y – 600 ) / 700)
NOTE: My x and y are rotated

Example using coordinates
1600, 1600
floor(( 1600 – 600 ) / 700) = floor(1,4…) = 1st row
(from row 0,1,2,3)

64×64 Etch a Sketch

In the past I made a Etch a Sketch with my lasercutter.

Using two rotary encoders and the 64×64 matrix display I recently bought, I made a drawing thingy.
Like a Etch a Sketch.

Some Circuit Python code.
Now I have to fix an out of memory issue using below.
And make a colour selection button??? 🙂

import time
import board
import displayio
import math
import vectorio
import rgbmatrix
import framebufferio
import array
import bitmaptools

import rotaryio
import board

encoder1 = rotaryio.IncrementalEncoder(board.GP27, board.GP26)
encoder2 = rotaryio.IncrementalEncoder(board.GP18, board.GP19)

last_position1 = 0
last_position2 = 0

# Release any existing displays
displayio.release_displays()

# --- Matrix Properties ---
DISPLAY_WIDTH = 64
DISPLAY_HEIGHT = 64

# --- Matrix setup ---
BIT_DEPTH = 2
matrix = rgbmatrix.RGBMatrix(
    width=64, bit_depth=2, height=64,
    rgb_pins=[board.GP0, board.GP1, board.GP2, board.GP3, board.GP4, board.GP5],
    addr_pins=[board.GP6, board.GP7, board.GP8, board.GP9, board.GP22],
    clock_pin=board.GP10, latch_pin=board.GP12, output_enable_pin=board.GP13)
colrs = 13
display = framebufferio.FramebufferDisplay(matrix, auto_refresh=True)
b1 = displayio.Bitmap(display.width, display.height, colrs )
palette = displayio.Palette(colrs )
palette[0] = 0x000000  # black
palette[1] = 0x964B00  # brown (light yellow) 
palette[2] = 0x00FFFF  # cyan
palette[3] = 0x850101  # deep red 
palette[4] = 0x7F00FF  # violet
palette[5] = 0xC46210  # orange
palette[6] = 0x3D9140  # Cobalt green  
palette[7] = 0x004225  # british racing green 
palette[8] = 0x8B008B  # dark magenta 
palette[9] = 0x1F75FE  # crayola  blue
palette[10] =0x00308F  # air force blue US air force    
palette[11] =0xBF00FF  # electric purple 
palette[12] =0x08E8DE  # turquoise
g1 = displayio.Group(scale=1)
display.root_group = g1 

bmp = displayio.Bitmap(64,64, 2)

tilegrid = displayio.TileGrid(bitmap=bmp, pixel_shader=palette)
g1.append(tilegrid)
display.auto_refresh = True

tilegrid = displayio.TileGrid(bitmap=bmp, pixel_shader=palette)
while True:
        position1 = encoder1.position
        if last_position1 is None or position1 != last_position1:

            if position1 > last_position1:
                position1 = position1 + 1
            if position1 < last_position1:
                position1 = position1 - 1
            if position1 < 0:
                position1 = 0
            last_position1 = position1
        position2 = encoder2.position
        if last_position2 is None or position2 != last_position2:
            if position2 > last_position2:
                position2 = position2 + 1
            if position2 > last_position2:
                position2 = position2 - 1
            if position2 < 0:
                position2 = 0
            last_position2 = position2

        bmp[position1,position2]=1
        tilegrid = displayio.TileGrid(bitmap=bmp, pixel_shader=palette)
        g1.append(tilegrid)
        display.auto_refresh = True

I tried to recreate an optical illusion

My friend Tyrone posted something he recorded from TV.
It was an illusion, using rotated images.

The effect is that it seems that the card is rotating at different speeds, when pressing the s (show/unshow) key, you see the card rotating at the same speed as before.

So I wanted to try to recreate this using python.
The effect is there, but a little less.
What can I improve?

Mine:

Around the 30 seconds mark I disable the background, you’ll see the card rotating as before.

Original:

Better version, larger and using s key to toggle water off, to see the card rotating

import pygame
import math

# 20240409 added s to toggle 

pygame.init()
screen = pygame.display.set_mode((1600, 900))
clock = pygame.time.Clock()

def blitRotate(surf, image, pos, originPos, angle):

    image_rect = image.get_rect(topleft = (pos[0] - originPos[0], pos[1]-originPos[1]))
    offset_center_to_pivot = pygame.math.Vector2(pos) - image_rect.center
    rotated_offset = offset_center_to_pivot.rotate(-angle)
    rotated_image_center = (pos[0] - rotated_offset.x, pos[1] - rotated_offset.y)
    rotated_image = pygame.transform.rotate(image, angle)
    rotated_image_rect = rotated_image.get_rect(center = rotated_image_center)
    surf.blit(rotated_image, rotated_image_rect)

try:
    image = pygame.image.load('cards.png').convert_alpha()
    image2 = pygame.image.load('clear+sea+water-2048x2048.png').convert_alpha()
except:
    text = pygame.font.SysFont('Times New Roman', 50).render('imagemissing', False, (255, 255, 0))
    image = pygame.Surface((text.get_width()+1, text.get_height()+1))
    image2 = image
    image.blit(text, (1, 1))

w, h = image.get_size()
angle = 0
angle2 = 0
done = False
while not done:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    pos = (screen.get_width()/2, screen.get_height()/2)
    
    screen.fill(0)
    keys = pygame.key.get_pressed()
    if (not keys[pygame.K_s]):
        blitRotate(screen, image2, pos, (900, 900), angle2)
    blitRotate(screen, image, pos, (w/2, h/2), angle)
    angle += 1
    angle2 += math.sin(math.radians(angle))
    pygame.display.flip()
    
pygame.quit()
exit()

What to do when waiting for your ribs on the smoker. (Programming some python)

This time I used a rub with the following ingredients:
Seasalt, garlic, brown sugar, mustard seeds, paprica, cilantroseeds, black pepper, red pepper, oregano, thyme and cumin.

Doing a simple 3-2-1 smoke session, so .. what to do in dose 6 hours?

Lets make something using a Sense hat and Python.
Same HAT I used for my xmas ornament thingy in our tree.

  • Generate a large maze (80×80 for now)
  • Paint the maze using colors on the SenseHat
  • Read joystick movement and scroll the maze accordingly, keeping the player in the middle

Now I have to paint my ribs with BBQ sauce, and leave it in the smoker for yet another hour. (Nice glazing)

Next steps for the maze:

Use a better way to generate (reverse backtracking as I made for my other maze thing)

Wall collision detection is nearly completed.

Better placement “birth” of player in the maze.

# # # # # # # # # # # # # # # # # # # # 

# R D . . . . . R D . . . . R R D R D # 

# D L . . . . . U D . . . . U . R U D # 

# D . . . . R R U R D . . R U U L . D # 

# R D . . . U . . . R R D U . . U L D # 

# . R D R R U . . . . . D U . . . U L # 

# . . D U L . . . . . D L U . . . . . # 

# . . R R U . . . . . R R U . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# . . . . . . . . . . . . . . . . . . # 

# # # # # # # # # # # # # # # # # # # #