Ultrasonic sensor, dc motor and sw420 in Python - python

I am developing a system where I am avoiding an accident by slowing down the motor speed using distance provided by ultrasonic sensor. Also, if accident happens, it must be sense through sw420 and accident occurred result should be displayed.
The problem is that, i have code for both motor mgmt. - distance sensing and impact detection. But as I want them to run parallel i.e.., both are running at same time. How to do it?
Eg. If car is running smoothly, suddenly another car hits you from, let's say, from back.....then automatically, sw420 sensor should sense it and alert the accident occurred message.
Or in other words, some type of multiprocessing concept is needed which i am unaware of.
Here's what i have done till now -
1. Motor is perfectly slowing down when ultrasonic sensor senses shorter distance.
import RPi.GPIO as GPIO
import time
# Define GPIO For Driver motors
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
gpio.setup(7,gpio.OUT)
pwm=GPIO.PWM(18,100)
# Define GPIO for ultrasonic central
GPIO_TRIGGER_CENTRAL = 23
GPIO_ECHO_CENTRAL = 24
GPIO.setup(GPIO_TRIGGER_CENTRAL, GPIO.OUT) # Trigger > Out
GPIO.setup(GPIO_ECHO_CENTRAL, GPIO.IN) # Echo < In
# Functions for driving
def goforward():
pwm.start(100)
GPIO.output(12, True)
GPIO.output(16, False)
GPIO.output(18, True)
def goforwardslow():
GPIO.output(12, True)
GPIO.output(16, False)
GPIO.output(18, True)
def stopmotors():
GPIO.output(12, False)
GPIO.output(16, False)
GPIO.output(18, False)
def buzzer():
try:
while True:
gpio.output(7,0)
time.sleep(0.2)
gpio.output(7,1)
time.sleep(0.2)
except KeyboardInterrupt:
gpio.cleanup()
exit
#Detect front obstacle
def frontobstacle():
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER_CENTRAL, False)
# Allow module to settle
time.sleep(0.2)
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER_CENTRAL, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER_CENTRAL, False)
start = time.time()
while GPIO.input(GPIO_ECHO_CENTRAL) == 0:
start = time.time()
while GPIO.input(GPIO_ECHO_CENTRAL) == 1:
stop = time.time()
# Calculate pulse length
elapsed = stop - start
# Distance pulse travelled in that time is time
# Multiplied by the speed of sound (cm/s)
distance = elapsed * 17150 # distance of both directions so divide by 2
print "Front Distance : %.1f" % distance
return distance
# Check front obstacle and stop if there is an obstacle
def checkanddrivefront():
while frontobstacle() < 15:
pwm.ChangeDutyCycle(25)
buzzer()
goforwardslow()
time.sleep(3)
goforward()
# Avoid obstacles and drive forward
def obstacleavoiddrive():
goforward()
start = time.time()
# Drive 5 minutes
while start > time.time() - 300: # 300 = 60 seconds * 5
if frontobstacle() < 15:
pwm.ChangeDutyCycle(25)
goforwardslow()
checkanddrivefront()
#elif rightobstacle() < 30:
# stopmotors()
# checkanddriveright()
#elif leftobstacle() < 30:
# stopmotors()
#checkanddriveleft()
# Clear GPIOs, it will stop motors
#cleargpios()
#def cleargpios():
#print "clearing GPIO"
#GPIO.output(12, False)
#GPIO.output(13, False)
#print "All GPIOs CLEARED"
def main():
# First clear GPIOs
#cleargpios()
print "start driving: "
# Start obstacle avoid driving
obstacleavoiddrive()
if __name__ == "__main__":
main()
Vibrations is also detecting by sw420
import RPi.GPIO as GPIO
from time import sleep
channel = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
sleep(0.1)
while True:
result = GPIO.input(channel)
if result == 1:
print ("Vibration")
Now the problem is that, where should i place or how can i use vibration/sw420 code in the MAIN CODE so that both run parallel and whenever accident happens, sw420'code occupies higher priority than motor code and gives accident occurred message.
Please share your advice.
NOW THIS IS WHAT LATEST I HAVE DONE TILL NOW -
import RPi.GPIO as GPIO
import time
from multiprocessing import Process
# Define GPIO For Driver motors
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.OUT)
pwm=GPIO.PWM(18,100)
channel = 11
GPIO.setmode(GPIO.BOARD)
GPIO.setup(channel, GPIO.IN)
sleep(0.1)
# Define GPIO for ultrasonic central
GPIO_TRIGGER_CENTRAL = 23
GPIO_ECHO_CENTRAL = 24
GPIO.setup(GPIO_TRIGGER_CENTRAL, GPIO.OUT) # Trigger > Out
GPIO.setup(GPIO_ECHO_CENTRAL, GPIO.IN) # Echo < In
# Functions for driving
def goforward():
pwm.start(100)
GPIO.output(12, True)
GPIO.output(16, False)
GPIO.output(18, True)
def goforwardslow():
GPIO.output(12, True)
GPIO.output(16, False)
GPIO.output(18, True)
def stopmotors():
GPIO.output(12, False)
GPIO.output(16, False)
GPIO.output(18, False)
def buzzer():
while True:
GPIO.output(7,0)
time.sleep(0.2)
GPIO.output(7,1)
time.sleep(0.2)
def vib():
while True:
result = GPIO.input(channel)
if result == 1:
print ("Vibration")
#Detect front obstacle
def frontobstacle():
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER_CENTRAL, False)
# Allow module to settle
time.sleep(0.2)
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER_CENTRAL, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER_CENTRAL, False)
start = time.time()
while GPIO.input(GPIO_ECHO_CENTRAL) == 0:
start = time.time()
while GPIO.input(GPIO_ECHO_CENTRAL) == 1:
stop = time.time()
# Calculate pulse length
elapsed = stop - start
# Distance pulse travelled in that time is time
# Multiplied by the speed of sound (cm/s)
distance = elapsed * 17150 # distance of both directions so divide by 2
print "Front Distance : %.1f" % distance
return distance
# Check front obstacle and stop if there is an obstacle
def checkanddrivefront():
while frontobstacle() < 15:
pwm.ChangeDutyCycle(25)
buzzer()
goforwardslow()
time.sleep(3)
goforward()
# Avoid obstacles and drive forward
def obstacleavoiddrive():
goforward()
start = time.time()
# Drive 5 minutes
while start > time.time() - 300: # 300 = 60 seconds * 5
if frontobstacle() < 15:
pwm.ChangeDutyCycle(25)
buzzer()
goforwardslow()
checkanddrivefront()
#elif rightobstacle() < 30:
# stopmotors()
# checkanddriveright()
#elif leftobstacle() < 30:
# stopmotors()
#checkanddriveleft()
# Clear GPIOs, it will stop motors
#cleargpios()
#def cleargpios():
#print "clearing GPIO"
def main():
print "start driving: "
# Start obstacle avoid driving
obstacleavoiddrive()
if __name__ == "__main__":
p1 = multiprocess.Process(target = main)
p2 = multiprocess.Process(target = vib)
p1.start()
p2.start()
I HAVE USED MULTIPROCESSING ....BUT YET AGAIN ONLY MOTOR DRIVE FUNCTION IS EXECUTING, VIBRATION CODE IS NOT ACTIVE IN THE CODE....means no output from it.

Related

how do I loop servo motor and stop and loop again?

I bought mg995 servo motor but it seems controlling is different from the mg90 because it is digital.
What I want to do is spinning mg995 loop, stops when I press ctrl+c and starts loop again when I press the enter. the code is below but it won't loop again after servo1.stop()
from cmath import inf
from PIL import Image
import numpy as np
import RPi.GPIO as GPIO
from time import sleep
################# -----------------------------
GPIO.setmode(GPIO.BCM)
servo1_pin = 18
GPIO.setup(servo1_pin, GPIO.OUT)
servo1 = GPIO.PWM(servo1_pin, 50)
servo1.start(0)
servo_min_duty = 3
servo_max_duty = 12
def set_servo_degree(servo_num, degree):
if degree > 180:
degree = 180
elif degree < 0:
degree = 0
duty = servo_min_duty+(degree*(servo_max_duty-servo_min_duty)/180.0)
if servo_num == 1:
servo1.ChangeDutyCycle(duty)
#################-------------------------------
try:
while True:
set_servo_degree(1, 0)
except KeyboardInterrupt:
servo1.stop() # after servo stops, it won't start again.
print("should be end")
pass
go_button = input('go? press enter!')
if go_button == "":
## after press the enter, starts loop again.
try:
while True:
set_servo_degree(1, 0)
else:
break()
sleep(2)
GPIO.cleanup()
thank you!
The while loop should be outside of the set_servo_degree function.
The modified part of your code is as below
servo_num = 1
servo_deg = 0
while True:
try:
set_servo_degree(servo_num, servo_deg)
except KeyboardInterrupt:
servo1.stop()
go_button = input('go? press enter!')
if go_button == "":
set_servo_degree(servo_num, servo_deg)
else:
break
sleep(2)
GPIO.cleanup()

Wait for input during several iterations of a loop in python

I'm trying to write a python code to control the voltage of the GPIO Pins.
The idea behind it is that in a frequency of 1KHz if half of the time the pin is off and half of the time it is on than the voltage will be 50%.
I need to keep the while loop running while waiting for user input so that I can change the speed of the motor.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.OUT)
# The higher the number for speed the slower the motor will rotate
def motor(speed):
i = 0
run = True
# Runs until user tells it to stop
while run == True:
# Pins should vary at every second
time.sleep(0.001)
i += 1
if i % speed == 0:
GPIO.output(4, GPIO.HIGH)
else:
GPIO.output(4, GPIO.LOW)
# This block is causing the issue
# I need the loop to keep running while waiting for the input
if i % speed * 10 == 0:
com = int(input("Enter 0 to quit"))
if com == -1:
GPIO.output(4, GPIO.LOW)
break
GPIO.output(4, GPIO.LOW)
run = True;
while (run):
speed = int(input("Select Speed"))
if speed == 0:
run = False
else:
motor(speed)
GPIO.cleanup()

ultrasonic sensor didn't work with raspberry pi

I have a problem with raspberry pi 3b and ultrasonic sensor
I want to sense and indicate the obstacle
I connect it as many tutorial on google and measure it a while ago and it was working before
today i came and execute same code with same connection, it didn't need to measure
the problem is that the echo pin didn't become 1
this is the code i used , I made a print statement to debug, but only testttt was printed.
enter code here
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO_TRIGGER = 12
GPIO_ECHO = 16
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def distance():
while True:
GPIO.output(GPIO_TRIGGER, 0)
time.sleep(2)
GPIO.output(GPIO_TRIGGER, 1)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, 0)
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
print"testttt"
While GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
print"test"
TimeElapsed = StopTime - StartTime
distance = TimeElapsed * 17150
dis=round(distance,2)
print"distabce=" +str(dis)+"cm"
distance()

Raspberry PI: 2 buttons, 2 LEDs

I'm trying to make a Python program with Raspberry Pi that when I push a button, only the red LED brightens, and when I press another button, only the green LED brightens. When no buttons are pushed, all the LEDs are off. But when I try to run it, both LEDs stay on, and when I press the button, the monitor says I pressed it, but nothing changes. What can I do to fix this? I'm 100% certain there are no wiring problems, and the monitor shows no errors. BTW, here's the code:
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
red_walk_LED = 16
green_traf_LED = 15
Btn_one = 22 # pin12 --- button
Btn_two = 29 # pin29 --- 2nd button
# GLOBAL VARIABLES
red_Led_status = 1
Green_Led_status = 1
flag_btn_one_pushed = 0
flag_btn_two_pushed = 0
def all_leds_off():
GPIO.output(green_traf_LED, GPIO.HIGH)
GPIO.output(yellow_traf_LED, GPIO.HIGH)
GPIO.output(red_traf_LED, GPIO.HIGH)
GPIO.output(red_walk_LED, GPIO.HIGH)
GPIO.output(white_walk_LED, GPIO.HIGH)
def setup():
global green_LED_frequence
global red_LED_frequence
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
#set LEDs as outputs
GPIO.setup(green_traf_LED, GPIO.OUT)
GPIO.setup(red_traf_LED, GPIO.OUT)
GPIO.setup(Btn_one, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode as input, and pull up to high level(3.3V)
GPIO.setup(Btn_two, GPIO.IN, pull_up_down=GPIO.PUD_UP)
red_LED_frequence = GPIO.PWM(red_traf_LED, 1000) # set Frequece to 1KHz
green_LED_frequence = GPIO.PWM(green_traf_LED, 1000)
red_LED_frequence.start(0) # Duty Cycle = 0
green_LED_frequence.start(0)
def Btn_one_push(ev=None):
print('OK, the 1st button was pushed')
global red_Led_status #we are allowed to change these variables in this function
global my_counter
global flag_btn_one_pushed
global red_LED_frequence
red_Led_status = not red_Led_status #change LED status 0-1 or 1-0
flag_btn_one_pushed = 1
my_delay = 0.2
GPIO.output(green_traf_LED, GPIO.HIGH)
if red_Led_status == 1: #1-on
print('ok, reds on')
for dc in range(0, 101, 4): # Increase duty cycle: 0~100
red_LED_frequence.ChangeDutyCycle(dc) # Change duty cycle
time.sleep(0.02)
for dc in range(100, -1, -4): # Decrease duty cycle: 100~0
red_LED_frequence.ChangeDutyCycle(dc)
time.sleep(0.02)
all_leds_off() #turn all LEDs off!!
flag_btn_pushed = 0
def Btn_two_push(ev=None):
print('OK, the 2nd button was pushed')
global Green_Led_status
global flag_btn_two_pushed
global green_LED_frequence
Green_Led_status = not Green_Led_status #change LED status 0-1 or 1-0
flag_btn_two_pushed = 1
my_delay = 0.2
GPIO.output(red_traf_LED, GPIO.HIGH)
if Green_Led_status == 1: #1-on
print('This is supposed to work!')
for dc in range(0, 101, 4): # Increase duty cycle: 0~100
print(green_LED_frequence)
green_LED_frequence.ChangeDutyCycle(dc) # Change duty cycle
time.sleep(0.08)
for dc in range(100, -1, -4): # Decrease duty cycle: 100~0
green_LED_frequence.ChangeDutyCycle(dc)
time.sleep(0.08)
all_leds_off() #turn all LEDs off!!
flag_btn_two_pushed = 0
def loop():
global flag_btn_one_pushed
global flag_btn_two_pushed
GPIO.add_event_detect(Btn_one, GPIO.FALLING, callback=Btn_one_push) # wait for change in GPIO 0-1 or 1-0
GPIO.add_event_detect(Btn_two, GPIO.FALLING, callback=Btn_two_push)
while True: #when the button isn't pushed, do this
all_leds_off()
else:
pass
def destroy():
all_leds_off()
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
You should try removing these lines:
while True: #when the button isn't pushed, do this
all_leds_off()
else:
pass
and replacing them with:
all_leds_off()
The callbacks should be fired every button press.
Here is another example to look at:
https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=102631&p=760629
Also, have you tried some simple snippets of code to individually turn the LED's on and off and detect the button presses to prove that's its not a wiring problem? It doesn't take much to get the wiring wrong!

Raspberry Webiopi GPIO one time Email Trigger

I have been trying to make this code I have to only email once after the Door pin has been tripped. I am newish to python and have been reading the posts with similar question and trying what I have seen to my Script. But can't seem to get it to only send the email one time.
enter code here
import webiopi
import datetime
import smtplib
import subprocess
import os
GPIO = webiopi.GPIO
ARM = 7 # GPIO pin using BCM numbering
FLASH = 8
START = 25 # relay
DOOR = 11
HOUR_ON = 8 # Turn Light ON at 08:00
HOUR_OFF = 18 # Turn Light OFF at 18:00
def setup():
GPIO.setFunction(ARM, GPIO.OUT)
GPIO.setFunction(FLASH, GPIO.OUT)
GPIO.setFunction(START, GPIO.OUT)
GPIO.setup(DOOR, GPIO.IN, pull_up_down=GPIO.PUD_UP)
now = datetime.datetime.now()
# test if we are between ON time and tun the light ON
if ((now.hour >= HOUR_ON) and (now.hour < HOUR_OFF)):
GPIO.digitalWrite(ARM, GPIO.HIGH)
GPIO.digitalWrite(FLASH, GPIO.HIGH)
def loop():
# retrieve current datetime
now = datetime.datetime.now()
# toggle light ON all days at the correct time
if ((now.hour == HOUR_ON) and (now.minute == 0) and (now.second == 0)):
if (GPIO.digitalRead(ARM) == GPIO.LOW):
GPIO.digitalWrite(ARM, GPIO.HIGH)
# toggle light OFF
if ((now.hour == HOUR_OFF) and (now.minute == 0) and (now.second == 0)):
if (GPIO.digitalRead(ARM) == GPIO.HIGH):
GPIO.digitalWrite(ARM, GPIO.LOW)
if (GPIO.digitalRead(ARM) == GPIO.HIGH):
GPIO.digitalWrite(FLASH, GPIO.HIGH)
webiopi.sleep(.5)
GPIO.digitalWrite(FLASH, GPIO.LOW)
if (GPIO.digitalRead(DOOR) == GPIO.HIGH):
SendText()
# gives CPU some time before looping again
webiopi.sleep(1)
def SendText():
os.system("python /home/pi/html/myemail.py")
# destroy function is called at WebIOPi shutdown
def destroy():
GPIO.digitalWrite(ARM, GPIO.LOW)
GPIO.digitalWrite(START, GPIO.LOW)
#webiopi.macro
def getLightHours():
return "%d;%d" % (HOUR_ON, HOUR_OFF)
#webiopi.macro
def setLightHours(on, off):
global HOUR_ON, HOUR_OFF
HOUR_ON = int(on)
HOUR_OFF = int(off)
return getLightHours()
You can set a variable, send_email, to track if it is time to send an email and if that email has been sent.
Create a global variable, send_email = False, because the variable will go inside the loop method and needs to be initialized.
Add to the SendText() if statement and send_email
After the SendText() line set send_email = False
Add another if statement to check if GPIO.LOW and change the send_email to True
I have made the suggested changes to your code. I put * around all the text I added. Make sure to remove all the * from the code for it to work.
import webiopi
import datetime
import smtplib
import subprocess
import os
GPIO = webiopi.GPIO
ARM = 7 # GPIO pin using BCM numbering
FLASH = 8
START = 25 # relay
DOOR = 11
HOUR_ON = 8 # Turn Light ON at 08:00
HOUR_OFF = 18 # Turn Light OFF at 18:00
*send_email = False*
def setup():
GPIO.setFunction(ARM, GPIO.OUT)
GPIO.setFunction(FLASH, GPIO.OUT)
GPIO.setFunction(START, GPIO.OUT)
GPIO.setup(DOOR, GPIO.IN, pull_up_down=GPIO.PUD_UP)
now = datetime.datetime.now()
# test if we are between ON time and tun the light ON
if ((now.hour >= HOUR_ON) and (now.hour < HOUR_OFF)):
GPIO.digitalWrite(ARM, GPIO.HIGH)
GPIO.digitalWrite(FLASH, GPIO.HIGH)
def loop():
# retrieve current datetime
now = datetime.datetime.now()
# toggle light ON all days at the correct time
if ((now.hour == HOUR_ON) and (now.minute == 0) and (now.second == 0)):
if (GPIO.digitalRead(ARM) == GPIO.LOW):
GPIO.digitalWrite(ARM, GPIO.HIGH)
# toggle light OFF
if ((now.hour == HOUR_OFF) and (now.minute == 0) and (now.second == 0)):
if (GPIO.digitalRead(ARM) == GPIO.HIGH):
GPIO.digitalWrite(ARM, GPIO.LOW)
if (GPIO.digitalRead(ARM) == GPIO.HIGH):
GPIO.digitalWrite(FLASH, GPIO.HIGH)
webiopi.sleep(.5)
GPIO.digitalWrite(FLASH, GPIO.LOW)
if (GPIO.digitalRead(DOOR) == GPIO.HIGH) *and send_email*:
SendText()
*send_email = False*
*if (GPIO.digitalRead(DOOR) == GPIO.LOW) and not send_email*:
*send_email = True*
# gives CPU some time before looping again
webiopi.sleep(1)
def SendText():
os.system("python /home/pi/html/myemail.py")
# destroy function is called at WebIOPi shutdown
def destroy():
GPIO.digitalWrite(ARM, GPIO.LOW)
GPIO.digitalWrite(START, GPIO.LOW)
#webiopi.macro
def getLightHours():
return "%d;%d" % (HOUR_ON, HOUR_OFF)
#webiopi.macro
def setLightHours(on, off):
global HOUR_ON, HOUR_OFF
HOUR_ON = int(on)
HOUR_OFF = int(off)
return getLightHours()

Categories