04/02/2018
WATER LEVEL INDICATOR ( Part 4)
Step 4: Coding
The code is quite simple and is quite similar to that as shown in the step 3 of this project, in addition we are now adding some more libraries to get the I2C LCD working. You can download the libraries form here. Make sure you have entered the right I2C address in the code, the default address of the I2C is 0x3f.
Copy and paste the below code into the arduino IDE and select the arduino nano and the right port and then hit upload.
ntered the right I2C address in the code, the default address of the I2C is 0x3f.
Copy and paste the below code into the arduino IDE and select the arduino nano and the right port and then hit upload.
"Wire.h" // For I2C
"LCD.h" // For LCD "LiquidCrystal_I2C.h" // Added library* //Set the pins on the I2C chip used for LCD connections //ADDR,EN,R/W,RS,D4,D5,D6,D7 LiquidCrystal_I2C lcd(0x3f,2,1,0,4,5,6,7); // 0x27 is the default I2C bus address of the backpack-see article
echoPin 3 // Echo Pin (OUTPUT pin in RB URF02) trigPin 2 // Trigger Pin (INPUT pin in RB URF02)
int led = 5; int maximumRange = 350; // Maximum range needed int minimumRange = 0; // Minimum range needed long duration, distance; // Duration used to calculate distance int brightness;
void setup() { lcd.begin (16,2); // 16 x 2 LCD module lcd.setBacklightPin(3,POSITIVE); // BL, BL_POL lcd.setBacklight(HIGH); Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(led, OUTPUT); }
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); distance = duration/58.2; //Calculate the distance (in cm) based on the speed of sound. lcd.home (); // Set cursor to 0,0 lcd.print("The Water Level is"); lcd.setCursor (0,1); lcd.print(distance); // Custom text lcd.print("cm"); Serial.println(distance); // distance in cm brightness= map(distance,1,100,0,255); analogWrite(led, brightness); delay(1000); //Delay 50 ms }