이 코드는 아두이노와 조도(illuminance) 센서를 사용하여 주변 밝기를 측정하고, 그 값을 Serial Monitor에 출력하는 예제입니다. 조도 센서는 빛의 양에 따라 아날로그 값을 출력하며, 아두이노는 이를 analogRead()를 통해 읽어와 빛의 세기를 수치로 표현합니다.
코드 설명
변수 선언
int cds = A0;
cds: 조도 센서가 연결된 아날로그 핀 번호(A0)를 나타내며, 조도 센서의 아날로그 신호를 읽어옵니다.
setup() 함수
voidsetup() { Serial.begin(9600);}
Serial.begin(9600);: 아두이노와 컴퓨터 간의 시리얼 통신을 시작하여, 초당 9600bps의 속도로 데이터를 Serial Monitor에 출력할 수 있도록 설정합니다.
loop() 함수
voidloop() { int cdsValue =analogRead(cds); Serial.print("Illuminance Value (cds) = "); Serial.println(cdsValue);delay(200);}
cdsValue = analogRead(cds);: cds 핀에서 아날로그 값을 읽어 cdsValue 변수에 저장합니다. 이 값은 조도에 따라 0에서 1023 사이의 값으로 나타나며, 빛이 강할수록 값이 낮고, 빛이 약할수록 값이 높아집니다.
Serial.print("Illuminance Value (cds) = ");: Serial Monitor에 “Illuminance Value (cds) = “라는 텍스트를 출력하여 다음에 출력될 값이 조도 센서 값임을 나타냅니다.
Serial.println(cdsValue);: cdsValue 값을 Serial Monitor에 출력하고 줄을 바꿔줍니다.
delay(200);: 0.2초 동안 대기한 후 조도 값을 다시 측정합니다. 이 지연은 너무 빠른 반복을 방지하여 Serial Monitor에서 값을 쉽게 읽을 수 있게 합니다.
동작 원리
조도 센서 동작:
조도 센서는 빛의 양을 측정하는 장치로, 빛이 강할수록 센서의 저항이 낮아지고 빛이 약할수록 저항이 높아집니다.
아두이노는 센서의 아날로그 출력을 읽어 빛의 세기에 따라 0에서 1023 사이의 값을 받습니다. 일반적으로 값이 낮을수록 주변의 빛이 강하고, 값이 높을수록 어두운 환경을 나타냅니다.
아두이노와의 상호작용:
아두이노는 analogRead() 함수를 사용하여 조도 센서에서 빛의 세기를 읽어와 cdsValue 변수에 저장합니다.
이 값을 Serial Monitor에 출력하여 사용자가 현재 조도 상태를 실시간으로 확인할 수 있습니다.
출력 예시:
밝은 환경에서는 낮은 값(예: 300 이하)이 Serial Monitor에 표시되며, 어두운 환경에서는 높은 값(예: 700 이상)이 표시됩니다.
Serial Monitor에는 Illuminance Value (cds) = [값] 형식으로 0.2초마다 측정된 값이 출력됩니다.
/* Title: Display illuminance sensor value on Serial Monitor Content: Continuously output the illuminance value to the Serial Monitor.*/// The illuminance sensor is connected to the analog A0 pin.int cds = A0;// This is the first function called when the code is executed. It runs only once.// Includes code for declaring or initializing variables.voidsetup() {// Set up serial communication to check the operating status of the illuminance sensor. (transmission speed 9600bps)// Click menu Tool -> Serial Monitor Serial.begin(9600);}// After the setup() function is called, the loop() function is called,// The code within the block is executed infinitely.voidloop() {// Read the brightness value measured from the illuminance sensor.// Converts and returns a value in the range of 0 to 1023 depending on the level of voltage (0 to 5 V) input from the illuminance sensor. int cdsValue =analogRead(cds);// Output the measured brightness value to the serial monitor. Serial.print("Illuminance Value (cds) = "); Serial.println(cdsValue);// Wait for 0.2 seconds before taking the next reading.delay(200);}
이 코드는 주변의 밝기를 쉽게 측정하고 모니터링할 수 있도록 설계되었습니다. 이 값을 기준으로 특정 밝기 수준 이하에서는 조명을 켜거나 하는 자동화 시스템을 구축할 수 있습니다.