Pages

Friday, November 30, 2018

Alarm !!

For an index of all my stories click this text

This story tells about an alarm for paintings, But do not be set off by that. You can use the same alarm for doors that open, drawers and cookie jars.

As you might know by now, my girlfriend paints and often has expositions.



Due to the new and utterly stupid privacy laws in the Netherlands I had to blur out the faces from this photo.


At this moment she has an exposition in a gallery that shares its place with the local library. Nothing wrong with that, because it attracts more people. There is however a small problem and that is security. The building has security, the paintings are insured. However there is always a chance that something happens as the gallery is not manned all the time while the library is.

So I decided to design an alarm system for the paintings.

The idea

I wanted to be able to send a notification to my phone and that of some other people when a painting is agitated or moved. To do this I used several techniques and parts which have been covered in previous stories. It all comes together here.

First the movement detection. I am going to use the SW18010P vibration sensor for that. You can find the details about this sensor in this story: http://lucstechblog.blogspot.com/2018/05/vibration-detection.html

Next I am using an ESP8266 and I am going to program it in ESP-Basic. Find an introduction about ESP-Basic here: http://lucstechblog.blogspot.nl/2017/03/back-to-basic-basic-language-on-esp8266.html

The ESP is not going to do much. It just sits there and waits till agitation or movement is detected. I can not use a wall mounted power outlet. So I have to feed it with batteries. To use as less power as is possible I am going to use Deepsleep. Find details about Deepsleep here: https://lucstechblog.blogspot.com/2018/07/esp-power-reduction-withn-deepsleep.html

Next step is to send the information to mine and others phones. As Mit's App inventor has no push notification detection until now I am going to use IFTTT for this. You can find detailed information about IFTTT in this story (which has a link to the other stories about IFTTT): https://lucstechblog.blogspot.nl/2017/09/ifttt-4-send-notification-to-my-phone.html

And then there is a housing needed. The frame of the paintings is less then 2 cm thick. So I needed to design a housing that would fit into the frame and yet holds batteries and the perfboard.

Last but not least. The location has free internet that can be used by everyone. That is just what I need for this alarm to work.

The hardware.

I am going for a minimalistic design here. There has nothing to be done except detecting a movement and sending a message. So an ESP-01 will do the trick.

From the Deepsleep article (read it by clicking here
https://lucstechblog.blogspot.com/2018/07/esp-power-reduction-withn-deepsleep.html you will know that we can put the ESP8266 into Deepsleep and it can be woken by connecting RST (reset) to ground. We are going to use the second schematic from that article here. However we are going to modify it a bit as we do not need the led we used in the test-setup.




As you can see I attached the SW18010P directly to ground and the RESET pin of the ESP. To make sure the Reset pin only gets connected to Ground when needed I attached a pull-up resistor 10K to the VCC and the Reset pin. So reset will be high all the time until vibration is detected and that attaches it to Ground which wakens the ESP.




And here you can see the Stripboard version. you are looking at the soldering side. The components are in real life at the back-side.

The ESP is at the top and the antenna is at the top.




This is how it looks in real life.

What I did in this prototype is to solder the SW18010P thight against the stripboard. In my next version the SW18010P will be floating above the stripboard. I leave the leads longer and therefore there will be more space between the stripbaord and the sensor which makes it more sensitive.

Power


As the ESP01 is in Deepsleep it will consume very little power and therefore I can use batteries. 3 AA-type batteries will supply the power. Just like they did with the rain-sensor (read that story by clicking here).



The battery case I am using is just 1.6 mm high which neatly fits into the painting frame.
 

The stripboard has even less height and it's length just fits within the width of the battery case. The only thing we have to do is to expand the battery case and adapt it so the stripboard fits within.





The ESP-Basic Program

Programming the ESP in ESP-Basic is done with an on-screen editor in your web-browser which makes programming and editing very comfortable. Again: read the basics (pun intended) about ESP-Basic programming here: http://lucstechblog.blogspot.nl/2017/03/back-to-basic-basic-language-on-esp8266.html

The program is very straightforward:



cls
wprint "I am awake"
wprint wget("maker.ifttt.com/trigger/alarm/with/key/PUT-YOUR-KEY-HERE")
wprint "<br>"
button "go to sleep",[sleep]
wprint "<br>"
button "stop",[stop]
wait

[sleep]
cls
wprint "sleeping"
sleep 0
wait

[stop]
end


No fancy webpage. Just a button to start the sleep function and a button to stop the program.

What happens when you power the ESP01 up for the first time is that it sends a notification through IFTTT. This makes sure that everything works as intended and you have an internet connection. Now you can mount the ESP in the frame.




Then press the "go to sleep" button

The ESP enters Deepsleep mode for an undefined time (sleep 0). When the painting vibrates the sensor will connect Ground to the Reset pin of the ESP01 and the ESP will awake and start the default.bas program.



Just make sure in the SETTINGS page that default.bas wil automatically run when the ESP is booted. So the cycle just repeats.

IFTTT

I have written several stories about IFTTT which I suggest you read them all. Here are the links:

https://lucstechblog.blogspot.nl/2017/04/ifttt-if-this-then-that.html
https://lucstechblog.blogspot.nl/2017/05/ifttt-part-2-maker-channel.html
https://lucstechblog.blogspot.nl/2017/05/ifttt-part-3-basic-alert-over-ifttt.html
https://lucstechblog.blogspot.nl/2017/09/ifttt-4-send-notification-to-my-phone.html



Start with making a webhook (the IF section) and link it to a notification (the THEN section).

The notification



Here you can see what happens on my Android Phone when vibration is detected.


If you want a copy of the STL files of the casing for 3D printing or adjusting for your own needs just send me an email.


Till next time
Have fun !!

Luc Volders

Friday, November 23, 2018

Alarm with Raspberry, camera and PIR

For an index to all my stories click this text

This is (for now) the last in a series about working with the Raspberry Photocamera.

The first story that describes how to make a photocamera can be found here: https://lucstechblog.blogspot.com/2018/11/raspberry-pi-camera.html And I really urge you to read that story first before starting this project. This project will use many steps explained in the Photocamera story that will not be repeated here.

The second story is a project for making a timelapse camera. You can re-read that story here:

https://lucstechblog.blogspot.com/2018/11/raspberry-timelapse-camera.html

And this story is about making a camera that takes a picture when movement is detected. The story uses a PIR which basic functionality is described here:
https://lucstechblog.blogspot.nl/2017/01/pir-basics-movement-detection.html

You can use this as a security camera that takes pictures when someone enters a room or approaches your front door. You can also put this at a bird (or other animals) feeding place. As usual: use your imagination.

The difference with the photocam project

The difference in using a PIR in stead of a pushbutton for making a photo is in the use of the GPIO pins. Normally the state of an IO pin is high and we pull it LOW when pushing a button.

The PIR works different as you may have read in my story about it (https://lucstechblog.blogspot.nl/2017/01/pir-basics-movement-detection.html). The PIR normally sends out a LOW signal and switches to HIGH when movement is detected. We will look at the software adjustments for this later on. First let us have a look at the hardware.

The Hardware

The hardware is basically the same as the hardware for the Photocamera.



The ON/OFF switch and the leds are the same. The switch for taking the picture has been replaced with the PIR. The PIR gets its power from Pin No2 on the raspberry which delivers 5 volts.
The PIR (as described in the pir-basics story) works at 5 volts but delivers 3.3 volts on its trigger pin. However your's might be different so check that !!! Remember the Raspberry Pi is not 5 volts compatible. So only send a 3.3 volts signal to the IO pins.

The Software



#!/usr/bin/python3

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

sleep(5)

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

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_DOWN)

def takepic(picture):
        GPIO.output(15, GPIO.HIGH)
        global number
        # number2 = int(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()
        sleep(6)
        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.RISING, callback=takepic, bouncetime=10)


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


As you can see the program in Python is not that much different from the Raspberry fotocam software which you can find here:

Like discussed in that previous story, write the program with the nano editor and put it in the home/pi directory.

As the program needs a way to wait between taking pictures the sleep function is imported from the time library.

At the start of the program the line:

sleep(5)

makes sure that the PIR is settled before the program really begins. The story about the PIR Basics showed that the PIR needs about a minute to test its environment before it can be used.
The PIR gets power as soon as the Raspberry Zero is powered up. So the PIR should be settled when the program starts. Test if that is indeed the case in your situation and alter the sleep(5) in a longer time when needed. If you are using a Raspberry PI 3 you should really test this well as the Pi3 boots many times faster as the Pi Zero does.

The GPIO setup for pin 21 has been changed in:


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

This makes sure that the PIN is kept in the LOW state until the PIR puts a HIGH signal on the pin.

The def takepic(picture) routine has a line added that stops the program for 6 seconds after taking a picture. This makes sure the picture that is just taken is written safely to disk and the PIR is reset again if no movement has been detected anymore.

The interrupt routine for pin 21 (where the PIR is attached to) is also altered:

GPIO.add_event_detect(21, GPIO.RISING, callback=takepic, bouncetime=10)

The interrupt wil now be triggered when GPIO 21 receives a HIGH signal.

As I said the alterations to the Photocam software are few.

Enter the file in the nano editor and save it in the /home/pi/ directory. Call it alarm.py or any name you like.

Alter the startup file as I showed in the fotocam story but now with the same name of the just saved file:

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

That's all folks.

Modifications.

You now have a full working Raspberry motion detecting camera.
If you want to use it as a safety camera that takes pictures when someone enters your home/room or steals your butterfingers I suggest to leave out the leds and hide the camera in a non obvious place. This way no intruder will know a picture is taken. If you leave out the leds in the hardware you can remove all references to GPIO 15 en 18 in the software too.

I am thinking of making a double function camera. Using a button to take a picture and also have the possibility of using it as a motion camera. Should not be to difficult. Use a switch to choose between the PIR and the button. Make sure that the button is connected to a pull-down resistor (in stead of pull-up) and connected to +5 volts so it gives a LOW when not pushed and a HIGH when pushed just like the PIR. That way you would need almost none alterations to the software.

Till next time

Have fun

Luc Volders

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