Useful things about Raspberry Pi. Applyable to Raspberry Pi OS // BookWorm
Image Files
Write an image file to an SDCard via dd
sudo dd bs=4M if=image.img of=/dev/sdX status=progress
For more accurate and slower write, use value 1M for bs, like: sudo dd bs=4M if=image.img of=/dev/sdX status=progress
/dev/sdX
is the device, NOT the partition ex. /dev/sda
not /dev/sda1
WiFi Connection
To add a WiFi connection, headless, create a file named like <SSID>.nmconnection
and place it in directory /etc/NetworkManager/system-connections/
. Where <SSID>
put the SSID name of your WiFi network. The string is case sensitive! An example file is below:
[connection]
id=COSMOTE-xxxxxx
uuid=8cd2f6cc-671b-482a-aeec-d11d0db5033d
type=wifi
interface-name=wlan0
[wifi]
mode=infrastructure
ssid=COSMOTE-xxxxxx
[wifi-security]
auth-alg=open
key-mgmt=wpa-psk
psk=thepasswordplaintext
[ipv4]
method=auto
[ipv6]
addr-gen-mode=default
method=auto
[proxy]
For this example the file should be named like COSMOTE-xxxxxx.nmconnection
. To create a UUID string, just use the uuidgen
tool in Linux.
Hotspot Connection
To create a hotspot connection using the default wifi device (wlan0), use the script below. Make sure to change password and SSID. To run this script, you have to use the /etc/rc.local
file, which by default in RPiOS Bookworm is not created! To create it read the 4.2.5 Creating /etc/rc.local
section on this file raspberry-boot.pdf , which is found here: https://forums.raspberrypi.com/viewtopic.php?t=314455
#!/bin/bash
# Config
HOTSPOT_IFACE="wlan0"
HOTSPOT_SSID="PiHotspot"
HOTSPOT_PASSWORD="12345678"
PING_TARGET="8.8.8.8"
# Function to check internet
check_internet() {
echo "Checking internet connection..."
if ping -q -c 2 -W 2 "$PING_TARGET" > /dev/null; then
echo "Internet is up."
return 0
else
echo "No internet connection."
return 1
fi
}
# Function to start hotspot
start_hotspot() {
echo "Starting hotspot on $HOTSPOT_IFACE..."
# Check if hotspot is already active
if nmcli connection show --active | grep -q "Hotspot"; then
echo "Hotspot is already running."
return
fi
# Disconnect current wifi if any
nmcli device disconnect "$HOTSPOT_IFACE"
# Start hotspot
nmcli device wifi hotspot ifname "$HOTSPOT_IFACE" ssid "$HOTSPOT_SSID" password "$HOTSPOT_PASSWORD"
if [ $? -eq 0 ]; then
echo "Hotspot started successfully."
else
echo "Failed to start hotspot."
fi
}
# Main logic
main() {
if ! check_internet; then
start_hotspot
else
echo "No need to start hotspot. Internet is available."
fi
}
main
To disable the hotspot use this script:
#!/bin/bash
echo "Disabling Hotspot..."
sudo nmcli device disconnect wlan0
sudo nmcli device up wlan0
Buttons
Below is a python script to use in raspberry pi, when booted up, to control. It uses the hotspot scripts from above also. It manages 4 buttons, Shutdown, Reboot, Hotspot On and Hotspot Off. The Pins diagram is also below. Use Cron to make it start at re/boot.
+3V3---1-|O O|--2--+5V
GPIO2---3-|O O|--4--+5V
GPIO3---5-|O O|--6--_ GROUND
GPIO4---7-|O O|--8-----GPIO14
GROUND _--9-|O.O|-10-----GPIO15
GPIO17--11-|O O|-12-----GPIO18
GPIO27--13-|O O|-14--_ GROUND
GPIO22--15-|O O|-16-----GPIO23
+3V3--17-|O O|-18-----GPIO24 / HOTSPOT ON
GPIO10--19-|O.O|-20--_ GROUND
GPIO9 --21-|O O|-22-----GPIO25 / HOTSPOT OFF
GPIO11--23-|O O|-24-----GPIO8
GROUND _-25-|O O|-26-----GPIO7
ID_SD---27-|O O|-28-----ID_SC
GPIO5---29-|O.O|-30--_ GROUND
GPIO6---31-|O O|-32-----GPIO12
GPIO13--33-|O O|-34--_ GROUND
GPIO19--35-|O O|-36-----GPIO16
REBOOT SCRIPT / GPIO26--37-|O O|-38-----GPIO20
GROUND _-39-|O O|-40-----GPIO21 / SHUTDOWN SCRIPT
#!/usr/bin/python3
import time
from gpiozero import Button, LED
import os
import requests
import logging
import shutil
import math
sdir='/home/x/scripts/'
pwr = Button(21, pull_up=True, hold_repeat=False)
rst = Button(16, pull_up=True, hold_repeat=False)
hon = Button(24, pull_up=True, hold_repeat=False)
hoff= Button(25, pull_up=True, hold_repeat=False)
logging.basicConfig(
filename=sdir+'system.log', # Specify the log file name
level=logging.INFO, # Set the logging level to INFO
format='%(asctime)s - %(levelname)s - %(message)s' # Define the log message format
)
def internet_connection():
try:
response = requests.get("https://google.com", timeout=5)
return True
except requests.ConnectionError:
return False
def button_pressed():
print("Button pressed.")
def button_released():
print("Button released.")
def pressed_reset():
logging.info('RESET button pressed')
print("Rebooting system...")
os.system('sudo reboot')
def pressed_power():
logging.info('POWER OFF button pressed')
print("Powering off system...")
os.system('sudo shutdown now')
def pressed_hotspot_on():
logging.info('HOTSPOT ON button pressed')
os.system(sdir+'hotspot-on.sh')
time.sleep(1)
def pressed_hotspot_off():
logging.info('HOTSPOT OFF button pressed')
os.system(sdir+'hotspot-off.sh')
time.sleep(1)
pwr.hold_time = 2
pwr.when_held = pressed_power
rst.hold_time = 2
rst.when_held = pressed_reset
hon.hold_time = 2
hon.when_held = pressed_hotspot_on
hoff.hold_time = 2
hoff.when_held = pressed_hotspot_off
print("Press CTRL-C to exit.")
while True:
time.sleep(1)
Custom.toml file
There is also a new? way to customize settings on installation, which a) i haven't tested yet b) have read, that in future may be disabled.
Create a file named custom.toml
in the /bootfs
partition. The contents of the file can be found here: https://gist.github.com/lpenz/ef21bb38a7aa12ebde17fa719a8546b5
# Raspberry PI OS config.toml
# This file is used for the initial setup of the system on the first boot, if
# it's s present in the boot partition of the installation.
#
# This file is loaded by firstboot, parsed by init_config and ends up
# as several calls to imager_custom.
# The example below has all current fields.
#
# References:
# - https://github.com/RPi-Distro/raspberrypi-sys-mods/blob/master/usr/lib/raspberrypi-sys-mods/firstboot
# - https://github.com/RPi-Distro/raspberrypi-sys-mods/blob/master/usr/lib/raspberrypi-sys-mods/init_config
# - https://github.com/RPi-Distro/raspberrypi-sys-mods/blob/master/usr/lib/raspberrypi-sys-mods/imager_custom
# Required:
config_version = 1
[system]
hostname = "raspberrypi"
[user]
# If present, the default "rpi" user gets renamed to this "name"
name = "rpi"
# The password can be encrypted or plain. To encrypt, we can use "openssl passwd -5 raspberry"
password = "$5$pN7oRnie.WDOHoJY$aWEYmKUytN/S/bxMza5ksBiurbSJmcvcysBKHSmYa45"
password_encrypted = true
[ssh]
# ssh_import_id = "gh:user" # import public keys from github
enabled = true
password_authentication = false
# We can also seed the ssh public keys configured for the default user:
# authorized_keys = [ "ssh-rsa ... user@host", ... ]
[wlan]
ssid = "mywifi"
password = "$5$pN7oRnie.WDOHoJY$aWEYmKUytN/S/bxMza5ksBiurbSJmcvcysBKHSmYa45"
password_encrypted = true
hidden = false
# The country is written to /etc/default/crda
# Reference: https://wireless.wiki.kernel.org/en/developers/Regulatory
country = "IE"
[locale]
keymap = "gb"
timezone = "Europe/London"
Edit crontab file
Not suggested!!!!
In case you don't have ssh access and want to add a command to start on boot, you can edit the root crontab file, which is not suggested! The location is at /var/spool/cron/crontabs/
, the file name is root
and has these permissions:
-rw------- 1 root crontab 1165 Aug 7 17:58 root
Edit it as root and to add a command to execute at boot, add a line like this:
@reboot /home/x/scripts/buttons.py &