Lesson 8 Relay

Share for us
Share on facebook
Share on twitter
Share on pinterest
Share on whatsapp

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_LcdStartKit /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.

Code

 #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; }