Friday, September 28, 2018

Raspberry Pi Internet Radio Part 2 B

For a complete index of all my stories click this text

How to find Radio Streams

After my last story about building an internet radio with the Raspberry Pi Zero I got some mails from readers. They did not totally understand how to find the links for the radio broadcasts they wanted to listen to. As I believe there are more of you who struggled with this (but where afraid to ask) I am going to a detailed explanation here.

Basically all an internet radio does is to play an MP3 stream that is broadcast by a radio station. To make a more fancy internet radio (like I did in part 2)  it is nice to be able to choose between several radio stations. Therefore you will need to find the links to the MP3 streams.

I am going to show you how to do this on my windows system.



The easiest way to do that is to use Vtuner to find the streams. So first point your browser to: http://www.vtuner.com/


Look at the right side of the screen where it says : Check out our huge station list!
Click on this link and the next page appears.
 



As you can see you can search radio stations by Genre, Location or Language. If you browse by location you will be taken to a new page where the different regions are presented and per region the countries. 




Look at that huge list !!! Vtuner has just for the Netherlands 907 internet radio stations listed. And 3428 stations for Germany !! Scroll further down and you will find thousands of stations for the US.

Let us suppose you want to add CBS to your internet radio.
Just fill in CBS in the search box and click search.


 
The picture shows you what Vtuner has found and suppose we want the second one: CBS FM International
You can also see in the last column that it is an MP3 stream.





Press the green play button and in my Firefox browser a window opens in which the browser asks wether to open the stream with VLC player or to save the file (sorry it is in Dutch but thet's my native language).


Choose to save the file.

 
 
In Firefox at the right side of the screen is a down-arrow. This points to all the recently downloaded files. Open the download map and look for that particular file.



 

Open the file in Notebook and there is the desired link:

This is the link to the MP3 stream and this is the link we need to copy into our Python radio2.py program we made in the previous story. Just paste it in one of the SOUND lines in radio2.py like this:

SOUND =  'mpg123 -q http://217.28.20.20:8018/stream &'

And you're done.

Till next time.
Have fun

Luc Volders

Friday, September 21, 2018

Raspberry Pi Internet Radio Part 2

For a complete index of all my stories click this text

This is the second story in the series of 3 where I am going to make an internet radio with the humble Raspberry Pi Zero.

In the previous story I showed you what materials you need, how to install the raspberry OS and make it up to date, how to find radio stations on the internet and how to play an internet radio station from a Python program. You can re-read that story here: http://lucstechblog.blogspot.com/2018/09/raspberry-internet-radio-part-1.html
 

In this story I am going to expand the program so you will have the choice of multiple radio stations.

The radio stations

I love news shows and radio documentaries and radio drama. Therefore I choose the radio stations that broadcast these programs. It is a mix of 3 Dutch and 2 English stations for which the links are:

NPO1                       http://icecast.omroep.nl/radio1-bb-mp3
NPO2                       http://icecast.omroep.nl/radio2-bb-mp3
NPO5                       http://icecast.omroep.nl/radio5-bb-mp3
BBC Radio 4            http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio4fm_mf_p
BBC World news     http://bbcwssc.ic.llnwd.net/stream/bbcwssc_mp1_ws-einws

Feel free to replace these with your ow preferred radio stations.

The Python program

What I wanted in the end is a Raspberry Pi with just a few buttons that allow me to choose some preset radio stations without the need for a screen, mouse or keyboard. And that is what we are working towards. But maybe you want something different. That is why I am first going to make an internet radio with a nice menu that allows me to choose between the stations.



When your Raspberry has booted open a terminal window by clicking on its icon at the left side on your screen where the arrow in the picture points at.

Next make sure that you are going to work in the moe/pi directory by giving the following command:

cd ~

Then start the Nano editor by giving the next command in the terminal:

sudo nano radio2.py

This makes sure that the Nano editor is started and a new file is made with the name radio2.py

Then copy the next program and paste it in the terminal window



import os
import sys

SOUND =  'mpg123 -q http://icecast.omroep.nl/radio1-bb-mp3 &'
SOUND2 = 'mpg123 -q http://icecast.omroep.nl/radio2-bb-mp3 &'
SOUND3 = 'mpg123 -q http://icecast.omroep.nl/radio5-bb-mp3 &'
SOUND4 = 'mpg123 -q http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio4fm_mf_p &'
SOUND5 = 'mpg123 -q http://bbcwssc.ic.llnwd.net/stream/bbcwssc_mp1_ws-einws &'

while True:
 os.system('clear')
 print ("")
 print ("====================================================") 
 print ("             Internet radio stations")
 print ("====================================================")
 print ("")
 print ("1  Radio 1")
 print ("")
 print ("2  Radio 2")
 print ("")
 print ("5  Radio 5")
 print ("")
 print ("b  BBC 4")
 print ("")
 print ("w  BBC world news")
 print ("")
 print ("s  Shutdown system")
 print ("")
 nummer = input('What is your choice: ')

 if nummer == "1":
  os.system('sudo killall mpg123')
  os.system(SOUND)
 if nummer == "2":
  os.system('sudo killall mpg123')
  os.system(SOUND2)
 if nummer == "5":
  os.system('sudo killall mpg123')
  os.system(SOUND3) 
 if nummer == "b":
  os.system('sudo killall mpg123')
  os.system(SOUND4)
 if nummer == "w":
  os.system('sudo killall mpg123')
  os.system(SOUND5)     
 if nummer == "s":
  os.system('sudo killall mpg123')
  os.system('sudo shutdown now')


When the file is copied close the nano editor with CTRL-X and answer yes at the question wether the file has to be saved and check if the right filename is used: radio2.py

A closer look to the program.

The program starts with importing the necessary libraries for accessing Operating System functions from within Python.

Next the radio stations are defined. Let's look closer at one of the definitions.

SOUND3 = 'mpg123 -q http://icecast.omroep.nl/radio5-bb-mp3 &'

MPG123 calls the program that plays our MP3 broadcasts.
The -q makes sure that mpg123 does not display any information.
The & at the end of the line makes sure that mpg123 works in the background so that the python program radio2.py is always the program that has the focus,

while True:

makes sure that the program keeps running

os.system('clear')

Clears the terminal window so that we have a nice clean screen.

Then the screen is build up by the print commands and

nummer = input('What is your choice: ')

waits for us to input our choice followed by ENTER.

Nexts the IF statements test what choice we have made. Again let us look at an example:

        if nummer == "5":
                os.system('sudo killall mpg123')
                os.system(SOUND3)

If we choose "5" first any previous choice of a radio station is shutdown by sudo killall mpg123and then the new choice is activated by os.system(SOUND3).

And take a closer look at these lines:

        if nummer == "s":
                os.system('sudo killall mpg123')
                os.system('sudo shutdown now')

These lines make it possible to safely shutdown the Raspberry Pi by choosing s
If you have read my story on making an on-off button for your Pi you now have 2 ways to shut the Pi down.

That's all folks !!!

How to start the program.

After the Raspberry Pi has booted open a terminal window and type:

python3 radio2.py



Your screen will look like the picture above.

Autostart the program.

Maybe you do not want to start the program manually all the time. I surely don't. So the option is to start the internet radio program automatically when booting the Raspberry Pi.

This program has to be started after the Raspberry has completely booted and started its Graphical environment. To do this we need to alter the autostart file.

Searching the internet you can find numerous ways to autostart a Python program when booting the Raspberry. All these solutions have the same problem. The program starts but no terminal window is automatically opened. So there is no way you can choose the radio station or whatever.
So we need to have a specific way to autostart the program and open it in a terminal window. This is a bit more complicated.

Just follow the next steps and you´ll be good.

We´ll start with writing a simple script that will start the python program. Open again the terminal window and make sure you are working in the /home/pi directory by typing the following command:

cd ~

Next step is to write the script. Open the Nano editor with:

sudo nano startpy.sh

This will open the ditor and creates a new file called startpy.sh
Type in the following commands or copy and paste the next lines in:

#!/bin/bash
echo "starting internet radio"
python3 /home/pi/radio2.py

Close the editor with CTRL-X and answer yes to the question wether to save the file. Also check if it is saved with the right name: startpy.sh

Now this bash file can not be started without telling the OS that it should be an executable script. You can do that by typing the following command:

chmod +x startpy.sh

So if everything went well we now have an executable script that will start our radio2.py program. Let's try this by typing the following command in the terminal window:

./startpy.sh

The screen will briefly display starting internet radio and then the screen will clear and the radio2.py screen will be displayed. Don't forget to type the point and slash at the beginning of the command.
If this does not work carefully check the previous steps.

You can end the radio2.py program (like any Python program) by pressing CTRL-C.

The onlything left to do now is to make sure that the program starts when the Raspberry Pi boots. So in the terminal window type the following command:

sudo nano ~/.config/lxsession/LXDE-pi/autostart

The Nano editor opens and displays the autostart file which looks (in my case) like this:

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@xscreensaver -no-splash
@point-rpi

Now add the following line to the bottom:

@lxterminal -e /home/pi/startpy.sh

This line makes sure a terminal window is opened and startpy.sh is executed which in turn starts radio2.py in the terminal window !!!

The complete file will then look like:

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
@xscreensaver -no-splash
@point-rpi
@lxterminal -e /home/pi/startpy.sh

When done press CTRL-X to stop the editor and make sure you answer yes to the question wether the changes must be saved. Also like usual check if the right filename is used at saving: ~/.config/lxsession/LXDE-pi/autostart

Finished !!!!

You can now reboot your Raspberry Pi with the command:

sudo reboot now

Or reboot from the menu.

The Pi will shutdown / restart and when the GUI is started a terminal window will open in which the Internet Radio program will run.

Stand alone version

We now have a full working internet radio that allows you to choose from several broadcasters. However you still need a screen and keyboard to control it. This can be done through your computer with VNC. This means that your computer should be on.

What I want is an Internet Radio that works without a screen, mouse or keyboard and where you can choose the stations by preset buttons just like a normal radio. And that is what we are going to do in the next part.

Till then: have fun

Luc Volders

Friday, September 14, 2018

Raspberry Internet Radio part 1

My girlfriend and I love radio. Radio gives me up to date information and in depth intervieuws, documentaries and background stories. I prefer it far over television. The reason for this is that I can do things while listening to the radio. When watching TV it is (for me anyhow) not possible to do something simultaneous.

However the radio world is changing. Many radio stations here in the Netherlands are no longer available on the FM band, they are only available over cable or digitally. For listening to digital broadcasted radio stations one needs a special DAB+ radio. In my work-room I don't have a cable connection and I certainly do not want to buy a special DAB+ radio.

So listening to my favorite station on my computer would be an onvious solution. However the problem is structual. It not only occurs in my hobbyroom but in more rooms in our house. And I do not have a computer in every room. The solution would be a stand-alone internet radio. So let's build one !!

The Raspberry Pi Zero




After more as a year of waiting (due to popular demand) last year suddenly the Raspberry Pi Zero became available in the Netherlands. For those of you living under a rock: a bit of information. The Raspberry Pi Zero is a small (3cm x 7cm) full fledged computer. You add some components and you'll have a full Linux computer to your availability. It has a 1 Mhz broadcomm processor, 512Mb memory, a Full-HD HDMI connector, 26 available I/O ports, and 2 usb connectors. These are impressive specifications for such a small footprint. However the best part is that it only will set you back 5USD (6 Euro) !!




There is no network (UTP) connector. This can be solved in two ways.
There is a USB to network adapter widely available for just 5 euro. Or you can buy the Raspberry Pi Zero W which not only has Wifi but also Bluetooth and will cost just 10 USD (11 Euro).



You will still need some extra components to get it working:
- A SD-card for the operating system (8Gb is sufficient)
- An usb power supply (a 2amps phone power supply will do just fine)
- An USB hub for attaching mouse, keyboard, network adapter and audio Dac (I will get to that later)

And you will off course need a keyboard, mouse and screen. To start things up you can use your telly as the screen and borrow a mouse and keyboard from your computer. These will only bee needed when programming the Raspberry. When finished it will run so called headless, meaning that no mouse, keyboard or screen are needed anymore.

Even better: the Raspberry has a VNC license. So just download the VNC viewer on your PC and you will be able to use your PC as the screen, mouse and keyboard for your Raspberry. Your PC will function as a graphical computer terminal just like in the old days of computing. Activating VNC is a common practice with my setups as most of my Raspberry systems are running headless.




Next to that the Raspberry Pi Zero has no real audio connection (except for digital audio coming out of the HDMI connector). And while it is possible to create one with some complicated programs (by redirecting IO pins) and additional hardware it is easier (and cheaper) to buy a small USB-Audio-Dac. I bought mine for less then 2USD from Ali-Express.

The picture above shows the USB - DAC (Digital Analog Converter) with  on the left side a 3.5mm microphone connection and on the right side a 3.5mm headphone or active speakers connector. Active speakers are speakers that have a build in amplifier just like your computer speakers or speakers for your smart-phone.


That is about the complete picture.

The complete price-list for an internet radio.

As I am building an internet radio it is good to know how my DIY project will compare against a commercial DAB+ radio.

So here is the overall components list:

- Raspberry Pi Zero 6 Euro
- 8GB SD card 7 Euro
- USB power supply 5 Euro
- USB Hub 5 euro
- USB-network adapter 5 euro
- USB audio Dac 5 euro
- Speakers 11 Euro
Grand total 44 Euro

If you would use a Pi-Zero W you could save some money as you would not need the USB-Hub:
- Raspberry Pi Zero W 11 Euro
- 8Gb SD card 7 Euro
- USB power supply 5 Euro
- USB Audio Dac 5 Euro
- Speakers 11 Euro
Grand total 39 Euro.

 
I included speakers in the total price. However if you are going to attach the Internet Radio to your existing stereo or surround system no speakers are needed !!!
 

By good sourcing and scavenging your stockpile of rubble the total price can be lower.

Compare these prices to a commercial available DAB+ Radio or internet radio !!!

Installing the PI Zero Operating system.

There are ample descriptions on this all over the Internet. The best source is off-course the Raspberry home page which can be found here https://www.raspberrypi.org/documentation/  So I am not going into that.

And let's make sure the Linux version we are using is fully up to date. So open a terminal window by clicking on the terminal icon on the left-top side of the screen, where the arrow is pointing at.
As the picture below shows, a terminal window will open.

Now start by issuing the following commands:

sudo apt-get update
sudo apt-get upgrade


After each command press enter and wait till it is finished. Answer Y to any questions that might occur. After these have finished your Rapsberry Linux version is up to date.

Setting USB-Audio

As said before the audio will be send over HDMI by default. As we will not be using a monitor we need to make sure that the audio is re-directed to our USB audio DAC.

First make sure you are in the home/pi directory .




In the terminal window type:

CD ~

This makes sure you are in the home/pi directory.
In this directory we need to make a file that redirects the audio. to the DAC so carefully copy the following command:

sudo nano .asoundrc

And do not forget the . before the name asoundrc. The . makes the file hidden for normal vieuws.
The sudo nano command opens an editor window in which a file will be created called .asoundrc

Now type in the following commands or just copy and paste:



pcm.!default 

{
  type hw
  capture.pcm "mic"
  playback.pcm "speaker"
}
pcm.mic {
  type plug
  slave {    pcm "hw:1,0"
  }
}
pcm.speaker {
  type plug
  slave {
    pcm "hw:1,0"
  }
}

pcm.!default {
 type hw
 card 1
}

ctl.!default {
 type hw
 card 1
}


When done press Ctrl-x for stopping the editor and answer Yes to the question wether to save the file.

If everything went well you should now have a file called .asoundrc
You can check that by looking at the directory with the ls -a command

Now plug the speakers into the USB-Dac and attach the Dac to the Raspberry-Pi and reboot the Raspberry by choosing Reboot in the Shutdown menu (last item in the menu).




When the Raspberry has booted again open a terminal window and type in the next command:

speaker-test -t wav

If everything went as it should you should get a test signal on your speakers.

Playing MP3 files.

The standard Raspberry linux distribution does not support MP3 audio. And as most radio streams are broadcast in MP3 format we do need an MP3 player. There are several options for this. You could choose for Mplayer or for MPG123. Mplayer offers many features for audio and video playback. If you want most options you should choose this player. As I needed only MP3 playback I choose MPG123.

To install MPG123 just type in the terminal window:

sudo apt-get install mpg123

Finding radio stations

Most radio stations broadcast over the internet. But how to find them. Well Google is your friend. Just search for: list of internet radio stations
The most interesting directories I found were:

- http://www.listenlive.eu/
- http://dir.xiph.org/
- http://www.hendrikjansen.nl/henk/streaming.html
- http://vtuner.com/setupapp/guide/asp/BrowseStations/startpage.asp
- http://www.radiosure.com/stations/

The one I use most for searching stations is vtuner

Playing radio stations.

So you have found your favorite station and want the Pi-Zero to play it live for you.
For that we need to write a small Python program.

First open the terminal window again and make sure you are in the home directory. To get there just type:

cd ~

This makes sure you are directed to the /home/pi directory.

Now let's write the python program.

Type:

sudo nano radio.py

The Nano editor opens and you can write your program.
It's just a few lines:



#!/usr/bin env python

import os
os.system

('mpg123 http://icecast.omroep.nl/radio1-bb-mp3')


Just make sure you replace mpg123 http://icecast.omroep.nl/radio1-bb-mp3 with the link for the radio station you want to listen to.

After typing these lines press CTRL-X and make sure you answer yes to the question wether the program must be saved and check if the right name is used (radio.py).

That's it.
Let's test it.

In the terminal window just type:

python3 radio.py

And you should hear your favorite radio station over the speakers !!!

And that's all for now. The internet radio is working.

Next steps

In the second story in this series of 3 I am going to show you how to expand the python program to choose from more radio stations. And in the last story I am going to show you how to make a stand-alone headless (no screen, mouse and keyboard needed) internet radio with multiple preset stations.

Till then, happy listening

Luc Volders

Friday, September 7, 2018

It's leaking

After living for several years in our house we decided to have all our window frames replaced by plastic window frames. No more painting. And plastic does not deteriorate like wooden frames do. So long story short it is done.

However a problem has risen. When the wind blows straight towards our house and it is pouring we have a leak. At one time we had a real puddle of water in our living room which almost ruined our parquet.

Second problem: we are not always at home. Therefore it would be nice when we had some kind of leak detection system.

ESP to the rescue

The hardware setup.

There was one spot where it was leaking under the above mentioned conditions which do not happen often luckily. So we put a reservoir below the window-still where the leak was occuring. That will take care of the water pouring from the leak. However how to know when we are not at home.

So I started testing if I could detect water with my ESP. And that proved to be easy.



I just attached a wire to ground and a wire to an IO pin (D1) and that was sufficient.

If you want to replicate this project attach a 10K pull up resistor to the IO pin for safety. I can not guarantee that your ESP will react to water like mine does !!

I powered it with a power bank which supplies enough current to last a day. So we have to recharge it every day. Forunately we do not need this every day as it is not storming all the time !! A USB charger can do the trick when you have no power-bank available.

The notification.

How are we to know that it is leaking. Well like most people today I carry my phone always with me. It is an Android Phone. The obvious solution is to have the ESP send a notification to Els's and my phone.

And that is easily done.

For this purpose I use ESP-Basic as it is the quickest way to implement a project.

What the software does is test if the IO-pin is pulled LOW (when water is detected) and then trigger IFTTT to send a message to my phone.

The Basic program



interrupt d1, [leak detected]

wait

[leak detected]
iftttkey = "YOUR IFTTT KEY"
trig = "maker.ifttt.com/trigger/Leak Detected/with/key/" & iftttkey
print wget(trig)
print "yep did it"

interrupt d1

wait


This is as simple as it can get.

An interrupt is initiated when IO-port D1 changes state. This jumps to the routine [leak detected]
The variable trig is then filled with the IFTTT key and recipes name. And a wget command send the data to IFTTT


IFTTT

I am not going to write down how IFTTT works as you can read that in my 4 part story published on this weblog. Click here for the Index to my webpages and look for the IFTTT stories. Read them and it will be clear how IFTTT works.




I just give you here my IFTTT recipe which is self-explanatory.

And it works !!




Above you can see the complete setup.



Here you can see that the IFTTT recipe was triggered.

We are just still waiting for the repairs to happen.

Till next time.
Watch the flooding and have fun !!!

Luc Volders

Saturday, September 1, 2018

Back to school !!!

For a complete index of all my stories click this text

Sometimes I realise that I do lack some basic-background in my hobby. Well that is not strange as my education was economics and not electronics/computer science.



Therefore I was pleasantly surprised when I stumbled upon edX. https://www.edx.org/

edX is an institution that is founded by Harvard University and the MIT to provide for free-open-source courses. Nowadays universities from all over the world are contributing and famous names from the industry expalin some technical details from their expertise.



Here is their statement to the world.

This weblog forces me to pursue all kinds of technical information. It is about electronics sure, but they have to be programmed. So it is also about Arduino Language (C++), Python, HTML and CSS, Javascript (delving into that), Wifi protocols.

And guess what: EDX covers them all with courses for free !!!

What no charges ???

Indeed. No charges !!!

You can follow the courses in 3 ways (and each gives you the same lessons):
- Just read them and further nothing
- Read them, participate in the quizzes, discussions and tests
- The same as above but aim for a certificate.

In the last case you do have to make a payment. edX charces 49,-- USD for a certificate. Mind you that is not a degree. It is a certificate that shows that you followed the course positively ended with a test.

Some courses are running at the time you visit the site. Some are not. You can also enroll for courses from the past and those that are not running at the moment. They are all archived and you can get access to the course and follow it. There is obviously no feedback from staff or other students in this case and you can not get a certificate for courses that are not active.

So if you are interested in delving deeper into your hobby, have a look at the edX website and search for courses.

On the top of the webpage https://www.edx.org/ there is a search function. I searched for several points of interest to me like: C++ and Electronics. This is what they have on offer:


This is what the search for C++ brings




And here are the results for Electronics.

Loads of courses in all kinds of grades.

APP Inventor

Maybe you know by now that I use MIT's App-Inventor often to devellop my own APP's for my smart phone. However App-Inventors website does not provide all the information I need for what I want to do. That means: searching the web.



EDX has 2 couses on APP-Inventor a beginners course and an advanced course.
So being modest as I am I started with the beginners version.

How does it work ?

No formal classes. You do everything at home in your own pace. All couses are only online available. That has some disadvatages (no live discussions with fellow students) . But it also has enormous advantages. You can follow the course in your own pace and from anywhere in the world.


The APP-Inventor course is split up in 6 weeks. EDX advise that you study 6 to 8 hour a week.

Each part let's you make an APP with a step by step explanation.




There are video's




And there are quizzes. Some easy like the one above and some really though.

And at the end of each lesson you have a real working APP and learned all kinds of techniques and get side-information.

I learned for example a lot about lossy and lossless compression techniques for photo's and I have learned how to put hidden information in a photo (like a note or secret instructions). This is the suff that spies like ;)

You can follow the course on your own pace. So if you need 3 days (or 1 day) for the lessons of week 1 just move on to the next weeks lessons as everything is available direct from the beginning.
If you need more as the 6 weeks, no problem either. Do it at your own pace. However if you are not ready with the lessons when the course has finished you can not apply for a certificate.

Next to that I indeed learned a lot about APP-Inventor and I am sure that I will follow some other courses also.

Besides it gave me the back-to-school feeling (except for all the lovely girls in my classes).  It really was a lot of fun following the first course. So do yourself a favor and enroll and start learning something.

HIGLY RECOMMENDED.
And fun !!!

Till next time

Luc Volders