lakerz690
Posts: 13
Joined: Mon Nov 26, 2018 7:13 am

HC-SR04, 16x2 LCD, and three LED lights

Tue Nov 27, 2018 1:36 am

Hello, I am brand new to this forum and still relatively new to working with the Pi. I am working on a project that consists of the HC-SR04 Ultrasonic sensor, a 16x2 LCD display, and three LED lights. So far the code works with the sensor and LED lights, but I just started messing around with the 16x2 LCD display and I'm trying to get it to display the distance so I don't have to read it from the IDE. It is hooked up and will display the basic examples that were included in the Adafruit code. I have been searching the internet the past week on how to get this to work, and I am stumped. Like I mentioned earlier, the code works for the ultrasonic sensor and the three LEDs. When the distance reaches a certain measurement, the LEDs act as an indicator when an object gets too close. Any help is greatly appreciative. Thank you.

BTW I also keep receiving this error when trying to run this code from my IDE:

Traceback (most recent call last):
File "/home/pi/Documents/UPDATED.py", line 6, in <module>
import Adafruit_CharLCD
ImportError: No module named 'Adafruit_CharLCD'

Code: Select all


#!/usr/bin/python

#Libraries
import RPi.GPIO as GPIO
import time
import Adafruit_CharLCD as LCD

GPIO.setwarnings (False)
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)

#LCD Pin Select
lcd_rs        = 25 
lcd_en        = 24
lcd_d4        = 23
lcd_d5        = 13
lcd_d6        = 6
lcd_d7        = 26
lcd_backlight = 4

#LCD Type
lcd_columns = 16
lcd_rows    = 2

#LCD Initialization
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                           lcd_columns, lcd_rows, lcd_backlight)

#GPIO Pin Component
TRIG = 4
ECHO = 18

GREEN = 17
YELLOW = 27
RED = 22

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

GPIO.setup(GREEN, GPIO.OUT)
GPIO.setup(YELLOW, GPIO.OUT)
GPIO.setup(RED, GPIO.OUT)

def green_light():
    GPIO.output(GREEN, GPIO.HIGH)
    GPIO.output(YELLOW, GPIO.LOW)
    GPIO.output(RED, GPIO.LOW)
    
def yellow_light():
    GPIO.output(GREEN, GPIO.LOW)
    GPIO.output(YELLOW, GPIO.HIGH)
    GPIO.output(RED, GPIO.LOW)
    
def red_light():
    GPIO.output(GREEN, GPIO.LOW)
    GPIO.output(YELLOW, GPIO.LOW)
    GPIO.output(RED, GPIO.HIGH)

def get_distance():
    GPIO.output(TRIG, True)
    time.sleep(0.0001)
    GPIO.output(TRIG, False)

    while GPIO.input(ECHO) == False:
            start = time.time()

    while GPIO.input(ECHO) == True:
            end = time.time()

    sig_time = end-start

    #inches:
    distance = sig_time / 0.000148

    print('Distance: {} inches'.format(distance))
    return distance

while True:
    distance = get_distance()
    time.sleep(0.5)
    
    if distance >= 55:
        green_light()
    elif 55 > distance > 35:
        yellow_light()
    elif distance <= 35:
        red_light()
        

pcmanbob
Posts: 9441
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: HC-SR04, 16x2 LCD, and three LED lights

Tue Nov 27, 2018 11:32 am

Hi.

My first question is which IDE are you using because I believe the ones on the pi default to python 3 now and your code appears to be written for python 2 which means you may also have only installed Adafruit_CharLCD for python 2 also.

you could test this by simply running your program from the command line using

Code: Select all


python /home/pi/program name.py

this assumes your program is saved in the default directory , you need to replace "program name .py" with the actual program name.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

lakerz690
Posts: 13
Joined: Mon Nov 26, 2018 7:13 am

Re: HC-SR04, 16x2 LCD, and three LED lights

Tue Nov 27, 2018 2:12 pm

I'm using Thonny, it was already preinstalled on the Raspian OS. I will try running it through CMD and see what happens, I wasn't exactly sure if my code checks out, that was my main concern.

pcmanbob
Posts: 9441
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: HC-SR04, 16x2 LCD, and three LED lights

Tue Nov 27, 2018 6:39 pm

Well your code works for the distance measurement and led driving because you said it works, what you don't have is any code to print the result to the LCD.

I don't use that particular LCD driver but there should be a command something like lcd.write or lcd.print to write text to the LCD.

You should find the correct command line in which ever example setup you followed to set up Adafruit_CharLCD.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

lakerz690
Posts: 13
Joined: Mon Nov 26, 2018 7:13 am

Re: HC-SR04, 16x2 LCD, and three LED lights

Thu Nov 29, 2018 7:30 am

So at this point I'm completely lost and frustrated as to why nothing I have been trying is even working. I researched all that I could and tried several different scripts to get this thing to even run. At this point I have just tried to just get it to pull up the distances with only the ultrasonic sensor and disregarded the LEDs. Nothing is working, but when I run the "Adafruit_CharLCD" examples the LCD works, and when I run the sonar separately it works even with the LEDs. I feel like I am going in circles here, I cant find anymore new forums, videos, etc that are helpful anymore. I also tried adding the command line that is used to print text to the LCD but nothing is working. At this point anything is helpful, I just want to get this thing to work :|

pcmanbob
Posts: 9441
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: HC-SR04, 16x2 LCD, and three LED lights

Thu Nov 29, 2018 9:30 am

So your LCD works if you run one of the examples provided, that's a start.

So did you have to run the example using python 2 or python 3 ?

Now all you need to do is add the code to take the distance reading and write it on to the LCD, the example code should have the correct commands within it that your can copy and modify to do this.

If you post the example code that works and let me know which version of python you need to use to run the example code that works I will see if I can help you add the correct code to your existing program, but you will have to do the testing because as I said before I don't use Adafruit_CharLCD to drive my LCD's
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

lakerz690
Posts: 13
Joined: Mon Nov 26, 2018 7:13 am

Re: HC-SR04, 16x2 LCD, and three LED lights

Thu Nov 29, 2018 4:34 pm

You are a life saver my friend. I believe the example is running on Python 2, like I stated in my first post I am still very new to coding. But when I try to run it with my Thonny IDE it throws an error, when I run it with terminal, all is well.

Code: Select all

#!/usr/bin/python
# Example using a character LCD connected to a Raspberry Pi or BeagleBone Black.
import time

import Adafruit_CharLCD as LCD


# Raspberry Pi pin configuration:
lcd_rs        = 25  # Note this might need to be changed to 21 for older revision Pi's.
lcd_en        = 24
lcd_d4        = 23
lcd_d5        = 13
lcd_d6        = 6
lcd_d7        = 26
lcd_backlight = 4

# Define LCD column and row size for 16x2 LCD.
lcd_columns = 16
lcd_rows    = 2

# Initialize the LCD using the pins above.
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                           lcd_columns, lcd_rows, lcd_backlight)

# Print a two line message
lcd.message('Hello\nworld!')

# Wait 5 seconds
time.sleep(5.0)

# Demo showing the cursor.
lcd.clear()
lcd.show_cursor(True)
lcd.message('Show cursor')

time.sleep(5.0)

# Demo showing the blinking cursor.
lcd.clear()
lcd.blink(True)
lcd.message('Blink cursor')

time.sleep(5.0)

# Stop blinking and showing cursor.
lcd.show_cursor(False)
lcd.blink(False)

# Demo scrolling message right/left.
lcd.clear()
message = 'Scroll'
lcd.message(message)
for i in range(lcd_columns-len(message)):
    time.sleep(0.5)
    lcd.move_right()
for i in range(lcd_columns-len(message)):
    time.sleep(0.5)
    lcd.move_left()

# Demo turning backlight off and on.
lcd.clear()
lcd.message('Flash backlight\nin 5 seconds...')
time.sleep(5.0)
# Turn backlight off.
lcd.set_backlight(0)
time.sleep(2.0)
# Change message.
lcd.clear()
lcd.message('Goodbye!')
# Turn backlight on.
lcd.set_backlight(1)
Preferably I would like to use Python 3 because that is what my other code for the ultrasonic sound sensor is currently utilizing. If the code you're using to run your LCD's uses Python 3, I wouldn't mind using that. That is if it's ok with you.

pcmanbob
Posts: 9441
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: HC-SR04, 16x2 LCD, and three LED lights

Thu Nov 29, 2018 7:11 pm

Ok so I guess my assumption that Thonny now defaults to python 3 was correct then.

If you want to use python 3 then you need to install Adafruit_CharLCD for python 3 but as I don't know how you installed it for python 2 I cant tell you how to install it for python 3.

I don't see any reason that your posted code shouldn't run ok in python 2 for now at least you can continue learning to code until your get Adafruit_CharLCD installed for python 3 you will just have to run your program from the command line.

If you give me some time I will add the LCD code to your program for you to test.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

pcmanbob
Posts: 9441
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: HC-SR04, 16x2 LCD, and three LED lights

Thu Nov 29, 2018 7:41 pm

So here is some code for you to test , note it is untested so there may be errors.

Code: Select all


#!/usr/bin/python

#Libraries
import RPi.GPIO as GPIO
import time
import Adafruit_CharLCD as LCD

GPIO.setwarnings (False)
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)

#LCD Pin Select
lcd_rs        = 25 
lcd_en        = 24
lcd_d4        = 23
lcd_d5        = 13
lcd_d6        = 6
lcd_d7        = 26
lcd_backlight = 4

#LCD Type
lcd_columns = 16
lcd_rows    = 2

#LCD Initialization
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
                           lcd_columns, lcd_rows, lcd_backlight)

#GPIO Pin Component
TRIG = 4
ECHO = 18

GREEN = 17
YELLOW = 27
RED = 22

GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

GPIO.setup(GREEN, GPIO.OUT)
GPIO.setup(YELLOW, GPIO.OUT)
GPIO.setup(RED, GPIO.OUT)

def green_light():
    GPIO.output(GREEN, GPIO.HIGH)
    GPIO.output(YELLOW, GPIO.LOW)
    GPIO.output(RED, GPIO.LOW)
    
def yellow_light():
    GPIO.output(GREEN, GPIO.LOW)
    GPIO.output(YELLOW, GPIO.HIGH)
    GPIO.output(RED, GPIO.LOW)
    
def red_light():
    GPIO.output(GREEN, GPIO.LOW)
    GPIO.output(YELLOW, GPIO.LOW)
    GPIO.output(RED, GPIO.HIGH)

def get_distance():
    GPIO.output(TRIG, True)
    time.sleep(0.0001)
    GPIO.output(TRIG, False)

    while GPIO.input(ECHO) == False:
            start = time.time()

    while GPIO.input(ECHO) == True:
            end = time.time()

    sig_time = end-start

    #inches:
    distance = sig_time / 0.000148

    print('Distance: {} inches'.format(distance))
    return distance

while True:
    distance = get_distance()
    
    
    if distance >= 55:
        green_light()
    elif 55 > distance > 35:
        yellow_light()
    elif distance <= 35:
        red_light()
        

    # convert distance to 2 decimal places and text for lcd.
    distance2 = "%.2f" % distance   # convert to 2 decimal places
    dist_text = str(distance2)      # convert to text
    
    mtext = "Distance\n" + dist_text + " inches"
    
    # display text on lcd.
    lcd.clear()
    lcd.message(mtext)
    
    time.sleep(2)
    
so just save this code in a new file with the py extension and run it using the command line like I said before using python 2

python /home/pi/file name.py

assuming you have the program saved in the default directory or change the path if you have it saved elsewhere.

As your example LCD code had no positioning example code I have used their example to spread the text over 2 lines that's why I have assembled the text to be posted as one line with a \n to force a newline as per the example code.
We want information… information… information........................no information no help
The use of crystal balls & mind reading are not supported

lakerz690
Posts: 13
Joined: Mon Nov 26, 2018 7:13 am

Re: HC-SR04, 16x2 LCD, and three LED lights

Thu Nov 29, 2018 8:48 pm

That would be great, I'm going to continue to see if I can get Adafruit_CharLCD for python 3. Also, mess around with trying to get this code to run properly. Thank you.

lakerz690
Posts: 13
Joined: Mon Nov 26, 2018 7:13 am

Re: HC-SR04, 16x2 LCD, and three LED lights

Fri Nov 30, 2018 6:37 pm

You are my frickn' hero! This code works perfectly, did not even have to make one single change. Thank you so much my friend, you don't understand how grateful I am right now!! You're the best!

Return to “Automation, sensing and robotics”