Quantcast
Channel: lucstechblog
Viewing all 318 articles
Browse latest View live

More I/O pins for your ESP-01

$
0
0

For some time something was nagging me.
I have always learned that the ESP-01 has only 2 I/O pins being GPIO-0 and GPIO-2.

The module has some more pins but they have dedicated functions. There is the Reset pin, the VCC and Ground pins and the CH-PD pin which has to be connected to VCC to let the chip function. Next to that there is the RX and TX pins but they are used for programming the chip.

Ehh are they ???

Well yes they are, but only in certain circumstances.

Lately I have been playing with ESP-Basic which is really great. It is a very usefull programming environment for the ESP8266 with loads of features and it gets the devellopment job done in a real short time. Really worth checking out.

Now ESP-Basic has one very convenient feature: it programs the ESP-8266 over the air (OTA). That means that when you have uploaded ESP-Basic to the ESP chip no more attachment is needed to your computer to get your Basic program into the chip. You only have to power it and then you can program it over wifi from your computer, notebook, tablet or even your phone. So there is no need anymore to carry around a notebook with a programming environment. The Basic interpreter is in the chip and your web-browser is your programming screen.



My usual devellopping setup is a Node-MCU which has many I/O pins. And I read on the ESP-Basic forum that it is possible to use the TX and RX lines as I/O lines. There: you might have learned something new here. They can be used as D9 and D10 and labeled GPIO-1 and GPIO-3.



Hey wait a minute.
The ESP-01 also has a TX and RX line. So would it be possible to use those as I/O lines.

The answer is YES but with some restrictions.

Above is the ESP-01 pin-out. You can see GPIO-0 and GPIO-2 and the TX and RX lines.

So let's make a simple setup on a breadboard.


The leds are connected through a 220 ohm resistor for delimiting power consumption.
GPIO-0 (yellow wire) is connected to the first led.
GPIO-1 (white wire) is the TX line connected to the second led
GPIO-2 (brown wire) is connected to the third led
GPIO-3 (green wire) is the RX line and connected to the fourth led.

It does not work !!!

Off course it did not work !!
The GND line is connected to the leds and supplies a minimal charge to the GPIO's. Therefore the ESP will not boot anymore when powered up. Remember when GPIO-0 is put to ground at start-up the ESP goes into programming mode. And we definitely do not want that. So we need the following setup.



As you can see the GND is interrupted by a switch. So we set the switch in the off-position at power-up time and after that switch it to the GND position.



And hell yeah everything works as expected.


 
I even tested it running on batteries.



timer1000,[blink]
button"off",[gooff]
wait

[gooff]
end

[blink]
fori=0to3
io(po,i,1)
delay1000
io(po,i,0)
nexti
wait

To test this setup for yourself use the above small basic program.
The program is straightforward. Every second it calls the blink routine which blinks GPIO-0 to GPIO-3 by using a for-next loop. 




It has been running on my desk for many hours without crashing. So it definitely works.

Another test


button"0",[pin0]
button"1",[pin1]
button"2",[pin2]
button"3",[pin3]
button"alles off",[alloff]
button"off",[gooff]
wait

[gooff]
end

[pin0]
io(po,0,1)
wait

[pin1]
io(po,1,1)
wait

[pin2]
io(po,2,1)
wait

[pin3]
io(po,3,1)
[alloff]
fori=0to3
io(po,i,0)
nexti
wait

Just to make sure that using the TX and RX lines as an output line would not interfere with normal Wifi operation of the ESP I wrote a simple Basic program that makes a web-page with buttons on it.


Pressing one of the buttons turns on the accompaning led. 


And this also worked flawlessly. As you can see. The picture shows that I turned on GPIO-1 and GPIO-3 over wifi. So the wifi communication does not interfere with the GPIO lines.

Any restrictions.

Well actually yes.
You can not use the extra pins as I/O pins. You can only use them as OUTPUT pins.
I tried using them as an input and they would just crash the ESP.

That is actually predictable as the ESP will look at the TX and RX lines for incoming communication and you will still need them when re-flashing the ESP for C, Lua, Python or other languages.

Not only Restrictions but Advantages

You can use GPIO-0 and GPIO-2 as input and GPIO-1 and GPIO-3 as output. This setup just gives you the possibility to have 2 inputs AND 2 outputs or 4 outputs on this tiny chip.

Summerising the setup:
- It will only work when programming OTA (over then air)
- GPIO-1 and GPIO-3 are only outputs
- Make sure there is no GND connection at booting

There are still some things to check:
- will this work with Python or Forth
- will this work when programmed with an FTDI (programming board) and then detached and operating as a stand-alone setup

So again something new to experiment with.

Till next time
have fun

Luc Volders

Washing Machine monitor

$
0
0
For an index off all my stories click this text.

Like most people we have a washing machine. No problem. There is however one annoying thing.

The washing machine is on the ground floor. And my girlfriend (who operates it, how bout that division of tasks) who is a painter has her work-place on the second floor of our house.
Now the washing machine will just shut down when it has finished its task. However when she is in her work-room she can't see that. So she has no other indication wether the machine has finished its task, as to leave her work every now and then and go downstairs to have a look. Waste of time and annoying. Surely there has to be an easier way, and there is.

Washing procedures.

The first thing to do to find an easier way to check if the washing machine has finished it's job is to look how it operates. Well that is fairly simple.



When the machine is put to work the led display and all kinds of indicators are on.



When the machine finishes it shuts itself down putting all indicators off. This offers possibilities.

It is about the same as checking wether the refridgerator door is open or closed like I did in this story:
https://lucstechblog.blogspot.nl/2017/03/cheapskate.html
I just wanted to make it a bit more fancy.

Overvieuw.

The ESP8266 is what I am going to build this with. I could not use the ESP-01 as I needed an analog input for the LDR, next to more I/O pins. So I used a NodeMcu. I am going to check the display of the washing machine with an LDR. Next to that I am going to attach a pushbutton to start the monitoring and a led that indicates that monitoring has indeed started. That is all we need for the hardware.
When the washing machine has finished I want it to send a signal to my girlfriends mobile phone. I am going to program the NodeMCU in ESP-Basic and use the Maker Channel from IFTTT for sending notice to the mobile phone.

For detailed information on installing ESP-Basic and use check this page:
https://lucstechblog.blogspot.nl/2017/03/back-to-basic-basic-language-on-esp8266.html

The hardware

Not much to it. Here is a list of what you'll need:

- NodeMCU
- USB Power supply (or powerbank)
- 1 led (I choose a green one)
- 1 220 ohm delimiting resistor for the led
- 1 Push-button
- 1 10K pull-up resistor for the button
- 1 LDR
- 1 10K pull-down resistor for the LDR



So for testing purposes I put everything on a breadboard.


 And here is how the prototype looks in real-life.

The software


io(po,d7,0)
timer1000,[test]
interruptd1,[change]
wprint|<bodystyle="background-color:LightSkyBlue ;">|
wprint|<spanstyle="color: red;">|
wprint|<h1style="text-align:center;">LucVolders</br>Washmachine</br>Monitor</br>|
wprint"<br/>"
wprint|<spanstyle="color: black;">|
wprint"LDR measures "
textboxvalue
wprint"<br/>"
wprint"keypress "
textboxkeypr
wprint"<br/><br/>"
button"<h2>Off</h2>",[Off]
wprint"<br/>"
wait

[test]
value=io(ai)
if(value<600)and(io(laststat,d7)=1)then
keypr="ready for use"
printwget("maker.ifttt.com/trigger/wash-finished/with/key/YOUR-PERSONAL-KEY")
io(po,d7,0)
endif
wait

[change]
ifio(laststat,d1)=0then
keypr="running"
io(po,d7,1)
endif
wait

[Off]
end

First a timer is set that will jump to the [test] routine which checks the LDR value every second. And an interrupt is defined that checks wether the button has been pushed.

Then the software starts with building a webpage which you can look at on your computer, phone or tablet. This is not necessary however convenient for testing and debugging. You can find the webpage by looking in your router at the IP-adress of the ESP and then pointing your web-browser to that IP adress like discussed here:
https://lucstechblog.blogspot.nl/2017/03/back-to-basic-basic-language-on-esp8266.html

The [test] routine then checks every second the value of the LDR.
The if statements tests wether the LDR measurement is below a certain value AND the LED is ON. If that is the case the washmachine has finished and the monitor program is working. The alert is send to IFTTT. The LED is then set OFF so that if the test is run again, no alert is send unless the LED has been set on again by pushing the button.

Replace YOUR-PERSONAL-KEY with your own personal IFTTT key, and if you like replace wash-finished with any other name you like as a trigger. Just make sure you use the same name in the next steps where you will create the IFTTT applet.

The [change] routine tests the state of the button and if that is 0 (button pressed) the LED is set ON.

That is all.

Testing.

Start with commenting-out the IFTTT trigger in the ESP-Basic program. Otherwise you will get notifications on your phone with each test you perform. You can do that by setting a ' in front of the line you do not want to run. In this case in front of the print wget( etc etc etc line.

For testing purposes I taped the LDR to the washing machine with some dark painters tape. I carefully looked at the values that appeared on the webpage when the lights of the washing machine where on and off. I tested with different environment lightning like open and closed curtains and on and off ceiling lights.Then values are shown on the ESP's webpage which will look as follows:


That gave me the right values that the LDR would register and I put those in the Basic program at the following line:

if (value < 600) and (io(laststat,d7) = 1) then

Replace the figure 600 with the value you will find.

Now uncomment the wget line by removing the '

Create an IFTTT applet

First make sure you have an IFTTT account and are connected to the Maker Channel. If everything went well you will have your personal IFTTT key. Fill that key in at the right place in the ESP-Basic program.

Start with choosing to make a new applet.



Click on the blue +this

Now choose a service. You are presented with many possibillities bus just type in web and then webhooks will emerge.

 Now choose a trigger. Not many choices at this moment but sufficient for our purpose. Click on "Receive a web request"



Complete the trigger fields. I typed Wasmachine monitor but replaced with wash-finished. Use exactly the same name as is filled in in the ESP-Basic program. Otherwise the IFTTT part will not work.




Now click on the blue +that

The IF part is done now we need to make the THAT part. Choose an action presents you again with many possibillities however type in no at the search functions and Notifications will emerge. Click on that.


Again not many choices so use the "Send a notification" action.

Fill in any text you want to be shown on your phone when the washmachine has finished. I chose the utterly original "The wasmachine has finished"


The final check

And you're done.

Autostarting the program.

Go back to the ESP-Basic editor and rename the program in default.bas and save it.

Now go to the SETTINGS page



Make sure you check, at the bottom, that default.bas is run at startup.

Real-life use.

You will have to have IFTTT installed on your phone/tablet and running

Plug the USB-Power plug in the wall and wait about a minute. The NodeMCU will by then have booted and the default.bas program will be running.

Set the washing machine ON and press the button on the breadboard.
The LED on the breadboard will go ON.

Just wait till the washmachine has finished, or shut the power down manually.

The LED on the breadboard will go OFF and you will get (when activated) an audible alert and maybe a blinking led on the phone/tablet.


On the start-screen of your phone you will see the IFTTT logo on the left upper part.


And this is what the notification screen on your phone will look like.


If you would open your webbrowser and point it to the ESP you will also find a notification on the webpage.

Additional benefit

Girlfriend Happy !!
And that is the best part.

Now I only have to put the hardware on a stripboard and then design and print a nice casing.

Till next time.
Have fun and keep your partner happy.

Luc Volders

Vibration detection

$
0
0
For an index of all of my stories click this text

I found this neat vibration detector called SW-18010P which just costs a few cents.



As you can see it is a very small sensor almost the height of a paperclip.
This makes it possible to build in secretly in all kinds of objects.

What does it do. Well exactly what the name indicates: it detects vibration. And it is very sensitive. Let's have a look at the inside.


As you can see the interior is very simple. It is a wire that as a matter of speak floats in a coil. So as soon as there is some vibration the wire will touch the coil and current can flow.

When I first received these sensors I thought they were broken. I tried to measure the contacts with a multimeter. However the vibration has such a short timespan that the multimeter is to slow to react on it.

So I decided to set up a test with a Wemos ESP8266 on a breadboard.



As far as I know there is no Fritzing part for this sensor so I used a reed-contact part for the schematics. As you can see the setup is simple.

The sw18010p is connected with a pull-up resistor to pin D2 of the Wemos.


Next I wrote a short program in ESP-Basic to test it.
It is very simple and straightforward and could easily be ported to Arduino code or Lua or whatever your favorite devellopment language is.

interrupt d2, [vibrated]
wait

[vibrated]
print "it moved"
delay 500
wait

Testing the IO port for a change from 1 to 0 could work. I intentionally say could as the vibration can easily be missed as it has a short timespan. Therefore an interrupt works best.


You can easily adapt this for use with an Arduino, Attiny or Raspberry PI or any other microcontroller of your liking.

I have a really good idea for a project with this, so keep coming back. In the mean time here are some ideas for which you could use this sensor:

- a box that reacts on knockin on it
- is the drawer being opened
- is the door being opened
- has my bike moved
- is somebody trying to steal my cookies

I am sure you can think of a few projects yourself. Basically anything that moves can be spied upon.

Till next time
Have fun

Luc Volders

ESP power reduction with deepsleep

$
0
0

We all now that the ESP8266 draws a lot of power. So what when you want to run it on a battery. That gives you a problem. Luckily we do have power-banks nowadays. They have a large capacity and will run the ESP8266 for a longer time. But even that can sometimes not be enough.

Suppose you have a project in which the ESP8266 is outside your home. Or it is in a place where no power outlet is available. Or you want to hide it. Etc. Etc. Etc. In these cases a battery or a power bank will not last long enough. What to do.

Deepsleep

The ESP8266 has a function that is called 'sleep' which is supported in most languages. If the ESP8266 gets into Deepsleep most functions are put on hold until the ESP wakes again.

There are several versions of sleep called Modem-sleep, Light-sleep and Deep-sleep.



As you can see from the table Deep-sleep is the most efficient and will reduce power use to a minimum. So that is what we want to use.

There are two methods of waking from Deep-sleep. Which one do you use ???

The automatic wake up version.

In this version GPIO16 (D0) is connected to the RST (Reset) pin of the ESP8266. The Reset pin is normally HIGH (even when not connected). When the RST pin is connected to GND it restarts the microcontroller.

Fortunately the build-in Deep-sleep function sends a LOW signal to GPIO16 (D0) when the ESP8266 wakes up from it's Deepsleep. This is done automatically.

It works like this:
We tell the ESP8266 to go into Deep-sleep. The only thing that is running inside is the RTC (Real Time Clock) and when the set time has expired the Clock sends a LOW signal to GPIO16 (D0).
We connect a wire between GPIO16 (D0) and RST. This makes sure that when the ESP8266 wakes GPIO16 (D0) sets RST to LOW and the ESP resets and wakes.

Setback.
This sounds ok but there is a setback. The ESP is a 32 bit processor and therefore the largest unsigned integer value it can handle is 0xffffffff being 4294967295, or 71 minutes. So when this method is used the ESP will wake about every 71 minutes. This is still less than 24 times a day so you will get an enormous power saving.

The manual wake up version.

There is also an infinite Deep-sleep method. If we use this version the ESP will stay in Deep-sleep until we manually give it a push. That is easily done. You just manually send a LOW signal to the RST pin.
You can do that with pressing a button or closing a reed-switch controlled by a magnet or any other mechanical switch that connects RST to GND.

When to use manual or automatic.

This depends on the situation and the project at hand.

Suppose you want the ESP to send the temperature or any other sensor reading every half an hour to Dweet, Thingspeak or your Domotics system you can use the automatic wakeup version.

Now if you want the ESP to send a signal when a button is pressed, or the fridge door is opened, or a window is opened you use the manual version. Just connect the switch or reed contact to GND and RST and you are done.

The different ESP versions.

ESP-01



Unfortunately the ESP-01 has no GPIO16 pin on the connector. So we can not use the automatic wake up function. You can only use the manual wake up function

NodeMCU




The NodeMCU has all the needed pins available. GPIO16 (D0) is available on the top left side. It is even called WAKE in the pin layout. RST can be found on the 3d pin from below on the left side.

Please be aware that this will not work on NodeMCU version 0.95 and lower. It only works on V1.0 and up. Well at least my version V0.95 did not work your mileage may vary but be carefull and test.

Wemos D1 mini



The Wemos D1 has GPIO16 (D0) as the 3d pin from the top on the left side. And RST is even the first pin. Tested and verified. Automatic wake up works on the Wemos D1.

Software commands.

Deepsleep is supported is most languages.

In Arduino (C++) you can use:

ESP.deepSleep(20e6);   // 20e6 is 20 microseconds

ESP.deepSleep(0); // infinite for manual wake-up


In ESP-Basic you can use:

Sleep 60   ‘60 seconds

Sleep 0    'sleep infinite for manual wake-up


In LUA (NodeMCU) you can use:

node.dsleep(60000000)

where 60000000 = 60 seconds = 60 x 1000 x 1000

Arduino example




I used a Wemos D1 mini for this and programmed it with the Arduino IDE. This is the infinite Deep-Sleep version which you have to wake-up manually. I did that with the loose-end wire that is connected to RST. Just plug it into GND to wake the ESP.



voidsetup()
{
pinMode(5,OUTPUT);
digitalWrite(5,HIGH);
delay(1000);
digitalWrite(5,LOW);
ESP.deepSleep(0);
}


voidloop()
{
digitalWrite(0,LOW);
}


The program sets the LED connected to GPIO5 (D1) ON, waits for a second and then sets the LED OFF and goes into Deep-Sleep.
The LED goes ON again when you connect RST to GND.


Basic example.



This is the schematic for automatic wake up. As you can see D0 is connected to RST.



cls
wprint"<h1>Deepsleep Test</h11>"
wprint"<br><br>"
io(po,d7,1)
button"testsleep",[sleeptest]
wait

[sleeptest]
io(po,d7,0)
sleep(60)
wait

The program is straightforward. Save it under the name 'default.bas' It sets a button on the screen and sets the LED ON. When the button is pressed the program jumps to the routine [sleeptest]. In [sleeptest] the LED is put OFF and the ESP is set to sleep for 60 seconds.

Before you run the program go to the SETTINGS page and make sure that 'run default.bas at startup' is checked. Otherwise the program will wake the ESP8266 but it will not restart the program automatically.

Just be aware that the ESP8266 will need about 30 seconds to start your Basic program after it is woken. The Arduino version is bloody fast.



This schematic is the version you will need for manual wake-up. When you want to use manual wake-up just alter the sleep command in:

sleep(0)

Real World usage

Let's see how it functions in real life.


The above reading is the current consumed when the ESP is working that is 0.07 Amps being 70 Ma.



And this is the reading when the ESP is in Deep-sleep.

Official figures from Espressif say that the actual current drawn in Deep-sleep is 300ua that is 0.3ma !!!

In the past I have published several projects on this weblog that could benefit from this technique.  for example the rain-sensor: https://lucstechblog.blogspot.nl/2016/08/rain-sensor-using-esp8266.html and the Thermometer: http://lucstechblog.blogspot.nl/2017/11/oh-no-not-another-wifi-thermometer.html.

I bet you can find projects that can benefit from this technique. I have one in my mind already.

Till next time
Have fun

Luc Volders

Motion detection with RCWL-0516 Radar

$
0
0
The most well-known motion detecting module is the PIR of which I described the basics in this story http://lucstechblog.blogspot.nl/2017/01/pir-basics-movement-detection.html and with which I made a simple alarm in this story http://lucstechblog.blogspot.nl/2017/05/ifttt-part-3-basic-alert-over-ifttt.html

However lately there is a lot of  fuss about a new module by the name RCWL-0516. So let's see what the difference with a PIR is.

A PIR makes a kind of infra red map of its location. After a while it makes a new infra red map and compares the two. When there is a change in the map that means there is motion and the PIR the makes its output high.
As this description suggests the PIR depends on a change of location of a heat source.

The RCWL-0516 is a magnetron / radar module. The module sends out pulses and measures the return time. If a change in the return time is detected that indicates that something in the path of the pulses has changed position. So the RCWL-0516 is not heat dependend but detects any movement. In real life that almost boils down to the same as most movements will mostly be made by people or animals which are also heat sources.

The connections


 
Do not let the size of this picture deceive you. The module is only 1.7 x 4 cm !!!

As you can see on the right side the module has 5 connections.

- 3.3 Volt
- GND
- OUT
- VIN
- CDS


I found no official papers on this module on the internet. However there are some hobbyists who have done some research and their findings is what I am using to work with.
 

As long as CDS is high the module functions. So it is the chip-select line. In the beginning I used the module with CDS unattached and it worked. Best results are gained when CDS is attached to +3.3 Volts.  Test what works best for you.

According to the literature I found on the internet the 3.3 Volts pin is an OUTPUT pin. So you should not use it to power the module. Power should be connected to VIN. Again according to the documentation found on the web anything from 4 to 28 Volt will work. I just attached it to the VIN from my NodeMCU unit and that works flawlessly.

First test

I did not find a Fritzing part for the RCWL-0516. I presume that that is because the module is so new.  I tried to make a simple alternative for it.




This first setup is very simple. In fact it almost looks like the first PIR setup.
Just attach a 5 volt source (I used an USB power bank) to GND and VIN and connect OUT to a led with a delimiting 220 Ohm resistor.

When I powered this setup for the first time I thought the module was not working or that I connected it wrongly. The LED was ON all the time. This will happen to you also if you use this setup. But do not worry. The module is not faulty and you did not do anything wrong. The module is just so sensitive that it notices any movement direct and therefore the LED will always be on.

So I sat totally still and the led went out.
When I as much as lifted a finger or nodded my head the LED went on again. This module is very sensitive.

The LED will stay on for about 2 seconds and then goes OFF if no movement is detected.

We have a long corridor in our house and I put this setup on one end and I stood on the other side and the module easily detected my movements. The distance was 6 meter !!!!

Attach it to an ESP8266

The next step was to connect the RCWL-0516 to an ESP8266. I used a NodeMCU for this as it supllies 5 Volts and 3.3 Volts and is easily powered over USB.




As you can see I powered it with 5 Volts from the NodeMCU and attached CDS to 3.3 Volts on the NodeMCU. I attached the led to D5 (through a 220 ohm delimiting resistor) and the RCWL-0516 OUT pin to D6 on the NodeMCU.

Software

For a quick result I wrote a program in ESP-Basic




timer1000,[test]

cls
wprint|<h1style="text-align:center;">LucVolders</br>RadarTester</br>|
wprint"<br/>"
textboxvalue
wprint"<br/><br/>"
button"<h2>Off</h2>",[Off]
wprint"<br/>"
wait

[test]
sensor=io(pi,d6)
ifsensor=0then
io(po,d5,0)
else
io(po,d5,1)
endif
value=sensor
wait

[Off]
io(po,d5,0)
end



First pin D5 is set as output (this is where the led is connected) and D6 is defined as input (where the RCWL-0516 output) is connected.
Next step is to set variable A to 0 so we can make an endless loop.
Then the program tests wether D6 is LOW. If that is the case the led stays off and the program jumps to subroutine green that sets the led on the web-page also off.
When D6 is HIGH (movement detected) the program sets the led on and jumps to subroutine red which sets the led on the webpage in the color red.

I put this setup in my room and aimed it at the door. Next I went outside my room and closed the door. I opened my webbrowser on my phone and look at what was happening.
The RCWL-0516 detected movement at a distance of 4 meter through a closed door !!!

This means that we can put this module INSIDE an enclosure and makes it more hide-able in case of an alarm system.

Summarising.

- The RCWL-0516 is a very cheap and yet sensitive motion sensor.
- It can be powered with anything from 3.3 to 28 volts
- The RCWL-0516 measures movement easily on a distance of 6 meter
- The RCWL-0516 measures movement from a distance of 4 meter through a closed door !!!
- The module just uses 1 data pin so can be used with an ESP-01 or even an Attiny85
- As the module can be powered with 3.3 or 5 volts and has a 3.3 signal pin it can be used with a Raspberry Pi

So you can build an enclosure for your project and put the RCWL-0516 inside and it will still work. Testing is recommended though.

Till next time.
Have fun

Luc Volders

Teatimer

$
0
0
For an index to all of my stories click here

At my work I drink lots of  tea. I start with 2 cups when I arrive, and then during the day I drink at least 8 cups. That is more then 10 cups of tea a day. The problem is that I often put the tea bag in the hot water and forget about it. The result then often is a cup that is too strong or even bitter.

The tea bags tell me the tea has to soak 2 to 3 minutes. Now how am I going to keep track of the time when I am busy at work. I could set a timer on my computer screen but that is too much hassle and not sexy at all. More sexy would be a timer with several leds that faded in or out. But what if the time ran out and I am not at my desk.

So I decided to build a tea timer.







The picture is taken in my hobby room, not at my work. And yes I need to reorganise as I have many projects cluttering up my desk.
 

My tea timer is a part electronics and part mechanical solution.
A microcontroller is attached to a servo. The servo drops the tea-bag into the cup and gets it out after a set time. This has been done a few times by using an Attiny85 with a servo and a pot-meter to set the time. That is a perfect acceptable solution. However I decided to do things different.

A tea-timer with a website

We are living in the IOT era so let's give the tea-timer a website. The idea is to take a NodeMcu (or Wemos d1 mini) attach a servo to it and do the rest in software. This is a bit more expensive as using an Attiny85 with a potmeter but has the advantage that it has power management on board. So I can feed it direct from an USB power source like a phone charger or power bank. Next to that I can control it from my phone or computer which is cool !!

The hardware

The hardware is straight-forward.



This could be done with an ESP-01 but I used a NodeMCU as it can be powered through USB which gives me an opportunity to use a powerbank as a powersupply when no computer is near. Next to that it supplies 5 volts to power the servo. The servo is attached to d7.

The software

Again I did this project in my favorite rapid devellopment environment: ESPBASIC. Well the software is so easy it speaks for itself.



The slider is used to set the number of minutes the teabag needs to soak. And there are 4 buttons. When the time is set with the slider and Start button is pressed the teabag will slowly be lowered into the tea. I lower it slowly on purpose as you do not want to be splashed by hot water. After the set time the teabag is lifted out of the cup slowly again.

The Up and Down buttons will rise and lower the teabag manually. This function is disabled when the start button is pushed.

The Off button also rises the teabag out of the cup but then ends the program.


timer500,[set]

wprint|<bodystyle="background-color:SaddleBrown ;">|
wprint|<spanstyle="color: SpringGreen;">|
wprint|<h1style="text-align:center;">LucVolders</br>TeaTimer</br>|
wprint"<br/>"
wprint|<spanstyle="color: White;">|

fori=1to45
servoval=i
io(servo,d7,servoval)
delay20
nexti

sliderminutes,0,8
wprint"<br>"
wprint"Minutes : "
minut2=minutes/2
textboxminut2
wprint"<br/><br/>"
button"<h2>Start<h2>",[Start]
wprint"<br><br>"
button"<h2>UP<h2>",[Up]
button"<h2>Down<h2>",[Down]
wprint"<br><br>"
button"<h2>Off</h2>",[Off]
wprint"<br/>"
wait

[set]
minut2=minutes/2
wait

[Up]
ifservoval<>45then
fori=0to45
servoval=i
io(servo,d7,servoval)
delay20
nexti
endif
servoval=45
wait

[Down]
ifservoval<>0then
fori=45to0step-1
io(servo,d7,i)
delay20
nexti
endif
servoval=0
wait

[Start]
fori=45to0step-1
io(servo,d7,i)
delay20
nexti
delayminut2*60*1000
fori=1to45
servoval=i
io(servo,d7,servoval)
delay20
nexti
servoval=45
wait

[Off]
ifservoval<>45then
fori=0to45
servoval=i
io(servo,d7,servoval)
delay20
nexti
endif
end

Some remarks concerning the program.

- The chosen time is tracked by the servoval variable.
- The SET function stes the minutes by 30 seconds
- The delay in the for loop determines how fast the bag will rise or be lowered
- The servo value 0 is down and 45 is up.
- Adjust the number 45 to your own needs, just keep the Pythagorean theorem in mind
- The delay in the Start function: delay minut2 * 60 * 1000 soaks the teabag for the choosen time.

To use this program start with installing ESP-Basic on the Nodemcu board. Open a new file and paste the above code in. Run the code and you are set to go. If you want to know how to do this look at my ESP-Basic introduction page which can be found here:
http://lucstechblog.blogspot.nl/2017/03/back-to-basic-basic-language-on-esp8266.html

The frame

The frame is made by experimenting. I made mine 24 cm high and 18 cm wide. First set the servo in the down position ( 0 degrees) and attach the arm so it rests horizontal. Attach a teabag and hold the servo at such a height that the teabag is on the bottom of a cup

 
Next position the arm so it is sticking as wide as possible out of the frame. In my case I positioned the servo at a hight of 18 cm and 11 cm from the left. This last part could be done better like 13 or 14 cm to the left. That way the cup is positioned a bit farther from the frame which is better when the arm is lifted.

I designed and 3D printed an arm and some feet for the frame. The feet have a gap which is 2mm wide which fits the carton I used for the frame. If you use a thinner carton just make the frame a bit longer and fold the carton at the bottom and press it in the feet. I did not print the frame itself. The feet took me about 2 hour to print so I was not patient enough to print the frame. If you want the STL files just send me an e-mail requesting them.

Thats it for this episode.
Have fun

Luc Volders

Installing the ESP32 the easy way

$
0
0
For an index to all my stories click this text

I can not believe it is already 2 years ago that Espressif introduced and released the ESP32.

For those who live in the void a quick introduction.
Espressif is the manufacturer of the ESP8266 chips. And the successor of the ESP8266 is the ESP32.


Above you can see a picture of the ESP family. The ESP8266 on the left and the ESP32 on the right. The form factor is not all that different but the possibilities are. Both are breadboard friendly.

 


Pinout of the ESP32. Just look at all the posibillities. Click on the picture to enlarge.

Well at least that was, what I presume, the plan when they released the ESP32. However things not always go as planned. The ESP8266 has a large base in the hobby/tinkerer world and we did not embrace the ESP32 as quick as was expected. There are in my humble opinion several reasons for this.

- The ESP8266 is sufficient for most projects
- The ESP32 is much more expensive
- The ESP32 is more difficult to install

On the last point I want to elaborate.
No matter how fond I am of Basic as a programming language and it is my preferred rapid devellopment environment for the ESP8266, the most used programming environment is undoubtedly the Arduino IDE. However installing the ESP32 into the Arduino IDE was (up to now) a painstaking tedious undertaking.

Considering these points it is understandable that most hobbyists stay with the ESP8266 notwithstanding the benefits of the ESP32.

However there might be a change coming up.
First the price of the ESP32 is dropping. A board comparable to the NodeMCU is now priced at about 4 Euro/USD at our chinese suppliers with free shipping !!!

https://nl.aliexpress.com/wholesale?minPrice=3.83&maxPrice=&isBigSale=n&isFreeShip=y&isNew=n&isFavorite=n&shipCountry=UK&shipFromCountry=&shipCompanies=&SearchText=esp-32&CatId=0&g=y&SortType=price_asc&initiative_id=SB_20180815111942&needQuery=n&groupsort=1

Next to that the Installation of the board in te Arduino IDE got simplified in such a way that you can install it in a few minutes and as easily as an ESP8266.

Before I show you how to install it, let's look at a few of the benefits of this board:

- running at 160Mhz (or 240 Mhz) thats double the speed of the ESP8266
- 520KB ram
- Wifi AND Bluetooth
- 18 channel ADC
- 10 capacitive touch pins
- 4 SPI interfaces
- 2 i2s interfaces
- 2 i2C interfaces
- Can Bus
- 16 PWM channels

It is obvious that the ESP32 should get more attention as there are far more possibillities with this module as with the ESP8266 especially now the price is so attractive.

Installing the ESP32 the easy way

I'll show you how to easily install the ESP32 boards in the Arduino IDE.



First go to https://www.arduino.cc/en/Main/Software and install the lastest version of the IDE on your computer. At this moment in time that is version 1.8.5



When installed open the Arduino IDE and from the file menu choose preferences (highlighted here).



In the preferences in the last line which is the Additional Boards Manager URL's copy the following URL:

https://dl.espressif.com/dl/package_esp32_index.json



Now open the boards manager which can be found in the tools menu under board.



In the boards manager look for ESP32 by Espressif systems.

As you can see in my version I already installed but you will get the option to Install. So choose install and see the magic happen.

First test

When installing has finished we can test the board.

Attach your ESP32 with an USB cable to your computer. Choose the right COM port just like you are used to do with the ESP8266.



From the Examples in Communication choose ASCII-Table. Compile and upload it withe the arrow symbol at the left top of the IDE.



Next open the Serial monitor at 9600 baud and see your first program run.

That's all.

Now you can easily start devellopping ESP32 programs with the ESP32.

Life just got a lot easier !!!

Projects with the ESP32 will be coming up in the future, so please visit this blog often.

Till next time
Have fun

Luc Volders

Breadboard hack for ESP32 and ESP8266

$
0
0
For an index to all my stories click this text

When the NodeMCU came out some years ago there was a problem fitting it on a breadboard. The module was simply to wide to fit.



So I devellopped an aid which you can see in the picture above and which was described in the story you can read here:
http://lucstechblog.blogspot.com/2015/09/nodemcu-breadboard-aid.html

However time passes and the Wemos D1 came out which solved the problem cause it had the same functionality as the NodeMCU but fitted nicely on a breadboard.

Then the ESP32 came along and the problem started all over.



As you can see the module itself fits on a breadboard but there is no space for attaching leads.

The problem can be solved by building a similar aid as I did for the NodeMCU. However there rises a problem. At this moment there are several versions of the ESP32 devellop boards around. And they have different sizes.
Well stick to one brand/model/size then !!!
Hey I am Dutch and I buy that module which is cheapest at the time. So I never know which will be my next buy.



With an ESP2866 (NodeMCU) you can put half of the module on the breadboard and let the other half stick outside. Most pins we need are on one side anyway.

This is not easily done for the ESP32 because it has interesting pins on both sides.



Fitting the ESP32 on two breadboards next to eachother is not going to work either. As you can see the ESP32 devellopment board I am using now is just a few mm short.

So then I had this stupid Idea.



Look at the breadboard. In the middle there is a gap with no holes.



So just cut it in half. Use a saw like above.



No we have to halves.



As you can see the ESP fits neatly as we can move the two halves away from eachother.

This works and is great for attaching cables to the breadboard. However there is no easy way to add switches etc.

Then I had another ide which I think is the best.



From one side of the breadboard bend the power rail off and cut it loose.



Now the ESP will fit neatly on two breadboards and you have ample space to add all kinds of electronics for your project.

The prices of breadboards are so darn cheap that it is not a waste to use this trick. You can buy 5 of them for about 4.50 Euro/USD at our favorite chinese suppliers.

Till next time
happy breadboarding

Luc

Back to school !!!

$
0
0
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

It's leaking

$
0
0
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



interruptd1,[leakdetected]

wait

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

interruptd1

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

Raspberry Internet Radio part 1

$
0
0
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

{
typehw
capture.pcm"mic"
playback.pcm"speaker"
}
pcm.mic{
typeplug
slave{pcm"hw:1,0"
}
}
pcm.speaker{
typeplug
slave{
pcm"hw:1,0"
}
}

pcm.!default{
typehw
card1
}

ctl.!default{
typehw
card1
}


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

importos
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

Raspberry Pi Internet Radio Part 2

$
0
0
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



importos
importsys

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 &'

whileTrue:
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: ')

ifnummer=="1":
os.system('sudo killall mpg123')
os.system(SOUND)
ifnummer=="2":
os.system('sudo killall mpg123')
os.system(SOUND2)
ifnummer=="5":
os.system('sudo killall mpg123')
os.system(SOUND3)
ifnummer=="b":
os.system('sudo killall mpg123')
os.system(SOUND4)
ifnummer=="w":
os.system('sudo killall mpg123')
os.system(SOUND5)
ifnummer=="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

Raspberry Pi Internet Radio Part 2 B

$
0
0
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

Eindhoven Maker Faire

$
0
0
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

Raspberry Pi Internet Radio Part 3

$
0
0
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

importos
importsys
importRPi.GPIOasGPIO

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)

defstation1(channel):
os.system('sudo killall mpg123')
os.system(SOUND)

defstation2(channel):
os.system('sudo killall mpg123')
os.system(SOUND5)

defstationq(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)

whileTrue:
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

Raspberry Cookbook

$
0
0
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

Raspberry Pi Camera

$
0
0
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

Raspberry Photo Camera 2

$
0
0
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

importpicamera
importRPi.GPIOasGPIO
importos

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)



deftakepic(picture):
GPIO.output(15,GPIO.HIGH)


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



defprogend(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)

whileTrue:
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

Raspberry timelapse camera

$
0
0
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

importpicamera
importRPi.GPIOasGPIO
importos
fromtimeimportsleep

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)

deftakepic(picture):
GPIO.output(15,GPIO.HIGH)
globalnumber
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)

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

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

whileTrue:
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

Alarm with Raspberry, camera and PIR

$
0
0
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

importpicamera
importRPi.GPIOasGPIO
importos
fromtimeimportsleep

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)

deftakepic(picture):
GPIO.output(15,GPIO.HIGH)
globalnumber
# 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)

defprogend(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)


whileTrue:
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
Viewing all 318 articles
Browse latest View live