Step 2 - Detecting Movement
Now we have the circuit set up, lets try and do something useful with it. We can start really simple, and just use it like a dimmer switch. It will be up to you later on to make it do something more exciting!
Show Me The Code
Right, lets write the code! The example code is shown below, can you work out which lines do what? See if you can explain to yourself where we work out how fast the sensor value is changing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#define SENSOR_PIN A0
#define LED_PIN 11
// This will store the most recent value of our swipe sensor.
int currentSensorValue;
// This stores the value we will compare with.
int previousSensorValue;
// This stores how fast the sensor value is changing.
int sensorSteepness;
void setup() {
// Start the serial connection with the PC.
Serial.begin(115200);
}
void loop() {
// read the sensor value and store it.
currentSensorValue = analogRead(SENSOR_PIN);
// Update the new steepness value.
sensorSteepness = currentSensorValue - previousSensorValue;
// Move the most recent sensor measurement to the previous one.
previousSensorValue = currentSensorValue;
// Make the LED brighter or dimmer.
int brightness = map(currentSensorValue, 0,1023,0,25);
analogWrite(LED_PIN, brightness);
// print the sensor steepness value for the plotter.
Serial.print(currentSensorValue);
Serial.print(" ");
Serial.println(sensorSteepness);
delay(1);
}
Again, upload the code, and have another look at the output of the serial plotter. What do you see?
Hopefully, you will see that if you move your finger across the two LDRs slowly that you can control the height of the blue plotter line? See if you can gradually move it up and down. If you move your finger slowly, the red line will not move. Now, if you quickly move your finger, you'll see the red line jump up and down very quickly. Can you remember why it jumps only if we move our finger quickly?
A Bright Idea
Now we can see how our code works, and that the circuit works too, lets extend it and make a little dimmer switch. You can copy the circuit below, and hopefully, when you finish it, the code will make the LED brighter or dimmer depending on how you move your finger over the sensor.
Now you've mastered that, let's move on to trying to do actual gestures!
< Previous | Home | Next >