Sunday, July 26, 2015

The RasPi Lights Tutorial

This blog post is a bit special. Not only am I writing this at a time I had hoped it would be over, this one is also a bit of a tutorial or How-To. I recently posted about a small little project I was working on here, and then just a few days back, when it was nearly finished, I posted a short video about it on google+. Surprisingly there was a bit of interest shown in that. xD

Here is that video

RGB mode to RED, on top of my bigger workspace.

Same thing as above, Now in blue.

This is just a temporary arrangement. I will mount the LED strip properly later.


So, here is a Not-So-Detailed tutorial on how I did it.

Disclaimer: - I did very little coding to get the work done. Most of what I did was simply copying over and merging codes into one single file. I take no credit, apart from assembling the hardware. Also, if you are looking for an absolute beginner guide sort of this, I recommend that you check out Adafruit's guides. They are simply amazing and very easy to follow.



So my basic aims with this little project were:-
·        Web interface controlled, PWM based RGB LED accent lighting
·        Temperature and humidity data logging of my room
·        Character LCD displaying the IP address, temperature and humidity in real-time.

The character LCD was an important add-on later since I was running the pi in headless mode, i.e. without a display, and knowing the IP address is very useful, since IP addresses are assigned dynamically at every reboot by the router.

Now onto the materials. The complete list of the materials I used are


·        Raspberry Pi B+ v1.2            [Not the latest Rpi2, but it should work]
·        Edimax Ew-7811un Wi-Fi adapter
·        Any character LCD display based on the Hitachi HD 44780 chip. [It should have 16 pins]
·        Analog RGB LED strip
·        Logic Level N-channel MOSFETs. I am using the IRLZ34N.                                                                 [Any mosfet with greater than 5 amp drain current at 2.5 volts of gate voltage should do here.]
·        Appropriate power supply for the Pi and the RGB strip.
·        Wires. Lots of wires. Jumper wires, MM/MF/FF type.
·        Breadboard. You aren’t going to solder everything in the first place.


The RGB strip I am using pulls around 1.2 amperes at white colour, i.e. all red green blue LED's turned on. At 5 meters. Some strips can pull up to 4 amperes for 1 meter only.  It’s best to check with a Multimeter. I played safe and slapped a 350 watt ATX power supply to it. I used the +5VSB line (the purple wire in the 22 pin ATX connector) to power the pi via GPIO. Although I recommend that standard USB port is used to power the pi since using the GPIO bypasses all the fuse and over voltage protection built into the pi. Wired incorrectly, you will kill the pi instantly.

Again, Adafruit's tutorials are much better explained and even if you are not planning to execute a certain guide, it will be helpful in other aspects. They are just so well written.

Coming to the execution side of this little project, let’s set up everything first.
Make sure you have a working RPi, and the raspbian is updated to the latest version.

If you have a smaller SD card and on a tight budget, read the Q&A at the end of this post.

First go to Adafruit's Character LCD guide, and follow that. Make sure that you have the libraries mentioned installed and the default example is working as intended. This will work for all common character matrix displays based on the Hitachi HD 44780. Usually all the 16x2, 16x4 and 20x4 character displays. Remember the 16 pin configuration.

Next, go to Adafruit's DHT sensor guide. I have used a DHT-11 but you can use the DHT-22 or AM2320 as well. Again, make sure that the libraries are installed and the demo program works fine.

Ok, with the screen and the DHT sensor handled and working, let’s move onto the RGB LED lighting setup. This one is a bit tricky.

The best guide I have found for this is over at GitHub. But we only need the hardware part of that guide. I used a different software for the LED strip, but the connections required are wonderfully explained by the author.

Once all the wiring is done, we need to install certain software that enables PWM or pulse width modulation on all of the GPIO pins of the raspberry. By default, only 1 pin is capable of that.
What is PWM? Get over here to check out. This is just for info. Not related to the stuff here.

I used a software called pi-blaster. The original pi-blaster was made sarfata. (GitHub) but at the time of writing this blog, his version of pi-blaster supports the older Raspberry B, not the B+ with 40 GPIO pins. So I am using a fork of the same software. It is exactly the same code, apart from a few lines which enable PWM on all the pins of RPi B+ and the RPi 2.

Instructions on how to install pi-blaster are posted along with the source code, which is compiled on the raspberry itself. Once installed, wire up the LED strip and test it using the echo commands. Again, they are mentioned in the Readme file of pi-blaster.
That is all the hardware part done. And actually nearly all of the software done as well.



Now comes the tricky part. The part where I struggled for nearly 3 weeks. That is, how do I get everything to work together? Well, the short answer is, I had to hack and create my own programs.
First, let us set up the Web Interface that controls the RGB LED strip using a web page.

Obviously, the first step is to install apache web server with PHP support onto the raspberry pi.

Next, comes the most important part. Here is the link to a zip file which has all the necessary files and a small ReadMe included in it. Basically, all you have to do is to copy over the files in the exact same directory structure as it is in the zip. These will be:-

"/usr/lib/cgi-bin/" - For the python scripts
and
"/var/www/" - For the hosted Web Page

You can use the sudo cp commands to copy stuff. I simply copied all the stuff from a different computer into the directories mentioned.

Once you have copied all of the files in the respective locations, you have to make the python scripts executable, which are in the /usr/lib/cgi-bin directory.

Use “chmod +x *.py” to make all the python files in the directory executable.

I found this zip file on a YouTube Video. All credits to original author.


VERY IMPORTANT.
After a lot of trial and error, I've observed that the PWM outputs are fine only on the GPIO_GENx pins. I'm not sure why that is, but this happens. Now if you wired your display as per the Adafruit guide, you have already used up all the GPIO_GENx pins. So we have a problem...

Or do we? Nope! In the python file used for running the display, change any 3 GPIO_GENx pins to simple GPIO pins, because the LCD works fine for any GPIO, as long as it is configured correctly. For example, I changed GPIO 23, 24, 25 to GPIO 13, 19, 26, hence freeing up the GPIO_GEN pins, which I then used for PWM. See the Rpi B+ pinout diagram to know which pins are GPIO_GENx pins. X here is a number.

Notice the GPIO_GEN pins? That's where correct PWM is.


You will need to edit the python scripts in the zip file, according to the pinouts you are using for the LED strip. In LED.py and stop.py, make sure you change the corresponding GPIO pins for the Red, Green and blue channel. Remember that the number is the GPIO number, and not the actual number. IE if you want to use GPIO 23 for Red channel, change the value of red channel to 23, which is the GPIO number, and NOT 16, which is the actual pin count. There are 2 places in the LED.py and one place in stop.py where the changes are required.

So now, all is done and the simple task of running it all together remains. It is a good idea to check that every component works individually. Make sure the demo programs by Adafruit of the Character LCD and the DHT sensor work. Also, issue the echo commands when the pi-blaster service is running to re-confirm that PWM is also working for the RGB LED strip.


Assuming everything is done up to this point, let’s start hacking code.
Now the base of the code is the same script as the character LCD example, because that is the most complex and we need the LCD script base.

The base code of Adafruit_CharLCD.py


After editing the char_lcd.py to barebones, add the DHT sensor.py into the same file.Remember to change the python code so that you don’t have to enter the GPIO pins in the input, as required by the original code of Adafruit, and works on the defined pin only.

Adafruit_DHT with predefined pins, inside an infinite While loop


Also add the code which pulls the IP address of the pi and stores it as a variable.

This part is actually above DHT and out from the infinite loop, as IP once assigned does not changes, until reboot. This saves additional processing if the IP code was also included in the loop.
I know I'm smart.


Then use the lcd.print() function to print the variables on the LCD screen. Put all of this inside an infinite loop so that the temperature and humidity keep on getting refreshed on the screen.
Lost track on how to do so? Let me help. :)

Here is the complete python file, for LCD displaying temp, humidity and IP


Character LCD with IP Address

Yeah, its quite hot here. I should say humid though.


Now, we want that this script starts up automatically at boot. Obviously, if I don’t know the IP address, how can I SSH into the pi to run the script that tells me the IP? So for that, I’m using the CRON task scheduler, which, I’ve been told, is built into every Linux system. Neat!
I programmed CRON to run the python script at every reboot, i.e., whenever the pi is turned on. This is by far the easiest method I have seen to run scripts at boot.
Remember that while setting up the pi-blaster, if you ran "sudo make install", pi-blaster will automatically start at every boot. No need to cron that.

Small guide to CRON Task Scheduler


With everything set up, fire up your laptop, PC, mobile or tablet, connect it with your Home wifi, open a browser, type in the IP Address that is shown on the LCD, and you should see something like this.

For some reason, the buttons work only when the text is clicked.


Press any option here, according to your taste. Except for the All colors, you will be able to select the color you want the lights for.

The All colors option cycles through every possible color, hence no color selector.

Press the activate button and hopefully, you will see something like this.



#SWAG



Now, someone asked me for a basic introduction to pi, as well as some general questions. The good thing about the pi is that there is a lot of information which is available on the internet. The BAD thing is that you really have to make an effort to get that information. All those small bits and pieces are scrambled throughout the net. Let me try to answer some of them in a Q&A form.

Q1. I’m a beginner and I don’t have the anything lying around, should I buy the kit or should I get individual parts?

A1. That depends upon you and your needs. I got only the RPi at first and I had no idea what I was going to do with it. As I progressed, I got the stuff I needed. If you are just getting started, I don’t think a full kit is needed, since most of the accessories are already there. Things like USB keyboard, mouse, HDMI monitor etc., are common now. Also, if you are using Wi-Fi, don’t forget to get a Wi-Fi dongle as well. The Edimax Ew-7811un is excellent.


Q2 .How cool would it be to attach an Arduino with it?

A2 .Very cool! But I don’t really know, since I haven’t tried that yet. If you are planning something with a lot of sensors, then it’s a great idea. I've tried something called GrovePi. It's basically a HAT board for Raspberry with Arduino on top. Also, the sensor connectors are standardized for the GrovePi, hence allowing for easy connections. The code is also available on their GitHub. Except for the wiring limitations and cost in India, it is an excellent starting point for IoT.


Q3. I’ve got some old SD cards, but of very small size. Is there any way I can use them?

A3. I had the same problem, and since I was on a shoestring budget, I found a way to work around that. Assuming you have a lot of pen drives, you can use one for storing the OS on the pen drive. The catch is that RPi still needs an SD card to boot from. The way to get around that is very simple.

Get an .img file of the OS of your choice. Usually Raspbian. No NOOBS, only the .img file. Next, install that .img onto your pen drive just as you would install the img on your sdcard. This will partition your pen drive into 2 parts. One will be a FAT partition of around 60 MB named boot. Other will be ext4, which stores the actual OS. There may be some unallocated space left.

Then, insert your sdcard, format it to FAT, name it as boot, and copy over all the stuff from the boot partition of the pen drive into the boot partition of the sdcard.
Open your sdcard, there will be a file named cmdline.txt
Change the line in cmdline.txt on sdcard from” root=/dev/mmcblk0p2” to “root=/dev/sda2”
This reassigns the root of the OS from the sdcard to the pen drive.

Lastly, you may like to merge the unallocated space of the pen drive the root partition of the pen drive. This can be easily done using Gparted on Linux. I don’t think it’s possible on widows.

The end result of the bootable Pendrive for RPi, as seen from Ubuntu.



Q4. is it necessary to have Linux installed on a main PC/Laptop? Can’t I use Rpi with a windows machine?
A4. Well, you can. But I’ve found out that tools like Putty and VNC are much more stable on Ubuntu as compared to windows. I’m not saying that they don’t work, I’m saying is that there is a bit of lag on while using windows to run commands on rpi using SSH or VNC. It’s not that bad, but it’s noticeable. If you are planning to run your RPI as a full-fledged computer then you don’t have to worry about all this, since you will be running Linux anyways. Exception to Windows 10 IoT.


Q5. What about the power source to the Pi?

A5. This is a fairly important part. Technically you can use any Mobile phone charger with a MicroUSB wire. But the Amps the charger is capable of supplying is very important. I tried a Moto charger, limited to 500mA only and it causes random freezes on the pi. 

500mA. Seriously Motorola?


Anyways. The power consumption/draw varies on what all is connected on the pi. To be on the safe side, I recommend a 10W or 2Amp charger. The voltage should not exceed 5 volts on the USB.
If someone is a bit crazier like me, you can also power the Rpi from the GPIO pins. But as I said, that bypasses all the power protection circuits and puts pi on a great risk. I’m myself using a 350w power supply. Overkill. But that also powers the speakers, the LED strips, a DIY 4 port USB charger and the 5V sensors.

The PSU I have mounted under my desks, that powers everything. I'll be adding a UPS here so that PSU continues to work even if there is a power outage. White LED's for added effects.


Here are some other Photos of my apparatus.

The brains behind all, The RPi B+
The 3 wires going to the left are for the LED PWM

The LCD display, DHT-22, 3 MOSFET's and a guest appearance by Ultrasonic sensor
This is the minimalist wiring possible.

A slightly better look at the MOSFET's. These were the hardest to get components for me. Logic Level MOSFET's.
Logic level is important.


So I guess that's it. Please feel free to comment, ask questions and suggest improvements. As usual, all feedback is welcome. Drop by on G+ and say Hi!

:)


Thursday, June 4, 2015

The Massive Update Post (v1)

Yes, I know that I have failed to update my blog and literally just plain ignored stuff. I admit. And now, since I feel bad about that, i will try to fix this. Hopefully this one ginormous post will undo most of the damage inflicted on my own will. 

As you can very clearly see, I have been busy. And when I say busy, I mean REALLY busy. No online activity, not even on Google+! Well all this is due to a very good reason. Or perhaps a couple of reasons. Well earlier, I was busy in college, with no time even to process the photos in the camera. But even after that, I had tonnes of stuff to do, Computer stuff. LINUX STUFF!

My Laptop Work-space, with the unfinished lighting project
My Desktop Work-space (1)


My Desktop Work-space (2)


No, not just the software concept of Linux, which is open for all. Even the Open soured hardware has kept me busy. So when I found out about the Raspberry pi, I just could not resist it. Again, I'm quite late to join in the RPi party.

So when I got the first Rpi, I was plain confused, as to what should I do with it? There were so many possibilities! Then an idea struck me, and I decided to hook it up with my TV. At that time, i Installed RaspBMC, which is now called OSMC. Just install that image to an SD Card and boot the Pi up, and voila, you have a fully functional and with a little adjustments, insanely beautiful home theater system, which is also capable of streaming movies photos music and even act as a NAS device for your home. For the money, that is really really awesome.

If you wish to see more about this...

On the TV front, it is now working as a Steam machine as well, Casting games from my laptop to the TV. 35$ steam machine? Definitely impressive.

I was so impressed by the Pi, that i ordered another one, with sensors and stuff. I was daydreaming this completely automated room of mine.. Walk in, the lights turn on, and according to the ambient temperature, either the AC turns on or the fan. And when I proceed to sit on the desk, the desk lamp lights up. The concept seemed pretty plausible. So I got:-
Relays - to control high power stuff
PIR Sensor – to detect movement
Ultrasonic Ranger  - For that desk lighting
Light sensors and temp sensors

Raspberry Pi, GrovePi, and some sensors.

The day I received all this was also the very same day RPi 2 was announced, with much better specs for the same price. :| 


With all this cool looking stuff in front of me, I realized that I forgot about one very important part. And that was the knowledge of how to code that stuff to do what I want them to do. 

Thankfully, I have the GrovePi boards and the manufacturer (Dexter Industries) have a rather excellent set of documentation to get idiots like me started. Within one week.. I was controlling most of the sensors, together, in unison. I would walk into my room and a small LED strip would light up. And when my laptop got too hot, it would automatically turn on my DIY laptop cooling stand.

And then I hit another roadblock. And this was a big one. For any home automation system to be useful, it has to know the exact location of the persons(s) in the home. In my case, it would have to know how many people are in my room. For example, I configure the sensors in such way that when someone enters the room, it detects the motion and turns on the light. That's easy. What is difficult is that how would the system know if a person is still in the room, but not moving.. for example, sitting on laptop, reading a book, or perhaps, sleeping? For the system.. there was movement, so it turns on the lights for around 10 seconds.. then how does it know that it still needs to keep the lights on? How does it know if it has to turn the lights off if I go to sleep? That is a very big challenge.
I planned on using two light sensors and lasers to make a “people counter” apparatus. If the two lasers are cut in, say direction 1 to 2, then the system can say that a person has entered the room, and turn on the lights. If the lasers are cut in the opposite direction, the system gets the info that person has left the room. Theoretically it sounds good. It might also work. But practically, this system requires a lot of trial and error, for example, what should be the spacing between the lasers, what should be the time lag required to cut the laser path, and so on. And even if I had managed to program this correctly, there was the sleeping problem, which i haven't found the solution until now. All this is also ignoring the massive level of modifications needed in the house. So I ended up dumping this project.

Then, just some time ago, I came across two projects, both made with the base of RasPi, but fairly easy and potentially very awesome to build and make.
One of them, is a WLAN based plotter.Here is the tutorial.

The other was RGB LED strips controlled by a phone. And I was hooked to both. Although I managed to finish the WLAN plotter (in theory), The mood lighting setup is still struck as I cannot find the necessary components, ie, MOSFETs, to control the LED strips. For the curious, i will be using PWM, or pulse width modulation, to control the lighting.
Basic RGB LED tutuorial



The mobile controlled RGB LED Strips


Not that good at cable management


Basic wiring of the plotter

All this also made me realize that there is so much to learn from even the smallest things that we usually choose to ignore. And also no matter how much you end up reading about stuff, until you actually get down to doing it, you will not understand it. Who knew that those boring Basics of Electronic classes could be so much fun, when you actually started playing with that stuff!


Hopefully, I will be able to finish most of the small projects before my vacations are over. And if it turns out to be decent, I may as well write a guide. In case anyone is interested, the whole mood lighting setup will cost around 4k rupees, including the cost of Rpi.

I'd like to end this one with a travel recommendation to the Sundarbans. That place is simplyLEGENDARY. Wide open waters, with islands spotted all over, and forest so dense, you cant even see 10 meters into the island. Plus as there is no electricity, nearly all the tourist lodge i saw were completely working off solar energy, which again is awesome as well as essential in a place like sundarbans. But since one picture is worth a thousand words, I will let the pictures do the talking, with some pictures from the insanely laid back life of Kolkata.



These people were quite patient. Boat rides cost 1 rupee. 


This is the biggest banyan tree in the world, circumference of around 1 km!


My favorite Documentary type photo







You can always check my Google+ to find more pics.

Here's hoping I make another post here, before August.

:)