On 29/01/2021 09:22, Ralph Corderoy wrote:
Hi Peter,

BUT anytime I add anything to the program the subscriber stops firing
the LEDs.
‘Anything’ is very vague.  Can you attach the output of

     diff -u working.py broken.py

where you've done some simple change which breaks it, e.g...

I can't do that because every time it fails I back it out to the working code. 
Attached is the Python with the Logger code inserted.  It also contains the 
Ultrasonic detection and action [Distance() and us_act()].  Perhaps I don't 
know where to find the debug_log.txt.


#!python3
# 2020-09-14  This is a change to  RC car-7 from using Flask and HTML to using 
Mosquitto
# 2020-11-06  Edited to remove all the calculations leading up to the PWM 
percentage
# 2121-01-08  Adding Ultrasonic detection to forward motion, then halt, 
reverse, turn left,halt and back to forward
# 2121-01-16  Adding debug statements


# *** SET UP MQTT   ***

# from https://techtutorialsx.com/2017/04/23/python-subscribing-to-mqtt-topic/
import paho.mqtt.client as mqtt
import time
import logging
logging.basicConfig(filename='debug_log.txt', level=logging.DEBUG, 
format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a log message.')

Connected = False #global variable for the state of the connection

broker_address= "192.168.4.1"
port = 1883
user = "rc-car-11"
password = "carr0t"

# Create client   --?? Is this the same as User?
client = mqtt.Client(client_id="rc-car-11")

# Connect to broker
client.connect(broker_address,1883,60)

# Subscriber to topic
client.subscribe("rc-car-pwm")

# *** SET UP R-Pi GPIO        ***

# This gives us control of the Raspberry Pi's pins.
import RPi.GPIO as GPIO

# Tell it which pin number we'll  be using to refer to the GPIO pins.
# We will use the physical pin ordering. Set initial state of pins
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

MotorFwd = 18
MotorBack = 12
MotorLeft = 19
MotorRight = 23

GPIO.setup(MotorFwd, GPIO.OUT)
GPIO.setup(MotorBack, GPIO.OUT)
GPIO.setup(MotorLeft, GPIO.OUT)
GPIO.setup(MotorRight, GPIO.OUT)

# PWM pin = Motor Forward
u_d_pin_no = 18
GPIO.setup(u_d_pin_no, GPIO.OUT)

# Ultrasonic setup
GPIO_TRIGGER = 13
GPIO_ECHO = 15

GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)


frequency_hertz = 50
pwm = GPIO.PWM(u_d_pin_no, frequency_hertz)

PWM_Stop = 0
PWM_value = 0
PWM_increment = 15
# becomes 15 after calculations  [old comment]
# set to 15, removed calculations
# can remove  duty_cycle_percentage as it is same as PWM_Value

# reverse control   Nov 11 2020
# from 
https://www.electronicwings.com/raspberry-pi/raspberry-pi-pwm-generation-using-python-and-c
Backpin = 12
GPIO.setup(Backpin,GPIO.OUT)   # can remove this as it is MotorBack above
back_pwm = GPIO.PWM(Backpin,1000)

# ***    SET UP Functions   ***

def on():                    # STOP!
    global PWM_value
    PWM_value = 0
    pwm.start(PWM_value)
    GPIO.output(MotorBack, GPIO.LOW)
    back_pwm.start(0)    # added to stop pwm reverse
    logger.debug('STOP')

def up_15():
    global PWM_value
    PWM_value = PWM_value + PWM_increment
    pwm.start(PWM_value)
    logger.debug('Forward 15, now Distance test')
    if distance() < 40:
        us_act()


def down_15():
    global PWM_value
    logger.debug('Slow Down')
    if  PWM_value > 0 :
        PWM_value = PWM_value - PWM_increment
        pwm.start(PWM_value)
    else :
        PWM_value  = 0


def motorleft():
    GPIO.output(MotorLeft,GPIO.HIGH)
    GPIO.output(MotorRight, GPIO.LOW)
    logger.debug('Turn Left')
    time.sleep(1)
    GPIO.output(MotorLeft, GPIO.LOW)


def motorright():
    GPIO.output(MotorLeft, GPIO.LOW)
    GPIO.output(MotorRight, GPIO.HIGH)
    logger.debug('Turn Right')
    time.sleep(1)
    GPIO.output(MotorRight, GPIO.LOW)
    return ()


def mbackwards():
# stop forward motion
    global PWM_value
    PWM_value = 0
    pwm.start(PWM_value)
# wait a short time
    time.sleep(0.3)
# now go backwards
#    GPIO.output(MotorBack, GPIO.HIGH)
    back_pwm.start(30)          #30% duty cycle
    return ()

def on_message(client, userdata, message):
   logger.debug('Wait for button')
   if message.payload  == b'forward':
      up_15()
   elif message.payload  == b'slow':
      down_15()
   elif message.payload  == b'stop':
      on()
   elif message.payload  == b'motorleft':
      motorleft()
   elif message.payload  == b'motorright':
      motorright()
   elif message.payload  == b'backwards':
      mbackwards()
   else:
      print(message.payload)

def distance():
    logger.debug('Start distance sampling')

    # set Trigger to HIGH
    GPIO.output(GPIO_TRIGGER, True)

    # set Trigger after 0.01ms to LOW
    time.sleep(0.00001)
    GPIO.output(GPIO_TRIGGER, False)

    StartTime = time.time()
    StopTime = time.time()

    # save StartTime
    while GPIO.input(GPIO_ECHO) == 0:
        StartTime = time.time()

    # save time of arrival
    while GPIO.input(GPIO_ECHO) == 1:
        StopTime = time.time()

    # time difference between start and arrival
    TimeElapsed = StopTime - StartTime
    # multiply with the sonic speed (34300 cm/s)
    # and divide by 2, because there and back
    distance = (TimeElapsed * 34300) / 2

    return distance

def us_act();
    # stop, go backwards, turn left twice, stop, and then go forwards again.
    global PWM_value
    logger.debug('React to distance result')
    on()
    time.sleep(0.2)
    mbackwards()
    motorleft
    motorleft
    on()
    time.sleep(0.2)
    up_15()


# ****  Run Program  ***

def main():
    client.subscribe("rc-car-pwm")
    client.on_message = on_message
    client.loop_forever()


main()




--
 Next meeting: Online, Jitsi, Tuesday, 2021-02-02 20:00
 Check to whom you are replying
 Meetings, mailing list, IRC, ...  http://dorset.lug.org.uk
 New thread, don't hijack:  mailto:dorset@mailman.lug.org.uk

Reply via email to