0% found this document useful (0 votes)
105 views70 pages

Iradio: Oene Bakker © 2018

Uploaded by

Pramote Rodbon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views70 pages

Iradio: Oene Bakker © 2018

Uploaded by

Pramote Rodbon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

iRadio

Oene Bakker © 2018

Version: 1.0
Date: 02-04-2018
1 Preface
1.1 Introduction
In this book I’m going to describe the making of an Internet Radio using a Raspberry Pi and some
other hardware components like an audio amplifier and two speakers.

1.2 Content

Content
1 Preface ......................................................................................................................................... 2
1.1 Introduction ............................................................................................................................. 2
1.2 Content .................................................................................................................................... 2
2 Raspberry Pi installation .............................................................................................................. 4
2.1 Headless installation................................................................................................................ 4
2.1.1 Software .......................................................................................................................... 4
2.1.1.1 Raspbian Stretch.......................................................................................................... 4
2.1.1.2 Etcher........................................................................................................................... 4
2.1.1.3 SD Formatter ............................................................................................................... 5
2.1.1.4 PuTTY ........................................................................................................................... 6
2.1.1.5 WinSCP ........................................................................................................................ 6
2.1.1.6 Advanced IP Scanner ................................................................................................... 7
2.1.2 Hardware ......................................................................................................................... 8
2.1.2.1 Raspberry Pi ................................................................................................................. 8
2.1.2.2 LCD2004....................................................................................................................... 8
2.1.2.3 USB C-Media Audio Sound Card .................................................................................. 9
2.1.2.4 USB WiFi Adapter ........................................................................................................ 9
2.1.2.5 Power Adapter AC 220V to DC 12V – 2A .................................................................. 10
2.1.2.6 Power Adpater AC 220V to DV 5V – 1A ..................................................................... 10
2.1.2.7 Dual-Channel Amplifier ............................................................................................. 11
2.1.2.8 Speaker set ................................................................................................................ 11
2.1.2.9 USB Hub ..................................................................................................................... 12
2.1.2.10 Connect Raspberry Pi and LCD2004 ...................................................................... 13
2.1.2.11 Connect USB devices ............................................................................................. 14
2.1.2.12 Other hardware ..................................................................................................... 15

2
2.1.3 Format SD Card.............................................................................................................. 16
2.1.4 Copy image to SD card................................................................................................... 17
2.1.5 Setup SSH and Wifi ........................................................................................................ 20
2.1.5.1 Create a ssh file ......................................................................................................... 20
2.1.5.2 Create a wpa_supplicant.conf file ............................................................................. 21
2.2 Setup the Raspberry Pi .......................................................................................................... 22
2.2.1 IP Scan ........................................................................................................................... 22
2.2.2 Login on the Raspberry Pi .............................................................................................. 25
2.2.3 Configure the Raspberry Pi ............................................................................................ 27
2.2.4 Update and upgrade the Raspberry Pi .......................................................................... 39
2.2.5 Configure C-Media Audio Sound Card........................................................................... 40
2.2.6 Configure Music Player Daemon and Client .................................................................. 42
2.2.7 Configure the playlist..................................................................................................... 43
2.2.8 Configure LCD2004 ........................................................................................................ 45
2.2.9 Flask ............................................................................................................................... 49
3 iRadio ......................................................................................................................................... 51
3.1 Functional .............................................................................................................................. 51
3.2 iRadio.py ................................................................................................................................ 51
3.3 station.nvp............................................................................................................................. 57
3.4 iradio.html ............................................................................................................................. 58
3.5 Images ................................................................................................................................... 60
3.6 LCD Python scripts ................................................................................................................. 61
3.7 Test iRadio ............................................................................................................................. 61
4 Hardware ................................................................................................................................... 64
4.1 Splitting the power cable. ..................................................................................................... 64
4.2 Power supply ......................................................................................................................... 65
4.3 Dual channel amplifier .......................................................................................................... 65
4.4 Raspberry Pi........................................................................................................................... 66
4.5 Case ....................................................................................................................................... 67

3
2 Raspberry Pi installation
2.1 Headless installation

2.1.1 Software

2.1.1.1 Raspbian Stretch

Download the latest version of Raspbian. In this book we will use Raspbian Stretch Lite version
March 2018 because we don’t need a desktop.

Download link: https://www.raspberrypi.org/downloads/raspbian/

Download and extract the ZIP file.

2.1.1.2 Etcher

To copy the image to a preformatted SD-card we need Etcher. Download and install the latest
version of Etcher.

Download link: https://etcher.io/

4
Default the correct version should be available for download. Otherwise select your version from
the dropdown.

2.1.1.3 SD Formatter

Because a SD card can contain all sorts of file systems and files we need special software to
format a SD card correctly.

Download link: https://www.sdcard.org/downloads/formatter_4/

Download and install SD_CardFormatter0500SetupEN.exe.

5
2.1.1.4 PuTTY

To communicate with the Raspberry Pi we need a SHH terminal program like PuTTY.

Download link: https://www.PuTTY.org/

Download and install PuTTY-64bit-0.70-installer.msi

2.1.1.5 WinSCP

To transfer files over SSH to and from the Raspberry Pi we need an WinSCP.

Download link: https://winscp.net/eng/download.php

Download and install WinSCP-5.13-Setup.exe

6
2.1.1.6 Advanced IP Scanner

To determine which IP-address the Raspberry Pi uses after startup we need an network IP-address
scanner like the Advanced IP Scanner.

Download link: https://www.advanced-ip-scanner.com/en/

The downloaded program gives you the option to install or run it.

7
2.1.2 Hardware

2.1.2.1 Raspberry Pi

For this project we use a Raspberry Pi. In this example an Raspberry Pi model 2B. But the other
models also will work.

2.1.2.2 LCD2004

To show the selected radio station and volume setting we use a LCD panel. In this case a 4 line 20
character panel (LCD2004). A 2 line 16 character LCD panel will also work (LCD1602), but you
won’t be able to show all information at once (also you lack 4 characters on a single line).

8
2.1.2.3 USB C-Media Audio Sound Card

To get some better sound we use a cheap USB sound card. In this case a C-Media Virtual 7.1 USB
Stereo Audio Adapter External Sound Card.

2.1.2.4 USB WiFi Adapter

The Raspberry Pi I use doesn’t support WiFi. Therefore we need a USB WiFi Adapter. In this case
an Edimax WiFi adapter.

9
2.1.2.5 Power Adapter AC 220V to DC 12V – 2A

To connect the audio amplifier we need an AC to DC adapter. In this case we will use the AC-DC
24W Isolated AC110V / 220V To DC 12V 2A Switch Power Supply Converter Module.

2.1.2.6 Power Adpater AC 220V to DV 5V – 1A

Of course we also need a power adapter for the Rasberry Pi. In this case we use a 5V – 1A
adapter. If you have a Raspberry Pi you need a 5V – 2A adapter!

10
2.1.2.7 Dual-Channel Amplifier

In this project we use an 15W TDA7297 Dual-Channel Amplifier Board.

2.1.2.8 Speaker set

In this project we use 2 Visaton FR 10 F speaker 20W speakers (max. 30W).

11
2.1.2.9 USB Hub

We need an USB hub to connect the USB Audio adapter because there is not enough room
between the USB connectors on the Raspberry Pi to connect both the Wi-Fi Adapter and the
Audio adapter.

Remark:
Using this USB hub wasn’t stable in my case, so I connected the USB audio sound card to the
Raspberry Pi although there wasn’t enough room for both the Wi-Fi adapter and sound card.

12
2.1.2.10 Connect Raspberry Pi and LCD2004

The connection between the Raspberry Pi and the LCD2004 is made through a so called i2c
connection.

On the Raspberry Pi Model 2B the pin connection is:

Raspberry Pi pin: I2C module pin:


+5v (2) +5v
GND ` (6) GND
GPIO2 (3) SDA SDA
GPIO3 (5) SCL SCL

If you have another model please check the pin connections for that model. They can differ from
the one mentioned here.

13
2.1.2.11 Connect USB devices

Connect the WiFi adapter, the USB hub and Audio Adapter to the Raspberry Pi.

14
2.1.2.12 Other hardware

We need a plug, contra plug, connector and wires for the power supply.

And some bults and nuts, 4 x M3 (for the LCD panel) and 4 x M5 (for the 2 speakers). And also
some copper nails and glue.

15
2.1.3 Format SD Card

Format the SD card with SD Card Formatter. Start SD Card Formatter:

 Change Volume label name (optional)  Format

 Yes (Ja)

16
 OK

2.1.4 Copy image to SD card

Start Etcher to copy image to SD card.

 Select image  select the downloaded image.

17
 Open (Openen)

 Flash

18
Wait...

19
2.1.5 Setup SSH and Wifi

To be able to login on the Raspberry Pi we need to enable SSH on the Raspberry Pi. Also we want
to configure WiFi so we can contact the Raspberry Pi over WiFi. This will enable us to configure
the Raspberry Pi using PuTTY and WinSCP. This is called a headless setup (we don’t need to
connect to a monitor to do the configuration).

2.1.5.1 Create a ssh file

Open your favourite editor like Notepad or Notepad++ and create an empty file ssh.

Save this file on the SD-card (boot):

20
2.1.5.2 Create a wpa_supplicant.conf file

Open your favourite editor like Notepad or Notepad++ and create an wpa_supplicant.conf file.

Edit the file with the following content:

country=NL
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
ssid="Your SSID"
psk="Your Password"
scan_ssid=1
key_mgmt=WPA-PSK
}

Save this file also on the SD-card (boot).

Result should be:

21
2.2 Setup the Raspberry Pi
2.2.1 IP Scan

Now we’re ready for the first time setup on the Raspberry Pi. Insert the SD-card and boot the
Raspberry Pi. Don’t forget to connect your WiFi adapter! Give the Raspberry Pi some minutes to
start up.

To determine the IP-address the Raspberry Pi uses we need to start the Advanced IP Scanner we
downloaded earlier.

Select the language you want to use  OK

 Run (you may install it...)  Next

22
I accept the agreement  Run

 Scan (Scannen)

23
It can take sometime for the Raspberry Pi to become active on the network. If you don’t see your
Raspberry Pi do a re-scan.

If you see you Wifi adapter (like Edimax in the example) you can use the IP-address shown (in this
example 192.168.0.31).

If you don’t see your adapter you probably forget to connect your WiFi adapter or you didn’t add
a wpa_supplicant.conf in the root directory of your SD-card. Also check the SSID and password in
the wpa_supplicant.conf file.

24
2.2.2 Login on the Raspberry Pi

Start PuTTY.

IP address: 192.168.0.31  Port: 22  Check SSH   Open

Tip: You can also save your session. Type a name by Saved Session like Internet Radio and click on
Save. Then you can use the saved session to login.

25
 Yes (Ja)

Login with username pi and password raspberry.

If you can’t login you probably forgot to put an empty ssh file on your SD card.

26
2.2.3 Configure the Raspberry Pi

Now we’re ready to configure the Raspberry Pi. Before Raspbian Stretch we had to expand the file
system. In Raspbian Stretch this is done automatically. Check you file system with the command:

pi@raspberrypi:~ $ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/root 15G 968M 13G 7% /
devtmpfs 460M 0 460M 0% /dev
tmpfs 464M 0 464M 0% /dev/shm
tmpfs 464M 6.2M 458M 2% /run
tmpfs 5.0M 4.0K 5.0M 1% /run/lock
tmpfs 464M 0 464M 0% /sys/fs/cgroup
/dev/mmcblk0p1 42M 21M 21M 51% /boot
tmpfs 93M 0 93M 0% /run/user/1000

As you can see the file system is already expanded.

Now start raspi-config with:

sudo rasp-config

We need to adjust our localisation to your country and region. Because I live in the Netherlands I
will you the localisation for that country. You should choose your own country and region
settings.

27
Remove default setting en_GB.UTF-8 by pressing Space.

28
Add your locale by pressing Space

 Tab  OK  Select your locale  Tab  OK

29
30
 Tab  Ok

31
32
 Tab  OK

 OK

33
For our LCD2004 display we need i2c en we need to enable this.

 Select

34
 Yes

 OK

35
Force audio not to use HDMI

36
 OK

 Finish

37
 Yes

The connection is lost and PuTTY will display a error message.

 Ok

38
2.2.4 Update and upgrade the Raspberry Pi

Wait for the Raspberry Pi to start again.

PuTTY  right mouse click on the top bar  Restart Session

Log in again.

We need to update and upgrade the Raspberry Pi. Commands:

sudo apt-get update


sudo apt-get upgrade

It will some time to update and upgrade the Raspberry Pi, so be patient.

pi@raspberrypi:~ $ sudo apt-get update


Ophalen:1 http://archive.raspberrypi.org/debian stretch InRelease [25,3 kB]
Ophalen:2 http://mirrordirector.raspbian.org/raspbian stretch InRelease [15,0 kB]
Ophalen:3 http://mirrordirector.raspbian.org/raspbian stretch/main armhf Packages [11,7 MB]
Ophalen:4 http://archive.raspberrypi.org/debian stretch/main armhf Packages [144 kB]
Ophalen:5 http://archive.raspberrypi.org/debian stretch/ui armhf Packages [28,2 kB]
Ophalen:6 http://mirrordirector.raspbian.org/raspbian stretch/contrib armhf Packages [56,8
kB]
Ophalen:7 http://mirrordirector.raspbian.org/raspbian stretch/non-free armhf Packages [95,2
kB]
12,0 MB opgehaald in 17s (692 kB/s)
Pakketlijsten worden ingelezen... Klaar

39
pi@raspberrypi:~ $ sudo apt-get upgrade
Pakketlijsten worden ingelezen... Klaar
Boom van vereisten wordt opgebouwd
De statusinformatie wordt gelezen... Klaar
Opwaardering wordt doorgerekend... Klaar
De volgende pakketten zijn achtergehouden:
raspberrypi-sys-mods
De volgende pakketten zullen opgewaardeerd worden:
apt apt-transport-https apt-utils base-files bind9-host bluez bluez-firmware
bsdutils cpp-6 cron curl dbus dhcpcd5 firmware-atheros firmware-brcm80211
firmware-libertas firmware-misc-nonfree firmware-realtek g++-6 gcc-6
gcc-6-base gnupg gnupg-agent gpgv iproute2 isc-dhcp-client isc-dhcp-common
libapparmor1 libapt-inst2.0 libapt-pkg5.0 libasan3 libatomic1 libbind9-140
libblkid1 libc-bin libc-dev-bin libc-l10n libc6 libc6-dbg libc6-dev libcc1-0
libcurl3 libcurl3-gnutls libdb5.3 libdbus-1-3 libdns-export162 libdns162
libfdisk1 libgcc-6-dev libgcc1 libgnutls30 libgomp1 libgssapi-krb5-2
libicu57 libidn2-0 libisc-export160 libisc160 libisccc140 libisccfg140
libk5crypto3 libkrb5-3 libkrb5support0 libldap-2.4-2 libldap-common
liblwres141 libmount1 libncurses5 libncursesw5 libpam-systemd libperl5.24
libpython2.7-minimal libpython2.7-stdlib libraspberrypi-bin
libraspberrypi-dev libraspberrypi-doc libraspberrypi0 libsmartcols1
libsqlite3-0 libssl1.0.2 libssl1.1 libstdc++-6-dev libstdc++6 libsystemd0
libtasn1-6 libtinfo5 libubsan0 libudev1 libuuid1 libwbclient0 libxml2
linux-libc-dev locales mount multiarch-support ncurses-base ncurses-bin
ncurses-term openssh-client openssh-server openssh-sftp-server openssl perl
perl-base perl-modules-5.24 pi-bluetooth python2.7 python2.7-minimal
raspberrypi-bootloader raspberrypi-kernel raspi-config
raspi-copies-and-fills rsync samba-common sensible-utils ssh systemd
systemd-sysv tzdata udev util-linux vim-common vim-tiny wget wpasupplicant
xkb-data xxd
126 opgewaardeerd, 0 nieuw ge▒nstalleerd, 0 te verwijderen en 1 niet opgewaardeerd.
Er moeten 168 MB aan archieven opgehaald worden.
Na deze bewerking zal er 1220 kB extra schijfruimte gebruikt worden.
Wilt u doorgaan? [J/n] J

Answer Y (or J) to continue.

2.2.5 Configure C-Media Audio Sound Card

Connect your C-Media Audio Sound Card. Check if the connection is succeful. Command:

lsusb

pi@raspberrypi:~ $ lsusb
Bus 001 Device 004: ID 7392:7811 Edimax Technology Co., Ltd EW-7811Un 802.11n Wireless
Adapter [Realtek RTL8188CUS]
Bus 001 Device 006: ID 0d8c:000c C-Media Electronics, Inc. Audio Adapter
Bus 001 Device 005: ID 05e3:0608 Genesys Logic, Inc. Hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet
Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. SMC9514 Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Install some audio utilities with the command:

sudo apt-get install alsa-utils mpg321 lame

Edit the alsa.conf so it will use the C-Media Audio Sound Card.

sudo nano /usr/share/alsa/alsa.conf

40
Scroll down and edit:

...
defaults.ctl.card 1
defaults.pcm.card 1
...

 Ctrl + X  Y (or J)

Create a new file:

sudo nano /etc/asound.conf

Edit:

pcm.!default {
type hw card 1
}
ctl.!default {
type hw card 1
}

41
 Ctrl + X  Y (or J)

Reboot you Raspberry Pi.

sudo reboot

2.2.6 Configure Music Player Daemon and Client

After reboot connect to your Raspberry Pi and install the Music Player Daemon (mpd) and client
(mpc). We need an update first because we need some extra packages. Commands:

sudo apt-get update

sudo apt-get install mpd mpc

We now need to configure the daemon. Command:

sudo nano /etc/mpd.conf

# An example of an ALSA output:


#
audio_output {
type "alsa"
name "My ALSA Device"
device "hw:1,0" # optional
mixer_type "software" # optional
# mixer_device "default" # optional
# mixer_control "PCM" # optional
# mixer_index "0" # optional

 Ctrl + X  Y (or J)

42
Restart mpd with command:

sudo service mpd restart

Test you configuration with the following commands:

mpc add http://playerservices.streamtheworld.com/api/livestream-redirect/SKYRADIO

mpc play 1

If you configured the music player correctly you now should hear the radio stream.

2.2.7 Configure the playlist

Now it’s time to configure your own playlist. In this book we’re going to make a playlist with all 19
Sky Radio internet stream. On the internet there are lots of link showing URL’s you can use. For
example for the mainly Dutch radio stations:

http://www.hendrikjansen.nl/henk/streaming.html#cz

To create a playlist use the following command:

sudo nano /var/lib/mpd/playlists/my_playlist.m3u

Content:

http://playerservices.streamtheworld.com/api/livestream-redirect/SKYRADIO
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR01
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR02
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR03
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR04
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR05
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR06
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR19
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR07
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR15
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR16
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR20
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR08
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR17
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR21
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR22
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR23
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR24
http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR28

 Ctrl + X  Y (or J)

43
This list contains the following radio stations:
• Sky Radio 101 FM
• Sky Radio Hits
• Sky Radio Summerhits
• Sky Radio Lovesongs
• Sky Radio 80s Hits
• Sky Radio 90s Hits
• Sky Radio 00s Hits
• Sky Radio 10s Hits
• Sky Radio Lounge
• Sky Radio Smooth Hits
• Sky Radio Singer-Songwriter
• Sky Radio Feel Good Hits
• Sky Radio Christmas
• Sky Radio Bootcamp tracks
• Sky Radio Running Hits Starter
• Sky Radio Running Hits Gevorderd
• Sky Radio Running Hits Expert
• Sky Radio Running Hits Stretch & Relax
• Sky Radio Pop-Up

To test the play list use the following commands:

mpc clear

mpc load my_playlist

mpc play 3

44
2.2.8 Configure LCD2004

We need some installations before we can use the LCD2004 panel. Commands:

sudo apt-get install python-smbus python3-smbus i2c-tools

sudo modprobe i2c-dev

sudo modprobe i2c-bcm2708

sudo nano /etc/modules

Add i2c-bcm2708 to the file:

i2c-dev
i2c-bcm2708

 Ctrl + X  Y (or J)

sudo nano /boot/config.txt

Scroll down and uncomment (if necessary):

dtparam=i2c_arm=on

 Ctrl + X  Y (or J)

Besure your LCD2004 is connected (i2c). Check if you panel is recognized with the command:

sudo i2cdetect -y 0

or

sudo i2cdetect -y 1

You now should see a address (probably 27).

45
To use the LCD2004 panel with Python we need some installations. We first need to make a new
directory to hold te sources. Commands:

cd ~

mkdir iradio

cd iradio

Now we need to copy the LCD Python scripts in this directory. Commands:

sudo apt-get install git

git clone https://github.com/paulbarber/raspi-gpio.git

To test the LCD panel we first need to edit some Python files. Commands:

cd raspi-gpio

nano lcd_display.py

First change the address to the dectected address (in this example 27):

# LCD Address
ADDRESS = 0x27

46
Then change the code to be able to display 20 characters (instead of 16) and 4 (instead of 2) lines:

def display_string(self, string, line):


centered_string = string.center(20)
if line == 1:
self.write(0x80)
if line == 2:
self.write(0xC0)
if line == 3:
self.write(0x94)
if line == 4:
self.write(0xD4)

 Ctrl + X  Y (or J)

47
Test your changes. Edit lcd_test.py. Command:

sudo nano lcd_test.py

Source:

from lcd_display import lcd

my_lcd = lcd()
my_lcd.display_string("LCD 2004", 1)
my_lcd.display_string("Raspberry Pi", 2)
my_lcd.display_string("Test line 3", 3)
my_lcd.display_string("Test line 4", 4)

 Ctrl + X  Y (or J)

Test the LCD panel with the command:

python3 lcd_test.py

48
Now the LCD panel should display the 4 lines you previously editted.

2.2.9 Flask

We want to operate the iRadio using an Web Application. There for we need a kind of webserver
to host our HTML-pages. In this book we will use Flask. With Flask you can create web applications
using Python.

To install Flask use the following commands:

sudo apt-get install python3-pip

sudo pip3 install Flask

Create a test file to test flask. Commands:

cd ~

mkdir flask

cd flask

nano testflask.py

Content (don’t use port 80, it will give you a security exception!):

from flask import Flask


app = Flask(__name__)

@app.route("/")
def hello():
return "Hello World!"

if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000, debug=True)

49
Start your test file. Command:

python3 testflask.py

Result:

Open an browser and enter address”

http://192.168.0.31:5000/

Result:

50
3 iRadio
3.1 Functional
Now it’s time to program the iRadio software. Functional we want:
• Use a playlist of radio stations
• Show the selected radio station on the LCD panel
• Show the volume setting in %
• Show the IP-address to use in you browser
• Show the radio stations in an HTML-page
• Select a radio station in an HTML-page
• Show the current volume setting in an HTML page
• Set a new volume setting in an HTML-page

We already configured the playlist (see 2.2.7).

3.2 iRadio.py
We use a Python3 script to program the iRadio.

Commands:

cd ~

cd iradio

mkdir static

mkdir templates

nano iradio.py

Source:

#!/usr/bin/python3
# iRadio (c) 2018 v1.0
from subprocess import Popen, PIPE, check_output
from lcd_display import lcd
from time import sleep
from flask import Flask, render_template
import os, socket, tty, sys, string

# Constants
INIT_VOLUME = "60"
DEFAULT_STATION = "1"
PROGRAM = "iRadio v1.0 (c) 2018"
INIT_SECONDS = 10

# Globals
output = ""
stations = {}
gVolume = INIT_VOLUME
gPreset = DEFAULT_STATION

51
# Get IP-address
def getIP():
gw = os.popen("ip -4 route show default").read().split()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((gw[2], 0))
return s.getsockname()[0]

# Set station list


def stationlist():
# Load name value pair list
with open("/home/pi/iradio/station.nvp") as myfile:
for line in myfile:
name, val = line.partition("=")[::2]
# print(name + " - " + val)
stations[name.strip()] = val.strip()

# Run os command
def run_cmd(cmd):
pid = Popen(cmd, shell=True, stdout=PIPE)
output = pid.communicate()[0]
return output

# Run os command
def mpc_play(index):
pid = Popen(["/usr/bin/mpc", "play", str(index)])
output = pid.communicate()[0]
return output

# Refresh LCD
def refreshcounter(seconds):
info_lcd.display_string("System Init: " + str(seconds), 3)

def refreshlcd(output):
# info_lcd.clear()
info_lcd.display_string("Sky Radio", 1)

# Get seperate line from output


index = 0
line_list = []

# Index = 0 - Line 1 = URL


# Index = 1 - Line 2 = Playlist info, playlist index of max_index
# Index = 2 - Line 3 = Volume setting (%) and others
#
# For example:
# Line 1 = http://playerservices.streamtheworld.com/api/livestream-redirect/SKYRADIO
# Line 2 = [playing] #1/20 25:39/0:00 (0%)
# Line 3 = volume: 10% repeat: off random: off single: off consume: off
# volume:100% repeat: off random: off single: off consume: off
#
for line in output.split(b'\n'):
strLine = str(line,'utf-8')
line_list.append(strLine)
# print(line_list[index])
index = index + 1

# Get name from URL3


name = line_list[0][-8:]
print(name)

# Get station name (name, value pair from stations)


print("SkyRadio: " + stations[name])
info_lcd.display_string(stations[name], 2)

# Get volume %
tempVol = line_list[2][7:-55].strip()
print(tempVol)

52
# Get volume from mpc
x = "%"
for x in string.punctuation:
if x in tempVol:
tempVol = tempVol.replace(x,"")

volume = int(tempVol)
print("Volume= " + str(volume))
info_lcd.display_string("Volume " + str(volume), 3)

# Get IP
info_lcd.display_string(getIP() + ":5000", 4)
return volume

# Startup
def startup():
# Startup
seconds = INIT_SECONDS
for x in range(0, INIT_SECONDS):
sleep(1.0)
seconds = seconds - 1
refreshcounter(seconds)
sys.stdout.write('.')
sys.stdout.flush()
print("")
print("Startup [1] Play station 1")
mpc_play(1)
sleep(1.0)
print("Startup [2] Current mpc")
output = run_cmd("mpc play 1")
sleep(1.0)
print("Startup [3] Set volume " + INIT_VOLUME)
run_cmd("mpc volume " + INIT_VOLUME)
volume = refreshlcd(output)
return volume

# Shutdown
def shutdown_now():
info_lcd.display_string(PROGRAM, 1)
info_lcd.display_string("", 2)
info_lcd.display_string("System Shutdown", 3)
info_lcd.display_string("", 4)
run_cmd("sudo shutdown -h now")
sys.exit(1)

# Start Flask
app = Flask(__name__)

@app.route("/")
def main():
# Main: show preset and volume
global gVolume
global gPreset
msg1 = "PreSet " + gPreset
msg2 = gVolume + "%"

# Set preset and volume messages


templateData = {
'message' : msg1,
'volset' : msg2
}

# Render html page


return render_template('iradio.html', **templateData)

53
@app.route('/volume/<volume>')
def set_volume(volume):
# Set volume level to volume input value
global gVolume
global gPreset

# Set volume level


gVolume = str(volume)
msg1 = "PreSet " + gPreset
msg2 = gVolume + "%"

# Set volume
output = run_cmd("mpc volume " + gVolume)
volume = refreshlcd(output)

# Set preset and volume messages


templateData = {
'message' : msg1,
'volset' : msg2
}

# Render html page


return render_template('iradio.html', **templateData)

@app.route('/volume_sub')
def set_volume_sub():
# Set volume level to current volume - 1
global gVolume
global gPreset

# Set volume
volume = int(gVolume) - 1

# Check min volume


if volume < 0:
volume = 0

# Set volume level


gVolume = str(volume)
msg1 = "PreSet " + gPreset
msg2 = gVolume + "%"

# Set volume
output = run_cmd("mpc volume " + gVolume)
volume = refreshlcd(output)

# Set preset and volume messages


templateData = {
'message' : msg1,
'volset' : msg2
}

# Render html page


return render_template('iradio.html', **templateData)

54
@app.route('/volume_add')
def set_volume_add():
# Set volume level to current volume + 1
global gVolume
global gPreset

# Set volume
volume = int(gVolume) + 1

# Check max volume


if volume > 100:
volume = 100

# Set volume level


gVolume = str(volume)
msg1 = "PreSet " + gPreset
msg2 = gVolume + "%"

# Set volume
output = run_cmd("mpc volume " + gVolume)
volume = refreshlcd(output)

# Set preset and volume messages


templateData = {
'message' : msg1,
'volset' : msg2
}

# Render html page


return render_template('iradio.html', **templateData)

@app.route('/channel/<channel>')
def set_channel(channel):
# Set preset to channel input value
global gVolume
global gPreset

# Set channel
gPreset = str(channel)
msg1 = "PreSet " + gPreset
msg2 = gVolume + "%"

# Set channel
output = run_cmd("mpc play " + gPreset)
volume = refreshlcd(output)

# Set preset and volume messages


templateData = {
'message' : msg1,
'volset' : msg2
}

# Render html page


return render_template('iradio.html', **templateData)

55
@app.route('/channel_add')
def set_channel_add():
# Set preset to current channel + 1
global gVolume
global gPreset

# Set channel
channel = int(gPreset) + 1

# Check max channel


if channel > 19:
channel = 19

# Set preset
gPreset = str(channel)
msg1 = "PreSet " + gPreset
msg2 = gVolume + "%"

# Set channel
output = run_cmd("mpc play " + gPreset)
volume = refreshlcd(output)

# Set preset and volume messages


templateData = {
'message' : msg1,
'volset' : msg2
}

# Render html page


return render_template('iradio.html', **templateData)

@app.route('/channel_sub')
def set_channel_sub():
# Set preset to current channel - 1
global gVolume
global gPreset

# Set channel
channel = int(gPreset) - 1

# Check min channel


if channel < 1:
channel = 1

# Set preset
gPreset = str(channel)
msg1 = "PreSet " + gPreset
msg2 = gVolume + "%"

# Set channel
output = run_cmd("mpc play " + gPreset)
volume = refreshlcd(output)

# Set preset and volume messages


templateData = {
'message' : msg1,
'volset' : msg2
}

# Render html page


return render_template('iradio.html', **templateData)

56
@app.route('/shutdown')
def shutdown():
message = "System Shutdown"

# System shutdown
shutdown_now()

# Set shutdown messages


templateData = {
'message' : message,
}

# Render html page


return render_template('iradio.html', **templateData)

if __name__ == "__main__":
# Init lcd
print("Init System");
info_lcd = lcd()
info_lcd.display_string(PROGRAM, 1)
info_lcd.display_string("", 2)
info_lcd.display_string("System Init: " + str(INIT_SECONDS), 3)
info_lcd.display_string("", 4)

# Init
stationIndex = DEFAULT_STATION
stationlist()
volume = startup()

# Run flask
app.run(host='0.0.0.0',debug=True, use_reloader=False)

3.3 station.nvp
For showing the selected radio station I use a so called name value pair file station.nvp.

Source:

SKYRADIO=101 FM
SRGSTR01=Hits
SRGSTR02=Summerhits
SRGSTR03=Lovesongs
SRGSTR04=198x Hits
SRGSTR05=199x Hits
SRGSTR06=200x Hits
SRGSTR19=201x Hits
SRGSTR07=Lounge
SRGSTR15=Smooth Hits
SRGSTR16=Singer-Songwriter
SRGSTR20=Feel Good Hits
SRGSTR08=Christmas
SRGSTR17=Bootcamp tracks
SRGSTR21=Hits Starter
SRGSTR22=Hits Gevorderd
SRGSTR23=Hits Expert
SRGSTR24=Hits Stretch&Relax
SRGSTR28=Pop-Up

Based on the selected station URL it will display the station name on the LCD panel.

For example if the url is:


http://playerservices.streamtheworld.com/api/livestream-redirect/SRGSTR07

Then it will display Lounge on the LCD panel (SRGSTR07=Lounge).

57
3.4 iradio.html
In the directory templates we define the HTML-page we want to use. Flask uses the template
directory for html pages.

Source:

<!DOCTYPE html>
<html>
<head>
<title>iRadio (c) 2018</title>
<style>
table, th, td {
font-size: 30px;
}
td {
padding: 5px;
}
</style>
</head>
<body>
<table>
<tr>
<td><a href="/volume/10"><img src="/static/10.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/20"><img src="/static/20.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/30"><img src="/static/30.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/40"><img src="/static/40.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/50"><img src="/static/50.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/60"><img src="/static/60.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/70"><img src="/static/70.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/80"><img src="/static/80.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/90"><img src="/static/90.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume/100"><img src="/static/100.png"
alt="" height="100" width="30"></a></td>
<td><a href="/volume_sub"><img src="/static/min.png"
alt="" height="50" width="50"></a></td>
<td><a href="/volume_add"><img src="/static/plus.png"
alt="" height="50" width="50"></a></td>
<td><a href="/volume/0"><img src="/static/mute.png"
alt="" height="50" width="50"></a></td>
<td>{% if volset %}<h4>{{ volset }}</h4>{% endif %}</td>
</tr>
</table>

<table>
<tr>
<td><a href="/channel/1"><img src="/static/sky_101fm.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/2"><img src="/static/sky_hits.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/3"><img src="/static/sky_summertime.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/4"><img src="/static/sky_lovesongs.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/5"><img src="/static/sky_80s.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel_add"><img src="/static/plus.png"
alt="" height="50" width="50"></a></td>
</tr>

58
<tr>
<td><a href="/channel/6"><img src="/static/sky_90s.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/7"><img src="/static/sky_00s.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/8"><img src="/static/sky_10s.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/9"><img src="/static/sky_lounge.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/10"><img src="/static/sky_smooth.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel_sub"><img src="/static/min.png"
alt="" height="50" width="50"></a></td>
</tr>
<tr>
<td><a href="/channel/11"><img src="/static/sky_feelgood.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/12"><img src="/static/sky_songwriter.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/13"><img src="/static/sky_xmas.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/14"><img src="/static/sky_bootcamp.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/15"><img src="/static/sky_starter.jpg"
alt="" height="128" width="128"></a></td>
</td>
</tr>
<tr>
<td><a href="/channel/16"><img src="/static/sky_gevorderd.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/17"><img src="/static/sky_experts.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/18"><img src="/static/sky_relax.jpg"
alt="" height="128" width="128"></a></td>
<td><a href="/channel/19"><img src="/static/sky_popup.jpg"
alt="" height="128" width="128"></a></td>
<td>{% if message %}<h4>{{ message }}</h4>{% endif %}</td>
<td align="center"><a href="/shutdown">
<img src="/static/off.png" alt=""
height="64" width="64"></a></td>
</tr>
</table>
</body>
</html>

59
3.5 Images
For each station an image is made and put in the static directory. Flask uses the static directory
for images.

60
3.6 LCD Python scripts
We also need some Python script to operate the LCD panel. We already downloaded these scripts.
See 2.2.8.

Copy the following scripts to your iradio directory (from the raspi-gpio directory):
• i2c_lib.py
• i2c_lib.pyc
• lcd_display.py
• lcd_display.pyc
• lcd_i2c.py

3.7 Test iRadio


Now we can start the iRadio script.

Command:

cd ~

cd iradio

python3 iradio.py

61
Result:

LCD panel:

62
You can now start a browser on your mobile, tablet, laptop or personal computer. The address is
displayed on the LCD panel. In this case: 192.168.0.31:5000.

You should now be able to change the station, set the volume or do a system shutdown.

63
4 Hardware

4.1 Splitting the power cable.


We nee two kind of power supplies. One for the amplifier (AC 220 Volt to DC 12 Volt) and one for
the Raspberry Pi (AC 220 Volt to DC 5 Volt).

For this I have split the power cable in a two way power supply.

One is connected to the 220 Volt AC to 12 Volt DC adapter.


The other one is connected to a power contra plug.

64
4.2 Power supply
Connect the power adapter input to a main connection (AC 220 Volt).

Connect the power adapter output to the dual channel amplifier.

4.3 Dual channel amplifier


Connect speakers, DC 12 Volt power input and Raspberry Pi to the dual channel amplifier.

65
4.4 Raspberry Pi
Connect the Raspberry Pi to the dual channel amplifier and the 5 Volt DC power adapter. Also
connect the WiFi adapter, LCD 2004 panel and USB audio sound card.

66
4.5 Case
Putting it all together in some kind of case. Perhaps an old radio or some other kind of case. Or
built you own case. In my case I built my own case. You will need some room for all the
components.

The dimensions I used are:


• Length 40 cm
• Height 16 cm
• Width 20 cm

First I made a drawing:

67
Then made a drawing on a plate of MDF.

An then putting it all together:

68
And after putting the hardware in, nailing and glueing it, the final result is:

69
70

You might also like