MQTT – Instalando e Testando Mosquitto em Raspberry Pi

Implementado MQTT com Mosquitto.

Este é o primeiro tutorial sobre IoT publicado pelo HackerLab.  O intuito é o de desenvolver uma série de artigos que permitam ao leitor implantar sensores e monitorá-los remotamete.

Iniciaremos com a implementação em um Raspberry Pi (RPi) do Message Queuing Telemetry Transport (MQTT) que é um protocolo de conectividade machine-to-machine (M2M) utilizado na Internet of Things (IoT). MQTT é utilizado para monitoramento remoto onde os dispositivos requerem código enxuto ou em situações onde existe limitação de banda para comunicação.

Este tutorial foi baseado em um post do .


É uma arquitetura de comunicação por meio de mensagens onde os dispositivos que controlam os sensores são os publishers e os dispositivos que monitoram os sinais enviados pelos sensores são os subscribers. Os subscribers podem selecionar as mensagens que lhes interessam por meio de filtros. Para que isto ocorra, as menssagens são publicadas por tópicos ou canais lógicos.

Para a implementação completa desta estrutura é necessário um terceiro elemento chamado message broker, que receberá as mensagens dos publishers, as colocará em uma fila e as enviará, filtrada, aos subscribers.

Neste tutoria abordarei a instalação e testes do Mosquitto, um message broker que implementa o protocolo MQTT. Trata-se de uma aplicação bastante apropriada para a implementacão da”Internet of Things” utilizando sensores, celulares, tablets, Arduino e Raspberry Pi.

Instalando o Mosquitto no RPi

Pelo fato do apt-get do RPi não implementar as versão mais recente do Mosquitto, será necesário preparar o RPi antes da instalação propriamente dita.

sudo wget
sudo apt-key add mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget
sudo apt-get update
sudo apt-get install mosquitto

O próximo passo será a instalação das três partes do Mosquitto:

  • mosquitto: o broker MQTT;
  • mosquito-client: command line muito útil para depuração;
  • python-mosquitto: interfaces para a linguagem Python.
sudo apt-get install mosquitto mosquitto-clients python-mosquitto

Em alguns pacotes Linux o servidor MQTT é iniciado logo após a instalação.  Como teremos algumas modificações no arquivo de configuração, será necessário parar o servidor.

sudo /etc/init.d/mosquitto stop

Configurando o servidor Mosquitto

Antes de iniciarmos o uso do Mosquitto, será necessário adequar o arquivo de configuração localizado em /etc/mosquitto.

sudo nano /etc/mosquitto/mosquitto.conf

A configuração final do arquivo deverá ser conforme abaixo:

# Place your local configuration in /etc/mosquitto/conf.d/
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/

persistence true
persistence_location /var/lib/mosquitto/

log_dest topic

log_type error
log_type warning
log_type notice
log_type information

connection_messages true
log_timestamp true

include_dir /etc/mosquitto/conf.d

Iniciando o servidor Mosquitto

sudo /etc/init.d/mosquitto start

Testando o servidor Mosquitto

Serão necessários duas janelas de terminais.

No terminal 1 digite:

mosquitto_sub -d -t hello/world

Note que esta mensagem será publicada no canal hello/world.

No terminal 2 digite:

mosquitto_pub -d -t hello/world -m "HackerLab, - Nerd´s Playground"

Note que o subscriber está filtrando as mensagens do canal hello/world.

Após a intridução do comando no terminal 2, observe o terminal 1 com as seguintes mensagens:

~ $ sudo mosquitto_sub -d -t hello/world
Client mosqsub/3014-LightSwarm sending CONNECT
Client mosqsub/3014-LightSwarm received CONNACK
Client mosqsub/3014-LightSwarm sending SUBSCRIBE (Mid: 1, Topic: hello/world, QoS: 0)
Client mosqsub/3014-LightSwarm received SUBACK
Subscribed (mid: 1): 0
Client mosqsub/3014-LightSwarm received PUBLISH (d0, q0, r0, m0, 'hello/world', ... (32 bytes)) HackerLab, - Nerd´s Playground

Pronto! Você instalou um broker Mosquitto com sucesso!

Repetidoras de VHF em São Paulo


Extraído em 04/09/2016 às 11h39

Lista somente de repetidoras com responsabilidade da LABRE-SP.
Atualizada em 01/07/2015

# Indicativo Frequência CTCSS Estatus Cidade Altitude Echolink
1 PY2JZW 146.610 91.5 OK Apiaí 1.071m PY2JZW-R
2 PY2KAZ 146.690 100.0 OK Votuporanga 525m N/T
3 PY2KBZ 145.310 67.0 DES Cosmópolis 650m PY2KBZ-R
4 PY2KBC 146.930 79.7 OK Atibaia 810m PY2KBC-R
5 PY2KBE 146.950 88.5 OK Presidente Prudente 464m N/T
6 PY2KBF 147.060 88.5 OK Indaiatuba 620m PY2KBF-R
7 PY2KBS 145.330 123.0 OK Itapeva 1.050m PY2KBS-R
8 PY2KDY 439.000 77.0 OK Itapeva 1.050m PY2KDY-R
9 PY2KBX 146.610 123.0 OK Itap. da Serra 950m N/T
10 PY2KCH 147.360 67.0 OK Cajurú 1.090m PY2KCH-R
11 PY2KBL 146.850 74.4 OK Guaratinguetá 928m N/T
12 PY2KDD 145.430 77.0 OK Jaboticabal 639m PY2KDD-R
13 PY2KDO 147.330 74.4 OK Jundiaí 1.099m PY2KDO-R
14 PY2KET 438.500 D-STAR OK Jundiaí 1.099m N/T
15 PY2KDT 145.230 67.0 OK Neves Paulista 570m N/T
16 PY2KBM 146.650 N/T OK Tanabí 537m N/T
17 PY2KCI 147.210 N/T OK Itirapina 925m N/T
18 PY2KEV 145.470 67.0 OK  Cajati  1000m  PY2KEV-R
19 PY2KBA  147.300  N/T OK Torrinha  860M N/T


# Indicativo Frequência Cidade Orig.
Cidade Dest
RESP Estatus
1 PY2KBI 146.770 Cubatão 4 AGUARDANDO SEDE DES
2 PY2KDE 147.180 Flórida Paulista 4 SEDE DES

The powerful hacker culture

Copiado de

In my post the hacker culture is winning, I observed that the subculture developed in the software industry is infecting the wider world. One such visible culture shift is the concept of “version update”. In the industrial era, companies would design a phone, produce it and ship it. There might be a new type of phone the following year, but whatever you bought is what you got. In some sense, both politically and economically, the industrial era was inspired by the military model. “You have your orders!”

Yet, recently, a car company, Tesla, released an update so that all its existing cars acquired new functions (self-driving on highways). You simply could not even have imagined such an update in the industrial era.

It is an example of what I called innovation without permission, a feature of the hacker culture. It is an expression of the core defining hacker characteristic: playfulness and irreverence. Hackers will install Linux on the latest PlayStation even if Sony forbid it and made it impossible. Why would any team invest months of work on such a futile project?

What is unique to hackers is that displays of expertise have surpassed mere functionality to take a life of their own. Though my colleagues in the “Arts” often roll their eyes when I point it out, the hackers are the true subversive artists of the post-industrial era.

The hacker culture has proven its strength. We got Chelsea Manning’s and Julian Assange’s WikiLeaks, the somewhat scary underground work by Anonymous, Edward Snowden’s leak, the Panama papers and so forth. Aaron Swartz scared the establishment so much that they sought to put him behind bars for life merely because he downloaded academic articles.

You might object that many of these high-profile cases ended with the hackers being exiled or taken down… but I think it is fair to say that people like Aaron Swartz won the culture war. As a whole, more people, not fewer, are siding with the hackers. Regarding the Panama Papers, there were some feeble attempts to depict the leak as a privacy violation, but it no longer carries weight as an argument. TV shows increasingly depict hackers as powerful (and often rightful) people (e.g., House of Cards, The Good Wife, and Homeland).

Who is winning ground do you think?

What makes the hacker culture strong?

  • Hackers control the tools. Google, Microsoft and Apple have powerful CEOs, but they need top-notch hackers to keep the smartphones running. Our entire culture is shaped by how these hackers think through our tools.The government might be building up fantastic cyberweapons, but what the Snowden incident proved is that this may only give more power to the hackers. You know who has access to all your emails? Software hackers.Our tools have come to reflect the hacker culture. They are more and more playful and irreverent. We now have CEOs posting on Twitter using 140 characters. No “sincerely yours”, no corporate logo.
  • Hackers are rich with time and resources. Most companies need hackers, but they can’t really tell what the best ones are up to. How do you think we ended up with Linux running most of our Internet infrastructure? It is not the result of central planning or a set of business decisions. It happened with hackers were toying with Linux while the boss was looking. When you have employees stacking crates, it is easy for an industrial-age boss to direct them. How do you direct extremely smart people who are typing on keyboards?Apparently, Linus Torvalds work in his bathrobe at home. He spends a lot of time swearing at other people on posting boards. He can afford all of that because it is impossible to tell Linus what to do.

I don’t think it is mere coincidence if the powerful people are embracing the hacker culture. I could kid and point out that the true hackers may not represent many people, they may not formally hold much wealth, but they metaphorically control the voting machines and hold all the incriminating pictures. But rather, I think that smart people realize that the hacker culture might also be exactly what we need to prosper in the post-industrial era. The military approach is too crude. We don’t need more factories. We don’t need more tanks. But we sure can use smarter software. And that’s ultimately where the hackers take their power: they put results into your hands.

How to Become an Ethical Hacker

Do viruses, DDoS attacks, or buffer overflows tickle your fancy? If so, you might consider becoming a legal hacker, aka an ethical hacker, “white hat” hacker, or penetration tester.Businesses and government-related organizations that are serious about their network security hire ethical hackers and penetration testers to help probe and improve their networks, applications, and other computer systems with the ultimate goal of preventing data theft and fraud. You may not get the same adrenaline rush that you might with underground hacking, but you can earn a good and honest living–and not end up facing prison time, as some illegal “black hat” hackers do.

How does the job market look like for ethical hackers? Extremely good! The IT market overall continues to grow despite the current economic turmoil. Research firm Gartner estimates that worldwide enterprise IT spending grew by 5.9 percent between 2009 and 2010, to a total of $2.7 trillion. At the same time, security is becoming a more pressing concern. Gartner expects to see an increase of nearly 40 percent in spending on worldwide security services during the five-year period from 2011 to 2015, eventually surpassing $49.1 billion.

In your first years as an ethical hacker, you’ll be in a position to earn anywhere from $50,000 to $100,000 per year, depending on the company that hires you, and on your IT experience and education. With several years of professional experience, you could command $120,000 or more per year, especially if you do your own independent consulting.

You can’t just dive into an ethical hacker position, however. Without IT security experience, you won’t get very far, even with degrees and certifications. As is true for other IT jobs, employers typically want candidates who have college degrees, but related experience is king. And experience with certifications can typically take the place of some degree requirements.

Getting Started

What you need to do to get started on the road to becoming an ethical hacker depends on where you are in the IT field. If you haven’t started your IT career yet, you might even consider military service. The military offers many IT opportunities, and you get paid to go to school, even if you enlist in a part-time branch such as the National Guard or Reserves. Military service also looks good to employers that require security clearances.

Start with the basics: Earn your A+ Certification and get a tech support position. After some experience and additional certification (Network+ or CCNA), move up to a network support or admin role, and then to network engineer after a few years. Next, put some time into earning security certifications (Security+, CISSP, or TICSA) and find an information security position. While you’re there, try to concentrate on penetration testing–and get some experience with the tools of the trade. Then work toward the Certified Ethical Hacker (CEH) certification offered by the International Council of Electronic Commerce Consultants (EC-Council for short). At that point, you can start marketing yourself as an ethical hacker.

For a hacker, networking know-how is vital; but make sure that you gain experience in related areas as well. Discover and play with Unix/Linux commands and distributions. Make sure you also learn some programming–maybe C, LISP, Perl, or Java. And spend some time with databases such as SQL.

Soft Skills

Hacking isn’t all technical. It also requires so-called soft skills, just as any other IT job does. You’ll need a strong work ethic, very good problem-solving and communications skills, and the ability to say motivated and dedicated.

Ethical hackers also need street smarts, people skills, and even some talent for manipulation, since at times they need to be able to persuade others to disclose credentials, restart or shut down systems, execute files, or otherwise knowingly or unknowingly help them achieve their ultimate goal. You’ll need to master this aspect of the job, which people in the business sometimes call “social engineering,” to become a well-rounded ethical hacker.

Stay Legal!

It’s important never to engage in “black hat” hacking–that is, intruding or attacking anyone’s network without their full permission. Engaging in illegal activities, even if it doesn’t lead to a conviction, will likely kill your ethical hacking career. Many of the available jobs are with government-related organizations and require security clearances and polygraph testing. Even regular companies will perform at least a basic background check.

Becoming a Certified Ethical Hacker (CEH)

As noted earlier, becoming a Certified Ethical Hacker (CEH) involves earning the appropriate credential from the EC-Council after a few years of security-related IT experience. The certification will help you understand security from the mindset of a hacker. You’ll learn the common types of exploits, vulnerabilities, and countermeasures.

Qualification for a CEH (a vendor-neutral certification) involves mastering penetration testing, footprinting and reconnaissance, and social engineering. The course of study covers creating Trojan horses, backdoors, viruses, and worms. It also covers denial of service (DoS) attacks, SQL injection, buffer overflow, session hijacking, and system hacking. You’ll discover how to hijack Web servers and Web applications. You’ll also find out how to scan and sniff networks, crack wireless encryption, and evade IDSs, firewalls, and honeypots.

Through approved EC-Council training partners, you can take a live, five-day onsite or online training course to prepare for the CEH cert. You can generally take live online classes over five consecutive days; onsite courses typically offer the content spread over a couple weeks for locals. In addition, you can take self-paced courses and work with self-study materials (including the CEH Certified Ethical Hacker Study Guide book) with or without the training courses. The EC-Council also offers iLabs, a subscription based-service that allows you to log on to virtualized remote machines to perform exercises.

The EC-Council usually requires that you have at least two years of information-security-related work experience (endorsed by your employer) in addition to passing the exam before it will award you the official CEH certification.


If you’re interested in ethical hacking, you can consult many useful resources for more information. To start, check the resources section of the EC-Council site. A quick Amazon search will reveal many books on ethical hacking and the CEH certification, as well.

With some googling, you can find simple hacking how-tos, which may motivate you even more. Consider downloading the Firefox add-on Firesheep or the Android app Droidsheep, and hijack your online accounts via Wi-Fi (but don’t use these tools to hijack others’ accounts–you could find yourself in legal trouble if you do).

Another option is to experiment with the BackTrack live CD. Try enabling WEP security on your wireless router at home, and then take a stab at cracking it. Check out Hack This Site to test and expand your skills. You could even set up a Linux box with Apache or buy a used Cisco router and see what you can do with it. If you want to play with malware, consider downloading–cautiously, and at your own risk–a malware DIY kit or a keylogger, and use it to experiment on a separate old PC or virtual machine.

get started on the road to becoming an ethical hacker depends on where you are in the IT field. If you haven’t started your IT career yet, you might even consider military service. The military offers many IT opportunities, and you get paid to go to school, even if you enlist in a part-time branch such as the National Guard or Reserves. Military service also looks good to employers that require security clearances.

Start with the basics: Earn your A+ Certification and get a tech support position. After some experience and additional certification (Network+ or CCNA), move up to a network support or admin role, and then to network engineer after a few years. Next, put some time into earning security certifications (Security+, CISSP, or TICSA) and find an information security position. While you’re there, try to concentrate on penetration testing–and get some experience with the tools of the trade. Then work toward the Certified Ethical Hacker (CEH) certification offered by the International Council of Electronic Commerce Consultants (EC-Council for short). At that point, you can start marketing yourself as an ethical hacker.

For a hacker, networking know-how is vital; but make sure that you gain experience in related are

Like other IT areas, hacking has conventions and conferences dedicated to it, such as DefCon, one of the oldest and largest of these. Such gatherings can be a great place to meet and network with peers and employers, and to discover more about hacking. DefCon also has affiliated local groups in select areas.

And remember, never attack or intrude on anyone else’s network or computers without full written permission.

Eric Geier is the founder of NoWiresSecurity, which helps businesses easily protect their Wi-Fi networks with the Enterprise mode of WPA/WPA2 security by offering a hosted RADIUS/802.1X service. He is also a freelance tech writer—become a Twitter follower or use the RSS Feed to keep up with his writings.

Certified Ethical Hacker (CEH)

Replicado de

Definition – What does Certified Ethical Hacker (CEH) mean?

Certified Ethical Hacker (CEH) is a professional designation for hackers that perform legitimate services for IT companies and other organizations. A CEH is hired to locate and repair application and system security vulnerabilities to preempt exploitations by black hat hackers and others with potentially illegal intentions.

CEH oversight is provided by the International Council of E-Commerce Consultants (EC-Council).

Techopedia explains Certified Ethical Hacker (CEH)

Individuals that pass the CEH examination after training from an accredited training center (ATC) or self study receive the CEH designation. Self study learners must back up their qualifications with two years of practical working experience in information security (IS). Without this experience, a detailed educational background is required for review on a case-by-case basis.

As of May 2012, the most current version of the exam (7) required a 70 percent passing score with 150 multiple choice questions and a four-hour limit. The cost of version 7 is $500. The cost of version 6 is $250 plus a $100 eligibility fee to cover both versions. Prices differ by territory.

The CEH exam is administered by computer through any EC-Council ATC.

Posted by:

Mount USB Memory Stick On Raspberry Pi

Find out how to mount a USB flash drive on your Raspberry Pi

If you are using your Raspberry Pi to play music or video you will soon run out of storage on the SD card which holds the operating system. The easiest way to increase the capacity of the Raspberry Pi to store your media files is with a USB flash drive memory stick. These are very cheap to buy and typically available in sizes up to 128GB; though at the time of writing (Aug 2013) the most cost effective size of good quality drives is 16GB or 32GB. (Click here for SanDisk 32GB Cruzer Blades from £13)

USB flash drive memory stick for Raspberry Pi

If you have a free USB port on your Raspberry Pi then insert your memory stick. If you do not have a free port (because of your mouse and keyboard) then you will need a USB hub. Plug the hub into your Raspberry Pi, and then plug the memory stick and other peripherals into the hub. If you are going to be inserting and extracting the memory stick frequently then it is better to use a USB hub even if you have a free port on the Raspberry Pi, to reduce wear and tear on the Raspberry Pi.

Assuming you are using the standard Raspbian (e.g. Raspbian “Wheezy“) version of Linux on your Raspberry Pi, the memory stick will automatically be detected and given the id sda1. You can check that your memory stick has been correctly identified by entering the command.

ls -l /dev/sda1

and you should see something like the following:

…if the USB memory stick has not been identified then you will instead see:

ls: cannot access /dev/sda1: No such file or directory

Next you need to create a sub-directory in the /media directory on your Raspberry Pi so that the memory stick can be mounted.

sudo mkdir /media/usb

…where you can replace usb with your choice of name if you want, but keep it short as you will probably end up typing it a lot.

Mount USB Flash Drive on Raspberry Pi

Assuming you are logged in as user pi, enter the following command to mount your USB memory stick to /media/usb:

sudo mount -t vfat -o uid=pi,gid=pi /dev/sda1 /media/usb

Now you can confirm you can see the contents of the memory stick with the command ls -l /media/usb which should generate a list of the files and directories on the stick.

To check how much memory you have available on the memory stick (and also on your Raspberry Pi SD card), enter the command df.

Using df command to check free storage space on Raspberry Pi USB memory

Look down the file system ID column to find the line with /dev/sda1 or look down the Mounted on column to find the line with /media/usb. In the example above an 8GB USB flash drive has been mounted and is shown to be 18% full. (Use the command df -BM for the same information on your file system but with all memory size values given in MB for better clarity.)

Unmount USB Flash Drive from Raspberry Pi

Before you disconnect the USB memory stick from the Raspberry Pi, you must first unmount it with the following command:

sudo umount /media/usb


Brief Notes on Rebooting

If you shutdown or reboot your Raspberry Pi, any USB memory sticks mounted in the way described above will be no longer be mounted when the Pi reboots – i.e. you will not be able to access the files on the memory stick until you enter the mounting command. If you plan to keep the USB memory stick permanently or semi-permanently attached to the Raspberry Pi, then it is better to have this occur automatically when the Pi reboots. There are many ways to achieve this, but here is a simple one using Cron.

Enter the command sudo crontab -e to edit your cron tasks file. Use the arrow keys to move down to the end of this file and add the following line:

@reboot mount -t vfat -o uid=pi,gid=pi /dev/sda1 /media/usbGet USB drive to mount automatically at reboot with Raspberry Pi using cron

Now press ctrl-x, then y, then enter to save the changes. This will automatically mount the attached USB drive /dev/sda1 to the directory /media/usb for the user pi when the Raspberry Pi is rebooted.


raspistill is the command line tool for capturing still photographs with the camera module.

Basic usage of raspistill

With the camera module connected and enabled, enter the following command in the Terminal to take a picture:

raspistill -o cam.jpg

Upside-down photo

In this example the camera has been positioned upside-down. If the camera is placed in this position, the image must be flipped to appear the right way up.

Vertical Flip & Horizontal Flip

With the camera placed upside-down, the image must be rotated 180° to be displayed correctly. The way to correct for this is to apply both a vertical and a horizontal flip by passing in the -vf and -hf flags:

raspistill -vf -hf -o cam2.jpg

Vertical and horizontal flipped photo

Now the photo has been captured correctly.


The camera module takes pictures at a resolution of 2592 x 1944 which is 5,038,848 pixels or 5 megapixels.

File size

A photo taken with the camera module will be around 2.4MB. This is about 425 photos per GB.

Taking 1 photo per minute would take up 1GB in about 7 hours. This is a rate of about 144MB per hour or 3.3GB per day.

Bash script

You can create a Bash script which takes a picture with the camera. To create a script, open up your editor of choice and write the following example code:


DATE=$(date +"%Y-%m-%d_%H%M")

raspistill -vf -hf -o /home/pi/camera/$DATE.jpg

This script will take a picture and name the file with a timestamp.

You’ll also need to make sure the path exists by creating the camera folder:

mkdir camera

Say we saved it as, we would first make the file executable:

chmod +x

Then run with:


More options

For a full list of possible options, run raspistill with no arguments. To scroll, redirect stderr to stdout and pipe the output to less:

raspistill 2>&1 | less

Use the arrow keys to scroll and type q to exit.

Full documentation

Full documentation of the camera can be found at hardware/camera.


To create a time-lapse video, you simply configure the Raspberry Pi to take a picture at a regular interval, such as every minute, then use an application to stitch the pictures together in a video.

A good way to automate taking a picture at a regular interval is using cron.

Open the cron table for editing:

crontab -e

This will either ask which editor you would like to use, or open in your default editor. Once you have the file open in an editor, add the following line to schedule taking a picture every minute (referring to the Bash script from the previous page):

* * * * * /home/pi/ 2>&1

Save and exit and you should see the message:

crontab: installing new crontab

Ensure your scipt does not save each picture taken with the same filename. This will overwrite the picture each time.

Stitching images together

Now you’ll need to stitch the photos together in to a video.

You can do this on the Pi using mencoder but the processing will be slow. You may prefer to transfer the image files to your desktop computer or laptop and processing the video there.

Navigate to the folder containing all your images and list the file names in to a text file. For example:

ls *.jpg > stills.txt

On Raspberry Pi or other Linux computer

Install the package mencoder:

sudo apt-get install mencoder

Now run the following command:

mencoder -nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=16/9:vbitrate=8000000 -vf scale=1920:1080 -o timelapse.avi -mf type=jpeg:fps=24 mf://@stills.txt

Once that’s completed, you should have a video file called timelapse.avi containing a time-lapse from your images.

Raspberry Pi Webcam

Esse artigo foi extraído do site em 14/10/2014. Transcrevi integralmente por considerar ser a melhor orientação para configurar um webserver integrado a uma camera.

How to turn your Raspberry Pi and its camera board into a constantly refreshing webcam with text overlay. Feedback welcomed at the Raspberry Pi Forum.


Install a web server and PHP including the php_gd extension. Use nohup to start raspistill in time-lapse mode. Create an index page that embeds the webcam image and a PHP script that generates the webcam image. Upon page request, grab the latest buffered image. Optionally overlay text before outputting.


  • Raspberry Pi computer.
  • SD card, 4 GB or larger, the faster the better but doesn’t have to be especially fast for this webcam.
  • Latest Raspbian operating system.
  • Internet connection to download and update the OS and additional software.
  • Raspberry Pi camera board.
  • To view on another computer: a LAN connection.
  • To view on the web: a public IPv4 or IPv6 address, or a modem/router with port forwarding.

Wireless adapters seem flaky on Linux; sometimes it is hard to get them to even work and in my experience they are often prone to drop the connection. My advice is to buy a Raspberry Pi model B with integrated USB-LAN adapter (ethernet port) and run a network cable to your modem or router. That way, the network connection will be stable and almost certainly a lot faster. Also, twice the amount of RAM in the Model B will not hurt wile having a camera attached and running a web server with PHP. Although I am sure this will work with a Model A.


Install the camera by following the official instructions. Be careful while handling bare circuit boards like the camera! Static electricity can easily ruin them and the flat cable and connectors are fairly fragile. Before turning on the computer, now is a good time to try and think of a clever way to fix the camera with a good view of its surroundings and maybe protect it from the elements and (further?) careless handling. Two 2 mm bolts will fit the holes. For my first try, I improvised by sticking one sturdy twist-tie through them, front to back, and wrapping the ends around a small stick.


Amendment to the official instructions: to get the latest firmware and camera code, don’t just run apt-get upgrade, but also rpi-update:

sudo apt-get update
sudo apt-get dist-upgrade
sudo rpi-update
sudo reboot

In the latest Raspbian OS release, the rpi-update package is included. In an older release, should apt-get dist-upgrade not fetch it automatically, try sudo apt-get install rpi-update before running rpi-update.

After updating, make sure you enable the camera by running

sudo raspi-config

and pressing Enter on the appropriate option:


After confirmation and return to the main screen, press Tab to get to the Select / Finish options, right arrow to move to Finish, Enter, and confirm reboot. Test to see if everything works so far:

raspistill -o ~/Desktop/cam.jpg

which should turn the camera on (check the light), display a preview if you are running the graphical desktop, wait 5 seconds and save a photo called cam.jpg on your Desktop. To disable the camera light, for stealth operation, edit config.txt:

sudo nano /boot/config.txt

and add this on a new line: disable_camera_led=1. Save and exit by typing Ctrl-x, y, Enter. Next, install the lighttpd web server and PHP:

sudo apt-get install lighttpd php5-cgi php5-gd

Apache would also work but is more of a resource hog. Enable PHP:

sudo lighty-enable-mod fastcgi
sudo lighty-enable-mod fastcgi-php
sudo service lighttpd force-reload
echo '<?php phpinfo(); ?>' | sudo tee /var/www/phpinfo.php

and check to see if it works by pointing the Midori browser on your RPi to http://localhost/phpinfo.php. From another computer on the LAN, use the IP address of your Raspberry Pi (check by running ifconfig) or its hostname if your router understands that (probably requires installing avahi-daemon on the RPi). E.g. or http://raspberrypi/phpinfo.php. If your modem / router provides IPv6 connectivity, try enabling it on the RPi:

sudo modprobe ipv6
sudo nano /etc/modules   # add a new line with: ipv6

Normally, having an IPv6 address would immediately make your computer accessible from the web, without having to configure port forwarding on your modem / router. This is good and bad. Good, because no configuration and people may surf to your webcam. Bad, because hackers. Whenever your computer is visible from the outside, make sure to at least change your standard password! Use the password option in raspi-config or run passwd. Enable your router’s IPv6 firewall but open port 80 for general web access or another port (1024 or higher) for semi-private access. Because this is a direct connection without any port translation (forwarding), if you use a port other than 80, reconfigure lighttpd to listen to that port.

Similar for the “normal” IPv4 connection: to make your webcam page accessible from the outside, configure port forwarding in the router from any address on the outside (all traffic for port 80 or otherwise 1024+) to port 80 on your RPi’s LAN address. Change the outside port for semi-private access. If you change the inside port, you’ll have to reconfigure your web server to listen to that port. Check your router manual for details :-). If that all went well, your RPi web server should be accessible to anyone surfing the web as http://your-public-internet-address:the-outside-port-you-opened/, e.g. (which is not a webcam, just the IP address of and port 8080).

Now to get the webcam up and running. You need to create two files in the web server root directory (/var/www) and copy text to them from the two code blocks below. In general, I find the easiest way to do that is to open an SSH session to the RPi from my Mac, run an editor on the RPi: sudo nano /var/www/index.html (sudo is needed because the /var/www directory is owned by user root) and on the Mac copy-paste the text from the web browser to Terminal where the editor is running via SSH. In this case I also provided download links so you may do:

sudo cp webcam-html-1.0.0.txt /var/www/index.html
sudo cp webcam-php-1.0.3.txt /var/www/webcam.php

If wget is not installed on your RPi, run this first: sudo apt-get install wget.

Save this as /var/www/index.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
Version : 1.0.0
Date : 2013-08-11
File : /var/www/index.html
Info :
<html xmlns="" lang="en-gb" xml:lang="en-gb">
	<head profile="">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>My Webcam</title>
		<meta name="keywords" content="raspberry pi, camera, webcam, raspistill, php, javascript" />
		<meta name="description" lang="en-gb" content="This is my webcam. There are many like it, but this one is mine." />
		<meta name="author" content="Ewoud Dronkert" />
		<style type="text/css">
			img#view { display: block; }
		<script type="text/javascript">
			var shotinterval = 5;     // Seconds between shots
			var shottimer = null;     // Countdown timer to the next shot
			var shootingnow = false;  // To avoid parallel execution

			// Start the timer
			function start() {
				shottimer = window.setTimeout(shoot, 1000 * shotinterval);

			// Stop the timer
			// Return previous state (was it running? true/false)
			function stop() {
				if (shottimer) {
					shottimer = null;
					return true;
				return false;

			// Stop the timer when running, start when not running
			// Avoid undefined state by checking for image refresh in progress
			function toggle() {
				if (!shootingnow) {
					var wasrunning = stop(), node;
					if (node = document.getElementById("ctrl"))
						node.innerHTML = wasrunning ? "Start" : "Stop";
					if (!wasrunning)

			// Refresh the webcam image by re-setting the src attribute
			function shoot() {
				shootingnow = true;
				var img; 
				if (img = document.getElementById("view"))  
					img.src = "webcam.php?" +;
				shootingnow = false;
	<body onload="start()">
		<img id="view" src="webcam.php" alt="[webcam]" title="Webcam" />
		<a id="ctrl" href="#" onclick="toggle()">Stop</a>

Save this as /var/www/webcam.php. It is very important to not have any blank lines or spaces before the first <?php or after the last ?>.


/* Version : 1.0.3
 * Date : 2013-08-14
 * File : /var/www/webcam.php
 * Info :

$now = time();     // Current time on the server
clearstatcache();  // To get fresh results for all file-info functions
$cam = '/dev/shm/webcam.jpg';  // Where raspistill will save every image
$buf = '/dev/shm/buffer.jpg';  // Buffer to avoid read/write collisions, also added text
$err = '/dev/shm/error.jpg';   // Error message if reading $cam or $buf failed

// Get file modification time of the camera image
$t_cam = 0;
if (file_exists($cam))
	if (is_readable($cam))
		$t_cam = filemtime($cam);

// Get file modification time of the image buffer
$t_buf = 0;
if (file_exists($buf))
	if (is_readable($buf))
		$t_buf = filemtime($buf);

// If camera image not found or not accessible
if (!$t_cam)
	$t_cam = $now;  // For the file name time-stamp

// JPEG image headers, time-stamped file name
header('Content-Type: image/jpeg');
header('Content-Disposition: inline; filename="webcam_' . date('Ymd_His', $t_cam) . '.jpg"');

// If the camera image is newer than the buffer and can be read
if ($t_cam > $t_buf && $im = @imagecreatefromjpeg($cam)) {

	// Save a new buffer
	$black = @imagecolorallocate($im, 0, 0, 0);
	$white = @imagecolorallocate($im, 255, 255, 255);
	$font = 1;  // Small font
	$text = date('r', $t_cam);  // ISO format date/time
	@imagestring($im, $font, 2, 1, $text, $black);  // Bottom-right shadow
	@imagestring($im, $font, 1, 0, $text, $white);
	@imagejpeg($im, $buf);  // Save to disk
	@imagejpeg($im);  // Output to browser (avoid another disk read)
	exit();  // End program early

// We are here if camera image not newer than buffer (or both not found)
// or reading the camera image failed

// If buffer not found or not accessible
// or reading+outputting the old buffer fails
// or reading+outputting existing error image fails
if (!$t_buf || !@readfile($buf) || !@readfile($err)) {

	// Create an error image
	$width  = 800;  // Should ideally be the same size as raspistill output
	$height = 600;

	if ($im = @imagecreatetruecolor($width, $height)) {

		$white = @imagecolorallocate($im, 255, 255, 255);
		$black = @imagecolorallocate($im, 0, 0, 0);
		@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $white);  // Background
		@imagerectangle($im, 0, 0, $width - 1, $height - 1, $black);  // Border
		$font = 3;  // Larger font
		$text = 'Read Error';  // Message
		$tw = @imagefontwidth($font) * strlen($text);  // Text width
		$th = @imagefontheight($font);
		$x = (int)round(($width - $tw) / 2);  // Top-left text position for centred text
		$y = (int)round(($height - $th) / 2);
		@imagestring($im, $font, $x, $y, $text, $black);  // Write message in image
		@imagejpeg($im, $err);  // Save to disk
		@imagejpeg($im);  // Output to browser



The last piece of the puzzle is to have the raspistill tool continuously save camera pictures in the background. When I first tried to build this webcam, I let every new page request run raspistill for a single new image. That was a bad idea for a number of reasons, foremost the fact that concurrent invocations of raspistill apparently made the camera board or the video processor crash, requiring a reboot of the RPi. So I separated the two file transfer paths as much as possible. There is only one process accessing the camera and saving camera images to disk. The webcam.php script on the server polls if there is an image newer than the previously saved buffer, and if so, copies the latest camera image to the buffer. That should happen only once, no matter how many clients are viewing your webcam.

If reading the camera image or the buffer fails, the script falls back to the old buffer image or an error image. This means that sometimes you won’t see the image refresh for a while. I have never seen it skip more than one time period, though.

Start the automated capture in a terminal window, at the console or via SSH:

nohup raspistill -n -e jpg -w 800 -h 600 -q 70 -t 2147483647 -tl 5000 -o /dev/shm/webcam.jpg &

where nohup lets the process continue even after you log off, -n prevents previews (I don’t have a monitor plugged in), -t 2147483647 makes it run for almost 25 days (largest number possible in this version of raspistill), -tl 5000 has it take a picture every 5 seconds, -o /dev/shm/webcam.jpg saves the image on RAM disk and & makes it all run in the background. Press Enter again to get the prompt back. The console will look like this:

pi@raspberrypi ~ $ nohup raspistill -n -e jpg -w 800 -h 600 -q 70 -t 2147483647 -tl 5000 -o /dev/shm/webcam.jpg &
[1] 3027
pi@raspberrypi ~ $ nohup: ignoring input and appending output to ‘nohup.out’

pi@raspberrypi ~ $ 

When you get back on the console or start a new SSH session, you can check if the raspistill process is still going by running ps ux or, if for some reason you used sudo, ps aux. To stop it: killall raspistill.

Last tip: three things have to be synchronised, in order of importance:

  • Essential: the file name (-o) in the raspistill command and the file name ($cam) in the webcam.php script.
  • Makes sense: The time-lapse (-tl) in the raspistill command and the time-lapse (shotinterval) in the javascript section of index.html.
  • For show: the size (-w, -h) in the raspistill command and the size ($width, $height) in the webcam.php script.

Install as a Start-Up Daemon

Copy this or download it and save as /etc/init.d/webcam:

# Provides:		webcam
# Required-Start:	$remote_fs $syslog
# Required-Stop:	$remote_fs $syslog
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Control raspistill
# Description:		Control raspistill camera time lapse
#			and save images to RAM disk.

[ -x "$EXE" ] || exit 0

SCR="webcam"   # script / service name
ARG="-n -w 800 -h 600 -t 2147483647 -tl 5000 -o /run/shm/$SCR.jpg"
LCK="/var/run/$"   # lock file location

update_lockfile() {
	PID=$(pgrep "$BIN")
	if [ -z "$PID" ]; then
		[ -f "$LCK" ] && [ -w "$LCK" ] && rm -f "$LCK"
		[ -e "$LCK" ] || touch "$LCK"
		[ -f "$LCK" ] && [ -w "$LCK" ] && echo "$PID" > "$LCK"

do_start() {
	$EXE $ARG &

do_stop() {
	killall -q "$BIN"

case "$1" in
		echo -n "Service $SCR is "
		if [ -z "$PID" ]; then
			echo "not running." >&2
			exit 3
			echo "running."
		echo -n "Starting service $SCR..."
		if [ -n "$PID" ]; then
			echo "already started." >&2
			exit 4
			echo "done."
		echo -n "Stopping service $SCR..."
		if [ -z "$PID" ]; then
			echo "already stopped." >&2
			exit 5
			echo "done."
		echo -n "Restarting service $SCR..."
		if [ -n "$PID" ]; then
			echo "failed to stop." >&2
			exit 6
			if [ -z "$PID" ]; then
				echo "failed to start." >&2
				exit 7
				echo "done."
		echo "Usage: $0 {status|start|stop|restart|force-reload}" >&2
		exit 8
exit 0

Install as a service that will start at boot time:

sudo chmod 755 /etc/init.d/webcam
sudo update-rc.d webcam defaults 99 01
sudo reboot

Manual start/stop:

sudo service webcam start
sudo service webcam stop

Raspberry Pi Web Server

Extraído de

Running a lightweight webserver on the Raspberry Pi (lighttpd)

This guide covers setting up a light webserver on Linux using the lighttpd web server on the Raspberry Pi. Most of these instructions can also be applied to other Debian or Ubuntu based distributions (except the tasks using the raspi-config tool). I’ve already written a tutorial based on the “full-fat” Apache webserver (running a LAMP Apache based webserver on the Raspbbery Pi).

Lighttpd provides a way of setting up a web server without putting too much load on the limited processing capability. It’s ideal for providing web access to the Raspberry Pi as a monitoring tool, or as a lightweight webserver for a personal website.

Debian Linux

This is based on the Debian Raspberry Pi Raspbian.

One of the advantages of Debian Wheezy on the Raspberry Pi is that ssh is enabled by default and that the raspi-config tool provides a convenient way to increase the size of the root partition (useful if you have an SD card bigger than 2GB) and to change the default password for the pi user (essential for everyone). The raspi-config tool should run when you first start the system, otherwise use sudo raspi-config.

Using the command line and editing files

As we are going to be doing this through the command line it is useful to understand a little about the shell. Although this provides step-by-step instructions if you haven’t used the command line previously I suggest you read the basic shell reference guide, and then return to this point.

Throughout the install you will see many commands prefixed with sudo. The sudo command allows the user to issue a command as the superuser (or in certain circumstances as another user). Without using the sudo command many of the commands would fail stating insufficient permissions. This is a security feature that protects the system from other users, but also limits the amount of damage that a user can do by mistake (although if prefixed with the sudo command it will not help against accidents).

Static network IP address

The next step is to give the Raspberry Pi an static IP address. This is a little more complex as it depends upon your own setup and what router you have on how to achieve this.

By default the Raspberry Pi will request a dynamic IP address which is issued by your router as required. This however may change in future which would make it hard to connect to the webserver. Instead we provide it with an address that doesn’t change such as
Note that this address can be used on the local network, but not on the Internet – later we’ll look at providing access through your router / firewall from the Internet.

First find out what DHCP address has been allocated by using the ifconfig command – see the extract below


eth0      Link encap:Ethernet  HWaddr b8:27:eb:8a:71:a0

          inet addr:  Bcast:  Mask:


This is saying that the ethernet port 0 – has an IP address of

You will also need to find out what address your router is, using the route command

$ route

Kernel IP routing table

Destination     Gateway         Genmask         Flags Metric Ref    Use Iface

default         UG    0      0        0 eth0     *        U     0      0        0 eth0

This shows that the router IP address (Gateway) is and all traffic is sent via that router.

At this point you will also need to check on what address range is being issued by the router. This depends upon the individual router. In my case I have a Belkin Wireless Router which can be reached by pointing a web browser to the IP address of the router

The LAN settings are shown below:




In this case the local network has valid addresses from to The router is at address and any DHCP requests will be given entries between and (you can change the range of the DHCP addresses if required). I have used for this server.

To change to static IP address

cd /etc/network

sudo nano interfaces

replace the line “iface eth0 inet dhcp” with

iface eth0 inet static




You should also take a look at the file /etc/resolv.conf

and check it has a nameserver entry (probably pointing at your default gateway)

Alternatively you could point directly at your ISPs DNS servers rather.

Whilst you can dynamically reload the network interface I suggest a reboot at this stage to make sure that the configuration is correct.

sudo reboot

After logging in check using ifconfig to confirm that we have a static ip address


eth0      Link encap:Ethernet  HWaddr b8:27:eb:8a:71:a0

          inet addr:  Bcast:  Mask:


Using ssh

SSH (Secure Shell) is a network protocol that allows you to login and control the computer through the command line remotely. As the name suggests it is secure as it encrypts communication across the network (so that others cannot see your password etc). It also has some great features such as tunnelling, which we won’t go into here.

Using the Wheezy image ssh is turned on by default. This can be enabled / disabled through the raspi-config tool if required.

You can now connect to the Raspberry pi remotely (on the same network) via ssh.
If you have another linux computer on the network then from a terminal run

which will login with the same username. If you want to use a different username then prefix that before the ip address with an @ sign.
ssh pi@

If you want to connect from Windows then there are several options, but I suggest the open source software Putty.

Making the server available on the Internet

Next we are going to configure the router to allow ssh logins and web traffics through its firewall to the Raspberry Pi.

You did remember to change the default password for the pi username didn’t you! If you haven’t already changed the default password then do it now otherwise anyone will be able to login to your Raspberry Pi.

As a home user the ip address used on your local network is a private address range that will not work over the Internet. Instead your ISP will provide a single dynamic IP address which is used by the router. To allow traffic to flow from the Internet to your Raspberry Pi needs the IP address of the Pi to be made to look as though it is from the router. This is a process called Network Address Translation (NAT).

The ports that need to be allowed through are port 80 (http) and if you would like to be able to login to the computer from the Internet then port 22 (ssh).

To do this you will need to consult the instructions on your router. In the case of my Belkin router this is through the Firewall > Virtual servers settings (see below), but Netgear this is Advanced > Security > IP Forwarding.





The final stage is to have a DNS entry point at your router’s IP address. In my case I have cable Internet through Virgin Media. Although it does have a dynamic IP address the address does not normally change. I have a static DNS entry on a Internet DNS server. The entry only needs to be changed about once every year or when Virgin Media perform significance maintenance on the Internet connection.

If you have a dynamic IP address that changes on a more recent basis then you will need to register for a dynamic dns service.

Installing lighttpd

To install the lighttpd web server issue the command.
sudo apt-get install lighttpd

This will install the web server and also pull in any other packages (called dependencies) that are required. The server will be automatically started and set to start by default after a reboot.
[ ok ] Starting web server: lighttpd.

Install mysql database (optional)

Whilst you can have a perfectly good website without a database, database provide a good way of holding data and are a requirement for many content management systems (CMS) and web based applications. If you don’t need a databse the you can skip this and go straight to configuring php.

Mysql is the most popular database server, whilst there are other alternatives some of which may require less resources most third party software for Linux is designed to use Mysql.If required it can be installed using

sudo apt-get install mysql-server

During the install there is a prompt request for a password.
The password is for the mysql root user.

Install PHP

Perl is installed as part of the operating system so I will just be adding PHP, which is an interpretted programming language. Whilst this is optional it is recommended that it is installed as it is particularly useful.

The following commands will install PHP version 5.

sudo apt-get install php5-common php5-cgi php5
Note it’s important to install in the order listed above. If you try to install php5 without first installing the php5-cgi package then it will install Apache as well, which we don’t want for this light-weight lighttpd server.

If you installed mysql then you should also issue the following command to install the php mysql libraries to allow PHP to access the mysql database.
sudo apt-get install php5-mysql

To enable the server to handle php scripts the fastcgi-php module should be enabled by issuing in the command
sudo lighty-enable-mod fastcgi-php
Then reload the server using
sudo service lighttpd force-reload

Set permissions on the web directory /var/www/

It is useful to change the permissions on the www directory to allow your user to update the webpages without needing to be root.

Change the directory owner and group
sudo chown www-data:www-data /var/www
allow the group to write to the directory
sudo chmod 775 /var/www
Add the pi user to the www-data group
sudo usermod -a -G www-data pi

You should logout and back in – to pick up group permissions, or if running X you can just start a new terminal.

Testing the server

Once the setup is complete you can access the web page by pointing your browser to the router IP address or DNS entry.

You should get a page back stating that it works, but that there is no content loaded.

To test that the webserver and PHP are working correctly then delete the file /var/www/index.lighttpd.html and create a file /var/www/index.php with the contents of this page.

Note that the filename of the link ends in .txt to prevent my webserver from running this, you should have the file ending with .php so that the file is run as a PHP script.