relay using gpio on raspberry pi

14
R a s p b e r r y P i D r i v i n g a R e l a y u s i n g G P I O P o s t e d o n J u n e 2 6 , 2 0 1 2 b y K e v i n S a n g e e l e e T h e r e s s o m e t h i n g e x c i t i n g a b o u t c r o s s i n g t h e b o u n d a r y b e t w e e n t h e a b s t r a c t w o r l d o f s o f t w a r e a n d t h e p h y s i c a l r e a l w o r l d , a n d a r e l a y d r i v e n f r o m a G P I O p i n s e e m e d l i k e a g o o d e x a m p l e o f t h i s . A l t h o u g h a s i m p l e p r o j e c t , I s t i l l l e a r n e d s o m e n e w t h i n g s a b o u t t h e R a s p b e r r y P i w h i l e d o i n g i t . T h e r e a r e o n l y f o u r c o m p o n e n t s r e q u i r e d , a n d t h e c o s t f o r t h e s e i s a r o u n d 7 0 p , s o i t w o u l d b e a g o o d c a n d i d a t e f o r a c l a s s r o o m e x e r c i s e . E v e n a c h e a p r e l a y l i k e t h e O m r o n G 5 L A - 1 5 D C c a n s w i t c h l o a d s o f 1 0 A a t 2 4 0 V . A w o r d o f c a u t i o n : d o n t t i n k e r w i t h m a i n s v o l t a g e s u n l e s s y o u r e r e a l l y ( r e a l l y ) s u r e a b o u t w h a t y o u r e d o i n g . A m e c h a n i c a l r e l a y a l l o w s a s a f e l e a r n i n g e n v i r o n m e n t , s i n c e y o u c a n s w i t c h a n y l o a d w i t h i t ( e . g . a 9 V D C b a t t e r y / b u l b c i r c u i t f o r t e s t i n g ) , a n d t h e c o n c e p t o f a m e c h a n i c a l s w i t c h i s v e r y e a s y t o g r a s p . A m o r e e f f i c i e n t a l t e r n a t i v e t o s w i t c h a n A C l o a d w o u l d b e t o u s e a s o l i d - s t a t e r e l a y ( e . g . o p t o - c o u p l e d T r i a c ) , b u t i t s q u i t e e a s y t o m a k e a w r o n g a s s u m p t i o n a n d b l o w e v e r y t h i n g u p w i t h a l o u d b a n g a n d a b i g s p a r k . I r e c o m m e n d s t i c k i n g w i t h m e c h a n i c a l r e l a y s u n t i l y o u r e e n t i r e l y s u r e a b o u t w h a t y o u r e d o i n g . T i p : y o u c a n b u y p l u g - i n l o w - v o l t a g e A C p o w e r - s u p p l i e s i f y o u w a n t t o p l a y w i t h t r i a c s . T h e C i r c u i t T h e r e a r e f o u r c o m p o n e n t s t o t h i s c i r c u i t . A r e l a y ( 5 V D C c o i l ) , a B C 3 3 7 N P N t r a n s i s t o r , a d i o d e , a n d 1 K r e s i s t o r . E s s e n t i a l l y , t h e t r a n s i s t o r i s u s e d t o e n e r g i s e t h e r e l a y s c o i l w i t h t h e r e q u i r e d v o l t a g e a n d c u r r e n t . A r e l a y w i l l o f t e n h a v e 3 s i g n i f i c a n t v o l t a g e / c u r r e n t r a t i n g s s p e c i f i e d ; c o i l , A C l o a d , a n d D C l o a d . T h e m o s t i m p o r t a n t t o o u r c i r c u i t i s t h e c o i l r a t i n g , w h i c h i s t h e c u r r e n t a t a s p e c i f i e d v o l t a g e r e q u i r e d t o e n e r g i s e t h e c o i l ( a c t i v a t e t h e s w i t c h ) , s o m e t i m e s e x p r e s s e d a s m i l l i w a t t s ( m W ) . T h e A C a n d D C l o a d r a t i n g s r e l a t e t o t h e s w i t c h - c o n t a c t s , a n d s t a t e t h e m a x i m u m l o a d c u r r e n t ( e . g . f o r y o u r l a m p , m o t o r , e t c . ) t h a t c a n b e c a r r i e d a t t h e g i v e n A C a n d D C v o l t a g e s . D C l o a d s a r e r a t e d l o w e r b e c a u s e t h e y a r c ( s p a r k ) m o r e , w h i c h e v e n t u a l l y w e a r s t h e c o n t a c t s t o t h e p o i n t o f f a i l u r e . I n g e n e r a l , l a r g e l o a d s n e e d h e a v i e r c o n t a c t s , w h i c h i n t u r n n e e d b i g g e r c o i l s t o s w i t c h t h e m , a n d b i g g e r c o i l s n e e d m o r e p o w e r f r o m y o u r c i r c u i t . R e l a y s s o m e t i m e s d o n t f i t e a s i l y o n t o a b r e a d b o a r d , s o y o u m i g h t w a n t t o b u i l d t h e c i r c u i t o n v e r o b o a r d i n s t e a d , o r j u s t m o u n t t h e r e l a y o n v e r o b o a r d a n d a d d t w o p i n s f o r t h e c o i l c o n t a c t s ( a l l o w i n g y o u t o b r e a d b o a r d i t ) . D o n t e v e r p u t A C m a i n s i n t o y o u r b r e a d b o a r d ! S u s a N E T K e v i n S a n g e e l e e

Upload: hyacinthe-mari-cadiz-madronero

Post on 28-Apr-2015

600 views

Category:

Documents


4 download

DESCRIPTION

Relay Using GPIO on Raspberry Pi

TRANSCRIPT

Page 1: Relay Using GPIO on Raspberry Pi

Raspberry Pi – Driving a Relay using GPIOPosted on June 26, 2012 byKevin Sangeelee

There’s something exciting about crossing the boundary between the abstract world of software and thephysical ‘real world’, and a relay driven from a GPIO pin seemed like a good example of this. Although a simpleproject, I still learned some new things about the Raspberry Pi while doing it.

There are only four components required, and the cost for these is around 70p, so it would be a good candidatefor a classroom exercise. Even a cheap relay like the Omron G5LA-1 5DC can switch loads of 10A at 240V.

Aword of caution: don’t tinker with mains voltages unless you’re really (really) sure about what you’redoing. A mechanical relay allows a safe learning environment, since you can switch any load with it (e.g. a 9VDC battery/bulb circuit for testing), and the concept of a mechanical switch is very easy to grasp. A moreefficient alternative to switch an AC load would be to use a solid-state relay (e.g. opto-coupled Triac), but it’squite easy to make a wrong assumption and blow everything up with a loud bang and a big spark. Irecommend sticking with mechanical relays until you’re entirely sure about what you’re doing. Tip: you canbuy plug-in low-voltage AC power-supplies if you want to play with triacs.

The Circuit

There are four components to this circuit. A relay (5V DC coil), a BC337 NPN transistor, a diode, and 1Kresistor. Essentially, the transistor is used to energise the relay’s coil with the required voltage and current.

A relay will often have 3 significant voltage/current ratings specified; coil, AC load, and DC load. The mostimportant to our circuit is the coil rating, which is the current at a specified voltage required to energise thecoil (activate the switch), sometimes expressed as milliwatts (mW).

The AC and DC load ratings relate to the switch-contacts, and state the maximum load current (e.g. for yourlamp, motor, etc.) that can be carried at the given AC and DC voltages. DC loads are rated lower because theyarc (spark) more, which eventually wears the contacts to the point of failure. In general, large loads needheavier contacts, which in turn need bigger coils to switch them, and bigger coils need more power from yourcircuit.

Relays sometimes don’t fit easily onto a breadboard, so you might want to build the circuit on veroboardinstead, or just mount the relay on veroboard and add two pins for the coil contacts (allowing you tobreadboard it). Don’t ever put AC mains into your breadboard!

SusaNETKevin Sangeelee

Page 2: Relay Using GPIO on Raspberry Pi

Schematic for a relay via GPIO on the Raspberry Pi

The GPIO pin used in the example code is GPIO_17, which appears on pin 11 of the Raspberry Pi’s 26-pinexpansion header (opposite GPIO_18 (PCM_CLK) and beside GPIO_21 (PCM_DOUT)). The choice of GPIO 17was simply because I considered it less likely to conflict with other peripherals likely to be in use.

Although the pin is marked 3.3V on the schematic, don’t confuse this with the 3V3 pin – I labelled it with thevoltage to highlight that a 3.3V GPIO pin is driving a 5V load – it could also drive a 24V coil, for example, if anappropriate DC power supply is used rather than the Raspi’s 5V line.

Essentially, to activate the relay, all the circuit does is send a few milliamps at 3.3V from the GPIO pin,through a 1K resistor (you may choose to increase this to 1.2K if you want to be strictly below 3mA). Thiscurrent is enough to saturate the BC337 transistor, causing current to flow on the 5V rail through thetransistor, and therefore also through the relay’s coil.

Most general purpose NPN transistors with an minimum hFE of say 50 to 100 could be used in place of theBC337 – it will depend on a) how much current you’re willing to draw from the GPIO pin, b) how much currentis required to energise the relay’s coil, c) the actual hFE of the transistor in your hand, since they vary wildlyand the current gain could easily be significantly more than the stated minimum.

The diode in the circuit is there to conduct the current generated by the de-energising coil back across the coil(e.g. when switched off), allowing the power to dissipate more gradually, avoiding a voltage spike.

Take care to orient the diode correctly, or you’ll short 5V to ground via the transistor when the GPIO is high.Similarly, take care to correctly identify the collector, base, and emitter pins on your transistor. The pinordering varies by type, so check the datasheet. I’d recommend you double check these two components before

Page 3: Relay Using GPIO on Raspberry Pi

powering up.

The breadboard photo shows it wired up. The pin numbering on my IDC plug should be though of from abovethe connector, to make it correspond with the 26-pin header numbering. Blue is 5V, and brown is Ground. Thegreen wire connects from GPIO 17 (pin 11 on the Raspi’s 26-pin header) to the transistor base via resistor R1.

You can test that the relay is working by disconnecting the wire from GPIO 17 (pin 11 of the 26-pin header)and touching it to 3V3 (pin 1). You should hear a click as you connect/disconnect 3V3. Make sure you keep theresistor in the circuit (e.g. don’t just take a wire from 3V3 to the transistor’s base pin).

Note that the circuit assumes the GPIO pin will be configured as an output. If it’s likely to also spend sometime as an input, then a resistor (10K would do) between the base and ground would ensure the transistor isfully off, rather than having a floating voltage applied.

Using the relay via the ‘/sys’ filesystem

Enable GPIO 17 access via the Kernel on path ‘/sys/class/gpio/’, and configure it as an output pin: -

echo "17" > /sys/class/gpio/exportecho "out" > /sys/class/gpio/gpio17/direction

View the current state of GPIO 17: -

cat /sys/class/gpio/gpio17/value

Set the state of GPIO 17 by writing “1″ for high (relay on) and “0″ for low (relay off): -

echo "1" > /sys/class/gpio/gpio17/valueecho "0" > /sys/class/gpio/gpio17/value

Page 4: Relay Using GPIO on Raspberry Pi

Finally, to use the C code instead, remove the pin from the control of the Kernel driver: -

echo "17" > /sys/class/gpio/unexport

The C Code Alternative

The C source code below shows how to drive the relay using the GPIO peripheral’s hardware registers. It’s all inone file for simplicity and for clarity, though there’s not much to it.

The usleep(1) call has been used to create a short delay before reading the LEVn register to feed back the pinstatus. This is because the rise time for a GPIO pin (the time for the voltage on the pin to rise to a level that’sconsidered ‘high’) is around 100ns to 3V. The ‘high’ threshold is probably less than half that, but even if it’s30ns, that’s 21 ARM clock cycles at 700MHz, and is enough time to read the LEVn register before it hastransitioned.

/** gpio_relay.c - example of driving a relay using the GPIO peripheral on a BCM2835 (Raspberry Pi)** Copyright 2012 Kevin Sangeelee.* Released as GPLv2, see <http://www.gnu.org/licenses/>** This is intended as an example of using Raspberry Pi hardware registers to drive a relay using GPIO. Use at your own* risk or not at all. As far as possible, I've omitted anything that doesn't relate to the Raspi registers. There are more* conventional ways of doing this using kernel drivers.*/

#include <stdio.h>#include <fcntl.h>#include <sys/mman.h>

#define IOBASE 0x20000000

#define GPIO_BASE (IOBASE + 0x200000)

#define GPFSEL0 *(gpio.addr + 0)#define GPFSEL1 *(gpio.addr + 1)#define GPFSEL2 *(gpio.addr + 2)#define GPFSEL3 *(gpio.addr + 3)#define GPFSEL4 *(gpio.addr + 4)#define GPFSEL5 *(gpio.addr + 5)// Reserved @ word offset 6#define GPSET0 *(gpio.addr + 7)#define GPSET1 *(gpio.addr + 8)// Reserved @ word offset 9#define GPCLR0 *(gpio.addr + 10)#define GPCLR1 *(gpio.addr + 11)// Reserved @ word offset 12#define GPLEV0 *(gpio.addr + 13)#define GPLEV1 *(gpio.addr + 14)

#define BIT_17 (1 << 17)

#define PAGESIZE 4096#define BLOCK_SIZE 4096

Page 5: Relay Using GPIO on Raspberry Pi

struct bcm2835_peripheral {unsigned long addr_p;int mem_fd;void *map;volatile unsigned int *addr;

};

struct bcm2835_peripheral gpio = {GPIO_BASE};

// Some forward declarations...int map_peripheral(struct bcm2835_peripheral *p);void unmap_peripheral(struct bcm2835_peripheral *p);

int gpio_state = -1;

////////////////// main()////////////////int main(int argc, char *argv[]) {

if(argc == 2) {if(!strcmp(argv[1], "on"))

gpio_state = 1;if(!strcmp(argv[1], "off"))

gpio_state = 0;}

if(map_peripheral(&gpio) == -1) {printf("Failed to map the physical GPIO registers into the virtual memory space.\n");return -1;

}

/* Set GPIO 17 as an output pin */GPFSEL1 &= ~(7 << 21); // Mask out bits 23-21 of GPFSEL1 (i.e. force to zero)GPFSEL1 |= (1 << 21); // Set bits 23-21 of GPFSEL1 to binary '001'

if(gpio_state == 0)GPCLR0 = BIT_17;

else if(gpio_state == 1)GPSET0 = BIT_17;

usleep(1); // Delay to allow any change in state to be reflected in the LEVn, register bit.

printf("GPIO 17 is %s\n", (GPLEV0 & BIT_17) ? "high" : "low");

unmap_peripheral(&gpio);

// Done!}

// Exposes the physical address defined in the passed structure using mmap on /dev/memint map_peripheral(struct bcm2835_peripheral *p){// Open /dev/memif ((p->mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {printf("Failed to open /dev/mem, try checking permissions.\n");return -1;

}

p->map = mmap(

Page 6: Relay Using GPIO on Raspberry Pi

NULL,BLOCK_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,p->mem_fd, // File descriptor to physical memory virtual file '/dev/mem'p->addr_p // Address in physical map that we want this memory block to expose

);

if (p->map == MAP_FAILED) {perror("mmap");return -1;

}

p->addr = (volatile unsigned int *)p->map;

return 0;}

void unmap_peripheral(struct bcm2835_peripheral *p) {

munmap(p->map, BLOCK_SIZE);close(p->mem_fd);

}

The code can be compiled and run with

root@pi:~# gcc -o gpio_relay gpio_relay.croot@pi:~# ./gpio_relay onGPIO 17 is highroot@pi:~# ./gpio_relay offGPIO 17 is low

Note: there was an error in the original example code, where it was initialising GPFSEL0 rather thanGPFSEL1. If the pin fails to go high, maybe you’ve got the original code.

References

BCM2835 Datasheet – abbreviated datasheet for Broadcom SoC.BCM2835 Datasheet PADS Addendum – additional registers to configure the GPIO peripheral.RPi Low Level Peripherals - wiki page that gives more details on GPIO (and more).My I2C RTC Example – Gives some info on using mmap() to access IO Peripherals, and has otherreferences to Gert Van Loo’s work, among others.Tutorial on Relays – a good beginners tutorial on relays by The Electronics Club.Tutorial on Transistors – a guide to transistors by The Electronics Club.

This entrywas posted in Technical Stuff and tagged Electronics, hardware, raspberry pi, raspi. Bookmark the permalink.

38 Responses to Raspberry Pi – Driving a Relay using GPIO

Page 7: Relay Using GPIO on Raspberry Pi

Phil Lavin says:June 29, 2012 at 8:03 am

Great post. Knocked one of these up last night – works a treat. I was impatient and only had Maplin to hand so I used N18AWrelay, a cheap diode, a cheap 1.2Kohm resistor and a 2N3904 transistor. Was just over £3 in total. All mounted on somestripboard.

Plan to make a Raspi controlled beer o’clock alarm for the office :DReply

Kevin Sangeelee says:July 3, 2012 at 6:58 pm

Ah yes, the noble aims of the Raspberry Pi Foundation celebrated with such enthusiasm :)Reply

mike says:July 9, 2012 at 1:52 am

What’s the diode you used?Great post, thanksReply

Kevin Sangeelee says:July 9, 2012 at 11:57 am

The diode happened to be a 1N4004, but most diodes would do (voltage and current conducted aren’t high when a 5Vcoil’s field collapses). I just used what was handy at the time.Reply

Simon C says:July 28, 2012 at 10:56 pm

Loved this post, I am making a build notification tool (lava lamp & buzzer alertion system ;)

The parts I used to build this, I got from Maplin:

QR40T – 2N3904 transistorRP68Y – 6V 10A PCB RelayQL76H– 1N4004S diodeM1K2 – 1K2 Metal Film 0.6WResistor

Hope this helps anyone else :)Reply

SteveWhite says:August 19, 2012 at 10:46 am

Great post.

Thanks to Simon C for the exact parts details.

Page 8: Relay Using GPIO on Raspberry Pi

Reply

Mike Kelly says:September 8, 2012 at 10:19 pm

Relay modules for Arduino coat about $1 per relay on eBay, they look like they will do the job. You can get from 1 to 16 relays.Google for “Relay Module Switch Board For Arduino”

MikeReply

Kevin Sangeelee says:September 23, 2012 at 11:59 pm

Thanks Mike – yes, it’s worth pointing out that if you just need relay control and aren’t interested in learning how todo the electronics stuff yourself, then there are numerous cheap options available – in fact, any board that accepts3.3V as a ‘high’ signal will work directly with the Raspberry Pi’s GPIO outputs. The power requirement of the relaycoils would need to be known, and a separate power source provided if they exceed, in total, the power available fromthe Pi.Reply

Michele says:September 12, 2012 at 8:36 pm

Hi!Nice word…Just a quick question…Is there a way to check the status of the gpio line using C language?I’m a total noob in C (but a great programmer in Delphi/Lazarus :P)Reply

Kevin Sangeelee says:September 12, 2012 at 8:39 pm

Yes, you just need to read the LEVn registers (see datasheet) to get the actual level on the pin. See another post Iwrote here (http://www.susa.net/wordpress/2012/07/raspberry-pi-gpfsel-gpio-and-pads-status-viewer/) for anexample – you can either compile and run from the shell, or use it as an example to incorporate into your own code.Reply

Adrian says:September 28, 2012 at 5:52 pm

I’m wondering if all this will work with a darlington array, such as uln2803 (which is basically the same thing, in an IC)

it’s a bit of a risk to see if the uln2803 will work at 3.3V though.. we’ll see :PReply

Kevin Sangeelee says:September 28, 2012 at 6:05 pm

I’ve not used that chip, but a darlington array should be ok, and would reduce the current requirement from the

Page 9: Relay Using GPIO on Raspberry Pi

GPIO pins. Regardless, they can provide enough current to drive most general purpose transistors for switching relaycoils.Reply

Adrian says:October 22, 2012 at 6:14 pm

Just to let you guys know, the ULN2308 IC arrived, it works perfectly :D

8 relays with one IC, not bad.Reply

Kevin Sangeelee says:October 22, 2012 at 6:50 pm

Good news. As you’ll be aware, you can drive motors and coils directly from the IC, without even theneed of a relay, but bear in mind that a line-driver will only switch DC loads.Reply

Adrian says:October 29, 2012 at 12:44 pm

yes, I’m planning to use the relays on home appliances and lighting (AC, obviously), so theyare necessary. DC stuff (LEDs, motors, etc) already work nicely, and at whatever voltage ichoose to input to the ICReply

Richard Stent says:September 30, 2012 at 3:46 am

Hi KevinI am attempting to use my Pi and this circuit to switch a garage door opener (GDO) with a 30V DC coil relay. The GDOprovides a Common (ground) and Relay (30V) connectors which when connected trigger the AC motor to open the door.When I connect this/your circuit but provide 30V from the Relay (instead of 5V from the Pi) it does not want to work. I havealso tried a test of a 12V and no luck. I have been using a SY-4080 SS Relay as a test relay (before connecting to the GDO) asit accepts 3V-32VDC – but will only trigger when I supply 5V.Your advise please.

Richard.Reply

Kevin Sangeelee says:September 30, 2012 at 10:22 am

Hi Richard,

I don’t want to give advice on switching mains level voltages, but in terms of energising a DC coil as per the post, youneed to ensure that your transistor can switch the load required of the coil (given either as ohms, mW, or mA –convert between them using Ohm’s Law). Also, the C-E voltage rating must be greater than the requirement of yourcoil.

Also, your DC power-supply grounds must be connected. If you have a 40V DC supply to energise a 30V DC coil, thenthe ground of this supply would need to be connected to the ground of the Raspberry Pi’s supply.

Page 10: Relay Using GPIO on Raspberry Pi

However, I suspect that you’ve confused the contact rating (the switch) with the coil rating (the bit that flicksthe switch) – a 30V DC coil would be very unusual, whereas 30V DC contact rating would be very common. A mistakeor misunderstanding on this, when using mains AC voltage, could easily kill your Raspberry Pi (and quite possiblyeven yourself).

I’d recommend you find a 12V DC power-supply, buy a relay with a 12V coil, and make that audibly click beforemoving on to anything else (and certainly before trying to control any domestic mains circuits).Reply

Richard Stent says:October 1, 2012 at 9:41 am

Hi Kevin

Thanks for your reply. Yes, I would think that I am trying to connect to (switch on) a 30V DC ‘contact’ as it iscurrently activating the relay/switch (inside the GDO) when the common and relay are briefly touched. Imeasured the voltage and current across the contacts (using a multimeter) and is it reads 30VDC and draws76mA.

I now believe I need a mechanical relay that has a 5V coil (powered from the Pi and energized with the BC337NPN transistor) that will allow me to switch this 30V DC contact load briefly (via GPIO on/off commandsfrom my Pi program).

Rest assured I am going no where near any AC mains level voltages. All that is contained inside the GDO.

Thanks for your help. I am learning lots … but feel free to comment if I still don’t seem to get it. :-) Your siteis very enlightening.

Richard.Reply

Kevin Sangeelee says:October 1, 2012 at 12:45 pm

If I understand correctly, connecting ‘relay’ (R) and ‘common’ (C) results in an internal relayenergising. The voltage across R->C is 30V, and the current through R->C is 76mA. If so, thenconnecting R to the transistor’s collector, C to the emitter and to the Raspberry Pi’s Ground should beenough to drive the internal relay coil.

I’d try it first without the Raspberry Pi – just find a 3V3 or 5V supply, connect a resistor to thetransistor’s base and then connect the other leg of the resistor alternately between +ve and ground ofyour supply. Don’t forget to join your ‘common’ and ground too. You’re essentially doing what theGPIO pin does when it goes high and low, so if it works, then it should work fine with the Pi.Reply

Richard Stent says:October 15, 2012 at 4:07 am

Hi Kevin

Yes, it is working now using the Pi and the (R) and (C) connections as you advised. Thanks foryour help. Regards Richard.

Page 11: Relay Using GPIO on Raspberry Pi

Reply

richard says:October 9, 2012 at 10:19 am

Hi Kevin

Yes, that is my way forward. Away on a ski holiday at present so apologies for the delayed reply. Will let you know how I geton in a week or so.

RichardReply

Bos says:October 18, 2012 at 7:20 pm

Hi,I’m a total noob, sorry if this is a stupid question, but:why is the transistor required? Can’t you just switch a (3V) relay with the 3.3V output from the GPIO pin?Reply

Kevin Sangeelee says:October 18, 2012 at 8:29 pm

It’s a perfectly reasonable question – the answer is that you can drive directly from a GPIO pin if you can find a relaythat will energise with the current that the GPIO pins can supply (e.g. a lot less than 25mA). Most small relaysrequire between 50mA to 150mA to energise.

The transistor conducts a relatively large current when a relatively small current is applied to the base pin – smallenough to be driven by a GPIO pin on the Raspberry Pi, which is why the transistor is required.Reply

David says:November 3, 2012 at 6:21 am

Great outline, thank you. Can you explain or (give some overview?) how one would customize this for each GPIOx. As best Ican tell there can be 17 to 21+ GPIO’s available in the new 2.0 512M boards.Reply

Kevin Sangeelee says:November 3, 2012 at 3:05 pm

More of the same really. For the C code, it’s just a matter of setting the appropriate GPFSELn bits to ’001′ (so thecorresponding pin functions as an output), and using GPSETn and GPCLRn bits to set and clear the bits that relate tothe pins you want to control.

The Bash approach makes it even more obvious – just replace 17 with the GPIO that you want to control. As long asyou know which physical pin on the Pi is connected to the GPIO you’re using, then you should be able to control it.You might try connecting the transistor to a different pin, then you’ll understand what’s required.Reply

Page 12: Relay Using GPIO on Raspberry Pi

Vinod says:December 7, 2012 at 9:38 am

Thanks for this post Kevin ( most detailed one I saw on this topic anywhere online). I plan to try out switchinga simple led with a 5v relay before moving on to switching on AC circuits at home, over the next couple ofweeks.Can all the pins on the RPi be used – 17-21 like David says above? Most forums seem to indicate that only 5odd are GPIO pins, others are I2C, PWM and other types ( I have yet to understand what these are).In short, it would be awesome if you can post a detailed tutorial like this one on driving a 16 channel 5V 10Arelays using the RPi – something like http://www.youtube.com/watch?v=8X6PgYaegz0 .Reply

Kevin Sangeelee says:December 7, 2012 at 11:17 am

Hi Vinod, most of the pins on the P1 header can be used for GPIO (some on other headers can be usedtoo). The GPIO function select registers determine what peripherals (I2C, SPI, PWM, etc.) are isconnected to (is active on) a pin. For our application, we configure the required pin as a GPIO Output.I believe that the default state for any pin, other than the UART, is GPIO Input. Certain kerneldrivers will reconfigure pins if loaded, and if so you might need to prevent them loading (e.g. blacklistthem).

As a starting point, read the datasheet to understand how the function-select bits work for each pin.The I2C and SPI peripherals are just for serial communications, PWM (Pulse Width Modulation)peripherals generate high/low pulses of a specified width, and at a specified frequency – commonlyused to generate a variable average voltage or to drive servos.

A 16 channel driver is really just more of the same as what’s here (and written elsewhere), so it’smore of an ‘exercise for the reader’ ;-) Between the datasheet, the schematic and the code, all theinformation you need is there to extend this. An enhancement might be a darlington array chip toprovide multiple high-gain transistors in a single package – neater than 16 x 3-pin transistors. Thepower supply would, of course, need to be capable of energising 16 relays simultaneously, unless youtake steps in software to stagger them.Reply

Vinod says:December 7, 2012 at 5:28 pm

Thanks for the detailed reply Kevin – was most useful, and helped me be a little moreconfident as I wired up a led today ( without worrying about using/messing up a wrong pin).I got the led on/off via GPIO working today, and thanks to webiopi, through a web interface –in about 30 minutes flat.Wrote about it at http://saranga2000.wordpress.com/2012/12/07/raspberry-pi-hello-gpio/- only as a thankyou to all the Giants (including you) on whose shoulders I stood today.Reply

David says:November 4, 2012 at 10:33 am

With respect to the C code above would it be possible to alter the code to take a variable input into the command line, forexample so that is might work like ./gpio_relay 17 on ie ./gpio_relay x on where x is the particular pin being controlled?Reply

Page 13: Relay Using GPIO on Raspberry Pi

Pingback:Getting Started with My Raspberry Pi – Part 1: Blog Post Survey | Lasse Christiansen Development

Kevin Sangeelee says:November 4, 2012 at 11:17 am

Hi David, yes it’s easy to get at parameters from the command line – define main with ‘int argc’ and ‘char *argv[]‘parameters (for reference, the RTC post has source-code that uses these), which contain the ‘count’ and ‘values’ ofparameters respectively. You can use the printf() function to display the parameters if you want to experiment a bit.Reply

Michael Horne says:December 7, 2012 at 10:49 am

Great post for beginners like me. Thanks :-)Reply

Vinod says:December 12, 2012 at 2:51 pm

Hi Kevin, Ive been trying to get a circuit like above ( controlling a relay with the GPIO) to work. I wired up the exact samecircuit but with different parts ( using what I had with me). I used1. BC547B transistor2. 1N4007 diode3. a local relay I got in a kit – that seems to indicate its a 6v relay ( pic attached).

Circuit and Relay spec pics are here:http://kannvin.freeshell.net/wiki/doku.php?id=personal:journal:2012-12-12-144621

I don’t get the clicking sound with the base connected through a 1K ohm resistor to the 3.3V pin.

I did some debugging and saw that:1. I am able to light up a LED through the same circuit, removing the diode, and passing the 5v through a 470ohm resistorthrough led2. the relay itself is working – i get a clicking sound if I connect the 5v pin and ground directly to the leads of the relay.

What am I doing wrong – the only thing I can think of is the BC547B is not able to power up sufficiently to turn on the 6Vrelay. Is this it? Or am I doing something else wrong? If former, what should I do different to drive the relay.Please help.Reply

Kevin Sangeelee says:December 12, 2012 at 3:00 pm

You can try using a lower value resistor to the base, to make sure that the transistor is reaching saturation – youcould use your 470R instead. You might also try a another transistor, since the actual gain varies wildly, even amongtransistors of the same type.

Note your link returns ‘permission denied’.Reply

Page 14: Relay Using GPIO on Raspberry Pi

SusaNET

Vinod says:December 12, 2012 at 4:09 pm

I just figured out what the problem was – I had the Emitter and Collector swapped.It works now. Although interestingly I was able to light up an LED even with the E & C swapped.The relay spec and circuit should now be accessible at http://kannvin.freeshell.net/wiki/doku.php?id=projects:rpi .Thanks for your prompt help Kevin.Reply

Kevin Sangeelee says:December 12, 2012 at 5:18 pm

There’s a symmetry in an NPN transistor, but not a perfect symmetry. So it will work similarly when connected inreverse like you did, just not so well (hence a small current flows, enough to drive an LED but not enough to drive arelay). A higher current through the base may actually drive it to saturation. To understand more you need to readabout doping of diodes, and consider that a bipolar transistor is made from two diodes – there are plenty of sources onthe net that will explain the details better than I could.

Glad you figured it out.Reply

scott says:December 19, 2012 at 11:59 pm

Thanks for posting this! Great place to start for a noob like me. Can you please explain the purpose of the diode in thisconfiguration? Would the diode still be required if a darlington array were used?

Cheers!Reply

Kevin Sangeelee says:December 20, 2012 at 12:06 am

This is nicely explained in the “Tutorial on Relays” (linked in the References) – “Current flowing through a relay coilcreates a magnetic field which collapses suddenly when the current is switched off. The sudden collapse of themagnetic field induces a brief high voltage across the relay coil which is very likely to damage transistors and ICs. Theprotection diode allows the induced voltage to drive a brief current through the coil (and diode) so the magnetic fielddies away quickly rather than instantly. This prevents the induced voltage becoming high enough to cause damage totransistors and ICs.”

It’s still required for a darlington pair, because there’s still a transistor driving the relay’s coil.Reply

Proudly powered by WordPress.