Friday, November 16, 2018

Raspberry timelapse camera

For an index to all my stories click this text

In my previous story about the Raspberry Pi Camera I showed you how to build a Lomography-like photocamera. As most steps described in this story are derivated from that story please read it carefully before proceeding: http://lucstechblog.blogspot.com/2018/11/raspberry-photo-camera-2.html

Now suppose you want a time-lapse camera. For those of you who are not familiar with the term: a timelapse camera is a camera that automatically takes pictures at certain pre-defined intervals. The fun in that is that you can make subsequent pictures of seeds germinating, molds growing, flowers opening and closing, a garden through the seasons, the build of a 3d print, a build of a project etc. etc. etc. It is a bit like a slow motion movie. The difference with a movie is that you will get seperate pictures, however there is software available to stich all photo's together to make a movie.

The Software

Actually we can use almost the same software as in the story about building the photocam. I just made some small alterations.


#!/usr/bin/python3

import picamera
import RPi.GPIO as GPIO
import os
from time import sleep

numberfile = open('/home/pi/number.txt','r')
number = numberfile.readline()
numberfile.close()
camera = picamera.PiCamera()
camera.resolution = (1920, 1080)

os.system('printf "\033c"')

GPIO.setmode(GPIO.BCM)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.output(18, GPIO.HIGH)

def takepic(picture):
        GPIO.output(15, GPIO.HIGH)
        global number
        number2 = int(float(number))
        number2 = number2 + 1
        namefile = "image" + str(number2) + ".jpg"
        camera.capture(namefile)
        numberfile = open('/home/pi/number.txt','w')
        numberstr = str(number2)
        number = numberstr
        numberfile.write(numberstr)
        numberfile.close()
        GPIO.output(15, GPIO.LOW)
        
def progend(stopprog):
 GPIO.output(18, GPIO.LOW)
 os.system('sudo shutdown now')         

GPIO.add_event_detect(3, GPIO.FALLING, callback=progend, bouncetime=300)

while True:
 takepic(21)
 sleep (10)

So where is the difference.First we only need one button. We only need the button to set the Raspberry ON or OFF.

As you can see there is just one interrupt and that is attached to that button:

GPIO.add_event_detect(3, GPIO.FALLING, callback=progend, bouncetime=300)
 

The line tests wether the button has been pressed and subsequently shuts the Pi down by calling the progend routine.

The takepic routine is exactly the same as the one in the Photocam story. It is not triggered by a button but triggered in the while True: routine

while True:
    takepic(21)
    sleep (10)


The sleep function is waiting for 10 seconds, then takepic(21) is called, and after that the routine is repeated.

The program is taking a picture around every ten seconds set by sleep (10).

Alter the figure 10 in any amount of seconds you might need.
If you want to take a picture every 30 minutes that would be sleep (30 x 60)

Here is the breadboard setup:


Wildlife adaption

The above software and hardware works great when making timelapse photo's of plants, molds, melting ice etc etc etc. However when you are making time-lapse photo's from animals I would remove the led attached to GPIO 15. This led is put ON everytime a picture is taken and then put OFF again. This could scare animals and ruin the sessions.

If you do not attach the LED on GPIO 15 you can leave out the next lines from the program.

GPIO.setup(15, GPIO.OUT)

This is in the setup section

GPIO.output(15, GPIO.HIGH)
GPIO.output(15, GPIO.LOW)

These can be found in the takepic(picture) routine.

Installing

My setup was made with the Raspberry Pi Zero which makes this very cheap. You could use the same setup and software with a Raspberry Pi 3

You will need to write the program with an editor and make it autostarting. This is all explained in the story about making the Photocamera so click here:
and follow the steps described there.

Real life example 

Naturally I tested it all using a simple setup and here are the results:








Take a carefull look at the pictures and you will see that they are not taken exactly 10 seconds after eachother. And that is no flaw.
Remember: the program takes a picture and then waits ten seconds. Taking the picture and writing it to the SD card will take some time.

In this short timelapse in which each time 10 seonds is waited this lead to time shifting. However if you're program waits 10 minutes or half an hour or even longer between pictures this will not be significant.

One last experiment I will be making with this setup is attaching a PIR to the Raspberry to make photo's of intruders or animals.

Till next time
Have fun

Luc Volders

Friday, November 9, 2018

Raspberry Photo Camera 2

For an index to all my stories click this text

This story is a follow up on the first story about the Raspberry Pi Camera. Before proceeding with this story I urge you to read the first story which you can find here: https://lucstechblog.blogspot.com/2018/11/raspberry-pi-camera.html

A Raspberry Photocam

The previous story about the Raspberry Pi Camera told you how to take a picture or make a video and alter the settings for the camera. . But that is not what my goal was. I wanted a camera and not a computer with a camera.
Meaning to say that I do not want a mouse, keyboard and monitor attached to my Raspberry. I just need some buttons to control it and a power supply. That's it. So first I'll define what I want:

- an ON-OFF button
- a led indicating that the camera is on or off
- a button for taking a picture
- a led that indicates that the picture is taken

Let's build it.

The hardware.

Start with soldering headers to the Pi Zero or, if you are confident about your soldering techniques, solder the wires direct to the PCB. The last option is the best if you are damn sure you are not going to use the Pi Zero for any other projects.


Next make the breadboard connections as shown above.

Gnd ==> GND
GPIO 3 ==> button
GPIO 21 ==> button 2
GPIO 18 ==> green led
GPIO 15 ==> blue led

Make sure you connect both leds to a 1K delimiting resistor otherwise you will damage your Raspberry Pi.



Above you can see my setup. This is made during my final tests, so no HDMI, keyboard or mouse but just a USB power bank. The Pi is somewhat hidden beneath the camera cable.

The software.

Again we will use Python to write software that controls our camera.

As usual start with installing a fresh Raspbian installation on a SD card and make sure that you update it. If you are not sure how to do that read my story about building an internet radio or check the Raspberry Foundation pages:
https://www.raspberrypi.org/documentation/installation/installing-images/README.md

Boot the Raspberry and wait till the desktop is ready. You can attach a monitor, keyboard and mouse to your Raspberry Pi, however I prefer controlling the Raspberry with my PC using VNC. This keeps me from using a second monitor, keyboard and mouse and also makes it more convenient to copy and paste texts and programs from and to the Raspberry. VNC is standard installed on every Raspberry and you really ought to check it out. For more info on this check the VNC pages: https://www.realvnc.com/en/raspberrypi/


Now open a terminal window by clicking on the terminal icon (where the red arrow poits to). first let us make sure we are working in the /home/pi directory by typing the following command:

cd ~

Open the nano editor and make sure a new file is opened called foto01.py by giving the following command:

sudo nano foto01.py

When the nano editor opens type (or paste) in the following code:


#!/usr/bin/python3

import picamera
import RPi.GPIO as GPIO
import os

numberfile = open('/home/pi/number.txt','r')
number = numberfile.readline()
numberfile.close()
camera = picamera.PiCamera()
camera.resolution = (1920, 1080)

os.system

('printf "\033c"')

GPIO.setmode(GPIO.BCM)
GPIO.setup(15, GPIO.OUT)


GPIO.setup(18, GPIO.OUT)


GPIO.setup(3, GPIO.IN, 

pull_up_down=GPIO.PUD_UP)
GPIO.setup(21, GPIO.IN, 

pull_up_down=GPIO.PUD_UP)

GPIO.output(18, GPIO.HIGH)



def takepic(picture):
        GPIO.output(15, GPIO.HIGH)


        global number
        number2 = int(float(number))
        number2 = number2 + 1
        namefile = "image" + str

(number2) + ".jpg"
        camera.capture(namefile)
        numberfile = open('/home/pi/number.txt','w')
        numberstr = str(number2)
        number = numberstr
        numberfile.write(numberstr)
        numberfile.close()
        GPIO.output(15, GPIO.LOW)


        
def progend(stopprog):
 GPIO.output(18, GPIO.LOW)


 os.system('sudo shutdown now')         

GPIO.add_event_detect(3, 

GPIO.FALLING, callback=progend, bouncetime=300)
GPIO.add_event_detect(21, 

GPIO.FALLING, callback=takepic, bouncetime=1000)

while True:
 pass
    


    

If all is done close the editor by typing CTRL-x and anser yes when asked it the file must be saved and make sure the right name is used at saving.

A closer look at the code

First the import commands make sure the necessary libraries are included in the program.

Then a file is opened and a variable called number is read from the file.
This variable is used to store the number of the photo that is made.

Let me get a bit deeper into this. Some programs incorporate the date and time functions into the name of the photo's when they are written to the SD card. That is neat because it tells you exactly when a photo is made. Unfortunately I can not use that. The camera will work stand-alone. So it has no internet connection and therefore will never know the right day and time. So if we would use day and time to stamp the name of a photo there is a possibillity of duplicates when the camera is shut down and restarted. So I will give each photo a subsequent number.

Next the camera is initiated and the GPIO's are set. For the buttons I make use of the internal pull-up resistors by using

    GPIO.IN, pull_up_down=GPIO.PUD_UP

Then GPIO 18 is set HIGH so the led goes on and we know the camera is ready for use.

Next two routine's are defined called def takepic and def progend.

In def takepic several things happen.

        GPIO.output(15, GPIO.HIGH)

First GPIO 15 is set HIGH so the second led will go ON. This way we know a picture is being taken.

        global number
        number2 = int(float(number))
        number2 = number2 + 1
        namefile = "image" + str(number2) + ".jpg"
        camera.capture(namefile)

These lines determine the name of the file that the picture will get. It consists of the word image followed by the number.

And then the command camera.capture(namefile) takes the actual photo and writes it to the SD card in the /home directory.

        numberfile = open('/home/pi/number.txt','w')
        numberstr = str(number2)
        number = numberstr
        numberfile.write(numberstr)
        numberfile.close()

These lines make sure that the new number is saved to the SD card. The benefit off all this is that when you shut down the Raspberry Pi and restart it the next number the photo should get is retrieved from the SD card so you will not get duplicate numbers which would overwrite existing photo's.

Then GPIO 15 is set LOW again so we know the camera is ready for taking another picture.

The second routine:

def progend(stopprog):
    GPIO.output(18, GPIO.LOW)
    os.system('sudo shutdown now')

safely shuts down the Raspberry Pi. GPIO18 is set to LOW setting the led OFF so we know the Pi is shut-down.

Pressing the ON/OFF button again will automatically reboot the Pi. This is happens when GPIO3 is shortly connected to ground as described before in my stopy about the Raspberry ON-OFF button.

GPIO.add_event_detect(3, GPIO.FALLING, callback=progend, bouncetime=300)
GPIO.add_event_detect(21, GPIO.FALLING, callback=takepic, bouncetime=1000)

These commands constantly test wether a button is pressed and when that has happened activate the right routine. The bouncetime parameter takes care of any bouncing from the buttons.

while True:
      pass

These commands make sure the program runs indefinite.

Resolution

While taking photo's in real life I noticed the following phenomenon.
At first I did not set the camera resolution in the program. When I started making photo's they just had a resolution of 760 x 480 pixels. I had no idea why that was till I realised that the Pi did not see a HDMI connection and therefore switched to a lower resolution.

Therefore I incorporated the following line in the program:

camera.resolution = (1920, 1080)

Now this is the standard Full HD resolution and that will be enough for most purposes. However if you need a higher resolution, which will give better pictures change this into:

camera.resolution = (3280, 2464)

The tradeoff is that the pictures take more memory so you will have to clear out the SD card more often.

Choose wisely.

Making number.txt

As you have seen the program writes the number of the photo to a seperate file. However when the Python program starts for the very first time it searches for the file called number.txt and when it does not find it gives an error and quits.

If that would be the case we could never make photo's.

So we need to make the file number.txt manually. In the terminal window type the following command:

sudo nano number.txt

When the editor opens type at the first position on the first line a figure. I suggest 0 (zero)

Close the editor with CTRL-x and like usual answer yes when asked if it needs to be saved and check the name.

We now have a file with the number 0 in it that will be read by foto01.py increased by 1 and makes sure that the first photo that will be taken will get the name image1.jpg

There are other (easier) ways to make a file with just 1 line of text and if you know how then do not hesitate. But thats for real Linux wizzards. For simplicity just follow the way I just described. 

Testing

Before we go on it is best practice to test if the program works like intended.

Open the filemanager and make sure it is pointed at the /home/pi directory.
In the terminal window type the next command:

python photo01.py

The green led (on/off) should go on. Now press the photo button (the one attached to GPIO21) and a picture will be taken.


As you can see in my example it was my 21st picture.

Autobooting

We now know everything works as it should so we have to make sure the foto01.py program starts immediately when the Raspberry Pi boots.

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 ~/.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 alter the autostart file so that it looks like the next lines:

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
python3 /home/pi/foto01.py
@xscreensaver -no-splash
@point-rpi

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 !!!!

So lets do one more last test. Reboot the Pi with the command:

sudo reboot now

Or reboot from the menu.

The Pi will shutdown / restart and when the GUI is started the foto01.py program is automatically started in the background. No terminal window will be opened and just the plain desktop is shown. Open the File Manager and you will see the previous picture you have taken. Now press the photo button and a new picture will show up.

Done !!!

Pressing the ON/OFF button will shut down the Pi and pressing it again will re-boot the Pi and the photocamera program will be direct available again.

Shutting down manually.

If you need to make alterations to the program you can shut down the program manually even if it is running in the background.

Open the terminal window and type the following command

sudo killall python3

This kills any running Python3 program.

The last steps.

Best thing to do is to move all components to a stripboard and make that as convenient as you like.

Remove all other attachments like HDMI cable, mouse, keyboard, USB network adapter etc. Just plug in a power supply (like a power bank) or connect batteries and we have a stand-alone camera !!!

Start the Pi with the ON/OFF button and wait till the green led goes on. Then you can make pictures and switch the Pi off with the ON/OFF button.

Just do not forget to attach the Pi regularly to your PC or a NAS or an external harddisk to transfer the foto's. Clean up the /home/pi directory and you are set to make more photo's.

Now make a nice case / housing and start fotographing the lomographic style. https://en.wikipedia.org/wiki/Lomography I am going to design a casing and print it.

Forographing in real life.

Make sure you use a good powerbank or batteries. I had some trouble with a powerbank that was supposed to supply 2000Ma (2 Amps) and my pi just kept on re-booting just like the trouble I had with a 5 meter USB power cable.

When I switched it for a different power bank everything went smoothly.

After pushing the ON/OFF button it takes about 33 seconds for the Pi to power up and start the program. So watch the led and start shooting when it is ON, not earlier. Undoubtedly the Pi3 would speed this up, however I did not test it. The Pi3 would use more current and is bigger. So for me that is no option. Just have patience.





Above you can see some pictures I took in the evening in our garden. Meaning there was not a lot of light. Nevertheless I am satisfied. Remember we are talking here about a 35 Euro camera !!! The original resolution was 1920 x 1080 but I cropped them for this weblog to 1200 pixels wide and about 700 high.

So the actual pictures are far better as what you see here. And then there is the possibillity to add some more buttons to set ISO value which would have made them a bit more brighter. Well nobody obstructs you to alter my design and add more functionality !!

Have fun shooting
Till next time

Luc Volders

Friday, November 2, 2018

Raspberry Pi Camera

For an index to all my stories click this text

I thought I deserved a present for all the hard work I have done for this weblog ;)




 So I bought myself a Raspberry Pi Camera. And boy it is fun to play with !!!

Some background information.

At this moment V2 of the camera is being sold. The difference is mainly that it has a much larger resolution as V1. The first camera had a 5 Megapixel resolution and the V2 version has an 8 Megapixel resolution. That is an enormous increase and yet the price of the camera is very acceptible: around 30 euro. That is including the cable for the Raspberry Pi 3. Mind you the price for the camera is 6 times the price of a Raspberry Pi Zero !!!
 





That brings me to the Pi Zero.
The camera uses a special cable to connect directly to a camera port which is available on any Raspberry Pi. So it can also be connected to a Raspberry Pi Zero starting from version 1.3. The camera connector is on the right side of the board. However the Pi Zero has (due to its form factor) a smaller connector and therefore you will need to buy a special camera cable.

The camera itself is very small it is about 1 x1 cm. However it is mounted on a pcb of about 2.5 x 2.5 cm. That's about a square inch. The camera is a mobile phone camera. Nothing wrong with that however there is no zoom option. The lens is fixed.




In the picture above you can see the standard cable and the camera with the Pi Zero cable with the smaller connections.

As stated the camera will work on any Raspberry Pi that has a camera connector and this means on all recent Raspberry's. I am going to use it on the humble Pi-Zero. So all steps that follow are done on a Pi Zero but there is no difference in executing them on a Raspberry Pi2 or Pi3.

Installing the camera

Attaching the camera to the Raspberry is a matter of plugging the cable in. You can't go wrong.

You do have to make sure that the camera is enabled in the Raspbian operating system. There are two ways to do this.



First you can choose "Raspberry Pi Configuration" from the preferences menu and activate the camera.




The second way is to open a terminal window by clicking on its icon (where the red arrow points) and give the following command:

sudo raspi-config



The configuration menu will open and first choose interfacing options.




Next choose Pi camera and activate it.

You now have to reboot the Raspberry Pi. You can do that in the terminal window by giving the following command:

sudo reboot now

Or you can choose Reboot from the "Shutdown menu".

First test

If the cable is attached and the camera is enabled we can test if all is working like it should.



Open the Python 3 Idle from the programming menu.

Type in the following commands and press enter after each command:



import picamera
camera = picamera.PiCamera()
camera.start_preview()


You will immediately see the camera picture displayed on your screen.
Move the camera around and you will see the picture move. And look how fast it is on that humble Pi Zero !!!


This will only work on the Pi itself connected to a monitor. The previeuw function will not work when you are connected to the Pi using VNC or SSH.

To stop just press CTRL-d


The picture you are seeing is full-screen. Therefore it is not easy to access the other windows (like Idle). Fortunaltely you can alter the position, width and hight of the preview screen by instructing the preview command:

camera.start_preview(fullscreen=False, window = (100,150,640,480))

The preview window will open at position 100, 150 and the dimensions will be set to 640 x 480 pixels. This way it will not cover your complete screen.

Taking a picture.

The previous steps just presented you a preview. What we want is to make a real picture. Well that is easy. We just have to alter one line. So open the Python3 Idle again and type in the next commands:

import picamera
camera = picamera.PiCamera()
camera.capture('testpic01.jpg')


You can use the name testpic01.jpg like I did or use any name you like. Just make sure it ends with .jpg otherwise the camera will not be able to save the picture.


Direct after the last command you can find the picture in the /home/pi directory.
Open the directory with the Filemanager and double click on testpic01.jpg




The picture will open with the Image Viewer program. Most likely the picture is something stupid like mine as the camera is just pointing at something random. Mine was pointing at the ceiling of my workroom.

As you can see the picture has a resolution of 1920 x 1080 pixels. That is the default resolution pictures are taken in. You can change that resolution in the maximum with the following command

camera.resolution = (3280, 2464)

Let's test that.





In Idle give the commands like the picture above shows:

camera.resolution = (3280, 2464)
camera.capture('testpic02.jpg')




And as you can see the second picture has the larger resolution of 3280 x 2464 which is 8081920 pixels which is the promised 8Mb. You can clearly see that both pictures are of excellent quality.

The settings

First let us look at the resolution settings.



The table shows the various resolutions and the aspect ratio. As you can see some resolutions make foto's and video's in old style (4:3) being almost square. And some resolutions make the pictures and video's in widescreen (16:9) ratio. The 1920 x 1080 resolution in 16:9 ratio is what in televisionland is called Full HD.

The top resolution of 3280 x 1464 will normally not be used for video purposes as the aspect ratio is 4:3 which will not be displayed well on a Full-HD television. It can however be diplayed on most computer screens without a problem. However be aware that this is memory hungry.....

There are more settings that we can all adress from Python: 


camera.sharpness = 0
camera.contrast = 0
camera.brightness = 50

camera.saturation = 0
camera.ISO = 0
camera.video_stabilization = False
camera.exposure_compensation = 0
camera.exposure_mode = 'auto'
camera.meter_mode = 'average'
camera.awb_mode = 'auto'
camera.image_effect = 'none'
camera.color_effects = None
camera.rotation = 0
camera.hflip = False
camera.vflip = False
camera.crop = (0.0, 0.0, 1.0, 1.0)


Sharpness, contrast, brightness, saturation can be given a value between 0 and 100. ISO can be set to 0 (automatic) or values from 100 to 800.
The camera.image_effect can be any of the following: negative, solarize, sketch, denoise, emboss, oilpaint, hatch, gpen, pastel, watercolor, film, blur, saturation, colorswap, washedout, posterise, colorpoint, colorbalance, cartoon, deinterlace1 and deinterlace2.

If you own a photocam most settings will be familiar to you. Sharpness, contrast and brightness are settings also found on standard camera's just like the ISO value. AWB means automatic white balance and with hflip and vflip we can turn the pictues. Most of these options will work in preview mode to. Play with these commands in Idle to get familiar with them.

Use them as you would use the command for setting the resolution.

Recording video.

Besides being a great photocam with many features the Pi Camera is also a great videocam. So let's try to make a video.

Start with opening a terminal window like described in the beginning of this story.

First make sure we are in the /home/pi directory by typing the following command:

cd ~

Next we make a Python program with the Nano editor with the name recvideo.py by giving the following command:

sudo nano recvideo.py

When the editor opens type in the following program:

import picamera
from time import sleep

camera = picamera.PiCamera()

camera.start_recording('video01.h264')
sleep(5)
camera.stop_recording()


When these lines have been typed in you can stop the editor by typing CTRL-x
Make sure you answer yes when asked if the file need to be saved and check if the right filename is being used.

Now start this program with:

python recvideo.py

After 5 seconds (determined by the sleep command) the program will quit and a file can be found in the /home/pi directory and it will be called video01.h264

You can play this file by using the omxplayer which is standard installed on the Raspberry Pi by typing the following command in the terminal window:

omxplayer video01.h264

The video will start to play after a short pause.

You can alter this program easily. Alter the sleep(5) command in a longer or shorter time period, and alter the name of the video each time for saving several video's.

More details and information.

The above described steps will lead the way for devellopping your own projects with the Pi Camera. However there is detailed information available on the website from the Raspberry Pi Foundation:

https://www.raspberrypi.org/documentation/usage/camera/python/README.md

And more in depth information can be found on:

http://picamera.readthedocs.io/en/release-1.13/install.html#alternate-distro-installation

Now let's build a real camera

In a follow up story I am going to build a camera that just uses a few buttons to control it and does not need a screen, mouse and keyboard just like my Internet Radio.


In the mean time use your imagination: add a PIR (https://lucstechblog.blogspot.nl/2017/01/pir-basics-movement-detection.html) so you can make photo's of animals feeding or someone entering your room/home, make photo's at intervals of minutes-hours-days so you can watch plants grow, or add a rain/temperature/whatever sensor to make photo's of certain events. The possibillities are endless.
 

Till then.
Have Fun

Luc Volders

Friday, October 26, 2018

Raspberry Cookbook

February 2015 I wrote that I purchased a book which made me very happy: the Arduino Cookbook from O'Reilly. http://lucstechblog.blogspot.com/2015/02/the-bible-arrived-i-have-been-looking.html




Well recently a bought another book from O'Reilly publishers that made me equally happy. And this is also from the cookbook series being the Raspberry Cookbook.

I am aware that the Raspberry Pi in all its variations is basically a Linux computer and that it is impossible to describe in detail all things you can do with a Linux machine. The author however manages to cover (in detail) many aspects of this popular micro computer.

The book starts with the process of installing the operating system, then covers the Linux commands you probably will use most. It descibes how to use these commands from the command line and also covers how to use most aspects from the Graphical User Interface.

Next the Python language is covered. Python is important because it is flexible, free, included with the Raspberry operating system and can be used for almost any Raspberry project you want to realise.

The book goes on with briefly describing some programs you can use for image manipulation (Gimp), Office programs, Media player software, Retro computing emulators and packages like OpenCV which is used for objects and person recognition.

It even describes building an internet radio although it uses a different approach from what I did: http://lucstechblog.blogspot.com/2018/09/raspberry-internet-radio-part-1.html

After that the (for me) most interesting part comes: interfacing the Raspberry Pi's with all, kinds of sensors. And lastly building webpages (with Bottle) that will show your sensor readings to the world.

At this moment I already have several Raspberry Pi's fully oprational in my home working as:
- a media centre (playing movies and series on my TV)
- a printer server (making possible that anyone in my house can print from any location)
- controller for my 3D printer
- Domoticz home automation system
- Internet radio

Nevertheless I learned a lot from this book and I am really glad I bought it.

And yes I know that you can find anything you need on the internet. And yes I am even aware that you can download this book as a PDF from the internet. However buying a book now and then stimulates the writers to write more interesting books and stimulates publishers to keep publishing interesting stuff for us. Besides that I prefer holding a real book in my hands over reading on a screen.

So if you are interested in starting projects with a Raspberry Pi do yourself a favor and spend a little money on this book. It is not expensive (I paid 26 euro) and packs a ton of information.


Maybe an idea for a Christmas present.....
Highly recommended !!

Till next time.
Have fun

Luc Volders

Friday, October 19, 2018

Raspberry Pi Internet Radio Part 3

For a complete index to all my stories click this text

This is the third installment in a series of 3 stories on how to build a cheap internet radio with a Raspberry Pi Zero.

The first story described what accessories you need and how to write a small Python program that actually playes one radio station. You can find that story here: https://lucstechblog.blogspot.com/2018/09/raspberry-internet-radio-part-1.html

In the second story I expanded the Python program to give it a nice looking menu that gives the possibillity to choose from a number of radio stations. You can re-read that story here: https://lucstechblog.blogspot.com/2018/09/raspberry-pi-internet-radio-part-2.html

An intermezzo was story 2B that showed how to find MP3 Broadcasts on the internet that you can incorporate in the program made in story 2. Read it here: https://lucstechblog.blogspot.com/2018/09/raspberry-pi-internet-radio-part-2-b.html

In this last part we are going to make the Internet Radio headless.
This means that it is a stand-alone system. The Pi Zero will start when you press a button and shuts-down again when you press a button. Next to that there will be buttons for choosing the radio stations. No monitor, keyboard or mouse will be needed to operate the internet radio.

To achieve this there are several steps to be made:

1) the hardware
2) the Python Internet Radio program
3) assure that the Python Internet Radio program is started automatically at booting the Pi

The hardware

I am giving you the breadboard layout for an Internet Radio control with an on/off button and 2 buttons for Radio stations. Just have a good look at the setup and you can expand this easily.


First let us have a look at the Raspberry I/O pins.

GPIO3 (pin 5) has a special ability. When you momentarily connect it to ground the Pi Zero will boot. Now that is a nice feature we happily will use to set the Internet Radio ON.

Several I/O pins have multiple functions. So best is (in this case) not to use them for our Internet Radio. That is no problem as there are my pins left that can be used. I will use GPIO20 (pin 38) and GPIO21 (pin 40) as the pins that choose the radio stations.

I used one extra GPIO being GPIO18 (pin 12) to attach through a 1K delimiting resistor to a led.
This led will go ON as the Internet Radio program is running and OFF when the Internet Radio program stops.



So the above breadboard layout shows you how to wire the buttons. As there are many I/O pins freely available you can expand this with as many buttons as you like.



Above you can see my setup in real life. I just altered one thing.




The button in the picture is not an ordinary push button. It is a pushbutton with a build-in led. So what I did is connect the button to GPIO3 and connect the LED part to GPIO18. You can use one ground lead that can be attached to the two connectors on the switch. Don't forget to attach a 1k delimiting resistor to the LED. If you don't you will damage your Raspberry PI

This way I have a switch with a build in LED that goes on when I start my internet radio and the LED goes off when I shut down the Raspberry Pi. Neat !!!

The Software

To install the software I always enable VNC on the Raspberry Pi and download the VNC viewer on my PC (https://www.realvnc.com/en/download/vnc/windows/) so I can install everything remotely and I do not need to attach an extra  keyboard, mouse and monitor to the Raspberry.

Start with installing and updating the Raspberry OS as described here:
https://www.raspberrypi.org/documentation/installation/installing-images/README.md

Make sure Real-VNC is active and connect to your PC. Not only can you operate the Raspberry from your PC but as a bonus it is easy to copy files between the PC and Raspberry by the normal copy and paste commands.



When the Raspberry has booted start with opening a terminal window by clicking on its icon on the top-left of the raspberry window. That's where the arrow is pointing.

Now first make sure you are working in the home/pi directory by typing the following command:

CD ~

Next open the nano editor and make sure it starts a new file with the name radio3.py by giving the following command:

sudo nano radio3.py

When the nano editor has started copy the following program from this weblog and paste it into the editor.



#!/usr/bin/python3

import os
import sys
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(18, GPIO.OUT)

SOUND = 'mpg123 http://icecast.omroep.nl/radio1-bb-mp3 >/dev/null 2>&1 &'
SOUND5 = 'mpg123 http://bbcwssc.ic.llnwd.net/stream/bbcwssc_mp1_ws-einws >/dev/null 2>&1 &'

os.system('clear')
os.system(SOUND)

def station1(channel):
 os.system('sudo killall mpg123')
 os.system(SOUND)
 
def station2(channel):
 os.system('sudo killall mpg123')
 os.system(SOUND5) 
 
def stationq(channel):
 GPIO.output(18, GPIO.LOW)
 os.system('sudo killall mpg123')
 os.system('sudo shutdown now') 
 
GPIO.add_event_detect(20, GPIO.FALLING, callback=station1, bouncetime=300)
GPIO.add_event_detect(21, GPIO.FALLING, callback=station2, bouncetime=300)
GPIO.add_event_detect(3, GPIO.FALLING, callback=stationq, bouncetime=300)

while True:
 GPIO.output(18, GPIO.HIGH)
   


When everything is pasted in the editor close the Nano Editor with CTRL-x and make sure the file is saved by answering yes when asked and look if the right filename is used.

A closer look at the Internet Radio program

The import commands make sure the necessary libraries are present.

GPIO.setmode(GPIO.BCM)

This command makes sure that we can use the GPIO names instead of the pin numbers.
Next the GPIO's are defined as input with a pull-up resistor except GPIO18 on which the led is attached.

SOUND = 'mpg123 http://icecast.omroep.nl/radio1-bb-mp3 >/dev/null 2>&1 &'

The SOUND variables are filled with the links of the MP3 streams and the & at the end of the command makes sure that the MPG123 playes is opened in the background so that the radio3.py program keeps the focus and does not open a terminal window.

Next the screen is cleared and the radio station that is defined in the variable SOUND is activated. This way the station strats playing direct when the program is started.

The def station routines first make sure anything that MPG123 is playing is shutdown and then open the new choosen radio station defined in the accompanying SOUND variable.

The last def routine called stationq is activated when the button attached to GPIO3 is pressed. This will shut down the Raspberry Pi Zero. This is the ON/OFF button that has been described in this story:

GPIO.add_event_detect(20, GPIO.FALLING, callback=station1, bouncetime=300)

These commands test wether a button has been pushed, and incorporate a waiting time to stabilise button bouncing.

The last commands:

while True:
    GPIO.output(18, GPIO.HIGH)

Are an endless loop and make sure the program keeps running.

Expanding.

Just as easy as expanding the hardware with more buttons is it to expand the software.

Just add some SOUND variables. Add some GPIO.add_event_detect commands with the right GPIO numbers and attach them to some extra def station1(channel): routines. This should not give you any trouble.

Autostarting the program.

This is the last step. We have to make sure the Internet Radio program will start immediately after the Raspberry Pi has booted. If that would not be the case we would need a screen, mouse and keyboard to start the program and that is just the thing we want to avoid.

Before we make things permanent test if the program works as expected. Type the next command in the terminal window:

python3 radio3.py

The default radio station should be playing immediately. Pressing one of the pre-set buttons will change the radio station and pressing the ON/OFF button will shut the Raspberry Pi Zero down.

Re-booting the Pi is now easy as you just have to press the ON/OFF button. Remember what I said previously: that connecting GPIO3 shortly to ground will boot the Raspberry.

The Pi will re-boot but the radio3.py program will not start automatically. That is the last step we need to implement.

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 ~/.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 alter the autostart file so that it looks like the next lines:

@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
python3 /home/pi/radio3.py
@xscreensaver -no-splash
@point-rpi


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 the radio3.py program is automatically started in the background. No terminal window will be opened and just the plain desktop is shown. If everything goes well the default radio station is playing. Sometimes that does not happen, or it just plays for a few moments and then stops. No problem just push one of the pre-set radio buttons and that station begins to play.

Pressing the ON/OFF button will shut down the Pi and pressing it again will re-boot the Pi and the Internet Radio program will instantly be working again.

Shutting down manually.

If you need to make alterartions to the program like adding radio stations or altering stations you can shut down the program manually even if it is running in the background.

Open the terminal window and type the following command

sudo killall python3 mpg123

This kills any running Python3 program and also kills any MPG123 stream.

Expanding further

Like said above it is easy to expand the hardware with more butoons and it is equally easy to expand the software to add more radio stations.

You can expand further.

- Add some MP3 music files to your SD card and dedicate a button to randomly playing songs. 
- Dedicate 2 buttons and call them next and previous to step through your music files.
- Let the internet Radio play songs from your NAS
- Alter the software so that it can not only play headless but that it can also be controlled in a terminal window

- Add an LCD screen or Oled screen that displays what's playing.
- Exchange the pushbuttons for a rotary switch

This way you could build a complete media system.


Casing

Off course you can build any casing to your liking even from cardboard. You could also check the flea markets and find some vintage radio in which you can build-in the Pi-Radio. 

Luckily for me I have a 3D printer so I designed a simple box and put my radio in it. 



Till next time. Have fun

Luc Volders

Friday, October 5, 2018

Eindhoven Maker Faire

For an index to all my stories click this text



Last weekend I visisted the Maker Faire in Eindhoven (Netherlands). For those who are not aware about what a Maker Faire is a short introduction.

Maker Faires are initiated by Make magazine. You probably may only use the name Maker Faire when you meet their conditions. These are probable the number of stands,  variety etc. So far for the legal mumbo jumbo. Besides this it really is great fun.

Maker faires are a place where all kinds of creative people meet and show their tinkerings, give workshops and demonstrations and have fun in general. The Eindhoven Maker Faire has grown from one to three halls and an outdoor happening.





At the entrance we were visited by some enormous scorpions and Robots.



As you can see the halls are big and there were a lot of visitors.



One of the stands that really impressed me was that of http://enablingthefuture.org/
This organisation which thrives on volunteers brings together tinkerers with a 3D printer and people that are disabled. What they do is design 3D printed hands and make them freely available to anyone who needs one.
So if someone (mostly children as the dutch health care does not help them) needs an artificial hand, or finger you visit the website and they will bring you in contact with someone who has a 3D printer and wants to help.
If you do have a 3D printer and want to help you are asked to print a sample for approval and when approved you will get in contact with someone who needs help.
As a printed hand or finger just costs a few euro's to make all is based on voluntarely base.
Go take a look at their website and do not be ashamed if you get emotional when you see the video's and read the stories there. Highly recommended. http://enablingthefuture.org/



Next stop. Model railway hobbyists.
Well it is not exactly my 'thing' but I was amazed at the amount of work these guys put into replicating buildings, sceneries and old trainstations. The building in the photo is a 3D printed replica of ancient Eindhoven station. It was printed and then painted. Just look at the quality !!



Then there was a stand from Inmoov. Inmoov is an open source project to build a robot. Loads of electronics involved and ages of 3D printing. The result is getting better and better.
The website4 can be found here: http://inmoov.fr/



Outside there were all kinds of crazy vehicles and contraptions. This one was a autonomous vehicle that drew all kinds of figures by dropping coloured sand.



And a gigantic horse.



And this took my particular attention. A stand of the Things Network. The Dutch Lora association. They demonstrated all kinds of Lora applications. For those in the blind. Lora is a LOng RAnge network system with frequencies that are open for everyone. So there are commercial networks and free networks like the Things network. You can send short messages over the network which can be accessed from anywhere. A bit like wifi but then for outdoors and over long distances. I will be doing some Lora projects myself so keep following this weblog.

Next to that there were 3D printers everywhere, workshops on Lora, programming etc, lectures about a new sattelite communication system for hobbyists, a hall dedicated to tinkering for kids with marble runs, building with carton, educational electronic projects, starting with programming etc etc etc. There were Micro:bits, DIY plastic recycling projects, simple robot building workshops, paper plane building, robots playing football, robots fighting eachother, robots, robots, build your own miniature car and race it against others. Just too much.

I arrived there at 10 o'clock just before opening and left at 5 o'clock just before closing time and had the idea that I still had not seen and tried everything I wanted to see and try. I really am sorry that I lacked time to attend sokme very interesting workshops....

If there ever is a maker faire which you can attend do yourself a favour and go there !!!

Find maker fairs in your country through this link: https://makerfaire.com/

Till next time
have fun.

Luc Volders