Cảm biến ánh sáng quang trở MKE-S02 LDR light sensor: Difference between revisions

No edit summary
Line 68: Line 68:
|code=
|code=
<syntaxhighlight>
<syntaxhighlight>
#define echoPin 12 // Echo Pin
/*
#define trigPin 13 // Trigger Pin
    How the code work:
        - Read ADC value (0->1023) from pin A1 => Display on Serial Monitor with Baudrate speed 9600.
*/


float duration, distance; // Duration used to calculate distance
int analogPin      = A1;               // Declare input ADC pin


void setup() {
void setup(){
Serial.begin (9600);
    Serial.begin(9600);
pinMode(trigPin, OUTPUT);
    Serial.println("MakerLab.vn Demo Read Analog Sensor");
pinMode(echoPin, INPUT);
}
}


void loop() {
void loop(){
/* The following trigPin/echoPin cycle is used to determine the
    // Read value (0->1023) from analogPin (A1)
distance of the nearest object by bouncing soundwaves off of it. */
    int sensorValue = analogRead(analogPin);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);  


digitalWrite(trigPin, HIGH);
    // Display value on Serial Monitor
delayMicroseconds(10);
    Serial.println(sensorValue);
digitalWrite(trigPin, LOW);


duration = pulseIn(echoPin, HIGH);
    delay(100); // Wait 100ms then repeat
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58;
Serial.println(distance);


//Delay 50ms before next reading.
delay(50);
}
}
</syntaxhighlight>
</syntaxhighlight>
}}
}}
==Kết quả==
==Kết quả==
{{kxndone
{{kxndone