Category Archives: Free time

Part 3/3: Reading analog input using RPi

Continuing from the previous example, we would like our LED to turn on automatically, based on the light level of the environment.

Photoresistor

First we need to read the value of the photocell that measures the value of light. Photocells (aka. photoresistor) acts as a dynamically-adapting resistor according to the light levels. In dark areas, the resistance is high and in bright areas the resistance is low.

As Raspberry Pi does not have an analog input, we can make a trick to read a value from an analog sensor (resistor-based sensor). We just use a small capacitor and measure time that is needed to fill the capacitor to the full level.

On Raspberry Pi we use 3.3V pin as power supply, GND as ground and pin 18 as an input pin that will be used to measure time to fill the capacitor. In the circuit we measure voltage levels using pin 18 between photoresistor and capacitor.

To get the light level, we need to:

  1. Set pin 18 as out and to LOW voltage.
  2. Set pin 18 as input to be able to read input voltage. Now we can just read if voltage is LOW or HIGH.
  3. Measure, how much time is needed until read voltage on pin 18 is HIGH.

Normally you can use a 1μF but we had just a capacitor of 100μF (if it is designed to higher voltage, it is okay). The difference is only you will need more time to fill the capacitor in darker conditions. In our case, we need about 800000ms to detect dark light and about 30000ms to detect twilight.

Automatic light switching

Above we got the information whether the light conditions are daylight, twilight or darkness. Now we set a LED that will be turned off in daylight, burn lightly in twilight and be very bright in darkness.

For this, we use two pins to turn on a LED and for each pin, we use different resistor to set the brightness of a LED. For darkness we use a 220Ohm resistor and for twilight we use 1120Ohm (2x560Ohm) resistor.

The script to control all of the above looks like:

#!/usr/bin/env python
import RPi.GPIO as GPIO, time, os
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
 
#Variables setup
TWILIGHT_THRESHOLD = 30000
DARK_THRESHOLD = 800000
LIGHT_STATUS_PIN = 18
TWILIGHT_LIGHT_PIN = 22
DARKNESS_LIGHT_PIN = 23
 
class Light(object):
        DAYLIGHT = "Daylight"
        TWILIGHT = "Twilight"
        DARKNESS = "Darkness"
 
def LightInfo():
        GPIO.setup(LIGHT_STATUS_PIN, GPIO.OUT)
        GPIO.output(LIGHT_STATUS_PIN, GPIO.LOW)
        time.sleep(0.1)
        GPIO.setup(LIGHT_STATUS_PIN, GPIO.IN)
 
        # This takes about 1 millisecond per loop cycle
        repeats_to_full_capacitor = 0
        while (GPIO.input(LIGHT_STATUS_PIN) == GPIO.LOW):
                repeats_to_full_capacitor += 1
 
        if (repeats_to_full_capacitor < TWILIGHT_THRESHOLD):
                return Light.DAYLIGHT
        elif (repeats_to_full_capacitor < DARK_THRESHOLD):
                return Light.TWILIGHT
        else:
                return Light.DARKNESS
 
def TurnLEDOnOff(status):
        #Turn all off
        GPIO.setup(TWILIGHT_LIGHT_PIN, GPIO.OUT)
        GPIO.setup(DARKNESS_LIGHT_PIN, GPIO.OUT)
        GPIO.output(TWILIGHT_LIGHT_PIN, GPIO.LOW)
        GPIO.output(DARKNESS_LIGHT_PIN, GPIO.LOW)
        time.sleep(0.1)
        #Turn appropriate pin on
        if (status == Light.TWILIGHT):
                GPIO.setup(DARKNESS_LIGHT_PIN, GPIO.IN)
                GPIO.output(TWILIGHT_LIGHT_PIN, GPIO.HIGH)
        elif (status == Light.DARKNESS):
                GPIO.setup(TWILIGHT_LIGHT_PIN, GPIO.IN)
                GPIO.output(DARKNESS_LIGHT_PIN, GPIO.HIGH)
 
#Main program
status = Light.DAYLIGHT
while True:
        newStatus = LightInfo()
        print newStatus
        if (newStatus != status):
                TurnLEDOnOff(newStatus)
                status = newStatus

When we run the script as “sudo ./LightSwitch.py” in daylight conditions, the LED is off:

IMG_0164

In twilight, the LED is not that bright:

IMG_0165

Lastly in the darkness, the LED becomes very bright:

IMG_0166

Part 2/3: OpenHAB + RPi + LEDs + Camera

We are continuing with the example from the first part of the tutorial: http://www.zitnik.si/wordpress/2016/02/04/part-13-controlling-leds-using-raspberry-pi/.

In this part we are going to install OpenHAB platform on an RPi and remotely control LEDs.

OpenHAB (http://www.openhab.org/)  is a software that is intended to connect to many sensors or devices for home automation. It works as a smart devices gateway and includes tools to design a custom GUI to control these connected smart devices. A GUI can be accessed using a web browser or from a nice mobile application (iOS, Android).

OpenHab Installation

We first installed OpenHAB core and then Demo from the official site: http://www.openhab.org/getting-started/downloads.html. These are compressed packages which I unzip into /opt/openhab folder. Within the new directory, there’ll be a folder called configurations. Within this folder create a copy of the default configuration file openhab_default.cfg and name it openhab.cfg. This is where you’ll store all your settings for openHAB and any bindings you need.

To start the OpenHAB server, run /opt/openhab/start.sh.

OpenHAB configuration

To control our LEDs we will need to create three files.

Create a file configurations/items/default.items. This will be an inventory for definition of our sensors. The file should look like:

Switch RedLight				"Rdeca luc"
Switch GreenLight			"Zelena luc"
Switch YellowLight			"Rumena luc"

The next file should define the rules and actions for these sensors. So, create a file named configurations/rules/default.rules to look like:

import org.openhab.core.library.types.*
import org.openhab.core.persistence.*
import org.openhab.model.script.actions.*
import org.openhab.action.pushover.*
import org.openhab.action.pushover.internal.*
 
rule "RedLight changed"
when
 Item RedLight received command ON
then
 logInfo("RedLight", "Received red light command to turn on.")
 executeCommandLine("python /home/pi/red_on.py")
 pushover("Rdeca luc je bila prizgana.")
end
 
rule "RedLight changed"
when
 Item RedLight received command OFF
then
 logInfo("RedLight", "Received red light command to turn on.")
 executeCommandLine("python /home/pi/red_off.py")
end

As you can see I also configured the pushover service so that I am notified about the change via a push notification. It can also be observed that on some command received, a log message is created and a command line script is executed. These scripts look the same as in the first part of the tutorial, where we introduced how to turn LED on or off.

In the last file, named configuration/sitemaps/default.sitemap we will define the GUI for our application. Our file looks like this:

sitemap demo label="Raspberry demo"
{
 Frame label="Luci" {
   Switch item=GreenLight label="Zelena luc"
   Switch item=YellowLight label="Rumena luc"
   Switch item=RedLight label="Rdeca luc"
 }
 Frame label="Videokamere" {
   Text label="Raspberry kamera" icon="video" {
     Frame label="Raspberry kamera" {
       Video url="http://localhost:8081?action=stream" encoding="mjpeg"
     }
   }
   Text label="Raspberry kamera" icon="garden" {
     Frame label="Raspberry kamera (snapshot)" {
       Image url="http://localhost:8081?action=snapshot" refresh=5000
     }
   }
 }
}

For now you can skip the “Videokamere” part as it defines video stream and snapshot images of a camera that we will attach to the raspberry (below).

As you save the file and run the server, the GUI can be accessed via a web browser using URL http://RPi_IP:8080:

Screen Shot 2016-02-04 at 14.01.19

You can also use this URL in a mobile application and have a native interface – e.g. on your iPhone, which looks like this (for our sitemap definition):

IMG_0162

You should now be able to turn on or off your LEDs using OpenHAB platform. Try it out!

OpenHAB and Raspberry Pi Camera Module

Now we would also like to check our lights remotely via a camera. We will use mjpeg stream for video streaming.

We have an RPi Camera Module, which we attached to the RPi. After that we run “sudo raspi-config” command and enable the camera module.

First we need to install some dependencies:

sudo apt-get install libjpeg8-dev
sudo apt-get install imagemagick[prismatic_encoded class=%%language-bash%% data-lang=%%bash%%]DQpzdWRvIGFwdC1nZXQgaW5zdGFsbCBsaWJqcGVnNjItZGV2DQpzdWRvIGFwdC1nZXQgaW5zdGFsbCBjbWFrZQ==[/prismatic_encoded]
[prismatic_encoded class=%%language-bash%% data-lang=%%bash%%]c3VkbyBhcHQtZ2V0IGluc3RhbGwgbGlidjRsLWRldg0KI2NyZWF0ZSBhIHN5bWJvbGljIGxpbmsNCnN1ZG8gbG4gLXMgL3Vzci9pbmNsdWRlL2xpYnY0bDEtdmlkZW9kZXYuaCAvdXNyL2luY2x1ZGUvbGludXgvdmlkZW9kZXYuaA==[/prismatic_encoded]

Then we download mjpeg repository and build the library:

[prismatic_encoded class=%%language-bash%% data-lang=%%bash%%]PHNwYW4gY2xhc3M9ImMiPiMgWW91IGNhbiBhbHNvIGNob29zZSB0byBkb3dubG9hZCBzb21lIHN0YWJsZSB2ZXJzaW9uIGluc3RlYWQgb2YgY3VycmVudCBtYXN0ZXI8L3NwYW4+DQpnaXQgY2xvbmUgaHR0cHM6Ly9naXRodWIuY29tL2phY2tzb25saWFtL21qcGctc3RyZWFtZXIuZ2l0IC4NCnN1ZG8gbWFrZSBjbGVhbiBhbGwNCg==[/prismatic_encoded]

Now copy the directory of build files to /opt/mjpg-streamer and run mjpeg streamer using the following command (I am using parameter vf to vertically flip the image):

LD_LIBRARY_PATH=/opt/mjpg-streamer /opt/mjpg-streamer/mjpg_streamer -i "input_raspicam.so -fps 5 -q 50 -x 640 -y 480 -vf" -o "output_http.so -w /opt/mjpg-streamer/www -p 8081" &

If everything is okay, a video stream should be accessible at http://RPi_IP:8081:

Screen Shot 2016-02-04 at 14.26.03

Also if OpenHAB is configured as above, videostream should be accesible over its GUI:

Screen Shot 2016-02-04 at 14.28.36

Part 1/3: Controlling LEDs using Raspberry Pi

In this post I will review, how to turn on or off LEDs using Raspberry Pi 2, Model B (RPi).

First we copy Raspbian linux to a microSD card, turn on RPi and connect to it using ssh.

We use three LEDs and each needs to be connected to each own positive supply of the circuit and ground. For the positive supply on RPi we use pins 18, 17 and 27 as seen on the scheme below:

RPi_GPIO

 

As the current would be too high if we connect the LED directly into the circuit, we need to add a resistor for each LED. As it is written in the Raspberry Pi spec, it can safely allow up to 16mA current. Our pins can supply 3.3V. Therefore to allow the LED to be the brightest, we can use 210Ohm  or stronger resistor. Using stronger resistor will result in the LED not being so bright.

In this example I am using 560Ohm resistor. I am also attaching a nice scheme for calculating the resistance of 4-band resistors:

Screen Shot 2016-02-04 at 11.09.35

 

To control a specific LED, we can “turn on” a specific LED using a Python library. First we need to set a pin as output and then we can turn it on (GPIO.HIGH) or off (GPIO.LOW). An example of a script that turns on a LED:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
 
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,GPIO.HIGH)

Physical result:

IMG_0161

Mac OSX Lion: Time Machine to PC share

There are problems backing up Mac OSX computers to network shares (other than Apple :)) because Apple uses some proprietary protocols (to better sell other products :)). Instead of searching workarounds such as creating virtual disks on remote shares, I’ve found out a nicer option by searching the web.

SOLUTION: Installation of
a) Netatalk – an open-source implementation of AppleTalk protocols
b) Avahi – system for multicast service discovery in local networks

I own an older desktop PC “Barsabass”, running Ubuntu 11.10, which also serves me as DLNA, file server and from now on also as Time Machine backup server. In the following a simple procedure to get Time Machine from Mac to PC working is described. You can further add other shares or properties (conf files are nicely documented).

INSTALLATION:

Step 1: Install netatalk and avahi packages.

apt-get install netatalk avahi-daemon

Step 2: Enable netatalk server by editing /etc/netatalk/afpd.conf. Add following line.

“Barsabass” -tcp

Step 3: Enable some Apple shares by editing /etc/netatalk/AppleVolumes.default. Add line containg path to share folder (= TimeMachine bakup location), name of share, allowed users.

/media/Dokumenti/bcpks/slavko_mbpro_tm “slavko_mbpro_tm” allow:slavkoz

Step 4: Enable netatalk server run parameters in /etc/default/netatalk.

CNID_METAD_RUN=yes
AFPD_RUN=yes
TIMELORD_RUN=yes

Step 5: Setup afpd for broadcast. Create file /etc/avahi/services/afpd.service.

<?xml version=”1.0″ standalone=’no’?><!–*-nxml-*–>
<!DOCTYPE service-group SYSTEM “avahi-service.dtd”>
<service-group>
<name replace-wildcards=”yes”>%h</name>
<service>
<type>_afpovertcp._tcp</type>
<port>548</port>
</service>
<service>
<type>_device-info._tcp</type>
<port>0</port>
<txt-record>model=Xserve</txt-record>
</service>
</service-group>

Step 6: Restart both services.

/etc/init.d/netatalk restart

restart avahi-daemon

Step 7: Use Time Machine backup and enjoy! Your configured share should be now visible like on the picture below. After you successful share access by Finder, you can select the network drive in Time Machine and begin backing up you Mac.

LG TV and .mkv via DLNA

My LG TV played .mkv files from USB, but not via DLNA. After selecting .mkv file, “This file is invalid” dialog showed and TV restarted.

I have used various DLNA servers on Windows, Linux and today I tried Serviio. I just deleted “transcoding” tag int “profiles.xml” for “LG TV” profile and videos are played smoothly (without transcoding on my AMD64 3200+, 2GB@333Mhz).

Another nice thing Serviio does is automatically identifying series, grouping them and showing half-watched videos.

S kolesom do Pule

S kolegom Miho Longinom sva se 6.8.2011 odpravila s kolesom proti Puli. Plan je bil, da se najprej ustaviva z v kampu Lucija, nato v Poreču in nazadnje v Puli. Med temi postajami pa bi naredila vsakič 2 dni odmora.

Prvi dan: Jaz sem pot pričel na Vrbičju proti Ljubljani. Okoli 6h zjutraj sva se z Miho dobila pred FRI-jem in se napotila proti Portorožu. Prvi incident se je zgodil že na Vrhniškem klancu, ko je Mihi počila zadnja guma. Na srečo sem imel s sabo rezervno, zato sva lahko problem hitro rešila. Nadalje sva se ustavila v Logatcu na bencinski črpalki, kjer sva se okrepčala. Tam sem tudi v obcestni trgovini s kolesi Cult kupil novo zračnico. Do Kopra pa je manjše tehnične težave imelo moje kolo, saj sem moral nekajkrat ročno priviti “špice” na zadnjem platišču. V Kopru sva si v Tuš centru privoščila kosilo – seveda na študentske bone. Nato naju je le kratka razdalja ločila do Lucije, ki sva jo hitro dosegla. Pred tem pa je meni v Portorožu počila sprednja guma, ki sem jo lahko na srečo spet zamenjal in spet privil zadnje “špice”. Zvečer sva se prehitro podala na žur, ki se je začel šele po 23h, zato sva se optimistično odločila nekaj časa spočiti v kampu, kar je seveda pomenilo, da sva vse prespala.


Drugi dan: Ta dan sva preživela na slovenski obali. Zajtrk in kosilo je bilo seveda na študentske bone, zvečer pa ni bilo nobenega dogajanja. Kolegica iz avtobusne postaje nama je namignila, da se zna kaj dogajati v klubu Ayala, vendar ni bilo nič. Torej je sledilo spanje, pred katerim sem si še kupil penasto podlogo za spanje. Zaradi bolj primerne temperature sem spal zunaj v sožitju z lokalnimi ježi.

Tretji dan: Miha je predčasno ustal in še preden sem dojel, je spakiral šotor in mi sporočil, da zaradi boležin v mišicah in glavobola odhaja domov. Na recepciji si je izprosil lekadol, poklical taxi, ki ga je zapeljal do Kopra in z vlakom odšel domov. Jaz sem se ta dan zapeljal do Umaga, kjer sem na poti v Villi Zianni preveril, če imajo moj polnilec za mobitel, ki ga niso imeli. Nato sem se vrnil v portorož, kjer me je popoldne prišel iskat Peter Virant, saj se mi ni ljubilo samemu nadaljevati vožnje.

Ker se je “planirana tura” končala prehitro, bo treba splanirati novo.

Ročna ura/telefon

Že nekaj časa so mi bile zanimive ročne ure, ki imajo hkrati funkcijo telefona. Zato sem pred kratkim naročil Royal Watch Phone.

Ura izgleda v redu, zaslon na dotik je dovolj natančen za tipkanje s prsti, je dovolj majhna, vendar nima GPS-a :). Ker se mi zdi ta pomankljivost kar pomembna in sem navajen Nokia telefonov, bom šel nazaj na uporabo normalnega telefona.

Nekaj slikic:

Cycling a little bit

Yesterday, Blaž Hudobivnik came across. We went for a short trip to Turjak and through some old villages and wood back to my home.

He got his new camera few weeks ago (some Canon heavy piece :)) and took some incredibly nice photos:

Duga Uvala – July 2009

At the beginining of July, excplicitly from 10. – 14., 5 friends were staying at Virant Peter’s place in Duga Uvala. There were also Miha Longino, Miran Colič, Uroš Vrtar and me.

Pictures taken with my mobile phone:

Diving in Novi Vinodolski

Last weekend I have been diving in Novi Vinodolski. This was the last part of course for OWD – open water diver. Now I am eligible to borrow diving equipment at diving centers and to dive up to 18metres deep.

We have made 8 dives up to 24metres deep. Last dive was done from a boat.

It is quite nice down there.

Few images: