Lecture
Today we began by looking at the different types of sensors and actuators in the lecture.
A sensor – is a device that detects and responds to some type of input from the physical environment. The specific input could be light, heat, motion, moisture, pressure, or any one of a great number of other environmental phenomena.
Lab
In the lab we used an Arduino to connect a push button and an LED together which would allow the button when pressed to switch on the LED, this then progressed into allowing the led to fade in and out.
Code
Below is the code used from the lab that allowed for the button to switch on the LED and keep it switched on until the button was pressed again.
const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
int state = 0; // 0 = LED off while 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check if the input is HIGH (button pressed)
// and change the state
if (val == HIGH) {
state = 1 - state;
}
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}
Arduino button switching on/off the LED


Arduino LED – Complete Tutorial – The Robotics Back-End (roboticsbackend.com)
There were several versions of the same code but all of them had different improvements as it was found that as the Arduino runs quicker than the time it takes for a human to press the button, it would sometimes flicker. Altering the code allowed for the Arduino to have time to process so now no flickering would occur with the LED.
Controlling light with pulse-width modulation
We then coded the Arduino board to allow an LED light to fade the light from high to low using this code below.
// Fade an LED in and out, like on a sleeping Apple computer
const int LED = 9; // the pin for the LED
int i = 0; // We'll use this to count up and down
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
}
void loop(){
for (i = 0; i < 255; i++) { // loop from 0 to 254 (fade in)
analogWrite(LED, i); // set the LED brightness
delay(10); // Wait 10ms because analogWrite // is instantaneous and we would // not see any change }
for (i = 255; i > 0; i--) { // loop from 255 to 1 (fade out)
analogWrite(LED, i); // set the LED brightness
delay(10); // Wait 10ms
}
}