Home / How To / Distance meter with Arduino: 3 steps // definition of constants for the pins.

Distance meter with Arduino: 3 steps // definition of constants for the pins.



#include

LiquidCrystal LCD (2, 4, 7, 8, 9, 10); #define TRIG_PIN 13 #define ECHO_PIN 12

#define RED 6 #define GREEN 5 #define BLUE 3

// definition of constants to facilitate distance maintenance #define BLUE_LONG 60 #define BLUE_SHORT 30 #define GREEN_LONG 45 #define GREEN_SHORT 15 #define RED_LONG 30 #define RED_SHORT 0 void setup () { // start the LCD screen LCD start (16.2); // arrow LED mode mode pinMode (RED, OUTPUT); pinMode (GREEN, OUTPUT); pinMode (BLUE, OUTPUT); // arrow pin position for HC-SR05 pinMode (TRIG_PIN, OUTPUT); pinMode (ECHO_PIN, INPUT);

// turn off the LED (regular anode, off with HIGH) digitalWrite (RED, HIGH); digitalWrite (GREEN, HIGH); digitalWrite (BLUE, HIGH); } void loop () { // declaration of variables long duration, distance // le the distance and convert to cm digitalWrite (TRIG_PIN, LOW); delayMicroseconds (2); digitalWrite (TRIG_PIN, HIGH); delayMicroseconds (1

0); digitalWrite (TRIG_PIN, LOW); duration = pulseIn (ECHO_PIN, HIGH); distance = (duration / 2) / 29.1; // by distance, map the joint color using pwm // blue: from 60cm to 30cm // green: from 45cm to 15cm // red: from 30cm to 0cm if (distance> RED_LONG) digitalWrite (RED, HIGH); otherwise analog writing (RED, map (distance, RED_LONG, RED_SHORT, 255, 0)); if ((distance> GREEN_LONG) || (distance < GREEN_SHORT)) digitalWrite(GREEN, HIGH); else analogWrite(GREEN, map(distance, GREEN_LONG, GREEN_SHORT, 255, 0)); if ((distance > BLUE_LONG) || (distance < BLUE_SHORT)) digitalWrite(BLUE, HIGH); else analogWrite(BLUE, map(distance, BLUE_LONG, BLUE_SHORT, 255, 0)); // escreve a distancia no display lcd.clear(); lcd.setCursor(0,0); lcd.print("simaopintocorreia"); lcd.setCursor(0,1); lcd.print("Distancia: "); if (distance > 450) lcd.print ("> 50"); otherwise lcd.print (distance); lcd.print ("cm"); // waiting to read the sensor again delay (400); }


Source link