Make chimes on the hour and half hour
The steps to make the chimes are these:
- Attach the heat sinks to the Raspberry Pi board.
- Prepare your laptop.
- Download the Raspberry Pi operating system.
- Install the operating system.
- Write the Python code that makes the chimes.
To see a larger image, click the image.
Fix heat sinks to Raspberry
A heat sink is a metal square object that is attached to a Raspberry Pi board by means of thermal paste. It draws the heat away from the processor, the USB controller, and the ethernet controller. A chiming program running on a Raspberry Pi 4B should not heat the little computer too much, but it is safe practice to use heat sinks.
The three small corrugated squares that you see at the bottom left of the image are heat sinks. In the Raspberry Pi world, these corrugations are known as fins.
To see a larger image, click the image.
You must attach heat sinks to the CPU chip, the USB chip, and the network chip of the Raspberry Pi board. The one that goes over the CPU chip is the largest one; the one to use on the ethernet board is the smallest one.
- Peel off the adhesive strip at the back of the heat sink, all the while taking care that you don't touch the sticky part that the strip was covering. The sticky part is the thermal paste that will hold the sink in place.
- Press the sink ever so slightly on to the chip on the Raspberry Pi board.
I found this YouTube video to be helpful.
After the heat sinks are in place, prepare your laptop for the Raspberry Pi setup.
Prepare your laptop for the Raspberry Pi installation
Before you can use your laptop to run a Raspberry Pi OS installation, make sure that the following software is available on it.
- Download SD Memory Card Formatter. Before you can load an operating system on your microSD card, you must format it. Use the formatter provided by the SD Association because this formatter is platform-agnostic.
- Download Raspberry Pi Imager. The good folks at Raspberry Org have created a wizard that can install an operating system on a microSD card and also, simultaneously, configure the operating system with the barest minimum parameters that are needed to get a Raspberry Pi computer up and running. This wizard is known as Raspberry Pi Imager.
- Download Angry IP Scanner. If you don't plan to use an external mouse, keyboard, and monitor with your Raspberry Pi, you'll need to connect to it through your laptop. To do so, you need the IP address of the Raspberry Pi. A network scanner can show you the IP addresses of all devices that are connected to your network. One such network scanner is Angry IP Scanner, so download it.
- Download PuTTY. If you don't plan to use an external mouse, keyboard, and monitor with your Raspberry Pi, you'll need to connect to it through your laptop. One of the ways to do so is by using a secure shell (SSH) connection. PuTTY is an SSH client through which you can interactively run a command-line session on your Raspberry Pi.
- (Optional) Download WinSCP. If you need to transfer files to and from the Raspberry Pi computer, you need a secure file-transfer client. WinSCP is one such client.
When you're done, you should have the following software on your laptop.
You are now ready to install an operating system on your Raspberry Pi.
Download the operating system
For this step, you need a microSD card and a card reader that can be plugged into your laptop.
The operating system will be downloaded on to the microSD card, which will then be inserted into the microSD slot of the Raspberry Pi board, which will then be plugged into a power socket. That's what will get the little board up and running, and make it ready for the final steps of the project.
- Turn on your laptop. Make sure that it is connected to the internet.
- Plug the microSD card into your laptop, and format it by running SD Card Formatter. Use the Overwrite option to format; this option takes longer but ensures that everything on the SD card is wiped clean and the card formatted.
- On the laptop, run the Raspberry Pi Imager wizard and download Raspberry Pi's operating system to it. All Raspberry Pi computers run on operating systems that are based on the open-source Debian operating system. This project uses Debian Bookworm with the Raspberry Pi Desktop. Begin the download process by selecting the model as Raspberry Pi 4 and the operating system as Raspberry Pi OS 64-bit (A port of Debian Bookworm with the Raspberry Pi Desktop).
- On the page for OS customisation, click Edit settings. These settings are used for configuring the operating system with your credentials and environment. If prompted for loading Wi-Fi credentials from your host computer, respond in the affirmative. Then, specify the values for at least the following parameters. It's also a good idea to note down these values for easy reference, because you'll need these values later:
- On the General page:
- hostname, which is a name you call your Raspberry Pi by. This is the name that'll be displayed when you search for your Raspberry Pi on the network later.
- username and password, which are the credentials to use when logging in to Raspberry Pi remotely. The user name that you specify here will have administrator privileges to your Raspberry Pi.
- Wireless LAN, which should be prepopulated because you already asked the Wi-Fi credentials to be loaded from the host computer.
- Locale settings, for your time zone, keyboard preferences, and other such locale-related things.
- On the Services page, select the Enable SSH box and the option for password authentication. Later, when the project is up and running, you might choose to isolate your Raspberry Pi from the network, and if you decide to do that, you can turn SSH off, but for the time being, enable it because you might need it for troubleshooting purposes.
- On the Options page, select all the options.
- On the General page:
- Click Save and, when prompted for applying these settings, answer in the affirmative. Click Yes again, and then wait for the operating system to be copied on to the microSD card.
- When the process is complete, take the microSD card out of the laptop port.
Install an operating system on the Raspberry Pi
For this project, you install the operating system called Raspberry Pi OS 64-bit (A port of Debian Bookworm with the Raspberry Pi Desktop) for the model called Raspberry Pi 4.
- Insert the microSD card to the Raspberry Pi's board, plug in the power adapter to a wall socket, and insert the cable into the USB-C power slot of the Raspberry Pi. If you're going to use an external keyboard and mouse, insert the USB receivers for these devices into the USB ports of the Raspberry Pi.
- Turn on the power switch of the wall socket. The light on the Raspberry Pi board should glow green, and the display screen should first show a rectangle of rainbow colours, and then finally show you the Raspberry Pi desktop screen.
- If you don't have an external keyboard and mouse, log in to the Raspberry Pi from your laptop:
- Find the IP address of your nework gateway. To do so, on your laptop, open the command prompt, and type
ipconfig
. Then, note down the value that's displayed as Default Gateway. - Start Angry IP Scanner. For the first box in the IP Range field, specify the value of the default gateway that you noted down in the previous step. For the second field, specify a number that's about 15-20 stops away. For example, if your default gateway is
192.168.4.1
, specify the end range to be something around192.168.4.15
, so that the scan doesn't take too long. (The assumption here is that you don't already have more than 15-20 devices connected to your network!) Click Start and wait for the scan to be over. Then, in the Hostname column, look for the name of your Raspberry Pi. This is the name that you specified as the hostname in the OS Customisation settings while downloading the operating system on the microSD card. When you've spotted this hostname, look for the entry in the IP column. You need this value in the next step. - On your laptop, start PuTTY and enter the IP address of your Raspberry Pi. This is the value that you noted down in your previous step. Click Open. When prompted for login credentials, enter the user name and password that you specified in the OS Customisation settings while downloading the operating system on the microSD card. You should now see a prompt like this:
<hostname>@<username>:~ $
. For example, if your hostname isdelphi
and user name isoracle
, you'll seedelphi@oracle:~ $
It means you're now logged in to your Raspberry Pi and everything's working as expected.
- Find the IP address of your nework gateway. To do so, on your laptop, open the command prompt, and type
- Update the operating system that you installed on the microSD card. You used Raspberry Pi Imager for downloading the operating system but it might not contain the latest patches, fixes, and upgrades. Pull these things in:
- Open a terminal window. If you're logged in through your laptop, you're already in the terminal window. If you're using an external keyboard and mouse, move the mouse over the icons at the top left, locate the one labelled Terminal, and click it.
- To see if there are any updates to the operating system, run the following command:
sudo apt-get update
. The local cache of the Raspberry Pi is updated with the package information for the package repositories. You're shown a list of the these packages, and now it's up to you to upgrade them to their latest versions. - Upgrade the software shown on the list by running the following command:
sudo apt-get upgrade
. When prompted for permission to proceed with the upgrade, answer in the affirmative. The actual updates for the installed software and the operating system are now downloaded and installed on your Raspberry Pi.
- If you don't have an external mouse or keyboard, set up Raspberry Pi Connect so that you can control the Raspberry Pi through a laptop through the Raspberry Pi's desktop GUI itself. You're already logged into the Raspberry Pi through your laptop via SSH, but you can use only the terminal window when you're so logged in; you can't use the Raspberry Pi's desktop GUI. With the Connect software, you can log into your Raspberry Pi through any browser, and use it through its desktop environment.
- Install Connect by running the following command in the terminal window:
sudo apt install rpi-connect
. - Start Connect by running the following command in the terminal:
rpi-connect on
. - Generate a link that will connect your Raspberry Pi computer with your Connect account by running the following command from the terminal:
rpi-connect signin
. You're shown a sign-in URL on the terminal. - On your laptop, open a browser, type the URL shown on the Raspberry Pi terminal window, and follow the onscreen prompts to complete the signin and authentication process.
- In the same browser window, specify a name to identify your device, and click Create device and sign in.
- Install Connect by running the following command in the terminal window:
- If you're not immediately proceeding to the next step (where you write the Python program), shut down the Raspberry Pi.
- If you're using an external mouse, close the terminal window. Then click the Raspberry Pi icon near the top left and click Shutdown > Shutdown. Wait till the green light on the Raspberry Pi board stops flashing, and then switch off the power supply.
- If you're logged in through your laptop, type the following command on the terminal:
sudo shutdown -h now
. You should be disconnected from Raspberry Pi and the terminal window should disappear. Wait till the green light on the Raspberry Pi board stops flashing, and then switch off the power supply.
Now that your Raspberry Pi is ready to be used as a computer, you can proceed to creating the clock chimes.
Write the Python code for playing the clock chimes
For this clock-chiming project, the job of chiming on the hour and half-hour will be done by a Python program.
The operating system that you installed on the Raspberry Pi already includes Python, as well as an integrated development environment (IDE) that makes it easier for you to write, run, and edit Python programs. This IDE is the Thonny IDE. You'll use Thonny to write the Python program.
- Plug in the speaker to the Raspberry Pi, and switch both of them on.
- If you don't have an external keyboard or mouse, log in remotely to your Raspberry Pi by using Connect:
- On your laptop, open
https://connect.raspberrypi.com/
and sign in. - On the Devices page, click Connect via > Screen sharing, and wait for a few seconds for the remote session to start. You should then see the Raspberry Pi desktop in your laptop browser window.
- On your laptop, open
- Install any patches, fixes, and upgrades that might have been made to the operating system by opening the Raspberry Pi terminal window (the console icon near the top left) and running the following two commands one after the other:
sudo apt-get update
sudo apt-get upgrade
- Open Thonny by clicking the Raspberry Pi icon near the top left, and then clicking Programming > Thonny.
- Create a virtual environment for your project. A virtual environment is like a boxed enclosure that contains all the Python libraries and packages that are needed for your code to run. Click Tools > Options, and then click Interpreter. Make sure that the interpreter is
Local Python 3
. Then, click New virtual environment and follow the onscreen guidance to create an empty folder and designate it as the place where your project will live. When everything's done, click OK. - Open a new file by clicking File > New. Copy into it the code from The code section of this page.
- In the same virtual environment, at the same location as the
.py
file, paste a sound file containing the music you want to be played as the chimes. This sound file should be a.wav
file because thepygame
library can play only.wav
files. For this project, I downloaded a royalty-free sound file that had peeling church bells, and then edited the file in to separate out a 2-second clip of a dinging sound. - Install a Python package called
pygame
in the virtual environment. To do so, click Tools > Manage packages, search forpygame
, and click Install. - Edit line 7 of the Python code to make sure that the file name is correct. For example, if your sound file is called
dingdong.wav
, line 7 should besound_file = 'dingdong.wav'
. - Save the file, and click the Run icon. Wait for the half hour or the hour. You should be able to hear the chimes.
The code
import time
from datetime import datetime
import pygame
# Initialize pygame mixer
pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=4096)
sound_file = 'ding.wav'
chime_sound = pygame.mixer.Sound(sound_file)
def play_chime(times):
"""Play the chime the specified number of times."""
for _ in range(times):
chime_sound.play()
time.sleep(2) # A 2-second delay between chimes
try:
print('Chiming on the hour and half-hour. Press Ctrl+C to stop.')
while True:
now = datetime.now()
current_minute = now.minute
current_second = now.second
if current_minute == 30:
# Chime once for the half-hour
print('Chiming once for the half-hour.')
play_chime(1)
# Sleep until the top of the next hour
sleep_time = (60 - current_minute) * 60 - current_second
time.sleep(sleep_time)
elif current_minute == 0:
# Chime the number of times equal to the hour
chime_count = now.hour % 12 or 12 # Use 12 for midnight and noon
print(f'Chiming {chime_count} times for the hour {now.hour}.')
play_chime(chime_count)
# Sleep until the half-hour
sleep_time = 30 * 60 - current_second
time.sleep(sleep_time)
else:
# Determine whether to sleep until the half-hour or the hour
if current_minute < 30:
sleep_time = (30 - current_minute) * 60 - current_second
else:
sleep_time = (60 - current_minute) * 60 - current_second
time.sleep(sleep_time)
except KeyboardInterrupt:
print('\nStopped chiming.')
Notice the first three lines of the code.
import time
from datetime import datetime
import pygame
This is where you import the libraries and packages that are needed for this project. A Python library is a collection of programs that do a specific task, and can be called in your program by their name. Libraries make it easy to do things that would've otherwise needed you to write out, manually, the several lines of code needed to do that thing. For example, assume you need to count the number of words in a sentence. The manual (non-library) way of doing so would be to write something like this:
sentence = 'Beside the lake, beneath the trees, fluttering and dancing'
word_counts = {}
words = sentence.split() # Split the sentence into words
for word in words:
word = word.lower().strip(".,!?") # Remove punctuation
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
print('This sentence contains`, word_counts, 'words.')
Now, imagine doing the same thing with a library called collections
, which contains code to do the heavy lifting. If you were to use this library, your code would look something like this, where you use a class called Counter
to do the counting:
from collections import Counter
# Count word occurrences using a library
sentence = 'There was a time when meadow, grove, and stream, and every common sight to me did seem apparelled in celestial light.'
words = sentence.lower().split()
normalized_words = [word.strip(".,!?") for word in words]
word_counts = Counter(normalized_words)
print('This sentence contains`, word_counts, 'words.')
With libraries, you can write your programs with fewer lines of code, while using universal methods that can be recognised by any other Python programmer more easily than if they had to read non-library code.
Some libraries are included by default in every Python installation. The libraries called time
and datetime
, which are imported in the first two lines, are such libraries. Some other libraries are ones that you manually install in the virtual environment of your project. The pygame
library is one such library. It is a library for handling multimedia files like the sound file you use in this project.
Take a look at this part of the code:
time.sleep(2) # A 2-second delay between chimes
This bit specifies a 2-second delay when the chimes are going to be repeated for the number of hours. For example, if it is 4 o'clock, the playing is repeated four times, with a 2-second delay between the repetitions.
Look at how sleep_time
is calculated. It takes into account the seconds that have elapsed while the sound was playing; therefore, this sleep_time
is calculated twice, once on the hour and once on the half-hour.
sleep_time = (60 - current_minute) * 60 - current_second
...
sleep_time = 30 * 60 - current_second
Take a look at this bit, which controls the number of times the chime is played:
play_chime(1)
...
play_chime(chime_count)
chime_count
is calculated according to the current hour, as follows: chime_count = now.hour % 12 or 12
. The reason for using a modulus operation rather than a substraction operation (like chime_count = now.hour - 12
) is explained in the following table.
now.hour |
Modulus (now.hour % 12 ) |
Substraction (now.hour - 12 ) |
Notes |
---|---|---|---|
13 | 1 | 1 | Both methods return the correct hour. |
14 | 2 | 2 | Both methods return the correct hour. |
23 | 11 | 11 | Both methods return the correct hour. |
0 (midnight) | 0 | - 12 | Incorrect. Solved by using or 12 in the modulus operation. |
12 (noon) | 0 | 0 | Incorrect. Solved by using or 12 in the modulus operation. |
Notice the or
operater in chime_count = now.hour % 12 or 12
. This code sets the value of the chime_count
variable to the modulus value, but if the modulus is zero, sets the chime_count
value to 12.
Now, see this bit near the start of the code:
pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=4096)
This code initialises the pygame
module with the following parameters:
- frequency
, which is set to match my sound file's sample rate. To find the sample rate of your sound file, run the following command from the Raspberry Pi terminal: file <filename.wav>
, where filename.wav
must be replaced by the name of your sound file. You should get an output that's something like this: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, stereo 44100 Hz
- size
, which is the bit-depth of the sound file. In my case, because the format is PCM
, a negative sign (-16
) is used, which is standard for PCM data.
- channels
, which is set to 2
because my audio device is a dual-channel speaker.
- buffer
, increased from the default of 2048
to remove any stuttering.
You can also do a simpler initialisation, without specifying the parameters, like this: pygame.mixer.init()
. But sometimes, doing so might lead to the sound file seeming to stutter on playback due to buffering issues.
Troubleshooting the code
1. pygame
not found
If pygame
does not show up in the search results when you try to install it through Tools > Manage packages:
- Close Thonny.
- Open the terminal and run the following two commands one after the other:
sudo apt update
sudo apt install python3-full
- Go to the directory that contains your project files, and look for a file called
pyvenv.cfg
. Right-click the file, click Text editor, and make sure the value ofinclude-system-site-packages
is set totrue
. Save the file, and close it. - Reopen Thonny, and click Tools > Manage packages.
You should now be able to see pygame
in the list of installed packages.
2. Stuttering playback
If your sound file plays perfectly on your laptop but seems to be stuttering on the Raspberry Pi computer, the problem might lie with buffering. Increase the buffer size to 8192
or higher when initialising the pygame
library at line 6.