In: Computer Science
FOR ARDUINO PROGRAMMING;
WRITE CODE TO FIT THE BELOW REQUIREMENTS
1. LED 3 TURNS ON IN DARK CONDITIONS AND OFF IN LIGHT CONDITIONS
2. LED 4 TURNS ON WITH FIRST BUTTON PRESS AND STAYS ON UNTIL A SECOND BUTTON PRESS
Answer (1) = We need to glow LED in Dark conditions and off LED in Light conditions. To sense the light we need a "Light Dependent Register", which sense the light and generate a analog waveform of frequency according to the light intensity. The arduino code for this purpose is as below. Comments are shown by "//" operator at beginning of line.
source code :
int led = 3;
// main function
void setup(){
pinMode(led,OUTPUT);
}
// loop to manage led functionality
void loop(){
// connect Light Dependent Register to A1 and read the waveform using analogRead
int intensity=analogRead(A1);
// if intensity is greater than 50 means it is light conditions and off the led
if(intensity>50){
digitalWrite(led,LOW);
}
// if intensity is lesser than 50 then it is dark situation and on the led
else{
digitalWrite(led,HIGH);
}
}
Answer (2) = We need to manage led as "if we press any button then led is on, and if we press another button then led is off". The arduino code for this purpose is as below. comments are shown by "//" operator at beginning of line.
source code:
// button position in arduino
int btn = 2;
// led position in arduino
int led = 4;
// initially assume led is off
int state = false;
void setup(){
pinMode(led, OUTPUT);
pinMode(btn, INPUT_PULLUP);
}
void loop(){
// if button pressed then change the state and write state to
led
if (digitalRead(btn) == true) {
state = !state;
digitalWrite(led, state);
}
// while loop always on the led until next time button is not
pressed
while(digitalRead(btn) == true);
delay(50);
}