- Hands-On Robotics Programming with C++
- Dinesh Tavasalkar
- 308字
- 2021-06-24 15:30:33
Smart light program
In this smart light program, we will first read input from the LDR sensor and, based on the input value, we will turn the LED on or off. The program for smart light is described as follows. You can download the SmartLight.cpp program from the Chapter02 folder of this book's GitHub repository:
#include <iostream>
#include <wiringPi.h>
int main(void)
{
wiringPiSetup();
pinMode(0,OUTPUT);
pinMode(8,INPUT);
for(;;)
{
int ldrstate = digitalRead(8);
if(ldrstate == HIGH)
{
digitalWrite(0,HIGH);
}
else
{
digitalWrite(0,LOW);
}
}
return 0;
}
The explanation of the preceding program is as follows:
- Inside the main function, we have set wiringPi pin 8 as the input pin and wiringPi pin 0 as the output pin.
- Next, in the for loop, using the digitalRead(8) function, we are reading the incoming digital data from the digital pin(D0) of the LDR sensor and storing it inside the ldrstate variable. From the LDR sensor, we will receive HIGH(1) data or LOW(0) data. The ldrstate variable will be HIGH when there is no light and it will be LOW when there is light.
- Next, we will check whether the data inside the ldrstate variable is HIGH or LOW using an if...else condition.
- Using if(ldrstate == HIGH), we are comparing whether the data inside the ldrstate variable is HIGH. If it is HIGH, we are turning the LED on using digitalWrite(0,HIGH).
- If the ldrstate is LOW, then the else condition will execute and by using digitalWrite(0,LOW), we are turning the LED off. Next, you can click on the Compile button to compile the code and then test it by clicking the Build button.
Now that we understand the SmartLight program, we will explore the concept of Pulse Width Modulation (PWM) and use a library called softPWM to change the brightness of an LED.
推薦閱讀
- 玩轉(zhuǎn)Scratch少兒趣味編程
- 新一代通用視頻編碼H.266/VVC:原理、標(biāo)準(zhǔn)與實(shí)現(xiàn)
- 碼上行動:零基礎(chǔ)學(xué)會Python編程(ChatGPT版)
- Podman實(shí)戰(zhàn)
- 快速念咒:MySQL入門指南與進(jìn)階實(shí)戰(zhàn)
- 自然語言處理Python進(jìn)階
- Python機(jī)器學(xué)習(xí)基礎(chǔ)教程
- Building Microservices with .NET Core
- 深入解析Java編譯器:源碼剖析與實(shí)例詳解
- Web編程基礎(chǔ):HTML5、CSS3、JavaScript(第2版)
- 精通Spring:Java Web開發(fā)與Spring Boot高級功能
- Shopify Application Development
- 程序員面試金典(第6版)
- Scala編程(第4版)
- Mastering Data Analysis with R