วันพุธที่ 26 มิถุนายน พ.ศ. 2556

Arduino ใช้ LDR วัดแสง



อุปกรณ์ที่ใช้
  1. LDR (also known as a photocell)
  2. LED
  3. 220 to 330 ohm resistor (used to control current through LED)
  4. 1K to 10K resistor (used with the LDR to setup a voltage divider)
ตัวอย่างโค้ด1
/* LDR1.pde
  Light Dependent Resistor (LDR) is used to vary the blink rate
  of a LED connected to digital pin 13 based on the amount of
  light that strikes the LDR.
*/

#define LEDpin  13                   // LED connected to digital pin 13
#define LDRpin  0                    // LDR connected to analog pin 0

const int minDuration = 100;         // Minimum delay between blinks
const int maxDuration = 1000;        // Maximum delay between blinks

void setup()
{
  pinMode(LEDpin, OUTPUT);           // Set LED pin as an output
  Serial.begin(57600);               // Initialize serial port
}

void loop()
{
  int rate = analogRead(LDRpin);     // Read analog input
  float volts = (rate/1023.0) * 5.0;
  int rawRate = rate;                // Save raw analog input value

  if (rate < 100) rate = 100;        // Scale minimum limit
  if (rate > 1000) rate = 1000;      // Scale maximum limit

  // Scale blink rate between min and max duration
  rate = map(rate, 100, 1000, minDuration, maxDuration);

  Serial.print("Raw Rate: ");
  Serial.println(rawRate);           // Send raw analog value to serial port

  Serial.print("Map Rate: ");
  Serial.println(rate);              // Send scaled analog value to serial port

  Serial.print("Volts DC: ");
  Serial.println(volts);
  Serial.println();

  digitalWrite(LEDpin, HIGH);        // Turn on LED
  delay(rate);                       // Delay is based on light level
  digitalWrite(LEDpin, LOW);         // Set LED off
  delay(rate);                       // Delay is based on light level
}

ตัวอย่างโค้ด2
#define POTPIN 0
#define LEDPIN 13

int val = 0;

void setup() {
  Serial.begin(9600);
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  val = analogRead(POTPIN);    // read the value from the sensor
  digitalWrite(LEDPIN, HIGH);  // turn the ledPin on
  Serial.println(val);
  delay(val);                  // stop the program for some time
  digitalWrite(LEDPIN, LOW);   // turn the ledPin off
  delay(val);                  // stop the program for some time
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น