Category Archives: Computer engineering

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.


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
#Variables setup
class Light(object):
        DAYLIGHT = "Daylight"
        TWILIGHT = "Twilight"
        DARKNESS = "Darkness"
def LightInfo():
        # 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
                return Light.DARKNESS
def TurnLEDOnOff(status):
        #Turn all off
        #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):
                status = newStatus

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


In twilight, the LED is not that bright:


Lastly in the darkness, the LED becomes very bright:


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

We are continuing with the example from the first part of the tutorial:

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

OpenHAB (  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: 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/

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"
 Item RedLight received command ON
 logInfo("RedLight", "Received red light command to turn on.")
 executeCommandLine("python /home/pi/")
 pushover("Rdeca luc je bila prizgana.")
rule "RedLight changed"
 Item RedLight received command OFF
 logInfo("RedLight", "Received red light command to turn on.")
 executeCommandLine("python /home/pi/")

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


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
sudo apt-get install libjpeg62-dev
sudo apt-get install cmake
sudo apt-get install libv4l-dev
#create a symbolic link
sudo ln -s /usr/include/libv4l1-videodev.h /usr/include/linux/videodev.h

Then we download mjpeg repository and build the library:

# You can also choose to download some stable version instead of current master
git clone .
sudo make clean all

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 " -fps 5 -q 50 -x 640 -y 480 -vf" -o " -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, as well as, we needed laser cutting to get the perfect size. For the positive supply on RPi we use pins 18, 17 and 27 as seen on the scheme below:



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

Physical result: