Tag Archives: python

Dual PICO UART test with CirquitPython

Test for UART serial communication for my whack-a-mole game

CODE for Client

import board
import busio
import time

uart = busio.UART(
    tx=board.GP16,
    rx=board.GP17,
    baudrate=115200,
    timeout=1,
)

time.sleep(2)

commands = ["PING", "HELLO", "TEST"]
while True:
    for cmd in commands:
        print("Sending:", cmd)
        uart.write((cmd + "\n").encode())

        response = uart.readline()

        if response:
            print("Response:", response.decode().strip())
        else:
            print("No response")

        time.sleep(1)

CODE for server

import board
import busio
import digitalio
import time

# UART pins
uart = busio.UART(
    tx=board.GP0,
    rx=board.GP1,
    baudrate=115200,
    timeout=0.1
)

# Onboard LED
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

print("UART LED server ready")

while True:
    data = uart.readline()

    if data:
        command = data.decode("utf-8").strip()
        print("Received:", command)

        if command == "PING":
            # Blink LED
            led.value = True
            time.sleep(0.2)
            led.value = False

            # Reply
            uart.write(b"PONG\n")

        else:
            uart.write(b"UNKNOWN\n")

    time.sleep(0.01)

Blender plugin for 8 potmeter input

This weekend I saw a corridor crew video about controlling CGI objects using input devices.

This made me think of a half finished project I did a while ago.
So lets finish it.

(I know, dirty screen .. too much outside hacking)

8Angle M5 thingy using I2C (Pin D1 and D2)

CODE for wemos

Very simple code to read pots using I2C and printing values on the serial output using the wemos.
Only needs 5V,GND,SDA,SCL (D1 D2)

279,206,520,1023,1023,60,300,985,0
Output example 8 potmeters 0-1023 value and last value 0 or 1 for the switch

Serial plotter example below

#include "m5angle8.h"

M5ANGLE8 MM;

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

  Serial.println();
  delay(100);

  Wire.begin();
  MM.begin();
}


void loop()
{
  for (int ch = 0; ch < 8; ch++)
  {
    Serial.print(MM.analogRead(ch, 10));
    Serial.print(",");
    delay(1);
  }
  Serial.print(MM.inputSwitch());
  Serial.print("\n");
  delay(100);
}

Plugin for Blender

filename unit8angle_blender/__init__.py

made into a zip you can install using

zip -r myplugin.zip unit8angle_blender

Blender edit > preferences > add-ons > Install from disk

import bpy
import serial
import serial.tools.list_ports

ser = None


def open_serial():
    global ser

    if ser:
        return

    # Change this to your COM port
    ser = serial.Serial("/dev/ttyUSB0",115200,timeout=0)


class SERIAL_OT_start(bpy.types.Operator):
    bl_idname = "wm.unit8_start"
    bl_label = "Start Unit8"

    _timer = None

    def modal(self, context, event):

        if event.type == 'TIMER':

            global ser

            if ser and ser.in_waiting:

                line = ser.readline().decode(errors="ignore").strip()

                try:

                    values = list(map(int,line.split(",")))

                    if len(values) >= 8:

                        obj = context.active_object

                        if obj:

                            obj.location.x = values[0] / 100.0
                            obj.location.y = values[1] / 100.0
                            obj.location.z = values[2] / 100.0

#                            obj.location.x = values[0] / 1023.0
#                            obj.location.y = values[1] / 1023.0
#                            obj.location.z = values[2] / 1023.0

                            obj.rotation_euler.x = values[3] / 1023.0 * 6.28318
                            obj.rotation_euler.y = values[4] / 1023.0 * 6.28318
                            obj.rotation_euler.z = values[5] / 1023.0 * 6.28318

                            s = 0.1 + values[6] / 1023.0 * 3.0
                            obj.scale = (s,s,s)

                except Exception:
                    pass

        return {'PASS_THROUGH'}

    def execute(self, context):

        open_serial()

        wm = context.window_manager

        self._timer = wm.event_timer_add(0.01, window=context.window)

        wm.modal_handler_add(self)

        return {'RUNNING_MODAL'}


class SERIAL_PT_panel(bpy.types.Panel):
    bl_label = "Unit8Angle"
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_category = 'Unit8'

    def draw(self, context):
        self.layout.operator("wm.unit8_start")


classes = (
    SERIAL_OT_start,
    SERIAL_PT_panel,
)


def register():
    for c in classes:
        bpy.utils.register_class(c)


def unregister():
    for c in reversed(classes):
        bpy.utils.unregister_class(c)

DIY VR using two cameras on a Raspberry 5

Above a screenshot of a browser screen (Left and Right in fullscreen)
Colors are a little of (codec Red/Blue problem?)
But the setup works!

I used a android phone in above setup.
I tried a Quest 2 VR set, but I couldn’t get the browser in full screen mode. (YET)

Hardware setup

Two Raspberry Pi Camera Modules, connected via the two 4lane-MIPI DSI/CSI connectors.

Manually focussed and using some 3D printed stands on a piece of wood will do for now.

I build a RTSP NGinx proxy to test, which I previously used for OBS. But there was too much latency.

So I used below webrtc setup, with a latency below 80ms.
(I previously did some test using Janus)

CODE:

wget https://github.com/bluenviron/mediamtx/releases/download/v1.16.1/mediamtx_v1.16.1_linux_arm64.tar.gz
tar xzvf media*
cp mediamtx.yml mediamtx.org

NEW mediamtx.yml

webrtc: yes
webrtcAddress: :8889

rtmp: yes
rtmpAddress: :1935

paths:
  dualcam:
    source: publisher

run it

./mediamtx mediamtx.yml

Next make a streamer.
This Python script takes two square camera inputs, merge them side-by-side to one image and pushed the H264 frame to MediaMTX

import numpy as np
from picamera2 import Picamera2
import subprocess
import time

#WIDTH = 1280
WIDTH = 720
HEIGHT = 720
FPS = 30
BITRATE = "2500k"
RTMP_URL = "rtmp://127.0.0.1:1935/dualcam"  # MediaMTX RTMP

# FFmpeg  raw frames / H.264 
ffmpeg_cmd = [
    "ffmpeg",
    "-y",
    "-f", "rawvideo",
    "-pix_fmt", "bgr24",
    "-s", f"{WIDTH*2}x{HEIGHT}",
    "-r", str(FPS),
    "-i", "-",
    "-c:v", "libx264",
    "-preset", "ultrafast",
    "-tune", "zerolatency",
    "-b:v", BITRATE,
    "-g", str(FPS),  # keyframe every second
    "-x264-params", "keyint=30:min-keyint=30:no-scenecut=1",
    "-pix_fmt", "yuv420p",
    "-f", "flv",
    RTMP_URL
]


ffmpeg = subprocess.Popen(ffmpeg_cmd, stdin=subprocess.PIPE, bufsize=0)

picam0 = Picamera2(0)
picam1 = Picamera2(1)

cfg0 = picam0.create_video_configuration(
    main={"size": (WIDTH, HEIGHT), "format": "BGR888"}, controls={"FrameRate": FPS}
)
cfg1 = picam1.create_video_configuration(
    main={"size": (WIDTH, HEIGHT), "format": "BGR888"}, controls={"FrameRate": FPS}
)

picam0.configure(cfg0)
picam1.configure(cfg1)

picam0.start()
picam1.start()

print("Streaming to MediaMTX via RTMP...")

try:
    while True:
        f0 = picam1.capture_array()
        f1 = picam0.capture_array()
        combined = np.hstack((f0, f1))
        ffmpeg.stdin.write(combined.tobytes())
        time.sleep(1/FPS)
except KeyboardInterrupt:
    print("Stopping...")
finally:
    picam0.stop()
    picam1.stop()
    ffmpeg.stdin.close()
    ffmpeg.wait()

Open using http://REMOTEIP:8889/dualcam

Little OBS toy.

I use OBS sometimes to explain things, I thought it would be nice to have a moving avatar thingy in my screencast which moves when I talk.

The image is a transparent PNG, and I’m moving it up and down using the microphone and a python script.

CODE:

import pygame
import pyaudio
import numpy as np
import sys

# Settings
PNG_PATH = "your_image.png"  # Replace with your transparent PNG path
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
MOVEMENT_THRESHOLD = 1
GRAVITY = 3 # Tweak this, to get smoother "talk" bounch
JUMP_MULTIPLIER = 3  # Controls jump power Tweak this shit
MAX_JUMP_HEIGHT = 30   # Max  bounce 
START_OFFSET = -450      # How far below screen the PNG starts ( so my avator stays covered in bottom )

# Initialize PyAudio
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)

# Initialize Pygame
pygame.init()
info = pygame.display.Info()
screen_width, screen_height = info.current_w, info.current_h
screen = pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)
pygame.display.set_caption("Mic Bounce PNG")

# Load image
image = pygame.image.load(PNG_PATH).convert_alpha()
img_rect = image.get_rect()
img_rect.centerx = screen_width // 2
img_rect.top = screen_height + START_OFFSET  # Start below the screen

velocity_y = 0
clock = pygame.time.Clock()

def get_loudness():
    data = np.frombuffer(stream.read(CHUNK, exception_on_overflow=False), dtype=np.int16)
    volume = np.linalg.norm(data)
    return volume / CHUNK

# Bottom and top bounce limits
bottom_y = screen_height + START_OFFSET
top_y = screen_height + START_OFFSET - MAX_JUMP_HEIGHT

try:
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT or \
               (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                raise KeyboardInterrupt

        loudness = get_loudness()

        if loudness > MOVEMENT_THRESHOLD and img_rect.top >= bottom_y:
            # Jump upward with capped power
            velocity_y = -int(min((loudness - MOVEMENT_THRESHOLD) * JUMP_MULTIPLIER, MAX_JUMP_HEIGHT))

        # Apply gravity
        velocity_y += GRAVITY
        img_rect.y += velocity_y

        if img_rect.top >= bottom_y:
            img_rect.top = bottom_y
            velocity_y = 0

        if img_rect.top <= top_y:
            img_rect.top = top_y
            velocity_y = 0

        # Draw chromakey green background
        screen.fill((0, 255, 0))

        # Draw PNG
        screen.blit(image, img_rect)

        pygame.display.flip()
        clock.tick(60)

except KeyboardInterrupt:
    stream.stop_stream()
    stream.close()
    p.terminate()
    pygame.quit()
    sys.exit()

Pushover notifier for dates

Below is my python script to push messages via pushover to my phone.

It’s being run from a cron during the day.

CODE

import csv
import datetime
import requests

# configure own creds
PUSHOVER_USER_KEY = 'keykeykeykeykeykeykeykey'
PUSHOVER_API_TOKEN = 'tokentokentokentokentokentokentoken'
CSV_FILE = '/data/notifications.csv'

def send_pushover_notification(message):
    url = "https://api.pushover.net/1/messages.json"
    payload = {
        "token": PUSHOVER_API_TOKEN,
        "user": PUSHOVER_USER_KEY,
        "message": message
    }
    response = requests.post(url, data=payload)
    if response.status_code != 200:
        print("Failed to send notification:", response.text)

def check_and_notify():
    today = datetime.date.today()
    with open(CSV_FILE, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            try:
                day = int(row['day'])
                month = int(row['month'])
                if today.day == day and today.month == month:
                    send_pushover_notification(row['message'])
            except ValueError:
                continue

if __name__ == "__main__":
    check_and_notify()

notifications.csv file

day,month,message
1,1,Birthday of a new year
16,05,Project Deadline
16,05,Test2 (blah) 2
7,3,Glorious bastard Rik Mayall birthday
27,3,International whisky day

Nice to haves (didn’t implement because i’m a lazy bastard)

  • 3rd Saturday every may
  • Getting dates or updates from another app
  • Selecting Pushover device, level of alertness .. etc

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
  }
}