Fundamentals 7 min read

Build a DIY Smart Alarm Clock on Raspberry Pi with Python and Cron

This guide walks you through creating a Raspberry Pi‑based alarm clock that fetches weather data, converts it to speech using Baidu AI, plays audio with pygame, and triggers automatically via a Linux cron job, covering hardware requirements, Python code, and scheduling steps.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Build a DIY Smart Alarm Clock on Raspberry Pi with Python and Cron

Introduction

The author, while working on a smart factory project, decided to build a simple alarm clock using a Raspberry Pi 3B+, Python, and a few peripheral devices. The clock announces the weather and plays a random music file each morning.

Hardware List

RFID reader and an SD card for the OS

3.5 mm speaker

SSH client (SecureCRT, Xshell)

Broadband router (already available at home)

Raspberry Pi 3B+ with charger and CPU cooling fan

Python Dependencies

Install the required Python packages on the Pi:

pip3 install pygame
pip3 install baidu-aip

Core Code Overview

The script performs three main tasks: fetch weather data, synthesize speech, and play audio.

Fetching Weather

import urllib.request, json

def get_weather():
    url = 'http://www.weather.com.cn/data/cityinfo/101120201.html'
    obj = urllib.request.urlopen(url)
    data_b = obj.read()
    data_s = data_b.decode('utf-8')
    data_dict = json.loads(data_s)
    rt = data_dict['weatherinfo']
    weather = ('亲爱的:该起床了,别睡了,快变小猪了,哈哈哈哈哈,我想你了,' +
               '你想我吗?青岛的温度是 {} 到 {},天气 {}').format(
                   rt['temp1'], rt['temp2'], rt['weather'])
    if '雨' in weather:
        weather += '今天别忘记带雨伞哦!'
    du_say(weather)

Text‑to‑Speech with Baidu AI

from aip import AipSpeech

def du_say(weather):
    app_id = '****'
    api_key = '****'
    secret_key = '****'
    client = AipSpeech(app_id, api_key, secret_key)
    result = client.synthesis(weather, 'zh', 1, {'vol':5,'per':3,'spd':4})
    if not isinstance(result, dict):
        with open('weather.mp3', 'wb') as f:
            f.write(result)
        py_game_player('weather.mp3')

Audio Playback

import pygame, random

def py_game_player(file):
    pygame.mixer.init()
    print('播报天气')
    pygame.mixer.music.load(file)
    pygame.mixer.music.play(loops=1, start=0.0)
    print('播放音乐')
    while True:
        if pygame.mixer.music.get_busy() == 0:
            mp3 = "/home/pi/alarmClock/" + str(random.randint(1,6)) + ".mp3"
            pygame.mixer.music.load(mp3)
            pygame.mixer.music.play(loops=1, start=0.0)
            break
    while True:
        if pygame.mixer.music.get_busy() == 0:
            print('播报完毕,起床啦')
            break

Main Execution

if __name__ == '__main__':
    get_weather()

Cron Scheduling

To run the alarm automatically each morning, add a cron entry:

# Edit crontab for the pi user
crontab -e
# Example entry for 7:00 AM
00 07 * * * python3 /home/pi/alarmClock/play.py

After saving, verify the system time zone (the default may not be China/Shanghai) and adjust if necessary:

date                     # check current time
sudo dpkg-reconfigure tzdata   # select Asia/Shanghai

Conclusion

The resulting device is a basic, non‑intelligent alarm clock that announces the weather and plays a random music track. Although simple, the project demonstrates how to combine Raspberry Pi hardware, Python scripting, Baidu AI speech synthesis, and Linux scheduling to create a customizable DIY IoT gadget.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

IoTRaspberry PiPygameBaidu AIAlarm Clock
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.