Talking Clock

How many times have you wished you could have something just speak the time of day? Well with just a more work with Flite, a talking clock is yours.

The Unix/Linux date command provides a near infinite amount of flexibility in providing the date and time.  date --help lists all the available options.  Here are some handy formatting for date that work well spoken:

date +%T                  the time in hh:mm:ss format
date +%H:%M           the time in hour and minute (24 hour time)
date "+%I:%M %P"  the time in hour and minute with AM or PM at the end

date +%D    the date in mm/dd/yy format
date "+%A %B %d %Y"  the date like Sunday January 23 2016
date "+%A %d %B %Y"  the date like Sunday 23 January 2016

So take your favorites and you can add the commands to a shell script or python program like we did in the previous page:

date "+%H:%M %P" | flite                             (for just a clock)
date "+%H:%M %P %A %d %B %Y" | flite    (adds the date)

Clock Accuracy

There are some options.  If your Raspberry Pi is connected to the Internet, the operating system (Raspbian) gets the time from the Internet from a Network Time Protocol (NTP) server.  So you have a good time sync, accurate within a second or two. The Pi does not have a battery backed real-time clock (RTC) to keep time in case it is not connected to the Internet or if it loses power and does not have an Internet connection.  Several third-party add-on boards (sometimes called HATS) provide a hardware RTC that will keep very accurate time, sometimes even temperature compensated.  Finally, a GPS receiver can not only provide position data, but a GPS connected board can get the atomic accurate time from satellites as well.  GPS is not often used for time as it is more expensive and less common.

Add a Button

Reading the time of day in a loop is rather tiring. We need a trigger to read the time when an event happens.  The standard, safe way to add a button to a Pi GPIO pin is shown in the schematic below.  Safe in that no overcurrent will be placed on the GPIO when the button is pressed or released.

The Fritzing diagram for the button connected to the Pi:

Python Code

The code to check the switch in a loop and say the time if the button is pressed:

Download: file
import time
import RPi.GPIO as GPIO
import os

GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.IN)

#initialise a previous input variable to 0 (assume button not pressed last)
prev_input = 0
while True:
  #take a reading
  input = GPIO.input(17)
  #if the last reading was low and this one high, print
  if ((not prev_input) and input):
    print("Button pressed")
    os.system("date '+%I:%M %P' | flite")
  #update previous input
  prev_input = input
  #slight pause to debounce
  time.sleep(0.05)

And here it is in action:

This guide was first published on Feb 01, 2016. It was last updated on Feb 01, 2016. This page (Talking Clock) was last updated on May 21, 2019.