Lesson 8 Relay

Share for us

Introduction

Relays are suitable for driving high power electric equipment, such as lights, electric fans and air conditioning. We can use a relay to realize low voltage to control high voltage by connecting it to MCU.

Components

-1*Raspberry Pi

– 1*Network cable (or USB wireless network adapter)

– 1*Diode (1N4007)

– 1*NPN transistor(8050)

– 1*Resistor(1KΩ)

– 1*Relay

– Several jumper wires

Experimental Principle

When we make the IO connected to the Raspberry Pi and the transistor outputs low level (0V) by programming, the transistor will conduct because of current saturation. The normally open contact of the relay will be closed, while the normally closed contact of the relay will be broken; when outputting high level (3.3V), the transistor will be cut off, and the relay will recover to initial state.

Experimental Procedures

Step 1: Connect the circuit according to the following method

Step 2Edit and save the code with vim (see path/Rpi_UniversalStartKit /08_relay/relay.c)

Step 3Compile the code

            gcc  relay.c  -lwiringPi

Step 4: Run the program

            ./a.out

Now, press Enter, and you should be able to hear ticking sound. This sound is made by breaking normally closed contact and closing normally open contact. You can attach a high voltage device you want to control, for example, a bulb with 220V voltage, to the output port of relay, so the relay plays a role of automatic switch.

 relay.c

#include <wiringPi.h>
#include <stdio.h>

#define RelayPin 0

int main(void)
{
 if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
  printf("setup wiringPi failed !");
  return 1;
 }
 
 pinMode(RelayPin, OUTPUT);

 while(1){
  digitalWrite(RelayPin, LOW);  //relay off
  delay(500);                   //delay
  digitalWrite(RelayPin, HIGH); //relay on
  delay(500);                   //delay
 }

 return 0;
}

Python Code

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

RelayPin = 11    # pin11

def setup():
 GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
 GPIO.setup(RelayPin, GPIO.OUT)   # Set LedPin's mode is output
 GPIO.output(RelayPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def loop():
 while True:
  print '...relay on'
  GPIO.output(RelayPin, GPIO.LOW)
  time.sleep(0.5)
  print 'relay off...'
  GPIO.output(RelayPin, GPIO.HIGH)
  time.sleep(0.5)

def destroy():
 GPIO.output(RelayPin, GPIO.HIGH)
 GPIO.cleanup()                     # Release resource

if __name__ == '__main__':     # Program start from here
 setup()
 try:
  loop()
 except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
  destroy()