Python Forum

Full Version: Using a list of variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I have been working on a robot car for a while in an attempt to teach my son how to code. I have everything working but I am aware that my code is incredibly bad. Now that it is working I am trying to go back and redo parts to make it more efficient. I have read a lot about list (they seem useful) and am not trying to use one to average 3 Ultrasonic sensor readings. I did this originally using 3 variables adding them together and dividing by 3. I think I should be able to use a list of variables and a for loop to do the same thing but can not get it to work.

Code
def multi_signal_cleanup (trig, echo):  # averages 3 signals from ultrasound

    samples = [s1, s2, s3]
    for variable in samples:
        variable = getSonar()

    sample_ave = (s1+s2+s3)/3
    return sample_ave
I get an error

Error:
Program is starting... Traceback (most recent call last): File "/home/pi/mu_code/freenove us sensor program.py", line 61, in <module> loop() # File "/home/pi/mu_code/freenove us sensor program.py", line 53, in loop distance = multi_signal_cleanup(20, 19) # get distance *3 File "/home/pi/mu_code/freenove us sensor program.py", line 44, in multi_signal_cleanup samples = [s1, s2, s3] NameError: name 's1' is not defined >>>
I understand the error to have an undefined variable and I have tried to define it, but then it just has the value I attached to it and not the US distance.

Maybe I am assuming I can do something I can not. If there is a solution, please feel free to talk to me like I am 7, the last time I coded I had a line that said "goto line 10"

Thank you,

Gary
Could you post the full code please?

You may want to parse the values into the function as arguments like:

def multi_signal_cleanup (trig, echo s1, s2, s3):
#do something
#!/usr/bin/env python3
########################################################################
# Filename    : UltrasonicRanging.py
# Description : Get distance via UltrasonicRanging sensor
# auther      : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
import time

trigPin = 20
echoPin = 19
MAX_DISTANCE = 220          # define the maximum measuring distance, unit: cm
timeOut = MAX_DISTANCE*60   # calculate timeout according to the maximum measuring distance
GPIO.setwarnings(False)  # prevents some errors
def pulseIn(pin,level,timeOut): # obtain pulse time of a pin under timeOut                                                
    t0 = time.time()
    while(GPIO.input(pin) != level):
        if((time.time() - t0) > timeOut*0.000001):
            return 0;
    t0 = time.time()
    while(GPIO.input(pin) == level):
        if((time.time() - t0) > timeOut*0.000001):
            return 0;
    pulseTime = (time.time() - t0)*1000000
    return pulseTime

def getSonar():     # get the measurement results of ultrasonic module,with unit: cm                                                  
    GPIO.output(trigPin,GPIO.HIGH)      # make trigPin output 10us HIGH level
    time.sleep(0.00001)     # 10us
    GPIO.output(trigPin,GPIO.LOW) # make trigPin output LOW level
    pingTime = pulseIn(echoPin,GPIO.HIGH,timeOut)   # read plus time of echoPin                                          
    distance = pingTime * 340.0 / 2.0 / 10000.0     # calculate distance with sound speed 340m/s
    return distance

def setup():   #                                                                                                   
    GPIO.setmode(GPIO.BCM)      # use PHYSICAL GPIO Numbering
    GPIO.setup(trigPin, GPIO.OUT)   # set trigPin to OUTPUT mode
    GPIO.setup(echoPin, GPIO.IN)    # set echoPin to INPUT mode


def multi_signal_cleanup (trig, echo):  # averages 10 signals from ultrasound

    samples = [s1, s2, s3]
    for variable in samples:
        variable = getSonar()

    sample_ave = (s1+s2+s3)/3
    return sample_ave

def loop():    #                                                                                            
    while(True):
        distance = multi_signal_cleanup(20, 19) # get distance                                                                                            *3
        print ("The distance is : %.2f cm"%(distance))
        time.sleep(1)

if __name__ == '__main__':     # Program entrance
    print ('Program is starting...')
    setup()          #                                                                                                  
    try:
        loop()   #                                                                                              
    except KeyboardInterrupt:  # Press ctrl-c to end the program.
        GPIO.cleanup()         # release GPIO resource
This is a test code I am working on and not the whole robot code, but it is where I am getting the error.

thanks for the help.
Gary
I think you want to call the function getSonar 3 times, sum the result and divide by 3
try
def multi_signal_cleanup():
    return sum(getSonar() for _ in range(3))/3
which is the equivalent of
def multi_signal_cleanup():
    results = []
    for _ in range(3):
        results.append(getSonar())
    return sum(results)/3
Thank you both,

I will give that a try, it makes sense and I even understand the lower code. The short hand version misses me, It may very well work but I do not want to use code I do not understand, Ill get there in time.

Quick question related to your code.
In the line for _ in range(3):

what is the underscore "_" ?

Gary
_ refers to a variable in @Yoriz's post
The _ can be used in the position of a variable name to indicate that you don't intend to use the variable
ie the loop is just being used to repeat something the value from the loop is not required.