Athan System with raspberry Pi

The athan (or Adhan) is a special Islamic call to salah (prayer). A mu’athin calls athan from the minaret of a mosque to announce every prayer and worship event. According to Islamic custom, the athan is also the first thing that a newborn baby should hear. You can say the words in English, Arabic, or any other language that is meaningful to you.

Prayers in Islam are 5 times a day. Those times vary, so does that athan for them.

Since I am Muslim, I have created an athan “clock” that calls the athan 5 times a day. I use a Raspberry Pi and a speaker connected to it to play the athan sound.

I called it a “system” because it does more than just playing the sound at certain times. Here are all the functionalities it does:

  1. It calls a prayer API to get the prayer times to schedule the athan accordingly for each day.
  2. It plays an Arabic and English Du’a (prayer) after the athan.
  3. It serves the Fajr (first prayer time, before sunrise) for my phone to be able to retrieve it every morning (around 3:30am) to set a “dynamic” alarm.
  4. It is connected to the TV sound output to “listen” to the TV and determine if something is playing on the TV at the time of the athan.
  5. It has a simple IR circuit that programmed to match the TV remote control, and sends a PAUSE and MUTE signals to the TV IR at the time of the athan then PLAY and UNMUTE after the athan is done playing.

See it in action

This shows how the TV is auto paused and muted when the Athan comes on

 

and this one is when it finishes playing, the TV is resumed and unmuted automatically.


Athan API

I am using this Muslim Salat API that returns the times in JSON format for each day. I request this API once every day at 3:15am. Here is the cronjob that runs this scheduler code:

# Schedules athan times for each day runs at 3:15 am
15 3 * * * /usr/bin/python /home/pi/projects/athan/scheduler.py >/dev/null 2>&1

Athan Scheduler

I use the Linux at command to schedule a job to run in the background. Jobs scheduled with at run only once. That is the reason I chose this over cron jobs.

Since fajr athan sound is slightly different than the other 4 athan calls, I have 2 sound files one for fajr and one for the other ones.

Schedule for non-fajr athan

call(["at", "-M", "-f", ppath + "/playathan.sh", at_time + " today"])

Schedule for fajr athan

call(["at", "-M", "-f", ppath + "/playathan-fajr.sh", at_time + " today"])

TV monitoring to determine if anything is playing

The scheduler also sets up another at job for each athan one minute before the athan to start recording the output of the TV and then analyze that file to determine the volume.

Here is the part of the scheduler that takes care of that:

dt = time.strptime(time.strftime("%Y-%m-%d") + " " + result['items'][0][athan], "%Y-%m-%d %I:%M %p")
dt = datetime.fromtimestamp(time.mktime(dt))

at_time = dt.strftime("%H:%M")
at_time_1min = (dt - timedelta(minutes=1)).strftime("%H:%M")

call(["at", "-M", "-f", ppath + "/handle-tv-sound.sh", at_time_1min + " today"])

The script handle-tv-sound.sh uses a USB webcam that has a microphone to record from the TV composite audio output. I had to modify the webcam and remove the microphone, then connect the composite audio cable to the microphone wires (See picture)

webcam

I use arecord to record the sound and save it to a wav file, here is the handle-tv-sound.sh content

arecord -D plughw:1,0 -d 10 $ppath/tv_sound.wav

Then I use SoX (Sound eXchange) to analyze the recorded file

ppath="/home/pi/projects/athan"
threshold=0.05
sleep 45
arecord -D plughw:1,0 -d 10 $ppath/tv_sound.wav
soxout=$(sox -t .wav $ppath/tv_sound.wav -n stat 2>&1)

noise=$(echo $soxout | grep -oP "Maximum amplitude:\s(.*?)\s" | grep -oP "\d+\.\d+")

Muting and Pausing the TV

Once I get the noise value from SoX I compare it to the threshold that I have specified to determine if the TV is loud enough to be paused and muted then I use irsend command which is part of lirc package that sends signal to the output pin where the IR LED is connected on the Raspberry Pi to create a TV command

if [ $(echo " $noise > $threshold" | bc) -eq 1 ]
then
 irsend SEND_ONCE VIZIO KEY_PAUSE
 irsend SEND_ONCE VIZIO KEY_MUTE
 touch $ppath/tv_muted
fi

VIZIO is the TV alias in the lirc configuration file, this configuration file can be generated by capturing the TV remote IR signals with a IR receiver connected to Raspberry Pi or just downloaded from the LIRC website (or from the web by people who generated it)

Here is the configuration file that I am using:

# Vizio remote config file

begin remote

 name VIZIO
 bits 16
 flags SPACE_ENC|CONST_LENGTH
 eps 30
 aeps 100

 header 9052 4519
 one 540 1703
 zero 540 581
 ptrail 541
 repeat 9024 2276
 pre_data_bits 16
 pre_data 0x20DF
 gap 107705
 toggle_bit_mask 0x0

 begin codes
 KEY_SWITCHVIDEOMODE 0xF40B
 KEY_POWER 0x10EF
 amazon 0x57A8
 netflix 0xD728
 iheartradio 0x7788
 KEY_REWIND 0xAC53
 KEY_PAUSE 0xEC13
 KEY_PLAY 0xCC33
 KEY_FASTFORWARD 0x6C93
 cc 0x9C63 # closed caption
 KEY_RECORD 0x2CD3
 KEY_STOP 0x0CF3
 KEY_INFO 0xD827
 KEY_EXIT 0x926D
 KEY_MENU 0xF20D
 KEY_UP 0xA25D
 KEY_DOWN 0x629D
 KEY_LEFT 0xE21D
 KEY_RIGHT 0x12ED
 KEY_OK 0x22DD
 KEY_BACK 0x52AD
 KEY_EPG 0x38C7
 KEY_YELLOW 0x4AB5
 KEY_BLUE 0xCA35
 KEY_RED 0x2AD5
 KEY_GREEN 0xAA55
 KEY_VOLUMEUP 0x40BF
 KEY_VOLUMEDOWN 0xC03F
 vizio 0xB44B
 KEY_CHANNELUP 0x00FF
 KEY_CHANNELDOWN 0x807F
 KEY_MUTE 0x906F
 KEY_REDO 0x58A7
 KEY_1 0x8877
 KEY_2 0x48B7
 KEY_3 0xC837
 KEY_4 0x28D7
 KEY_5 0xA857
 KEY_6 0x6897
 KEY_7 0xE817
 KEY_8 0x18E7
 KEY_9 0x9867
 KEY_DISPLAYTOGGLE 0xEE11 # "wide" button
 KEY_0 0x08F7
 KEY_MINUS 0xFF00 # "long dash" button
 end codes

end remote

Fajr Time Server

I mentioned before that this system also serves the fajr time for my phone to dynamically set up an alarm everyday for me to wake up for the prayer. This server is a simple python server that returns the time to the phone when requested in plain text.

The server gets the time from the scheduler script, where the scripts writes that time to a text file

if athan == 'fajr':
  call(["at", "-M", "-f", ppath + "/playathan-fajr.sh", at_time + " today"])
  f = open(ppath + '/server/fajrtime.txt','w')
  f.write(result['items'][0][athan])
  f.close()

Then this file is served with this simple python server

#!/bin/bash
ppath=$( cd "$(dirname "${BASH_SOURCE}")" ; pwd -P )
pushd $ppath/server; python -m SimpleHTTPServer 8889; popd

Phone Dynamic Fajr Alarm

To set up this alarm I use the Tasker App to make the phone request the fajr time from the server and create an alarm using the AlarmPad app that supports tasker.

Tasker Profile Dynamic Alarm

The task Set Fajr Alarm looks like this:

Set Fajr Alarm task

The javascriplet treats the text (fajr time) returned from the server and assigns it to two variables; fajrtimeh and fajrtimem.

var fajrtime = global("HTTPD").replace("am","").trim().split(":");
var fajrtimeh = fajrtime[0];
var fajrtimem = fajrtime[1];

 

Then the AlarmPad action is set as follows:
AlarmPAd action

Source code

scheduler.py

import urllib
import json
import time
from datetime import datetime
from datetime import timedelta
from subprocess import call

import os
ppath = '/home/pi/projects/athan'

athan_times = ['fajr', 'dhuhr', 'asr', 'maghrib', 'isha']

url = 'http://muslimsalat.com/mountain+view/daily.json?key=<API KEY>'
result = json.load(urllib.urlopen(url))

for athan in result['items'][0]:
    if athan in athan_times:
        dt = time.strptime(time.strftime("%Y-%m-%d") + " " + result['items'][0][athan], "%Y-%m-%d %I:%M %p")
        dt = datetime.fromtimestamp(time.mktime(dt))

        at_time = dt.strftime("%H:%M")
        at_time_1min = (dt - timedelta(minutes=1)).strftime("%H:%M")

        call(["at", "-M", "-f", ppath + "/handle-tv-sound.sh", at_time_1min + " today"])
       
    if athan == 'fajr':
        call(["at", "-M", "-f", ppath + "/playathan-fajr.sh", at_time + " today"])
        f = open(ppath + '/server/fajrtime.txt','w')
        f.write(result['items'][0][athan])
        f.close()
    else:
        call(["at", "-M", "-f", ppath + "/playathan.sh", at_time + " today"])
    else:
        continue

 

playathan.sh

#!/bin/bash
ppath="/home/pi/projects/athan"
aplay $ppath/athan-day.wav
sleep 2
aplay $ppath/dua.wav

#check if tv was muted
if [ -e "$ppath/tv_muted" ];
then
    irsend SEND_ONCE VIZIO KEY_PLAY
    irsend SEND_ONCE VIZIO KEY_MUTE
    rm $ppath/tv_muted
fi

 

playathan-fajr.sh

#!/bin/bash
ppath="/home/pi/projects/athan"
aplay $ppath/athan-fajr.wav
sleep 2
aplay $ppath/dua.wav

#check if tv was muted
if [ -e "$ppath/tv_muted" ];
then
    irsend SEND_ONCE VIZIO KEY_PLAY
    irsend SEND_ONCE VIZIO KEY_MUTE
    rm $ppath/tv_muted
fi

 

start-fajr-server.sh

#!/bin/bash
ppath=$( cd "$(dirname "${BASH_SOURCE}")" ; pwd -P )
pushd $ppath/server; python -m SimpleHTTPServer 8889; popd

 

handle-tv-sound.sh

#!/bin/bash
ppath="/home/pi/projects/athan"
threshold=0.05
sleep 45
arecord -D plughw:1,0 -d 10 $ppath/tv_sound.wav
soxout=$(sox -t .wav $ppath/tv_sound.wav -n stat 2>&1)

noise=$(echo $soxout | grep -oP "Maximum amplitude:\s(.*?)\s" | grep -oP "\d+\.\d+")
echo "Noise: $noise"
if [ $(echo " $noise > $threshold" | bc) -eq 1 ]
then
   irsend SEND_ONCE VIZIO KEY_PAUSE
   irsend SEND_ONCE VIZIO KEY_MUTE
   touch $ppath/tv_muted
fi

10 thoughts on “Athan System with raspberry Pi”

    1. Nice! This one does more than just the Athan, it detects if the TV is playing and sends an IR command to pause/mute the TV. It also works as a server for dynamic alarm clock for my phone.

  1. I was thinking of making something like this! Hbattat, I am noob to Rasberry Pi, but I know basic Python, so I have a few questions:

    1) Which Raspberry Pi are you using?
    2) What did you install on your Pi? Raspbian?
    3) If I didn’t want the TV mute function, but wanted to have an attached LED display that would show the current time and upcoming adhan (and also play adhan audio), which Raspberry Pi do you recommend?

    Thank you very much brother!

    1. Asalam alaykom brother,
      1) I used Raspberry Pi b+, but this should work the same on any Pi. I off course recommend the newer Pi 2 (more ram and same price)
      2) I used Raspbian because that’s the only one that Pi B+ support. I usually run Ubuntu on Pi 2, but either one should work.
      3) There is an LED display from Adafruit, that I use all the time, it’s really nice and plugs on the 40-pin. Here is the link to the display and tutorial

      Please let me know if you need any help, or need any code (most of my code if Python and shell scripts)

      Salam.

      1. Wailaykum Assalam!

        Thank you so much for your detailed reply, it’s very helpful!

        Insha Allah, I’ll try and write the code myself so I can learn, but I will let you know if I need some help. Thank you once again!

  2. Assalamualaikum brother ,
    I would like to create a project using Raspberry Pi and Raspbian. I want it to function as below :

    1) Recite athan audio 5 times daily.
    2) Show the current time.
    3) I want to install few surah to it so i can play it , for example like a mp3 song player.
    4) I want it to be portable and chargeable (if it needs charge)

    So what should I do to create a project as a above , i mean like what parts and others ?
    I am new to this thing and willing to learn more about this. Thank you in advance.

    1. Walaykom asalam,

      For hardware, you would need:
      – Raspberry Pi 2
      – LED Display (can be found on Adafruit site)
      – Speaker (it can be a bluetooth or just connects to the 3.5mm headphone jack)
      – IR receiver (optional) if you want to control it with a remote to play next Surah, change volume, etc
      – Remote (optional)
      – Rechargeable battery pack with with USB output (5v, 2.1a or 1a)

      For software, you need to be able to write code 🙂 and the following:
      – Athan API to get the time of the Athan everyday (or the formula to calculate the time) I am using this http://muslimsalat.com/api/
      – Code to display the time on the screen
      – Code to play an MP3 or WAV file for the Athan
      – MP3 or WAV files for Athan (different file for Fajr)
      – Quran in MP3 or WAF format
      – Built-in OMXPLAYER or APLAY to play the files (these are already on RPi)
      – Code to read the LED display button presses to change Surah, play, pause, etc
      – LIRC to control receive IR commands from the IR remote

      It is an interesting project, I hope this helps.

      Salam,

  3. salem 3alikom

    I have a message error when i excecute python scheduler.py
    File “scheduler.py”, line 33
    else:
    ^
    SyntaxError: invalid syntax

    i have eliminated the last else
    so i have error

    Traceback (most recent call last):
    File “scheduler.py”, line 14, in
    result = json.load(urllib.urlopen(url))
    File “/usr/lib/python2.7/json/__init__.py”, line 278, in load
    **kw)
    File “/usr/lib/python2.7/json/__init__.py”, line 326, in loads
    return _default_decoder.decode(s)
    File “/usr/lib/python2.7/json/decoder.py”, line 368, in decode
    raise ValueError(errmsg(“Extra data”, s, end, len(s)))
    ValueError: Extra data: line 1 column 1 – line 5 column 1 (char 1 – 770)

    can you help me

      1. the content of scheduler.py is

        import urllib
        import json
        import time
        from datetime import datetime
        from datetime import timedelta
        from subprocess import call

        import os
        ppath = ‘/home/pi/projects/athan’

        athan_times = [‘fajr’, ‘dhuhr’, ‘asr’, ‘maghrib’, ‘isha’]

        url = ‘http://muslimsalat.com/sfax/daily.json?key=…..ef75fbea9e89d38d88bde50c4a6e’
        result = json.load(urllib.urlopen(url))

        for athan in result[‘items’][0]:
        if athan in athan_times:
        dt = time.strptime(time.strftime(“%Y-%m-%d”) + ” ” + result[‘items’][0][athan], “%Y-%m-%d %I:%M %p”)
        dt = datetime.fromtimestamp(time.mktime(dt))

        at_time = dt.strftime(“%H:%M”)
        at_time_1min = (dt – timedelta(minutes=1)).strftime(“%H:%M”)

        # call([“at”, “-M”, “-f”, ppath + “/handle-tv-sound.sh”, at_time_1min + ” today”])

        if athan == ‘fajr’:
        call([“at”, “-M”, “-f”, ppath + “/playathan-fajr.sh”, at_time + ” today”])
        f = open(ppath + ‘/server/fajrtime.txt’,’w’)
        f.write(result[‘items’][0][athan])
        f.close()
        else:
        call([“at”, “-M”, “-f”, ppath + “/playathan.sh”, at_time + ” today”])
        # else:
        continue

Leave a Reply