
For a few years I’ve used an iPad overnight as a means of lulling me back to sleep if I wake in the night. That’s okay but typically the iPad lights up the room and fully wakes me up with all the menu driving that it requires. I really want to just press a button and I would have radio or a podcast playing for half an hour and then it should turn itself off and not carry on to wake me up.
It struck me that I could build something using a Raspberry Pi as they are built with experimentation in mind having a bank of General Purpose Input Output pins which could be used to provide simple instructions.
I had an original Raspberry Pi Zero W (with wireless) kicking around in a box that hadn’t been used in 7 years together with a 4Gb microSD card and original Raspberry Pi PSU. I also had a couple of mechanical touch switches with no application intended. All I actually needed to buy was an enclosure.
Operation
The unit has two touch buttons which are used to select one of three podcast feeds, stop whatever is playing and also to increase and decrease the volume.
The program runs as a service and is started at boot time. In addition the SDCard is made read only with all temporary and log files being stored in RAM to preserve the life of the SDCard and permit the processor to be stopped by powering off abruptly by the wall switch without damaging the system.
Commands can also be fed to the program via a pipe which is mostly used for testing purposes, eg.
echo STOP > /tmp/radio_pipe
The program’s most recent status report is found by:
tail /tmp/radio_status
| Â | Button A or B presses | Pipe commands |
| Play podcast feed 1 | A once | POD1 |
| Play podcast feed 2 | A twice quickly | POD2 |
| Play podcast feed 3 | Hold A down for over a second | POD3 |
| Stop whatever is playing | B once | STOP |
| Volume up | B twice quickly | UP |
| Volume down | Hold B down for over a second | DOWN |
| Change timer from 30 mins to 40 mins | Â | TIMER:40 |
| Swap podcast feed 3 with URL (only podcast feeds 3 has this dynamic swap capability) | Â | SWAP3:http://www.etc.etc |
| Status | Â | STATUS |
Podcast feed choice
This was one of the most difficult aspects in building the project. I wanted to listen to BBC feeds mostly but found most of their feeds are now using DRM and quite complex to access. Podcast feeds are difficult to find but do exist. I decided to pick random episodes from The Word of Mouth podcast from BBC Radio 4 as POD1 and the latest episode of The Global News podcast from BBC World Service as POD2. Live streams are more difficult and I picked a North American feed of BBC World Service as POD3. Streams can be found on http://nossl.fmstream.org/
Hardware
The two touch buttons simply ground specific GPIO pins momentarily. Some pins seem better favoured than others for this work. I used this link for the specific pins on a Pi Zero WÂ https://www.pi4j.com/1.2/pins/model-zerow-rev1.html#J8_Pinout_40-pin_Header The different Pi processors have different pinouts.
- Pin 36 is used for button A
- Pin 34: Common Ground
- Pin 32 is used for button B
Setting up the serviceÂ
sudo nano /etc/systemd/system/squirrelplayer.service
[Unit] Description=SquirrelPlayer service After=network-online.target Wants=network-online.target [Service] ExecStart=/usr/bin/python3 /home/pi/squirrelplayer.py WorkingDirectory=/home/sq StandardOutput=inherit StandardError=inherit Restart=always User=sq [Install] WantedBy=multi-user.targetService control commandsÂ
systemctl status squirrelplayer.service
sudo systemctl stop squirrelplayer.service
sudo systemctl start squirrelplayer.service
sudo reboot (The program takes about 2 minutes to start after reboot and should be ready for echo commands about 30 seconds after that).Making the system read only
sudo raspi-config
go to Performance Options -> Overlay File System, and select No.
Reboot
Reversing to modify the system is almost the same in reverse:-
You must reboot for the SD card to become “writable” again.
Edit: Open your script (nano squirrelplayer.py), make your tweaks, and
Save. Test: Run the script manually or via systemctl to ensure the fix works.
Lock: Run sudo raspi-config, enable the Overlay (Yes), and reboot one last time.
Program
The program is in Python3 running on Raspberry Pi Lite OS and various imports are used for the functionality which will need to be installed using PIP or similar.
Squirrelplayer.py
Âglobal version version = "SquirrelPlayer v7 : Ready" # Author: David Brewerton - April 2026 import os, random, time, threading, subprocess, feedparser, socket import RPi.GPIO as GPIO # --- CONFIG --- socket.setdefaulttimeout(7) PODCASTS = [ {"name": "Word of Mouth", "url": "https://podcasts.files.bbci.co.uk/b006qtnz.rss", "mode": "random"}, {"name": "Global News", "url": "https://podcasts.files.bbci.co.uk/p02nq0gn.rss", "mode": "latest"}, {"name": "BBC World Service", "url": "http://vprbbc.streamguys.net:8000/vprbbc24.mp3", "mode": "live"} ] # alternative World Service feed is https://audio.kuer.org/kuer2low HW_OUT = "--audio-device=alsa/hw:0,0" PIPE_PATH = "/tmp/radio_pipe" BUTTON1 = 22 BUTTON2 = 36 SLEEP_MINS = 30 CURRENT_TRACK = "Nothing" TIMER_END_TIME = 0 sleep_timer = None # --- STATE --- stop_event = threading.Event() os.system("amixer sset 'PCM' 70% unmute") def update_status(msg): print(f"[STATUS] {msg}", flush=True) try: with open("/tmp/radio_status", "w") as f: f.write(msg + "\n") except: pass def play_beep(freq, duration=0.2): os.system(f"speaker-test -t sine -f {freq} -l 1 > /dev/null 2>&1 & sleep {duration} && pkill -n speaker-test") def stop_all(quiet=False): global sleep_timer, TIMER_END_TIME, CURRENT_TRACK if sleep_timer: sleep_timer.cancel() TIMER_END_TIME = 0 stop_event.set() os.system("sudo pkill -9 mpv") CURRENT_TRACK = "Stopped" if not quiet: play_beep(150, 0.4) update_status("User Stop: System Quiet") def speak_time(): # Format time as "14:30" -> "The time is 14 30" current_time = time.strftime("%H %M") text = f"The time is {current_time}" update_status(text) # -a 200 is volume, -s 150 is speed. # We use subprocess.run to make sure it finishes speaking before music starts. subprocess.run(["espeak-ng", "-a", "200", "-s", "150", text]) def start_sleep_timer(duration_minutes=30): global sleep_timer, TIMER_END_TIME if sleep_timer is not None: sleep_timer.cancel() # Record exactly when this timer will hit zero TIMER_END_TIME = time.time() + (duration_minutes * 60) update_status(f"Sleep timer set: {duration_minutes} mins") sleep_timer = threading.Timer(duration_minutes * 60, stop_all) sleep_timer.daemon = True sleep_timer.start() def fetch_and_play(idx): global CURRENT_TRACK stop_all(quiet=True) stop_event.clear() config = PODCASTS[idx] CURRENT_TRACK = config['name'] play_beep(440, 0.1) speak_time() update_status(f"Fetching {config['name']}...") try: # --- DISCRETE CHANGE STARTS HERE --- if config['mode'] == "live": url = config['url'] update_status(f"Live Stream: {config['name']} ({url})") start_sleep_timer(SLEEP_MINS) else: feed = feedparser.parse(config['url']) if stop_event.is_set(): return entry = random.choice(feed.entries) if config['mode'] == "random" else feed.entries[0] url = entry.enclosures[0].href update_status(f"Playing: {entry.title}") # --- DISCRETE CHANGE ENDS HERE --- subprocess.Popen([ "mpv", HW_OUT, "--no-video", "--really-quiet", "--cache=yes", "--demuxer-max-bytes=1MiB", "--demuxer-readahead-secs=1", url ]) except Exception as e: update_status(f"Error: {e}") # ----------------- BUTTON CLASS ----------------- class Button: def __init__(self, pin, double_press_window=0.7, long_press_time=1.0, stable_time=0.02): self.pin = pin self.double_press_window = double_press_window self.long_press_time = long_press_time self.stable_time = stable_time self.state = "IDLE" self.press_time = 0 self.release_time = 0 self.first_press_time = 0 self.long_press_triggered = False self.on_single_press = None self.on_double_press = None self.on_long_press = None GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(self.pin, GPIO.BOTH, callback=self._edge_detected, bouncetime=int(self.stable_time*1000)) def _edge_detected(self, channel): now = time.time() if GPIO.input(self.pin) == GPIO.LOW: self.press_time = now self.state = "PRESS_DETECTED" else: self.release_time = now press_duration = self.release_time - self.press_time if press_duration >= self.long_press_time: if self.on_long_press: self.on_long_press() self.state = "IDLE" self.first_press_time = 0 else: if self.state == "PRESS_DETECTED": if self.first_press_time == 0: self.first_press_time = now self.state = "WAIT_SECOND" else: if now - self.first_press_time <= self.double_press_window: if self.on_double_press: self.on_double_press() self.first_press_time = 0 self.state = "IDLE" else: if self.on_single_press: self.on_single_press() self.first_press_time = now self.state = "WAIT_SECOND" def update(self): if self.state == "WAIT_SECOND" and self.first_press_time != 0: if time.time() - self.first_press_time > self.double_press_window: if self.on_single_press: self.on_single_press() self.first_press_time = 0 self.state = "IDLE" # ----------------- BUTTON CALLBACKS ----------------- def finalize_tap_BUTTON2(): fetch_and_play(0) # For example, single press plays first podcast def handle_volume_up(): os.system("amixer sset 'PCM' 5%+") update_status("Volume Increased") def handle_volume_down(): os.system("amixer sset 'PCM' 10%-") update_status("Volume Decreased") def handle_stop(): speak_time() stop_all() # ----------------- INITIALIZATION ----------------- GPIO.setmode(GPIO.BOARD) button2 = Button(BUTTON2, double_press_window=0.7, long_press_time=1.0) button1 = Button(BUTTON1, double_press_window=0.7, long_press_time=1.0) # Button 2: Podcast control (single = Pod1, double = Pod2, long = Pod3) button2.on_single_press = lambda: fetch_and_play(0) button2.on_double_press = lambda: fetch_and_play(1) button2.on_long_press = lambda: fetch_and_play(2) # Button 1: Stop / volume (single = stop, double = volume up, long = volume down) button1.on_single_press = handle_stop button1.on_double_press = handle_volume_up button1.on_long_press = handle_volume_down # Pipe listener thread def listen_pipe(): global SLEEP_MINS if not os.path.exists(PIPE_PATH): os.mkfifo(PIPE_PATH) while True: try: with open(PIPE_PATH, 'r') as f: for line in f: clean_line = line.strip() if not clean_line: continue cmd = clean_line.upper() # Stream3 swap eg. echo "SWAP3:https://audio.kuer.org/kuer2low" > /tmp/radio_pipe if cmd.startswith("SWAP3:"): # We use clean_line here to preserve URL case (URLs are case-sensitive!) new_url = clean_line.split(":", 1)[1] PODCASTS[2]['url'] = new_url update_status(f"POD3 URL swapped to: {new_url}") # Timer change in mins eg. echo "TIMER:10" > /tmp/radio_pipe elif cmd.startswith("TIMER:"): try: SLEEP_MINS = int(cmd.split(":")[1]) # If something is currently playing, reset the timer live if CURRENT_TRACK != "Stopped" and CURRENT_TRACK != "Nothing": start_sleep_timer(SLEEP_MINS) update_status(f"Live Update: Timer reset to {SLEEP_MINS}m") else: update_status(f"Default Timer set to {SLEEP_MINS}m") except ValueError: update_status("Error: Timer must be a number") # Standard Commands elif cmd == "POD1": fetch_and_play(0) elif cmd == "POD2": fetch_and_play(1) elif cmd == "POD3": fetch_and_play(2) elif cmd == "STOP": stop_all() elif cmd == "UP": handle_volume_up() elif cmd == "DOWN": handle_volume_down() elif cmd == "STATUS": try: # Calculate minutes remaining if TIMER_END_TIME > time.time(): mins_left = int((TIMER_END_TIME - time.time()) / 60) timer_status = f"{mins_left}m left" else: timer_status = "Off" vol = subprocess.check_output(r"amixer get PCM | grep -oP '\[\d+%\]' | head -1", shell=True, text=True).strip() report = f"Playing: {CURRENT_TRACK}, Timer: {timer_status}, Vol: {vol}" update_status(report) except Exception as e: update_status(f"Status Error: {str(e)}") except Exception as e: # This prevents a pipe error from killing the thread time.sleep(1) threading.Thread(target=listen_pipe, daemon=True).start() play_beep(220, 0.5) update_status(version) try: while True: button1.update() button2.update() time.sleep(0.01) except KeyboardInterrupt: GPIO.cleanup()Â