Cảm biến quang trở với Ardunio

Bởi nguyentruongphi (11/09/2025) 0 Bình luận

File code:

const int sensorPin = A0;   // Assigns the pin A0 to the constant for the photoresistor
const int buzzerPin = 9;    // Assigns the pin 9 to the constant for the buzzer
const int threshold = 500;  // Set the threshold value
int led = 8;
int sensorValue = 0;  // To store the photoresistor reading

void setup() {
    // put your setup code here, to run once:
    pinMode(buzzerPin, OUTPUT);  // Set the buzzer pin as an output
    pinMode(led, OUTPUT);
    Serial.begin(9600);          // Initialize serial communication at 9600 baud rate
}

void loop() {
    // put your main code here, to run repeatedly:
    sensorValue = analogRead(sensorPin);  // Read the analog value from the photoresistor
    Serial.println(sensorValue);          // Print the photoresistor reading to the serial monitor
    delay(100);                           // Wait 0.1 seconds

    // Check if the reading is below the threshold
    if (sensorValue > threshold) {
        digitalWrite(buzzerPin, HIGH);  // If below threshold, turn on the buzzer
        digitalWrite(led, HIGH);
    } else {
        digitalWrite(buzzerPin, LOW);  // If not below threshold, turn off the buzzer
        digitalWrite(led, LOW);
    }
}

Đóng góp ý kiến

Hotline 0938379351