Monday, September 22, 2014

Arduino, QC1602A and HC-SR04

There are two ways to connect a LCD-Display and an Arduino: Via I2C or by connecting them as follows:

Wiring of the Arduino, HC-SR04 and the LCD-Display


The Arduino-Code:
#include 
/*
LCD-Connection:
VSS to GND
VDD to +5V
VO to potentiometer to GND
RS to 12
RW to 11
E to 10
D4 to 5
D5 to 4
D6 to 3
D7 to 2
A to 13 
K to GND

HC-SR04-Connection:
VCC to +5V
Trig to 8
Echo to 7
GND to GND

LED-Connection:
(GND-Resistor-LED)
green LED to 6
red LED to 9
*/


// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);
int backLight = 13; //pin 13 für Hintergrundbeleuchtung


#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define erPin 9 //Pin fur rote LED (zu weit weg)
#define goPin 6 // Pin fuer grüne LED (nahe genug)

int maximumRange = 2000; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup()
{
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(erPin, OUTPUT);
  pinMode(goPin,OUTPUT);
  
  pinMode(backLight, OUTPUT);
  digitalWrite(backLight, HIGH); // turn backlight on. Replace 'HIGH' with 'LOW' to turn it off.
  
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  //lcd.print("hello, world!");
  
}


void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */ 
 digitalWrite(trigPin, LOW); 
 delayMicroseconds(2); 

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10); 
 
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 
 //Calculate the distance (in mm) based on the speed of sound.
 distance = duration/5.82;
 
 if (distance >= maximumRange || distance <= minimumRange){
 /* Send a negative number to computer and Turn LED ON 
 to indicate "out of range" */
 // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.clear();
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print("-1");
  digitalWrite(erPin, HIGH);
  digitalWrite(goPin, LOW);
  
 
 //Serial.println("-1");
 //digitalWrite(LEDPin, HIGH); 
 }
 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.clear();
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(distance);
  digitalWrite(erPin,LOW);
  digitalWrite(goPin, HIGH);
 
 
// Serial.println(distance);
 //digitalWrite(LEDPin, LOW); 
 }
 
 //Delay 50ms before next reading.
 delay(100);
}