Code
The project code is in the same logic as TableLamp. Press the button to driver the transistor conducted.
Because the relay and LED are connected in parallel, they will be opened at the same time. And if you press
the button again, they will be closed.
C Code 14.1.1 Relay
First observe the project result, and then analyze the code.
1. Use cd command to enter 14.1.1_Relay directory of C code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/C_Code/14.1.1_Relay
2. Use following command to compile "Relay.c" and generate executable file "Relay".
gcc Relay.c -o Relay -lwiringPi
3. Run the generated file "Relay".
sudo ./Relay
After the program is executed, press the button, then the relay is opened, the Motor starts to rotate and LED
is turned on. If you press the button again, the relay is closed, the Motor stops running, and the LED is turned
off.
The following is the program code:
#include <wiringPi.h>
#include <stdio.h>
#define relayPin 0 //define the relayPin
#define buttonPin 1 //define the buttonPin
int relayState=LOW; //store the State of relay
int buttonState=HIGH; //store the State of button
int lastbuttonState=HIGH;//store the lastState of button
long lastChangeTime; //store the change time of button state
long captureTime=50; //set the button state stable time
int reading;
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring fairelay,print message to screen
printf("setup wiringPi fairelay !");
return 1;
}
printf("Program is starting...\n");
pinMode(relayPin, OUTPUT);
pinMode(buttonPin, INPUT);
pullUpDnControl(buttonPin, PUD_UP); //pull up to high level
while(1){
reading = digitalRead(buttonPin); //read the current state of button
if( reading != lastbuttonState){ //if the button state has changed ,record the
time point
lastChangeTime = millis();