CDS는 photo register 또는 photo cell 이라고도 부르며 빛의 밝기를 저항값으로 출력해주는 센서입니다.
PWM이란 펄스의 폭을 조절함으로써 전압을 제어하는 효과를 주는 기능으로 LED의 밝기를 조절한다거나 모터의 회전수를 조절하는등에 사용됩니다.
사용부품 : 220옴 2개, 10k옴 1개, led 2개
CDS가 스위치 역할을하여 초기상태보다 어두워지면 작동을 시작합니다.
즉 CDS의 빛을 가리면 작동을 시작합니다.
10번핀 LED는 천천히 켜졌다 어두워지고, 9번 LED는 빨리 켜졌다 어두워집니다.
두 속도가 다른 LED가 동시에 제어되는 예제입니다.
입력으로 CDS를 아날로그 0번 핀에 사용하고, 출력으로 LED 2개를 PWM 핀 9,10번에 연결했습니다.
위 동영상이 동작 모습입니다.
#include <stdio.h>
int photocellPin;
int buttonPin = 2;
int ledValue = LOW;
int cdsInitValue=0;
int fadeVal[12]={0};
long fadeTimer;
void InitCDS(int pin){
photocellPin = pin;
cdsInitValue=0;
int i;
for (i=0; i<10; i++){
cdsInitValue += analogRead(photocellPin);
}
cdsInitValue = cdsInitValue / i;
}
int IsCDSOn(int val){
int photocellReading = 0, i;
for(i=0; i<3; i++){
photocellReading += analogRead(photocellPin);
}
photocellReading /= i;
char s[255];
sprintf(s, "read=%d, initVal=%d\n", photocellReading, cdsInitValue);
//Serial.print(s);
if (val > 0){
if (photocellReading > cdsInitValue + val)
return 1;
else
return 0;
}
else {
if (photocellReading < cdsInitValue + val)
return 1;
else
return 0;
}
}
void InitFade(int val){
for(int i=0; i<12; i++){
fadeVal[i] = val;
}
fadeTimer=0;
}
int FadeCore(int pwmPin, int fadeSpeed, long startTime){
char s[255];
sprintf(s, "[%2d],timer=%ld, startTime=%ld\n",pwmPin, fadeTimer,startTime);
Serial.print(s);
if (fadeTimer < startTime) return fadeVal[pwmPin];
fadeVal[pwmPin] += fadeSpeed;
//char s[255];
sprintf(s, "spd=%d, cnt=%d\n", fadeSpeed, fadeVal[pwmPin]);
Serial.print(s);
if (fadeVal[pwmPin] < 0) fadeVal[pwmPin] = 0;
if (fadeVal[pwmPin] > 255) fadeVal[pwmPin] = 255;
analogWrite(pwmPin, fadeVal[pwmPin]);
/*
if (fadeSpeed > 0){
if (countFade < 255) return 1;
else return 0;
} else {
if (countFade > 0) return 1;
else return 0;
}
*/
return fadeVal[pwmPin];
}
void FadeDelay(long ms){
delay(ms);
fadeTimer += ms;
}
void Init(){
int cdsPin = 0, startVal = 0;
InitCDS(cdsPin);
InitFade(startVal);
}
void setup(void) {
Serial.begin(9600);
Init();
}
void loop(void) {
int fadeStep=3, fadePin10=10,fadePin9=9, cdsSense=-40, val1=0, val2=255, timeDelay=10;
while (IsCDSOn(cdsSense) == 0);
InitFade(0);
while(val1 < 255){
val1 = FadeCore(fadePin10, fadeStep, 0);
FadeCore(fadePin9, fadeStep*4, 80);
Serial.println(val1);
FadeDelay(timeDelay);
}
InitFade(255);
while(val2 > 0){
val2 = FadeCore(fadePin10, fadeStep * (-1), 0);
FadeCore(fadePin9, fadeStep * (-4), 80);
FadeDelay(timeDelay);
}
}
'Arduino/AVR > 2. Arduino프로젝트' 카테고리의 다른 글
| 재미 이론 (The fun theory) (0) | 2009.10.27 |
|---|---|
| 아두이노에서 써미스터(thermistor)로 온도 측정하기 (1) | 2009.08.27 |
| 아두이노에서 서보모터 구동하기 (0) | 2009.08.17 |
| 소리 감지를 위한 마이크 센서(앰프) 회로들(mic, sound sensor) (0) | 2009.07.14 |
| processing을 이용한 아두이노 오실로스코프(oscilloscope) (1) | 2009.06.18 |