Πέμπτη 21 Ιουλίου 2011

Arduino + Relay + Ultrasonic

Με βάση το προηγούμενο άρθρο και με την βοήθεια του Ultrasonic module HC-SR04, μπορούμε να ελέγξουμε ένα φωτιστικό με την απόσταση ή με την κίνηση ενός αντικειμένου. Ο αισθητήρας έχει 4 pin. Το Vcc και το Gnd συνδέονται στα 5V και στη γείωση αντίστοιχα. Το Trig στο Pin 13 ενώ το Echo στο Pin 12.






int pingPin = 13;
int inPin = 12;
int lampPin = 8;
void setup() 
{ 
pinMode(pingPin, OUTPUT); 
pinMode(inPin, INPUT); 
pinMode(lampPin, OUTPUT); 
Serial.begin(9600);} 
void loop(){ 
long duration, cm;   // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. 
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse: 
digitalWrite(pingPin, LOW); 
delayMicroseconds(2); 
digitalWrite(pingPin, HIGH); 
delayMicroseconds(10); 
digitalWrite(pingPin, LOW); 
// The same pin is used to read the signal from the PING))): a HIGH 
// pulse whose duration is the time (in microseconds) from the sending 
// of the ping to the reception of its echo off of an object. 
duration = pulseIn(inPin, HIGH); 
// Συνάρτηση για μετατροπή του χρόνου σε απόσταση  cm = microsecondsToCentimeters(duration); 
Serial.println(cm, DEC);   delay(200);  if (cm < 60) 
//για απόσταση μικρότερη από 60cm άναψε την λάμπα 
digitalWrite(lampPin,HIGH); 
else   digitalWrite(lampPin,LOW);} 
long microsecondsToCentimeters(long microseconds){ 
// The speed of sound is 340 m/s or 29 microseconds per centimeter. 
// The ping travels out and back, so to find the distance of the 
// object we take half of the distance travelled. 
return microseconds / 29 / 2;}
back to top