Friday, December 26, 2014

My first Arduino project.

After reading several books and testing few basic things with my first Arduino kit I decided to try to realize a simple project: a bar graph made of LEDs controlled by a light sensor. Nothing fancy or very original, but I needed something to start!
This is what I used for this project:
  • 1x Arduino Uno
  • 1x large 700 tie-points breadboard
  • 5x 3mm red LEDs
  • 5x 220Ω resistors
  • 1x LDR light sensor
  • 1x 10kΩ resistor
  • 9x jumper wires (male-male)
The project is divided in 2 main units: a light sensor measuring the light intensity of the environment (right of Pic1) and a bar graph made of 5 red LEDs 
I’m using 2 levels of brightness (full and 1/4) for every LED, so the bar graph can represents 10 levels of light intensity (f.e.: light level 5 ==> LEDs 1,2 ON full brightness, LED 3 ON 1/4 brightness, LEDs 4,5 OFF).
When starting the device in a dark room no LED is ON,
And obviously exposing the sensor to a close lamp turns more LEDs ON,
The sketch I wrote to control this device is pretty simple and the (many) comments should make it clear to everybody.
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// === CONSTANTS ===
// -- INPUT --
const int PIN_SENSOR = 0;
// -- OUTPUT --
const int NUM_LEDS = 5;
const int PIN_LEDS[NUM_LEDS] = { 3, 5, 6, 9, 10 };
// === CONSTANTS END ===
// === INITIALIZATION ===
void setup()
{
  // initialize serial communication at 9600 bits per second
  Serial.begin(9600);
}
// === INITIALIZATION END ===
// === MAIN LOOP ===
void loop()
{
  // read the value from the LDR and convert it into a [0-10] range
  int light_val = analogRead(PIN_SENSOR);
  int light_lvl = light_val / 102;
  // number of full-LEDs ON
  int leds_on = light_lvl / 2;
  // DEBUG
  Serial.print("light_val: ");
  Serial.print(light_val);
  Serial.print(" -> light_lvl: ");
  Serial.print(light_lvl);
  Serial.print(" -> leds_on: ");
  Serial.println(leds_on);
  int i;
  // turn LEDs ON - full brightness
  for(i = 0; i < leds_on; i++)
    analogWrite(PIN_LEDS[i], 255);
  // light level is odd -> turn one more LED ON - 1/4 brightness
  if(light_lvl % 2)
  {
    analogWrite(PIN_LEDS[i], 64);
    i++;
  }
  // turn remaining LEDs OFF
  for(; i < NUM_LEDS; i++)
    analogWrite(PIN_LEDS[i], 0);
  // 10 FPS
  delay(100);
}
// === MAIN LOOP END ===
This sketch is also using the serial port to print some debug output, but that code (lines 14 and 28-33) is totally optional and could be deleted without affecting the functionality of the device.




No comments:

Post a Comment