< async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"">

Friday, February 28, 2014

Arduino - controlling high voltage devices-from dc motors to ceiling fan speed controller

Arduinos and raspberry pi's operate at a lower voltage (5v) and controlling led's, servos etc can be done this voltage or with a simple transistor based switching. In this post i will show different techniques used to control devices at a higher voltage and power levels. These techniques can be used in conjunction with many other projects for e.g remote controllers  to control high power devices like room heaters, lamps e.t.c In general, you need to couple the 5voltage control signals to the input of these switching circuits.

Safety Considerations

Some parts of these circuits operate at extremely lethal voltage and current levels. Do not attempt to work on these without understanding and following ALL of the relevant safety guidelines for high voltage and/or line connected electrical and electronic systems.

Controlling DC motors at 12 volt with Speed controle (PWM)

Controlling DC motors with PWM (pulse width modulation, to control the intensity/speed) is straight forward. Here we use a special transistor (TIP-122, datasheet) which is a darlington pair and can switch a device up to 100Volts (DC). It is a TO-220 package with all inside the package (see figure). Connect the PWM output (for speed control) to the base of TIP-122. Connect emitter pin to ground and collector pin to C fan/motor and the other end of fan to positive end of 12v DC.

Use any pwm pin (eg Pin 9 with analogWrite(9,speed_value);) and connect it to the base of the transistor (TIP-122) via 1k resistor

TIP-122 pin connection for controlling 12volt motor with arduino/raspberryp pi

Controlling AC lights, heaters, fans (120/220Volt)

There are two approaches. The simplest is to use a relay and this can be done with the same circuit shown above. The relay has a small electromagnet which switches on/off a high voltage line. Asecond approach which doesnt have any mechanical parts is a solid state relay (SSR). These devices have built in semiconductors which does the switching and there is an isolation in the form of opto-couplers  or so to isolate the low voltage arduino lines from the mains. These SSR can switch devices at 120 or 220 volts depending on the bulit and can be obtained from manufactures like omron also can be spotted on online stores like ebay.
Solid state relay to easily control ac 220v/120v devices with arduino

Controlling AC fan speeds with arduino/raspberry pi

It is normal to think that the pulse width modulation can be used to control the speed / brightness of ac devices by pwm ing the SSR. But it is not feasible and a different approach is needed to adjust the motor speeds in AC. The lights can be controlled by converting AC to DC as they works on both while AC motors need some tricks to adjust their speed. This is done by controlling the on time of triacs after a delay from zero crossing (more details on this is beyond the scope of this post). A manual control circuit for AC fan speed is shown below

AC 220v ceiling fan speed control with arduino pwm trick

But here is a trick with out the need for zero crossing and is borrowed from an article (dont remeber where) which used a similar approach on a drilling machine. See the modification above where a cds ldr is used in place of the variable resistor used to control the capacitors charging time and a pwm ed led is used to adjust the resistance value. This is a quick and dirty hack and may help some one. The correct way is complex and need to sense the zero crossing and the firing time of triac with respect to the ac cycles.



Sunday, February 23, 2014

Setting up Nordic nRF24L01 RF modules on Raspberry Pi for Home automation

Using NRF24l01 in hobby projects helps to make things wireless. I was using it with arduinos and was using one arduino attached to raspberry pi as the hub for various sensors used in home automation so that they can communicate with the raspberry pi and hence to the internet. So i just did a quick test to run the nrf module directly on the pi. There were plenty of documentations out there and i was a bit over whelmed.

So here is a pi-nrf24 gymnastic to test the things out on the weekend (see figure ). Every thing is hanging on the wall for a quick test. I used the latest build of raspbmc (as my primary use of the pi is for watching media). There are special software like Occidentalis which is specifically made for easy i2c, spi etc (from Adafruit)
Gymnstics with raspberry pi and nrf24l01
I used Raspbmc and the first step was to get the SPI working and was pretty easy with the latest build. But for some reasons i need to use the following commands to make the spi up and running. So just type the code below before doing more experiments with SPI on raspbmc

 sudo boblightd --help

A bit more on spi getting up on Pi can be read here ( very nice article by Brian). In the next step i downloaded the rf24 library for raspberry pi and can be accessed on git hub at here. To make it simple i have a fork of the part needed for the raspberry pi at here

So ssh in to the pi and issue the following commands to compile it on the pi

git clone https://github.com/riyas-org/rf24pi
cd rf24pi
make 
sudo make install

If everything went fine, you can hook up your pi with nrf module. You can do it nicely but it is also possible to follow my gymnastic way as shown above/below

Raspberry pi as nrf240l hub for wireless sensors
To see the pins on the nrf module you can see this post. The gpio pins on the pi can be identified as follows
GPIO piout on raspberry pi for spi

Connect the module as follows

RPi GPIO9    (Pin 21)  to RF Module Pin 7 ( MISO )
RPi GPIO10  (Pin 19)  to RF Module Pin 6 ( MOSI )
RPi GPIO 11 (Pin 23)  to RF Module Pin 5 ( SCK )
RPI 3.3V       (Pin 17)  to RF Module Pin 2 ( VCC/3.3V )
RPi Gnd        (Pin 25)  to RF Module Pin 1 (GND)

RPi GPIO 25 (Pin 22) to RF Module Pin 3 ( CE )
RPi GPIO8 (Pin 24) to RF Module Pin 4 ( CSN )



To test cd to examples folder and run the scanner (sudo ./scanner) and it should show the rf signals around on different channels.

As a starting point, it may be easier to test a wifi scanner on the pi as described in this post, which will ensure that the module is working and connected properly (with a single module)

PIN Connections
Connecting NRF24l01 module to the pi (Rev2 board)


Saturday, February 22, 2014

Quickly make an ultrasound range detector with led display [HC-SR04 quickstart]

Seven-segment Led Range Sensor with Arduino

Measuring distance is an unavoidable stuff for DIYers. Often it is convenient to measure the distance to the ceiling or the water level in an over head tank in a non contact fashion. A simple solution is to use an ultrasound based range detector. Here is a simple and quick introduction to set up HC-SR04 module with an arduino and a seven segment led display. Purpose is to make a basic setup and can further improved to fit different needs. For instance adding an rf transceiver (nrf24l) and a solar cell with rechargeable battery can make it a remote water level measuring device for an overhead tank. After the break there is a simple video demo of the sensor and it seems very accurate. I used this one to quickly measure the dimensions of an apartment without the hurdle of using a tape (surprisingly missing in at my end!!)

Non contact range sensor prototype
To make it simple, i used a library for the sensor called new-ping which seems to support wide range of sensors and provides the distance measurements in inches and centimeters. Further to  provide a simple readout i used a 4X7 segment led module from hobby component and an arduino uno. The complete source code is given below. See the attached figures for easy wiring. The number of pins used can be drastically reduced with led display drivers. But here to make it simple i just used direct drive with couple of resistors and arduino pins 3-13.

Connecting the seven segment led module to arduino

The led module has a total of  12 pins. The connection to the Digital pins 3-13 on the arduino as shown in figure. Do not forget the 220 ohm resistors. The numbers written on are the digital pin number on arduino uno. Also see the sketch (source) if an other arduino (for eg Mega ) is used.
Connecting seven segment led to arduino [click to zoom]

Connecting the ultrasound module HC-SR04

The module has a vcc and ground which goes to 5v and ground pin on arduino. Connect trigger to A0 pin (14) and echo pin to A1 (15).

HC-SR04 Pin connection


If you get an error on compiling, get the library here and unzip it in arduino/library folder. HC7segment library can be obtained here (unzip and copy to arduinos library folder. Rename HC7segment-master folder to HC7segment) . Timed action library can be downloaded at here (http://playground.arduino.cc/Code/TimedAction)

/* 
 Runs HC-04 and SRF-06 and other Ultrasonic Modules
 Credits: http://playground.arduino.cc/Code/NewPing
 Also uses HC-SR04 ultrasound sensor from hobbycomponets

/*-----( Import needed libraries )-----*/
#include <NewPing.h>
#include <HC7Segment.h>
#include <TimedAction.h>
TimedAction timedAction = TimedAction(1000,blink);

/* For the Led display */
const byte u8PinOut_Digit[] = {13,6,5,2};
/* Pin order for segment DIO. The segment order is A,B,C,D,E,F,G,DP */
const byte u8PinOut_Segment[] = {3,7,11,9,8,4,12,10}; 
/* Create an instance of HC7Segment(). In this example we will be using a 4 digit 
   common cathode display (CAI5461AH)  */
HC7Segment HC7Segment(4, LOW);

/*-----Pin connection for Ultrasound sensor-----*/
#define  TRIGGER_PIN  14
#define  ECHO_PIN     15
#define MAX_DISTANCE 500 // Maximum distance we want to ping for (in centimeters).
                         //Maximum sensor distance is rated at 400-500cm.
/*-----( Declare objects )-----*/
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
/*-----( Declare Variables )-----*/
int DistanceCm;

void setup()   /****** SETUP: RUNS ONCE ******/
{
  //just for debug 
  Serial.begin(9600);  
  Serial.println("Debug:arduino and ultrasound sensor");
}//--(end setup )---


void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  timedAction.check();
  HC7Segment.vDisplay_Number(DistanceCm,1); 

}//--(end main loop )---

/*-----timed action which measures the distance-----*/
void blink(){  
  //delay(50);// Wait 50ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
  //DistanceIn = sonar.ping_in();// use if you need Inches
  //Serial.print("Ping: "); 
  delay(50);// Wait 50ms between pings (about 10 pings/sec). 29ms should be the shortest delay between pings.
  sonar.ping_median(10);//calculate median of 10 , to minimise error
  DistanceCm = sonar.ping_cm();
  
  Serial.print("Ping: ");
  Serial.print(DistanceCm); 
  Serial.println(" cm"); 
  
}



Sunday, February 16, 2014

Quickly test an AD9850 ebay module with an arduino and a software defined radio (SDR) [quick start for beginners]

Quick test for AD9850 ebay module with arduino, Note the jumper settings

Direct digital synthesis or DDS is becoming popular among many electronic hobbyists. The availability of the popular AD9850/51 based ebay modules at a very reasonable price has made it possible to quickly setup a nice RF signal generator with an AD9850 module and a micro-controller. In a previous post, i have described an option to control them without a microcontroller (Read here). The basic point is to tell the frequency value to the AD9850 in what ever possible way. The use of a microcontroller makes it easy and open up a wide range of possibilities. For example it is easy to build an automated CW  beacon or to make a simple sweep generator. This module can also be controlled by a raspberry pi and will be in an other post. If you are interested a pi can be used as an RF generator with its built in pll!

So for a quick test of the module you need an arduino boeard and i used  a uno with atmega328. But it should work with any other versions as well. Just keep track of the pin numbers used. So get a couple of connectors and hook it up to uno board as shown in figure. Load the sketch below and tune your receiver at 10MHZ and watch. Attached a small video of my test after a small break.

There are two popular ebay boards and their pin connections are usually written over them. But have a look at the figure below to get an idea

 

An other type of module has some jumpers on the board. It is important to set J1 (see the first figure on the start of the blog post) so that the board is ready to receive serial data on D7 pin

Connecting AD9850 ebay module to Arduino Uno (Click to Enlarge)

There is an other module which is also popular and the connections are similar. Make sure you connect D7 , W_CLK, FQ_UD, and RESET pins correctly to arduino (see figure for details)

AD9850 module quick pin connection details for arduino

After connecting the module you need to load the firmware and is much easier with arduino. Connect the arduino board with a usb cable to your computer. Download and install the arduino ide (From here)
Paste the code (courtesy : nr8o) below in to the ide and press upload and turn the receiver on and check at 10MHZ. I have put a frequency shift at every second and can be easily noticed. See the video at the end.

If you are interested in generating an RF signal, there is a simple way with a raspberry pi gpio (beware of some odd harmonics). You may read it here (Raspberry pi as a simple low cost rf signal generator [quick and dirty solutions])

Also an other application of the module to study weak signal propagation (WSPR or whisper) -


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* 
 * A simple single freq AD9850 Arduino test script
 * Original AD9851 DDS sketch by Andrew Smallbone at www.rocketnumbernine.com
 * Modified for testing the inexpensive AD9850 ebay DDS modules
 * Pictures and pinouts at nr8o.dhlpilotcentral.com
 * 9850 datasheet at http://www.analog.com/static/imported-files/data_sheets/AD9850.pdf
 * Use freely
 */
 
#define W_CLK 8       // Pin 8 - connect to AD9850 module word load clock pin (CLK)
#define FQ_UD 9       // Pin 9 - connect to freq update pin (FQ)
#define DATA 10       // Pin 10 - connect to serial data load pin (DATA)
#define RESET 11      // Pin 11 - connect to reset pin (RST).
 
#define pulseHigh(pin) {digitalWrite(pin, HIGH); digitalWrite(pin, LOW); }
 
 // transfers a byte, a bit at a time, LSB first to the 9850 via serial DATA line
void tfr_byte(byte data)
{
  for (int i=0; i<8; i++, data>>=1) {
    digitalWrite(DATA, data & 0x01);
    pulseHigh(W_CLK);   //after each bit sent, CLK is pulsed high
  }
}

 // frequency calc from datasheet page 8 = <sys clock> * <frequency tuning word>/2^32
void sendFrequency(double frequency) {
  int32_t freq = frequency * 4294967295/125000000;  // note 125 MHz clock on 9850
  for (int b=0; b<4; b++, freq>>=8) {
    tfr_byte(freq & 0xFF);
  }
  tfr_byte(0x000);   // Final control byte, all 0 for 9850 chip
  pulseHigh(FQ_UD);  // Done!  Should see output
}

void setup() {
 // configure arduino data pins for output
  pinMode(FQ_UD, OUTPUT);
  pinMode(W_CLK, OUTPUT);
  pinMode(DATA, OUTPUT);
  pinMode(RESET, OUTPUT);
   
  pulseHigh(RESET);
  pulseHigh(W_CLK);
  pulseHigh(FQ_UD);  // this pulse enables serial mode - Datasheet page 12 figure 10
}

void loop() {
  sendFrequency(10.e6);
  delay (1000);
  sendFrequency(10.01e6);  // freq
  delay(1000);
}

There are some better libraries if you want to do more with arduino and ad9850.


Friday, February 7, 2014

IR blasters - All you need to know about infrared remotes and ir extenders [for DIYers]

IR blaster or Infrared blaster is the term used for a wide range of products which can send infrared remote commands to a wide range of equipment like television sets, Satellite receivers, Set-top boxes, HVAC, projects etc. This can range from simple infrared extenders to control the devices hidden in a cupboard or in a different room to smart devices which can turn on the recording system or air-conditioner at specified times or via internet. Here is a simple guide to help you deal with infrared remote controls in a smart setting. A small over view of the function is given below

IR blaster and Infrared Extender basics (click to enlarge)

Basically an ir blaster or extender needs the following

  • An Infrared Sensor which detects the infrared signals from various remote controls
  • A controller which power-up and control the whole system
  • A blaster which will emit the infrared signals (it can be multiple in number to extend the range and locations)
  • In an advanced system, the controller can be interfaced to a network or internet which enables a lot of advanced capabilities like controlling devices from smartphone,tablet etc and also allowes teaching the remote and doing multiple operations with a single button
For a DIY project, the controller can be made from atmega (arduino), PIC or even a raspberry pi with media center like raspbmc can be used as an ir blaster, hence doing multiple things with a simple raspberry pi.

The entire range of  possibilities are shown in the following figure

IR blaster with raspberry pi/arduino-possibilites [click to enlarge]
A simple IR extender system can be made without any microcontroller. In this case the system simply relays the infrared pulses it receives from the remote controles. This is the basis of simple IR extenders which can be used to control the stack of devices inside a cupboard. An example circuit is given below

A simple IR extender for DIY


A simple IR extender/blaster circuit diagram

In the above circuit, the IR detector generates pulses based on the input signal. The 555 act as an oscillator at the IR carrier frequency (36-40khz) and can be adjusted with 10K linear potentiometer and need to be optimized for the receivers.  Finally the modulated pulses are transmitted from the IR led. The details of ir signalling and codecs are too long to be discussed in this post and hence is kept for later.

More powerful IR blasters - increasing the strength of IR signals 

Often it is necessary to have more power output in the form of ir signals to extend the range of the remote controller. It is also necessary when we need to control an over head projector or a fan which is located higher up in a ceiling. In such cases the following schematic may be useful. Just connect the output signal from the microcontroller or raspberry pi or even the signal from the previous circuit (extender , use output from pin3 of 555 timer ic) to the input of the circuit shown below. It uses two Infrared led's connected to BD139. Other possibilities are using a mosfet switching or an scr.

Powerful ir blaster led_driver

Basics of Infrared Remote


Infrared remote has  a special led (light emitting diode) which emit infrared light, which is invisible to our eyes. But part of it can be viewed if observed through a mobile phone camera. So point your TV remote to a camera and press a button. You will see something like the video below


The blinking led is transmitting  a message to the receiver. The rate of blink, basically the time space between the blinks or the length of on time (depending on different encoding protocols) determines the content of the message. As there is ambient infrared signals in the room, these visible blinks are in turn composed of faster invisible (to our eye due to the fast rate) blinks of the order of 38-40khz , known as the carrier waves. In scientific term, this is a pulse width modulation.

There are different encoding schemes like NEC, Sony, Philips etc. But all of them convey messages based on the length of  blink and non blink intervals. There is a nice description of IR message encoding by Giorgos which can be read here

IR protocols- tools of the trade

As mentioned there are several protocols for IR remotes. To analyse the IR protocols and signals from a remote control, it is ideal to have an oscilloscope, so that the signals can be seen. But in practice we dont need it. An ir receiver and some of the freely available tools can achieve the same results. If you work with linux or raspberry pi, your best friend is LIRC. Although it is a bit difficult to understand, it offers an extensive and comprehensive range of tools to deal with ir remotes. This is useful when dealing with various type of ir devices like usb irda, soundcard (connecting ir sensor to audio in!!) or GPIO (for raspberry pi) and so on.

A more elaborate tutorial on using a soundcard to capture IR protocol can be seen here

You can also use the reverse to generate an IR signal from sound card output and can form the basis for converting a smartphones audio output to an ir output with suitable adapter (if the phone lacks an ir transmitter). A simple example can be read in this instructable.

Bridging with a micro-controller or raspberry Pi


These simple ir blaster circuits shown above relays the information from their sensor to the devices in the cupboard or other targets. Adding a microcontroller like Arduino (atmega)/PIC can make things even more smarter. The device can then be linked to a wireless network, which allowes to control the ir devices over the internet and also to extend the capability to a very long range over the ip network (with in intranet or via internet!). If you use a raspberry pi as  a media center, then the same can be used as the controller! allowing a wide range of possibilities. More on controller integration are discussed in an other post which can be read here.

Smartphone as ir-blaster

Lately, there are smartphones like S4 with built in infrared led. Converting them to a simple ir transmitter is as easy as downloading an android app. If the phone lacks an ir led, it may be possible to use the audio jack and convert it in to ir transmitter. But in that case, using a system as mensioned above with a micro-controller- wifi-net bridge and hence the phone can be used to control the devices by using a simple web-browser.

Integrating the raspberry Pi based webcontrolled ir blaster

After reading a wonderful article by James on integrating a web controlled ir device on the raspberry Pi, I made a simple single step process for the beginners to quickly integrate a python and flask based web controller for their infrared projects for htpc (home theater projects).

Adding web control to ir blaster

To add web control, you need to follow the commands given below. Here it is assumed that the username is still pi (if not, you need to edit the remote.py file at a later step)

ssh in to the pi and issue

cd /home/pi

wget https://github.com/riyas-org/irweb/archive/master.zip

unzip master.zip
mv irweb-master irweb
cd irweb
python remote.py

Now the remote control can be accessed by navigating to the IP address of the raspberry pi

For eg http://192.168.0.100:5000 and see the magical interface (Thanks to James for bringing this)

Commercial solutions

If you want a quick solution there are some commercially available ir systems. They are bit expensive when it comes to features. It is worth searching for flirc, logitech harmony.

Thursday, February 6, 2014

raspbmc internet browser- a simple guide to aurora browser on the raspbmc

Internet browsing with raspbmc media center 

raspbmc internet browser
Finally there is a web browser in Raspbmc which is accessible from the menu. November update of raspbmc has a new web browser in addition to the xbmc. This is useful for those who want to quickly browse some webpages on a big screen, without turning an other computer on. This browser called aurora seems to be an experimental version. You should keep in mind that, many of the browser plugins like flash are not available. So if your aim is to watch streaming videos, you need not have to use this. Get corresponding video plugins from the xbmc repository, which will solve the problem in a more elegant way. If you want to remove the browser and its component, see my other post here.

This browser is almost like a different operating system installation. So when you need to run the browser, the raspberry pi reboots to the browser kernel and vice versa. So often people faces issues like reboot loops with raspbmc web browser and this can be solved by modifying the config.txt as described here.

To launch the web browser, choose the Raspbmc settings menu and there will be a launcher. you can also see it in programs menu. When you launch for the first time you need to wait for the download. Once installed the pi reboots to load the browser. to exit, choose file-exit as it replaces the config file back, so that the pi boots back to its original kernel for xbmc.

Before jumping to use this new browser, please keep in mind that, this browser is supported in wired network! so if you use WiFi, you are out of luck. You are out of luck if you assign a fixed IP address to the pi! So you need to use a dynamic ip address with DHCP and keep the Ethernet cable plugged. This is a first attempt and the effort by the developers needs to be appreciated. So don't complain! If you like to try, just try it. If you want to remove it, it can always be removed.

So if you get trouble in connecting to the internet with aurora web browser on raspbmc, make sure


  1. Enable dhcp for the raspberry pi (if you have fixed the ip adress on router)
  2. Use Ethernet cable to connect the Pi to internet (not wifi)
  3. Go to programs menu and launch the browser and wait for the raspbmc to reboot 
If you want to get rid of the browser, here is my post on Remove Raspbmc web browser- getting rid of Arora Web Browser and removing it from Program shortcuts in raspbmc


Here is a nice YouTube video from Michael Rieger describing the usage of the browser: