Tag Archives: python

Bios hacking

Followup on :

I wrote a little python script which checks the checksum of a Bios.

In a previous post i used hexedit to play around changing a Bios dump.

Below posted python script calculates the checkum using the following:

Add all bytes in the file and do a modulo 256 on this number. The output should be 0.

My previous edit gave me a output of C2, so I changed an unused byte FF into (FF-C2) 3D.
No more checksum errors when booting!

Next to do, get a Bios like Glabios or PcXtBios to start my own code from a secondary Eeprom.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import sys
# Bios sum modulo should be 0
# edit last or unused byte to fix
# python bios-checksum-test.py MYROM.edit.checksum
# 0
f = open(sys.argv[1],'rb')
m = f.read()
print '%x' % ( ( sum(ord(c) for c in m) & 0xFFFFFFFF ) % 256 )
import sys # Bios sum modulo should be 0 # edit last or unused byte to fix # python bios-checksum-test.py MYROM.edit.checksum # 0 f = open(sys.argv[1],'rb') m = f.read() print '%x' % ( ( sum(ord(c) for c in m) & 0xFFFFFFFF ) % 256 )
import sys

# Bios sum modulo should be 0
# edit  last or unused byte to fix
# python bios-checksum-test.py MYROM.edit.checksum
# 0

f = open(sys.argv[1],'rb')
m = f.read()
print  '%x' % ( ( sum(ord(c) for c in m) & 0xFFFFFFFF ) % 256 )

Python3

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import sys
# Bios sum modulo should be 0
# edit last or unused byte to fix
# python bios-checksum-test.py MYROM.edit.checksum
# 0
f = open(sys.argv[1],'rb')
m = f.read()
checksum = ( ( sum((c) for c in m) & 0xFFFFFFFF ) % 256 )
print(checksum, 'in hex =', hex(checksum))
import sys # Bios sum modulo should be 0 # edit last or unused byte to fix # python bios-checksum-test.py MYROM.edit.checksum # 0 f = open(sys.argv[1],'rb') m = f.read() checksum = ( ( sum((c) for c in m) & 0xFFFFFFFF ) % 256 ) print(checksum, 'in hex =', hex(checksum))
import sys

# Bios sum modulo should be 0
# edit  last or unused byte to fix
# python bios-checksum-test.py MYROM.edit.checksum
# 0

f = open(sys.argv[1],'rb')
m = f.read()
checksum =  ( ( sum((c) for c in m) & 0xFFFFFFFF ) % 256 )
print(checksum, 'in hex =', hex(checksum))

Spotify control using python

For usage in this project:

Goto https://developers.spotify.com and add a APP

Write down the Client_id Client_secret and Redirect URL (callback)

Create a bash and python script

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#!/bin/bash
export SPOTIPY_CLIENT_ID=2f660e11e70743febdxxxxxxxxxxxxx
export SPOTIPY_CLIENT_SECRET=b0741452a4fe43xxxxxxxxxxxxx
export SPOTIPY_REDIRECT_URI="http://localhost:8080/callback"
python3 spot.py $1
#!/bin/bash export SPOTIPY_CLIENT_ID=2f660e11e70743febdxxxxxxxxxxxxx export SPOTIPY_CLIENT_SECRET=b0741452a4fe43xxxxxxxxxxxxx export SPOTIPY_REDIRECT_URI="http://localhost:8080/callback" python3 spot.py $1
#!/bin/bash
export SPOTIPY_CLIENT_ID=2f660e11e70743febdxxxxxxxxxxxxx
export SPOTIPY_CLIENT_SECRET=b0741452a4fe43xxxxxxxxxxxxx
export SPOTIPY_REDIRECT_URI="http://localhost:8080/callback"

python3 spot.py $1

spot.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from pprint import pprint
from time import sleep
import spotipy.util as util
import sys
username = "username"
scope = "user-read-playback-state,user-modify-playback-state,playlist-read-private"
util.prompt_for_user_token(username,scope,client_id=SPOTIPY_CLIENT_ID,client_secret=SPOTIPY_CLIENT_SECRET,redirect_uri=SPOTIPY_REDIRECT_URI)
sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(scope=scope))
# Shows playing devices
res = sp.devices()
pprint(res)
myurl = 'spotify:playlist:' + sys.argv[1]
# Change track
results = sp.start_playback(context_uri=myurl, offset={"position": 1})
## Change volume example
#sp.volume(100)
#sleep(2)
#sp.volume(50)
#sleep(2)
playlists = sp.user_playlists(username)
playlists = sp.current_user_playlists()
for playlist in playlists['items']:
print(playlist['id'] + ' ' + playlist['name'])
import spotipy from spotipy.oauth2 import SpotifyOAuth from pprint import pprint from time import sleep import spotipy.util as util import sys username = "username" scope = "user-read-playback-state,user-modify-playback-state,playlist-read-private" util.prompt_for_user_token(username,scope,client_id=SPOTIPY_CLIENT_ID,client_secret=SPOTIPY_CLIENT_SECRET,redirect_uri=SPOTIPY_REDIRECT_URI) sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(scope=scope)) # Shows playing devices res = sp.devices() pprint(res) myurl = 'spotify:playlist:' + sys.argv[1] # Change track results = sp.start_playback(context_uri=myurl, offset={"position": 1}) ## Change volume example #sp.volume(100) #sleep(2) #sp.volume(50) #sleep(2) playlists = sp.user_playlists(username) playlists = sp.current_user_playlists() for playlist in playlists['items']: print(playlist['id'] + ' ' + playlist['name'])
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from pprint import pprint
from time import sleep
import spotipy.util as util
import sys

username = "username"
scope = "user-read-playback-state,user-modify-playback-state,playlist-read-private"
util.prompt_for_user_token(username,scope,client_id=SPOTIPY_CLIENT_ID,client_secret=SPOTIPY_CLIENT_SECRET,redirect_uri=SPOTIPY_REDIRECT_URI)

sp = spotipy.Spotify(client_credentials_manager=SpotifyOAuth(scope=scope))

# Shows playing devices
res = sp.devices()
pprint(res)

myurl = 'spotify:playlist:' + sys.argv[1]

# Change track
results = sp.start_playback(context_uri=myurl, offset={"position": 1})

## Change volume example
#sp.volume(100)
#sleep(2)
#sp.volume(50)
#sleep(2)

playlists = sp.user_playlists(username)

playlists = sp.current_user_playlists()
for playlist in playlists['items']:
    print(playlist['id'] + ' ' +  playlist['name'])

Run bash script as follows.

playlistplayspotify.sh 0bJvpsn0TDxxxxxxxxxxxx
(0bJvpsn0TDxxxxxxxxxxxx – is playlist ID, as example below)

OUTPUT:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
python3 spot.py 0bJvpsn0TDxxxxxxxxxxxx
{'devices': [{'id': 'e86eada2a91e29a396acxxxxxxxxxxxxxxxxxxxx',
'is_active': True,
'is_private_session': False,
'is_restricted': False,
'name': 'laptop',
'type': 'Computer',
'volume_percent': 100},
{'id': '8571468b6c41973ccb0axxxxxxxxxxxxxxxxxxxx',
'is_active': False,
'is_private_session': False,
'is_restricted': False,
'name': 'DESKTOP-xxxxxxx',
'type': 'Computer',
'volume_percent': 76},
{'id': '6c592503aa5a22b2fbdxxxxxxxxxxxxxxxxxxxxxx',
'is_active': False,
'is_private_session': False,
'is_restricted': False,
'name': 'TX-NR1030',
'type': 'AVR',
'volume_percent': 41}]}
0bJvpsn0TDxxxxxxxxxxxx Best Classical Music Of All Time
5aL9jeGMCAxxxxxxxxxxxx Programming music
37i9dQZEVCxxxxxxxxxxxx Discover Weekly
6pEJuA1UYJxxxxxxxxxxxx Highland/Small/Border Pipe Music
5p8Tabf5Zwxxxxxxxxxxxx Folk Instrumentals ( Celtic, Irish, Nordic, ... )
1oy8Ek4ddBxxxxxxxxxxxx Lounge
37i9dQZF1Dxxxxxxxxxxxx Irish Folk
etc etc
python3 spot.py 0bJvpsn0TDxxxxxxxxxxxx {'devices': [{'id': 'e86eada2a91e29a396acxxxxxxxxxxxxxxxxxxxx', 'is_active': True, 'is_private_session': False, 'is_restricted': False, 'name': 'laptop', 'type': 'Computer', 'volume_percent': 100}, {'id': '8571468b6c41973ccb0axxxxxxxxxxxxxxxxxxxx', 'is_active': False, 'is_private_session': False, 'is_restricted': False, 'name': 'DESKTOP-xxxxxxx', 'type': 'Computer', 'volume_percent': 76}, {'id': '6c592503aa5a22b2fbdxxxxxxxxxxxxxxxxxxxxxx', 'is_active': False, 'is_private_session': False, 'is_restricted': False, 'name': 'TX-NR1030', 'type': 'AVR', 'volume_percent': 41}]} 0bJvpsn0TDxxxxxxxxxxxx Best Classical Music Of All Time 5aL9jeGMCAxxxxxxxxxxxx Programming music 37i9dQZEVCxxxxxxxxxxxx Discover Weekly 6pEJuA1UYJxxxxxxxxxxxx Highland/Small/Border Pipe Music 5p8Tabf5Zwxxxxxxxxxxxx Folk Instrumentals ( Celtic, Irish, Nordic, ... ) 1oy8Ek4ddBxxxxxxxxxxxx Lounge 37i9dQZF1Dxxxxxxxxxxxx Irish Folk etc etc
python3 spot.py 0bJvpsn0TDxxxxxxxxxxxx
{'devices': [{'id': 'e86eada2a91e29a396acxxxxxxxxxxxxxxxxxxxx',
              'is_active': True,
              'is_private_session': False,
              'is_restricted': False,
              'name': 'laptop',
              'type': 'Computer',
              'volume_percent': 100},
             {'id': '8571468b6c41973ccb0axxxxxxxxxxxxxxxxxxxx',
              'is_active': False,
              'is_private_session': False,
              'is_restricted': False,
              'name': 'DESKTOP-xxxxxxx',
              'type': 'Computer',
              'volume_percent': 76},
             {'id': '6c592503aa5a22b2fbdxxxxxxxxxxxxxxxxxxxxxx',
              'is_active': False,
              'is_private_session': False,
              'is_restricted': False,
              'name': 'TX-NR1030',
              'type': 'AVR',
              'volume_percent': 41}]}
0bJvpsn0TDxxxxxxxxxxxx Best Classical Music Of All Time
5aL9jeGMCAxxxxxxxxxxxx Programming music
37i9dQZEVCxxxxxxxxxxxx Discover Weekly
6pEJuA1UYJxxxxxxxxxxxx Highland/Small/Border Pipe Music
5p8Tabf5Zwxxxxxxxxxxxx Folk Instrumentals ( Celtic, Irish, Nordic, ... )
1oy8Ek4ddBxxxxxxxxxxxx Lounge
37i9dQZF1Dxxxxxxxxxxxx Irish Folk
etc etc

Converting png images to composite pixels (6502)

Using searle’s design, i can draw pixels using composite video out.

Converting b/w png to hex include files, for usage in vasm I did the following.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#Python script to convert black levels to pixels
from PIL import Image
i = Image.open("fash.png")
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size
all_pixels = []
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
if cpixel[1] == 255:
s = '\t.db 0x05,' + hex(int(x)) + ',' + hex(int(y))
print (s)
#Python script to convert black levels to pixels from PIL import Image i = Image.open("fash.png") pixels = i.load() # this is not a list, nor is it list()'able width, height = i.size all_pixels = [] for x in range(width): for y in range(height): cpixel = pixels[x, y] if cpixel[1] == 255: s = '\t.db 0x05,' + hex(int(x)) + ',' + hex(int(y)) print (s)
#Python script to convert black levels to pixels
from PIL import Image
i = Image.open("fash.png")

pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size

all_pixels = []
for x in range(width):
    for y in range(height):
        cpixel = pixels[x, y]
        if cpixel[1] == 255:
            s = '\t.db 0x05,' + hex(int(x)) + ',' + hex(int(y))
            print (s)

Running and output example

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
python3 image.py > out
head out
.db 0x05,0x1,0x16
.db 0x05,0x1,0x18
.db 0x05,0x1,0x19
.db 0x05,0x2,0x7
.db 0x05,0x2,0x8
.db 0x05,0x2,0xc
.db 0x05,0x2,0xd
.db 0x05,0x2,0x17
.db 0x05,0x3,0x5
python3 image.py > out head out .db 0x05,0x1,0x16 .db 0x05,0x1,0x18 .db 0x05,0x1,0x19 .db 0x05,0x2,0x7 .db 0x05,0x2,0x8 .db 0x05,0x2,0xc .db 0x05,0x2,0xd .db 0x05,0x2,0x17 .db 0x05,0x3,0x5
python3 image.py > out

head out
	.db 0x05,0x1,0x16
	.db 0x05,0x1,0x18
	.db 0x05,0x1,0x19
	.db 0x05,0x2,0x7
	.db 0x05,0x2,0x8
	.db 0x05,0x2,0xc
	.db 0x05,0x2,0xd
	.db 0x05,0x2,0x17
	.db 0x05,0x3,0x5

Control codes and vasm include

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
01 (01) - Cursor home (Standard ASCII)
04 (04) - Cursor solid
05 (05) - Set graphics pixel (next two bytes = x,y)
0C (12) - Clear screen (Standard ASCII)
0D (13) - Carriage return (Standard ASCII)
0E (14) - Set column 0 to 79 (2nd byte is the column number) or 0 to 39 for a 40 char line
0F (16) - Set row 0 to 24 (2nd byte is the row number)
1B (27) - ESC - reserved for ANSI sequences
vasm include part:
message:
.db 0x01,0x0c ; home and clear
.db 0x1b,0x2d ; disable ansi translation
include "out" ; include hex "png"
.db 0x00 ; end with 0 (part of message print routine)
01 (01) - Cursor home (Standard ASCII) 04 (04) - Cursor solid 05 (05) - Set graphics pixel (next two bytes = x,y) 0C (12) - Clear screen (Standard ASCII) 0D (13) - Carriage return (Standard ASCII) 0E (14) - Set column 0 to 79 (2nd byte is the column number) or 0 to 39 for a 40 char line 0F (16) - Set row 0 to 24 (2nd byte is the row number) 1B (27) - ESC - reserved for ANSI sequences vasm include part: message: .db 0x01,0x0c ; home and clear .db 0x1b,0x2d ; disable ansi translation include "out" ; include hex "png" .db 0x00 ; end with 0 (part of message print routine)
01 (01) - Cursor home (Standard ASCII)
04 (04) - Cursor solid
05 (05) - Set graphics pixel (next two bytes = x,y) 
0C (12) - Clear screen (Standard ASCII)
0D (13) - Carriage return (Standard ASCII)
0E (14) - Set column 0 to 79 (2nd byte is the column number) or 0 to 39 for a 40 char line
0F (16) - Set row 0 to 24 (2nd byte is the row number)
1B (27) - ESC - reserved for ANSI sequences

vasm include part:

message: 
	.db 0x01,0x0c   ; home and clear
	.db 0x1b,0x2d   ; disable ansi translation
	include "out"   ; include hex "png"
	.db 0x00        ; end with 0 (part of message print routine)



I asked ChatGPT to write code for a Crack the Code game.

The Game

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
elcome to Crack the Code!
The code has 4 digits. Each digit is between 0 and 9.
You have 10 tries to guess the code.
After each guess, you will be told how many digits you got correct and how many were misplaced.
Good luck!
Enter your guess: 1234
Guess 1: 1234 - 0 correct, 0 misplaced
Enter your guess: 5678
Guess 2: 5678 - 2 correct, 1 misplaced
Enter your guess: 5689
Guess 3: 5689 - 1 correct, 2 misplaced
Enter your guess: 9688
Guess 4: 9688 - 1 correct, 2 misplaced
....
Sorry, you did not crack the code. The code was 5568.
elcome to Crack the Code! The code has 4 digits. Each digit is between 0 and 9. You have 10 tries to guess the code. After each guess, you will be told how many digits you got correct and how many were misplaced. Good luck! Enter your guess: 1234 Guess 1: 1234 - 0 correct, 0 misplaced Enter your guess: 5678 Guess 2: 5678 - 2 correct, 1 misplaced Enter your guess: 5689 Guess 3: 5689 - 1 correct, 2 misplaced Enter your guess: 9688 Guess 4: 9688 - 1 correct, 2 misplaced .... Sorry, you did not crack the code. The code was 5568.
elcome to Crack the Code!
The code has 4 digits. Each digit is between 0 and 9.
You have 10 tries to guess the code.
After each guess, you will be told how many digits you got correct and how many were misplaced.
Good luck!
Enter your guess: 1234
Guess 1: 1234 - 0 correct, 0 misplaced
Enter your guess: 5678
Guess 2: 5678 - 2 correct, 1 misplaced
Enter your guess: 5689
Guess 3: 5689 - 1 correct, 2 misplaced
Enter your guess: 9688 
Guess 4: 9688 - 1 correct, 2 misplaced
....
Sorry, you did not crack the code. The code was 5568.

Generated python code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import random
def generate_code():
code = ""
for i in range(4):
code += str(random.randint(0, 9))
return code
def check_guess(code, guess):
correct_digits = 0
misplaced_digits = 0
for i in range(4):
if guess[i] == code[i]:
correct_digits += 1
elif guess[i] in code:
misplaced_digits += 1
return (correct_digits, misplaced_digits)
def play_game():
print("Welcome to Crack the Code!")
print("The code has 4 digits. Each digit is between 0 and 9.")
print("You have 10 tries to guess the code.")
print("After each guess, you will be told how many digits you got correct and how many were misplaced.")
print("Good luck!")
code = generate_code()
num_guesses = 0
while num_guesses < 10:
guess = input("Enter your guess: ")
if len(guess) != 4 or not guess.isdigit():
print("Invalid input. Please enter a 4-digit number.")
continue
num_guesses += 1
correct, misplaced = check_guess(code, guess)
print(f"Guess {num_guesses}: {guess} - {correct} correct, {misplaced} misplaced")
if correct == 4:
print("Congratulations! You cracked the code!")
return
print(f"Sorry, you did not crack the code. The code was {code}.")
play_game()
import random def generate_code(): code = "" for i in range(4): code += str(random.randint(0, 9)) return code def check_guess(code, guess): correct_digits = 0 misplaced_digits = 0 for i in range(4): if guess[i] == code[i]: correct_digits += 1 elif guess[i] in code: misplaced_digits += 1 return (correct_digits, misplaced_digits) def play_game(): print("Welcome to Crack the Code!") print("The code has 4 digits. Each digit is between 0 and 9.") print("You have 10 tries to guess the code.") print("After each guess, you will be told how many digits you got correct and how many were misplaced.") print("Good luck!") code = generate_code() num_guesses = 0 while num_guesses < 10: guess = input("Enter your guess: ") if len(guess) != 4 or not guess.isdigit(): print("Invalid input. Please enter a 4-digit number.") continue num_guesses += 1 correct, misplaced = check_guess(code, guess) print(f"Guess {num_guesses}: {guess} - {correct} correct, {misplaced} misplaced") if correct == 4: print("Congratulations! You cracked the code!") return print(f"Sorry, you did not crack the code. The code was {code}.") play_game()
import random

def generate_code():
    code = ""
    for i in range(4):
        code += str(random.randint(0, 9))
    return code

def check_guess(code, guess):
    correct_digits = 0
    misplaced_digits = 0
    for i in range(4):
        if guess[i] == code[i]:
            correct_digits += 1
        elif guess[i] in code:
            misplaced_digits += 1
    return (correct_digits, misplaced_digits)

def play_game():
    print("Welcome to Crack the Code!")
    print("The code has 4 digits. Each digit is between 0 and 9.")
    print("You have 10 tries to guess the code.")
    print("After each guess, you will be told how many digits you got correct and how many were misplaced.")
    print("Good luck!")
    code = generate_code()
    num_guesses = 0
    while num_guesses < 10:
        guess = input("Enter your guess: ")
        if len(guess) != 4 or not guess.isdigit():
            print("Invalid input. Please enter a 4-digit number.")
            continue
        num_guesses += 1
        correct, misplaced = check_guess(code, guess)
        print(f"Guess {num_guesses}: {guess} - {correct} correct, {misplaced} misplaced")
        if correct == 4:
            print("Congratulations! You cracked the code!")
            return
    print(f"Sorry, you did not crack the code. The code was {code}.")

play_game()

After this i let the AI made some changes, which kinda worked.
Scary nevertheless

Python Baudot code for Wemos Matrix Led

I wrote a python script to generate binary data to include in my Arduino sketch.
This Arduino displays codes send though MQTT.

https://en.wikipedia.org/wiki/Baudot_code

CODE:

python3 matrix.py apple gives me

byte apple_Char[8] = {
  0b00000000,
  0b01000100,
  0b01111000,
  0b00000000,
  0b00110000,
  0b00000000,
  0b00111000,
  0b00000000
};

Python Code
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import sys
a = [
[0,0,0,0,0,0,0,0 ],
[0,0,0,0,0,0,0,0 ],
[0,0,0,0,0,0,0,0 ],
[0,0,0,0,0,0,0,0 ],
[0,0,0,0,0,0,0,0 ],
[0,0,0,0,0,0,0,0 ],
[0,0,0,0,0,0,0,0 ],
[0,0,0,0,0,0,0,0 ]
]
letters = [
[0,1,1,0,0,0,0,0 ],
[0,1,0,0,0,1,1,0 ],
[0,0,1,0,1,1,0,0 ],
[0,1,0,0,0,1,0,0 ],
[0,1,0,0,0,0,0,0 ],
[0,1,0,0,1,1,0,0 ],
[0,0,1,0,0,1,1,0 ],
[0,0,0,0,1,0,1,0 ],
[0,0,1,0,1,0,0,0 ],
[0,1,1,0,0,1,0,0 ],
[0,1,1,0,1,1,0,0 ],
[0,0,1,0,0,0,1,0 ],
[0,0,0,0,1,1,1,0 ],
[0,0,0,0,1,1,0,0 ],
[0,0,0,0,0,1,1,0 ],
[0,0,1,0,1,0,1,0 ],
[0,1,1,0,1,0,1,0 ],
[0,0,1,0,0,1,0,0 ],
[0,1,0,0,1,0,0,0 ],
[0,0,0,0,0,0,1,0 ],
[0,1,1,0,1,0,0,0 ],
[0,0,1,0,1,1,1,0 ],
[0,1,1,0,0,0,1,0 ],
[0,1,0,0,1,1,1,0 ],
[0,1,0,0,1,0,1,0 ],
[0,1,0,0,0,0,1,0 ]
]
number=0
word=str(sys.argv[1])
for col in range(len(word)) :
character=word[col]
number = ord(character) - 97
nextcol = col + 1
for row in range(len(a[col])) :
a[row][nextcol] = letters[number][row]
print("byte " + word + "_Char[8] = {")
for i in range(len(a)) :
print(" 0b", end = '')
for j in range(len(a[i])) :
print(a[i][j], end="")
if i < 7:
print(",")
print()
print("};")
import sys a = [ [0,0,0,0,0,0,0,0 ], [0,0,0,0,0,0,0,0 ], [0,0,0,0,0,0,0,0 ], [0,0,0,0,0,0,0,0 ], [0,0,0,0,0,0,0,0 ], [0,0,0,0,0,0,0,0 ], [0,0,0,0,0,0,0,0 ], [0,0,0,0,0,0,0,0 ] ] letters = [ [0,1,1,0,0,0,0,0 ], [0,1,0,0,0,1,1,0 ], [0,0,1,0,1,1,0,0 ], [0,1,0,0,0,1,0,0 ], [0,1,0,0,0,0,0,0 ], [0,1,0,0,1,1,0,0 ], [0,0,1,0,0,1,1,0 ], [0,0,0,0,1,0,1,0 ], [0,0,1,0,1,0,0,0 ], [0,1,1,0,0,1,0,0 ], [0,1,1,0,1,1,0,0 ], [0,0,1,0,0,0,1,0 ], [0,0,0,0,1,1,1,0 ], [0,0,0,0,1,1,0,0 ], [0,0,0,0,0,1,1,0 ], [0,0,1,0,1,0,1,0 ], [0,1,1,0,1,0,1,0 ], [0,0,1,0,0,1,0,0 ], [0,1,0,0,1,0,0,0 ], [0,0,0,0,0,0,1,0 ], [0,1,1,0,1,0,0,0 ], [0,0,1,0,1,1,1,0 ], [0,1,1,0,0,0,1,0 ], [0,1,0,0,1,1,1,0 ], [0,1,0,0,1,0,1,0 ], [0,1,0,0,0,0,1,0 ] ] number=0 word=str(sys.argv[1]) for col in range(len(word)) : character=word[col] number = ord(character) - 97 nextcol = col + 1 for row in range(len(a[col])) : a[row][nextcol] = letters[number][row] print("byte " + word + "_Char[8] = {") for i in range(len(a)) : print(" 0b", end = '') for j in range(len(a[i])) : print(a[i][j], end="") if i < 7: print(",") print() print("};")
import sys

a = [ 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ] 
    ] 

letters = [
        [0,1,1,0,0,0,0,0 ],
        [0,1,0,0,0,1,1,0 ],
        [0,0,1,0,1,1,0,0 ],
        [0,1,0,0,0,1,0,0 ],
        [0,1,0,0,0,0,0,0 ],
        [0,1,0,0,1,1,0,0 ],
        [0,0,1,0,0,1,1,0 ],
        [0,0,0,0,1,0,1,0 ],
        [0,0,1,0,1,0,0,0 ],
        [0,1,1,0,0,1,0,0 ],
        [0,1,1,0,1,1,0,0 ],
        [0,0,1,0,0,0,1,0 ],
        [0,0,0,0,1,1,1,0 ],
        [0,0,0,0,1,1,0,0 ],
        [0,0,0,0,0,1,1,0 ],
        [0,0,1,0,1,0,1,0 ],
        [0,1,1,0,1,0,1,0 ],
        [0,0,1,0,0,1,0,0 ],
        [0,1,0,0,1,0,0,0 ],
        [0,0,0,0,0,0,1,0 ],
        [0,1,1,0,1,0,0,0 ],
        [0,0,1,0,1,1,1,0 ],
        [0,1,1,0,0,0,1,0 ],
        [0,1,0,0,1,1,1,0 ],
        [0,1,0,0,1,0,1,0 ],
        [0,1,0,0,0,0,1,0 ]
        ]

number=0
word=str(sys.argv[1])

for col in range(len(word)) :
    character=word[col]

    number = ord(character) - 97
    nextcol = col + 1
    for row in range(len(a[col])) :
        a[row][nextcol] = letters[number][row]


print("byte " + word + "_Char[8] = {")
for i in range(len(a)) : 
    print("  0b", end = '')
    for j in range(len(a[i])) : 
        print(a[i][j], end="")   
    if i < 7:
        print(",")
print()
print("};")

Arduino test code

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClient.h>
#include "WEMOS_Matrix_LED.h"
MLED mled(5); //set intensity=5
const char* wifi_ssid = "MYSSID"; // Enter your WiFi name
const char* wifi_password = "MYSSIDPASS"; // Enter WiFi password
const char* mqtt_server = "MYMQTTSERVER";
const int mqtt_port = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
WiFiClient espClient;
PubSubClient mqtt(espClient);
void setup_wifi() {
delay(10);
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
byte clear_Char[8] = {
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000,
0b00000000
};
byte baudot_Char[8] = {
0b11111111,
0b01101010,
0b00011100,
0b11111111,
0b00110100,
0b00010000,
0b00000100,
0b11111111
};
#define TIME 500
void setup() {
Serial.begin(115200);
setup_wifi();
mqtt.setServer(mqtt_server, mqtt_port);
WiFiClient espClient;
PubSubClient mqtt(espClient);
mqtt.setClient(espClient);
mqtt.setServer(mqtt_server, mqtt_port);
delay(500);
mqtt.subscribe("escape/matrixledin");
delay(500);
mqtt.setCallback(callback);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println("callback");
String topicStr = topic;
byte value = atoi((char*)payload);
snprintf (msg, MSG_BUFFER_SIZE, "%1d", value);
mqtt.publish("escape/matrixledout", msg);
if (value == 1){
drawChar(baudot_Char);
}else if (value == 0){
drawChar(cleat_Char);
}else if (value == 2){
drawChar(test_Char);
}else if (value == 3){
drawChar(no_Char);
}
}
void reconnect() {
while (!mqtt.connected()) {
String clientId = "matrixClient-";
clientId += String(random(0xffff), HEX);
if (mqtt.connect(clientId.c_str())) {
mqtt.publish("escape/outTopic", "hello from 8x8led module");
Serial.println("resubscribe");
mqtt.subscribe("escape/matrixledin");
mqtt.setCallback(callback);
} else {
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!mqtt.connected()) {
Serial.println("reconnect called");
reconnect();
}
mqtt.loop();
}
void drawChar(byte character[8]) {
for(int y=7;y>=0;y--) {
for (int x=0; x <= 7; x++) {
if (character[(7-y)] & (B10000000 >> x)) {
mled.dot(x,y); // draw dot
} else {
mled.dot(x,y,0);//clear dot
}
}
mled.display();
}
}
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include <WiFiClient.h> #include "WEMOS_Matrix_LED.h" MLED mled(5); //set intensity=5 const char* wifi_ssid = "MYSSID"; // Enter your WiFi name const char* wifi_password = "MYSSIDPASS"; // Enter WiFi password const char* mqtt_server = "MYMQTTSERVER"; const int mqtt_port = 1883; const char* mqttUser = ""; const char* mqttPassword = ""; #define MSG_BUFFER_SIZE (50) char msg[MSG_BUFFER_SIZE]; int value = 0; WiFiClient espClient; PubSubClient mqtt(espClient); void setup_wifi() { delay(10); WiFi.mode(WIFI_STA); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(500); } } byte clear_Char[8] = { 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000, 0b00000000 }; byte baudot_Char[8] = { 0b11111111, 0b01101010, 0b00011100, 0b11111111, 0b00110100, 0b00010000, 0b00000100, 0b11111111 }; #define TIME 500 void setup() { Serial.begin(115200); setup_wifi(); mqtt.setServer(mqtt_server, mqtt_port); WiFiClient espClient; PubSubClient mqtt(espClient); mqtt.setClient(espClient); mqtt.setServer(mqtt_server, mqtt_port); delay(500); mqtt.subscribe("escape/matrixledin"); delay(500); mqtt.setCallback(callback); } void callback(char* topic, byte* payload, unsigned int length) { Serial.println("callback"); String topicStr = topic; byte value = atoi((char*)payload); snprintf (msg, MSG_BUFFER_SIZE, "%1d", value); mqtt.publish("escape/matrixledout", msg); if (value == 1){ drawChar(baudot_Char); }else if (value == 0){ drawChar(cleat_Char); }else if (value == 2){ drawChar(test_Char); }else if (value == 3){ drawChar(no_Char); } } void reconnect() { while (!mqtt.connected()) { String clientId = "matrixClient-"; clientId += String(random(0xffff), HEX); if (mqtt.connect(clientId.c_str())) { mqtt.publish("escape/outTopic", "hello from 8x8led module"); Serial.println("resubscribe"); mqtt.subscribe("escape/matrixledin"); mqtt.setCallback(callback); } else { // Wait 5 seconds before retrying delay(5000); } } } void loop() { if (!mqtt.connected()) { Serial.println("reconnect called"); reconnect(); } mqtt.loop(); } void drawChar(byte character[8]) { for(int y=7;y>=0;y--) { for (int x=0; x <= 7; x++) { if (character[(7-y)] & (B10000000 >> x)) { mled.dot(x,y); // draw dot } else { mled.dot(x,y,0);//clear dot } } mled.display(); } }
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClient.h>


#include "WEMOS_Matrix_LED.h"
MLED mled(5); //set intensity=5

const char* wifi_ssid = "MYSSID"; // Enter your WiFi name
const char* wifi_password =  "MYSSIDPASS"; // Enter WiFi password
const char* mqtt_server = "MYMQTTSERVER";
const int mqtt_port = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

WiFiClient espClient;

PubSubClient mqtt(espClient);

void setup_wifi() {
  delay(10);
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}
 
byte clear_Char[8] = {  
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000
};
 
byte baudot_Char[8] = {
  0b11111111,
  0b01101010,
  0b00011100,
  0b11111111,
  0b00110100,
  0b00010000,
  0b00000100,
  0b11111111  
};
 

 
#define TIME 500
 
void setup() { 
    Serial.begin(115200);
      setup_wifi();
        mqtt.setServer(mqtt_server, mqtt_port);

WiFiClient espClient;
PubSubClient mqtt(espClient);

  mqtt.setClient(espClient);
  mqtt.setServer(mqtt_server, mqtt_port);
      delay(500);

  mqtt.subscribe("escape/matrixledin");
        delay(500);

  mqtt.setCallback(callback);

  }

void callback(char* topic, byte* payload, unsigned int length) {
        Serial.println("callback");
    String topicStr = topic;
      byte value = atoi((char*)payload);
        snprintf (msg, MSG_BUFFER_SIZE, "%1d", value);

              mqtt.publish("escape/matrixledout", msg);
       if (value == 1){

drawChar(baudot_Char); 

 }else if (value == 0){
  drawChar(cleat_Char); 
  }else if (value == 2){
  drawChar(test_Char); 
  }else if (value == 3){
  drawChar(no_Char); 
 }
 }

void reconnect() {

  while (!mqtt.connected()) {
    String clientId = "matrixClient-";
    clientId += String(random(0xffff), HEX);
    if (mqtt.connect(clientId.c_str())) {
      mqtt.publish("escape/outTopic", "hello from 8x8led module");
                Serial.println("resubscribe");

      mqtt.subscribe("escape/matrixledin");
        mqtt.setCallback(callback);

    } else {
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
 
void loop() {

 if (!mqtt.connected()) {
          Serial.println("reconnect called");
    reconnect();
  }
    mqtt.loop();

}
 
void drawChar(byte character[8]) {
  for(int y=7;y>=0;y--) {
  for (int x=0; x <= 7; x++) { 
    if (character[(7-y)] & (B10000000 >> x)) {
     mled.dot(x,y); // draw dot
    } else {
     mled.dot(x,y,0);//clear dot
    }
  }
  mled.display();  
  }
}

Playing with lasercutter steppermotors

Busy day: I’ve airbrushed some 3D pieces a few days ago, but i need 50 or so more.
Meanwhile is was reinstalling octoprint, and making a new version of my Bluetooth page flipper. (Android Music Sheet Pedal Thingy. Which i also didn’t post apparently)
But the main project was this:

I was curious how fast the stepper motors are on my laser cutter. And for what can we utilize this!

So I took a Raspberry Zero and some rotary encoders, lets make an etch-a-sketch like thingy.


Some rotary encoder modules I had.

Next to do: 3D print a pen holder, and alter the code to enable the laser when moving!

CODE

Below code uses a simple rotary class, and generates control GCodes for the steppers/Sculpfun

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import time
import serial
import RPi.GPIO as GPIO
from encoder import Encoder
def valueChanged(value, direction):
print("* New value: {}, Direction: {}".format(value, direction))
GPIO.setmode(GPIO.BCM)
e1 = Encoder(20, 21, valueChanged)
e2 = Encoder(16, 12, valueChanged)
x = 0
y = 0
arduino = serial.Serial('/dev/ttyUSB0', 115200, timeout=.1)
newx = 0
mystringx = ""
newy = 0
mystringy = ""
arduino.write(str.encode("G00 G17 G40 G21 G54\r\n"))
arduino.write(str.encode('G90\r\n'))
arduino.write(str.encode('M4\r\n'))
arduino.write(str.encode('M8\r\n'))
arduino.write(str.encode('G0 X41.5Y36.05\r\n'))
arduino.write(str.encode('M3\r\n'))
#arduino.write(str.encode('G91\r\n'))
arduino.write(str.encode('G1 X2.5F6000S0\r\n'))
arduino.write(str.encode('G1 X0\r\n'))
arduino.write(str.encode('G1 Y0\r\n'))
try:
while True:
data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars
if data:
print (data)
arduino.write(str.encode("G1 F10000\r\n"))
newx=e1.getValue() *5 + 100
newy=e2.getValue() *5 + 100
mystringx=f"G1 X{newx}\r\n"
mystringy=f"G1 Y{newy}\r\n"
# print(mystringx)
arduino.write(str.encode(mystringx))
arduino.write(str.encode(mystringy))
except Exception:
pass
GPIO.cleanup()
import time import serial import RPi.GPIO as GPIO from encoder import Encoder def valueChanged(value, direction): print("* New value: {}, Direction: {}".format(value, direction)) GPIO.setmode(GPIO.BCM) e1 = Encoder(20, 21, valueChanged) e2 = Encoder(16, 12, valueChanged) x = 0 y = 0 arduino = serial.Serial('/dev/ttyUSB0', 115200, timeout=.1) newx = 0 mystringx = "" newy = 0 mystringy = "" arduino.write(str.encode("G00 G17 G40 G21 G54\r\n")) arduino.write(str.encode('G90\r\n')) arduino.write(str.encode('M4\r\n')) arduino.write(str.encode('M8\r\n')) arduino.write(str.encode('G0 X41.5Y36.05\r\n')) arduino.write(str.encode('M3\r\n')) #arduino.write(str.encode('G91\r\n')) arduino.write(str.encode('G1 X2.5F6000S0\r\n')) arduino.write(str.encode('G1 X0\r\n')) arduino.write(str.encode('G1 Y0\r\n')) try: while True: data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars if data: print (data) arduino.write(str.encode("G1 F10000\r\n")) newx=e1.getValue() *5 + 100 newy=e2.getValue() *5 + 100 mystringx=f"G1 X{newx}\r\n" mystringy=f"G1 Y{newy}\r\n" # print(mystringx) arduino.write(str.encode(mystringx)) arduino.write(str.encode(mystringy)) except Exception: pass GPIO.cleanup()
import time
import serial
import RPi.GPIO as GPIO
from encoder import Encoder

def valueChanged(value, direction):
    print("* New value: {}, Direction: {}".format(value, direction))

GPIO.setmode(GPIO.BCM)

e1 = Encoder(20, 21, valueChanged)
e2 = Encoder(16, 12, valueChanged)

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

newx = 0
mystringx = ""
newy = 0
mystringy = ""

arduino.write(str.encode("G00 G17 G40 G21 G54\r\n"))
arduino.write(str.encode('G90\r\n'))
arduino.write(str.encode('M4\r\n'))
arduino.write(str.encode('M8\r\n'))
arduino.write(str.encode('G0 X41.5Y36.05\r\n'))
arduino.write(str.encode('M3\r\n'))
#arduino.write(str.encode('G91\r\n'))
arduino.write(str.encode('G1 X2.5F6000S0\r\n'))
arduino.write(str.encode('G1 X0\r\n'))
arduino.write(str.encode('G1 Y0\r\n'))

try:
    while True:
        data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars
        if data:
                print (data)
        arduino.write(str.encode("G1 F10000\r\n"))
        newx=e1.getValue() *5 + 100
        newy=e2.getValue() *5 + 100
        mystringx=f"G1 X{newx}\r\n"
        mystringy=f"G1 Y{newy}\r\n"
#        print(mystringx)
        arduino.write(str.encode(mystringx))
        arduino.write(str.encode(mystringy))

except Exception:
    pass

GPIO.cleanup()

Movie to txt in dutch

In the past i’ve converted some VHS movies speech to text, using all kinds of tools.
Lets use some opensource tools!

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install moviepy
pip install SpeechRecognition
pip install moviepy pip install SpeechRecognition
pip install moviepy
pip install SpeechRecognition

Create a python script with the following:
(Called mine wav2txt.py)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import math, contextlib
import speech_recognition as sr
from moviepy.editor import AudioFileClip
movie_audio_file_name = "movieadiofile.wav"
with contextlib.closing(wave.open(movie_audio_file_name,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
total_duration = math.ceil(duration / 60)
r = sr.Recognizer()
for i in range(0, total_duration):
with sr.AudioFile(movie_audio_file_name) as source:
audio = r.record(source, offset=i*60, duration=60)
f = open("transcription.txt", "a")
f.write(r.recognize_google(audio, language="nl-NL"))
f.write(" ")
f.close()
import math, contextlib import speech_recognition as sr from moviepy.editor import AudioFileClip movie_audio_file_name = "movieadiofile.wav" with contextlib.closing(wave.open(movie_audio_file_name,'r')) as f: frames = f.getnframes() rate = f.getframerate() duration = frames / float(rate) total_duration = math.ceil(duration / 60) r = sr.Recognizer() for i in range(0, total_duration): with sr.AudioFile(movie_audio_file_name) as source: audio = r.record(source, offset=i*60, duration=60) f = open("transcription.txt", "a") f.write(r.recognize_google(audio, language="nl-NL")) f.write(" ") f.close()
import math, contextlib
import speech_recognition as sr
from moviepy.editor import AudioFileClip
movie_audio_file_name = "movieadiofile.wav"
with contextlib.closing(wave.open(movie_audio_file_name,'r')) as f:
    frames = f.getnframes()
    rate = f.getframerate()
    duration = frames / float(rate)
total_duration = math.ceil(duration / 60)
r = sr.Recognizer()
for i in range(0, total_duration):
    with sr.AudioFile(movie_audio_file_name) as source:
        audio = r.record(source, offset=i*60, duration=60)
    f = open("transcription.txt", "a")
    f.write(r.recognize_google(audio, language="nl-NL"))
    f.write(" ")
f.close()

Now convert a movie to wav using below.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ffmpeg -i /fileserver/path/koolhoven.mkv movieaudiofile.wav
ffmpeg -i /fileserver/path/koolhoven.mkv movieaudiofile.wav
ffmpeg -i /fileserver/path/koolhoven.mkv movieaudiofile.wav

run python3 wav2txt.py

output
(Note .. these are not timestamped for subtitles)
I only needed the things being said in the home movie recordings as text.

Ik zit hier in de film The James Dean aan de
wereld voorstelde en daarmee de tienerfilm ingeleverd introduceren zelden werden onrustige 10 asiel zo mooi blootgelegd als ik deze film van Nicolas bij en dat wordt dan meteen toevallig even de mooiste
titels ooit wel eens autocross vanavond kijken we naar de kom ik nog even veel zomer dat je voor het eerste meisje Zoem de eerste baantje

etc..

Raspberry Zero with display

I’ve installed a headless Raspbian on a Pi Zero with a 2×16 Chars lcd display. As part of the Escape Room over the internet

Using the raspberry imager:
I’ve set the username/password and ssh access in this tool.
For wifi access i’ve placed below file on the SDcard in /boot
(You can do this in the tool, but i want to make this dynamic when connected at a remote site.)
file: wpa_supplicant.conf

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
country=NL
update_config=1
ctrl_interface=/var/run/wpa_supplicant
network={
scan_ssid=1
ssid="MYSSID"
psk="MYSSIDPASS"
}
country=NL update_config=1 ctrl_interface=/var/run/wpa_supplicant network={ scan_ssid=1 ssid="MYSSID" psk="MYSSIDPASS" }
country=NL
update_config=1
ctrl_interface=/var/run/wpa_supplicant

network={
 scan_ssid=1
 ssid="MYSSID"
 psk="MYSSIDPASS"
}

ssh into the RPi

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sudo raspi-config
Interface options and enable I2C
sudo apt-get install python3-smbus
wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/RPi_I2C_driver.py
and
wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/examples.py
For python3 edit the example and put at the top
# requires RPi_I2C_driver.py
import RPi_I2C_driver
from time import *
unichr = chr
Run with
python3 examples.py
sudo raspi-config Interface options and enable I2C sudo apt-get install python3-smbus wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/RPi_I2C_driver.py and wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/examples.py For python3 edit the example and put at the top # requires RPi_I2C_driver.py import RPi_I2C_driver from time import * unichr = chr Run with python3 examples.py
sudo raspi-config
Interface options and enable I2C

sudo apt-get install python3-smbus

wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/RPi_I2C_driver.py
and 
wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/examples.py

For python3 edit the example and put at the top

# requires RPi_I2C_driver.py
import RPi_I2C_driver
from time import *
unichr = chr

Run with 
python3 examples.py
lcd display with i2c backpack
I2C backpack

Below is a mockup session.

Next todo:

  • Add more hardware (like buttons) to the RPI
  • Configure an Accesspoint on this Rpi for other devices to connect to
  • Install a local Mqtt broker, which connects secure to my internet facing broker
Setup example

Radar module RCWL-0516 with MQTT

RCWL-0516 module (radar)

Last year i was playing with this radar module also, but today i made a version with MQTT and a linux client.
(There is a project on the internet which uses a HC-SR04, and a arduino connected to the Laptop. This setup is more sensitive and no need for a usb thinghy.)

HC-SR04 module (ultrasound)

Last years version, using a micro transformer and a ESP-12

When using MQTT i can integrate this in HomeAssistant, Domoticz, NodeRed and more.
But i’ve written a python script which runs on my Laptop.
For example i can: Kill vlc, change to my work desktop, stop sound output and lock the screen. (everything you can script)

I wanted to have a “mobile” version of the sensor so i can place it anywhere. (Frontdoor, gardengate, candydrawer 🙂 )

These modules are very cheap, but do their job well!

I’ve used a Wroom ESP32 and a BattBorg together with the module, that’s it.

Simplified schematic (without the battborg)

I’m using PIN34 as an analog input.

Radar module pins:

  • CDS not used
  • VIN 5V power
  • OUT 0-3.3V signal (analog)
  • GND
  • 3v3 not used

Arduino sketch

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
const char* ssid = "MYSSID";
const char* password = "MYPASS";
const char* mqtt_server = "IP-MQTT-SERVER";
const char* mqtt_username = "";
const char* mqtt_password = "";
const char* clientID = "radar";
const int tiltPin = 34;
int tiltState = 0;
int previousState = 0;
WiFiClient espClient;
PubSubClient client(espClient);
String translateEncryptionType(wifi_auth_mode_t encryptionType) {
switch (encryptionType) {
case (WIFI_AUTH_OPEN):
return "Open";
case (WIFI_AUTH_WEP):
return "WEP";
case (WIFI_AUTH_WPA_PSK):
return "WPA_PSK";
case (WIFI_AUTH_WPA2_PSK):
return "WPA2_PSK";
case (WIFI_AUTH_WPA_WPA2_PSK):
return "WPA_WPA2_PSK";
case (WIFI_AUTH_WPA2_ENTERPRISE):
return "WPA2_ENTERPRISE";
}
}
void scanNetworks() {
int numberOfNetworks = WiFi.scanNetworks();
Serial.print("Number of networks found: ");
Serial.println(numberOfNetworks);
for (int i = 0; i < numberOfNetworks; i++) {
Serial.print("Network name: ");
Serial.println(WiFi.SSID(i));
Serial.print("Signal strength: ");
Serial.println(WiFi.RSSI(i));
Serial.print("MAC address: ");
Serial.println(WiFi.BSSIDstr(i));
Serial.print("Encryption type: ");
String encryptionTypeDescription = translateEncryptionType(WiFi.encryptionType(i));
Serial.println(encryptionTypeDescription);
Serial.println("-----------------------");
}
}
void connectToNetwork() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Establishing connection to WiFi..");
}
Serial.println("Connected to network");
}
void reconnect() {
while (!client.connected()) {
if (client.connect(clientID, mqtt_username, mqtt_password)) {
} else {
delay(2000);
}
}
}
void setup()
{
{
Serial.begin(115200);
scanNetworks();
connectToNetwork();
Serial.println(WiFi.macAddress());
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
pinMode(tiltPin, INPUT);
}
}
void loop() {
tiltState = analogRead(tiltPin);
if (tiltState < 3048) {
client.publish("radar/state", "0"); //
} else {
client.publish("radar/state", "1"); //
}
delay(100);
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
}
#include <WiFi.h> #include <PubSubClient.h> #include <Wire.h> const char* ssid = "MYSSID"; const char* password = "MYPASS"; const char* mqtt_server = "IP-MQTT-SERVER"; const char* mqtt_username = ""; const char* mqtt_password = ""; const char* clientID = "radar"; const int tiltPin = 34; int tiltState = 0; int previousState = 0; WiFiClient espClient; PubSubClient client(espClient); String translateEncryptionType(wifi_auth_mode_t encryptionType) { switch (encryptionType) { case (WIFI_AUTH_OPEN): return "Open"; case (WIFI_AUTH_WEP): return "WEP"; case (WIFI_AUTH_WPA_PSK): return "WPA_PSK"; case (WIFI_AUTH_WPA2_PSK): return "WPA2_PSK"; case (WIFI_AUTH_WPA_WPA2_PSK): return "WPA_WPA2_PSK"; case (WIFI_AUTH_WPA2_ENTERPRISE): return "WPA2_ENTERPRISE"; } } void scanNetworks() { int numberOfNetworks = WiFi.scanNetworks(); Serial.print("Number of networks found: "); Serial.println(numberOfNetworks); for (int i = 0; i < numberOfNetworks; i++) { Serial.print("Network name: "); Serial.println(WiFi.SSID(i)); Serial.print("Signal strength: "); Serial.println(WiFi.RSSI(i)); Serial.print("MAC address: "); Serial.println(WiFi.BSSIDstr(i)); Serial.print("Encryption type: "); String encryptionTypeDescription = translateEncryptionType(WiFi.encryptionType(i)); Serial.println(encryptionTypeDescription); Serial.println("-----------------------"); } } void connectToNetwork() { WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Establishing connection to WiFi.."); } Serial.println("Connected to network"); } void reconnect() { while (!client.connected()) { if (client.connect(clientID, mqtt_username, mqtt_password)) { } else { delay(2000); } } } void setup() { { Serial.begin(115200); scanNetworks(); connectToNetwork(); Serial.println(WiFi.macAddress()); Serial.println(WiFi.localIP()); client.setServer(mqtt_server, 1883); pinMode(tiltPin, INPUT); } } void loop() { tiltState = analogRead(tiltPin); if (tiltState < 3048) { client.publish("radar/state", "0"); // } else { client.publish("radar/state", "1"); // } delay(100); { if (!client.connected()) { reconnect(); } client.loop(); } }
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>

const char* ssid = "MYSSID";
const char* password = "MYPASS";
const char* mqtt_server = "IP-MQTT-SERVER";
const char* mqtt_username = "";
const char* mqtt_password = "";
const char* clientID = "radar";

const int tiltPin = 34;
int tiltState = 0;    
int previousState = 0;   

WiFiClient espClient;

PubSubClient client(espClient);

String translateEncryptionType(wifi_auth_mode_t encryptionType) {
 
  switch (encryptionType) {
    case (WIFI_AUTH_OPEN):
      return "Open";
    case (WIFI_AUTH_WEP):
      return "WEP";
    case (WIFI_AUTH_WPA_PSK):
      return "WPA_PSK";
    case (WIFI_AUTH_WPA2_PSK):
      return "WPA2_PSK";
    case (WIFI_AUTH_WPA_WPA2_PSK):
      return "WPA_WPA2_PSK";
    case (WIFI_AUTH_WPA2_ENTERPRISE):
      return "WPA2_ENTERPRISE";
  }
}
 
void scanNetworks() {
   int numberOfNetworks = WiFi.scanNetworks();
   Serial.print("Number of networks found: ");
  Serial.println(numberOfNetworks);
   for (int i = 0; i < numberOfNetworks; i++) {
 
    Serial.print("Network name: ");
    Serial.println(WiFi.SSID(i));
 
    Serial.print("Signal strength: ");
    Serial.println(WiFi.RSSI(i));
 
    Serial.print("MAC address: ");
    Serial.println(WiFi.BSSIDstr(i));
 
    Serial.print("Encryption type: ");
    String encryptionTypeDescription = translateEncryptionType(WiFi.encryptionType(i));
    Serial.println(encryptionTypeDescription);
    Serial.println("-----------------------");
 
  }
}
 
void connectToNetwork() {
  WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Establishing connection to WiFi..");
  }
   Serial.println("Connected to network");
 }

void reconnect() {
  while (!client.connected()) {
    if (client.connect(clientID, mqtt_username, mqtt_password)) {
    } else {
      delay(2000);
    }
  }
}
void setup()
{
  {
    Serial.begin(115200);
    scanNetworks();
    connectToNetwork();
    Serial.println(WiFi.macAddress());
    Serial.println(WiFi.localIP());
    client.setServer(mqtt_server, 1883);
    pinMode(tiltPin, INPUT);
  }
}
void loop() {
  tiltState = analogRead(tiltPin);
    if (tiltState < 3048) {
      client.publish("radar/state", "0"); //
    } else {
      client.publish("radar/state", "1"); //
    }
     delay(100);
   {
    if (!client.connected()) {
      reconnect();
    }
    client.loop();
  }
}

Lockscreen!

Below shows the speed of detection, and sending though the network

Python script which does a lock-screen using XDOTOOL

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from paho.mqtt import client as mqtt_client
import subprocess
import time
broker = 'MQTT-SERVER'
port = 1883
topic = "radar/state"
client_id = "radarclient"
def connect_mqtt() -> mqtt_client:
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
state = msg.payload.decode()
print (state)
if state == "1":
subprocess.Popen(["xdotool","key","Super_L+l"])
time.sleep(30)
client.subscribe(topic)
client.on_message = on_message
def run():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
if __name__ == '__main__':
run()
from paho.mqtt import client as mqtt_client import subprocess import time broker = 'MQTT-SERVER' port = 1883 topic = "radar/state" client_id = "radarclient" def connect_mqtt() -> mqtt_client: def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.on_connect = on_connect client.connect(broker, port) return client def subscribe(client: mqtt_client): def on_message(client, userdata, msg): state = msg.payload.decode() print (state) if state == "1": subprocess.Popen(["xdotool","key","Super_L+l"]) time.sleep(30) client.subscribe(topic) client.on_message = on_message def run(): client = connect_mqtt() subscribe(client) client.loop_forever() if __name__ == '__main__': run()
from paho.mqtt import client as mqtt_client
import subprocess
import time

broker = 'MQTT-SERVER'
port = 1883
topic = "radar/state"
client_id = "radarclient"

def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        state = msg.payload.decode()
        print (state)
        if state == "1":
            subprocess.Popen(["xdotool","key","Super_L+l"])
            time.sleep(30)


    client.subscribe(topic)
    client.on_message = on_message

def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()

if __name__ == '__main__':
    run()

change
subprocess.Popen([“xdotool”,”key”,”Super_L+l”])
into
subprocess.Popen([“switchdesktop”])
to run a script named switchdesktop

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#!/bin/bash
# This is the switchdesktop script, it goes to the next screen using winows-page-down combo
xdotool key "Super_L+Page_Down"
#!/bin/bash # This is the switchdesktop script, it goes to the next screen using winows-page-down combo xdotool key "Super_L+Page_Down"
#!/bin/bash
# This is the switchdesktop script, it goes to the next screen using winows-page-down combo
xdotool key "Super_L+Page_Down"

Todo:

3D print a case
Make a version which becomes a Access Point.
Then make another arduino setup which controls my Nikon.
So it can act like a wildcam (offline)

Something like below, using a optocoupler ( i still got some leftovers from my doorbell to gpio-pin project.)

Glade and python – network tester

THIS IS A WORK IN PROGRESS ! .. Updates follow

UPDATE: Found a glade project from 2002
https://www.henriaanstoot.nl/2002/02/20/reverse-engineering-a-alpha-ticker-led-scoller/

The goal of this project is to have a raspberry-pi with a screen wich shows network information.
It wil be using a battery, touchscreen .. maybe some status leds.
When debugging network issues we want to have information when/if/how a network port works on our switches.

It should show:

  • dhcp ip
  • gateway
  • can access internet?
  • speedtest
  • detect if vlan tagged network packets are present on the port?
  • icmp test
  • list of detected nearby hosts?

A long time ago i played with glade and C / Perl.

But i’d rather use python so i’m looking into glade/python combi for this little project.

Glade is a gnome/GTK user interface RAD tool. (Rapid Application Development)

i’ve used zenity and yad before to create simple gui’s for bash scripts, these where only for quick and dirty solutions. (See other posts)
Glade is a far better solution, but a little harder to use.

Below is a little framework i started with

Python script

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
class Handler:
def onDestroy(self, *args):
Gtk.main_quit()
def on_firstbutton_clicked(self, button):
print("Ping test")
builder = Gtk.Builder()
builder.add_from_file("mytest.glade")
builder.connect_signals(Handler())
window = builder.get_object("Main")
window.show_all()
Gtk.main()
import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk class Handler: def onDestroy(self, *args): Gtk.main_quit() def on_firstbutton_clicked(self, button): print("Ping test") builder = Gtk.Builder() builder.add_from_file("mytest.glade") builder.connect_signals(Handler()) window = builder.get_object("Main") window.show_all() Gtk.main()
import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class Handler:
    def onDestroy(self, *args):
        Gtk.main_quit()

    def on_firstbutton_clicked(self, button):
        print("Ping test")

builder = Gtk.Builder()
builder.add_from_file("mytest.glade")
builder.connect_signals(Handler())

window = builder.get_object("Main")
window.show_all()

Gtk.main()

Glade file

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.38.2 -->
<interface>
<requires lib="gtk+" version="3.20"/>
<object class="GtkWindow" id="Main">
<property name="can-focus">False</property>
<property name="title" translatable="yes">Networktool</property>
<property name="default-width">440</property>
<property name="default-height">250</property>
<property name="icon-name">network-wired</property>
<child>
<object class="GtkFixed" id="fixed1">
<property name="visible">True</property>
<property name="can-focus">False</property>
<child>
<object class="GtkButton" id="firstbutton">
<property name="label" translatable="yes">Ping test</property>
<property name="width-request">100</property>
<property name="height-request">16</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
<signal name="clicked" handler="on_firstbutton_clicked" swapped="no"/>
</object>
<packing>
<property name="x">56</property>
<property name="y">40</property>
</packing>
</child>
<child>
<object class="GtkButton" id="speedtest">
<property name="label" translatable="yes">Speed test</property>
<property name="width-request">100</property>
<property name="height-request">16</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
<property name="receives-default">True</property>
</object>
<packing>
<property name="x">56</property>
<property name="y">89</property>
</packing>
</child>
<child>
<object class="GtkTextView">
<property name="width-request">179</property>
<property name="height-request">166</property>
<property name="visible">True</property>
<property name="can-focus">True</property>
</object>
<packing>
<property name="x">222</property>
<property name="y">36</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
<?xml version="1.0" encoding="UTF-8"?> <!-- Generated with glade 3.38.2 --> <interface> <requires lib="gtk+" version="3.20"/> <object class="GtkWindow" id="Main"> <property name="can-focus">False</property> <property name="title" translatable="yes">Networktool</property> <property name="default-width">440</property> <property name="default-height">250</property> <property name="icon-name">network-wired</property> <child> <object class="GtkFixed" id="fixed1"> <property name="visible">True</property> <property name="can-focus">False</property> <child> <object class="GtkButton" id="firstbutton"> <property name="label" translatable="yes">Ping test</property> <property name="width-request">100</property> <property name="height-request">16</property> <property name="visible">True</property> <property name="can-focus">True</property> <property name="receives-default">True</property> <signal name="clicked" handler="on_firstbutton_clicked" swapped="no"/> </object> <packing> <property name="x">56</property> <property name="y">40</property> </packing> </child> <child> <object class="GtkButton" id="speedtest"> <property name="label" translatable="yes">Speed test</property> <property name="width-request">100</property> <property name="height-request">16</property> <property name="visible">True</property> <property name="can-focus">True</property> <property name="receives-default">True</property> </object> <packing> <property name="x">56</property> <property name="y">89</property> </packing> </child> <child> <object class="GtkTextView"> <property name="width-request">179</property> <property name="height-request">166</property> <property name="visible">True</property> <property name="can-focus">True</property> </object> <packing> <property name="x">222</property> <property name="y">36</property> </packing> </child> </object> </child> </object> </interface>
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.38.2 -->
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="Main">
    <property name="can-focus">False</property>
    <property name="title" translatable="yes">Networktool</property>
    <property name="default-width">440</property>
    <property name="default-height">250</property>
    <property name="icon-name">network-wired</property>
    <child>
      <object class="GtkFixed" id="fixed1">
        <property name="visible">True</property>
        <property name="can-focus">False</property>
        <child>
          <object class="GtkButton" id="firstbutton">
            <property name="label" translatable="yes">Ping test</property>
            <property name="width-request">100</property>
            <property name="height-request">16</property>
            <property name="visible">True</property>
            <property name="can-focus">True</property>
            <property name="receives-default">True</property>
            <signal name="clicked" handler="on_firstbutton_clicked" swapped="no"/>
          </object>
          <packing>
            <property name="x">56</property>
            <property name="y">40</property>
          </packing>
        </child>
        <child>
          <object class="GtkButton" id="speedtest">
            <property name="label" translatable="yes">Speed test</property>
            <property name="width-request">100</property>
            <property name="height-request">16</property>
            <property name="visible">True</property>
            <property name="can-focus">True</property>
            <property name="receives-default">True</property>
          </object>
          <packing>
            <property name="x">56</property>
            <property name="y">89</property>
          </packing>
        </child>
        <child>
          <object class="GtkTextView">
            <property name="width-request">179</property>
            <property name="height-request">166</property>
            <property name="visible">True</property>
            <property name="can-focus">True</property>
          </object>
          <packing>
            <property name="x">222</property>
            <property name="y">36</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

Which is generated using the Glade designer

When running you get below screen

Old glade program (2003)