Recently I purchased some Trinket 5V boards from ADAFRUIT. They are a great little board for Learning about electronics and they use the Arduino IDE for programming. With a price tag of $9 in Canada they make a great substitution for the Arduino board and its $30 price tag.
I have put together a great little project using the Trinket and a HC-SR04 distance sensor. All this is a simple back-up sensor. If there is a safe amount of space it displays a green light, as you approach a yellow and then red light are displayed.
Code:
int ECHOPIN = 3; // Pin to receive echo pulse
int TRIGPIN = 4; // Pin to send trigger pulse
int LED1 = 0;
int LED2 = 1;
int LED3 = 2;
void setup(){
pinMode(ECHOPIN, INPUT); // sets echo pin to recive pulse from range finder
pinMode(TRIGPIN, OUTPUT); //sets trigger pin so range finder can start pulse
pinMode(LED1,OUTPUT);
pinMode(LED2,OUTPUT);
pinMode(LED3,OUTPUT);
}
void loop (){
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
float distance = pulseIn(ECHOPIN, HIGH);
distance= distance/58;
if(distance >= 100){
digitalWrite(LED1, HIGH);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
delay(100);
}
if(distance <= 75 && distance >=50 ){
digitalWrite(LED2, HIGH);
digitalWrite(LED1, LOW);
digitalWrite(LED3, LOW);
delay(100);
}
if(distance <= 49.9 && distance >=25 ){
digitalWrite(LED3, HIGH);
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
delay(100);
}
if(distance <= 24.5 && distance >=15){
digitalWrite(LED3, HIGH);
digitalWrite(LED1, HIGH);
digitalWrite(LED2, HIGH);
delay(500);
digitalWrite(LED3, LOW);
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
delay(500);
}
if(distance <= 14.5){
digitalWrite(LED3, HIGH);
digitalWrite(LED1, HIGH);
digitalWrite(LED2, HIGH);
delay(100);
digitalWrite(LED3, LOW);
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
delay(100);
}
}
No comments:
Post a Comment