Ejemplo n.º 1
0
def get_ultrasonic(port, settings):
        try:
                if settings['ultrasonic_mode'] == 'distance':
                        if settings['units'] == 'cm':
                                return grovepi.ultrasonicRead(port)
                        elif settings['units'] == 'in':
                                return grovepi.ultrasonicRead(port) * 0.393701
        except ValueError:
                return "Not found"
Ejemplo n.º 2
0
def avoid_barrier(avoid_barrier):
	global avoid_count
	#print "head : ", str(grovepi.ultrasonicRead(ultrasonic_ranger_head)),"right : ", str(grovepi.ultrasonicRead(ultrasonic_ranger_right)),"left : ", str(grovepi.ultrasonicRead(ultrasonic_ranger_left))
	time.sleep(.2)
	set_speed()
	if(avoid_count < 5):
		print avoid_count
		try:
			if(grovepi.ultrasonicRead(ultrasonic_ranger_head) < 40):
				bwd()
				time.sleep(.2)
				print "avoid bwd"
				avoid_count += 1
				return False
			elif(grovepi.ultrasonicRead(ultrasonic_ranger_left) < 20):
				if(avoid_barrier == 'home'):
					fwd()
				else:
					bwd()
				time.sleep(.2)
				right()
				print "avoid right"
				avoid_count += 1
				return False
			elif(grovepi.ultrasonicRead(ultrasonic_ranger_right) < 20):
				if(avoid_barrier == 'home'):
					fwd()
				else:
					bwd()
				time.sleep(.2)
				left()
				print "avoid left"
				avoid_count += 1
				time.sleep(.2)
				return False
			else:
				print "avoid pass"
				#avoid_count = 0
				return True
		except:
			print "read ultrasonic fail"
			return False
	else:
		if(avoid_barrier == 'home'):
			fwd()
		else:
			bwd()
		time.sleep(.2)
		RightOrLeft = random.randint(0,10)
		if RightOrLeft > 0 and RightOrLeft < 5:
			time.sleep(.2)
			left()
		else:
			time.sleep(.2)
			right()
		#avoid_count = 0
		return True
Ejemplo n.º 3
0
def main():
    cfg = {
        "consumer_key":'9iHdYDCrzpNefQqtUyDh7tScN',
        "consumer_secret":'pYP8c8njj3vtJqeoDNZpR2kMwuNi0LQKmiGnBlL1Dg5sylEUyI',
        "access_token":'756129972075556864-8G9mT1j8RxOx7cgrTbWsQ9CqrK3f0iG',
        "access_token_secret":'ZmjDVFHZgYKNvI0Cr2bKQfSYue2tOh4R6uLBWblRUndvN'
    }

    grovepi.pinMode(button, "INPUT")
    print "Waiting for button to be pressed"

    while True:
        try:
            # get value of button status
            button_status = grovepi.digitalRead(button)

            # if button pressed
            if button_status == 1:
                api = get_api(cfg)
                print "I am posting a tweet via GrovePi!"
                
                # captures distance between ultrasonic sensor and the closest object
                distance = grovepi.ultrasonicRead(ultrasonic_ranger)
                tweet = "There is currently an object " + str(distance) + " cm away from my$
                status = api.update_status(status=tweet)
                # immediately print tweet
                print(tweet)
        except IOError:
            print("Error")
        except KeyboardInterrupt:
            exit()
Ejemplo n.º 4
0
    def coverCheck(self):
        counter = 0
        while True:
            try:
                dist = grovepi.ultrasonicRead(ultrasonic_ranger)
                print "DIST: " + str(dist) + " cm away."
                counter +=1
                if counter % 50 == 0 and dist > 500:
                    print "My cover is just sitting open, isn't it?"
                elif dist > 50:
                    try:
                        #Blink the LED
                        digitalWrite(rled,1)		# Send HIGH to switch on LED
                        digitalWrite(buzzer,1)
                        print "Hey!"
                        time.sleep(1)

                        digitalWrite(rled,0)		# Send LOW to switch off LED
                        digitalWrite(buzzer,0)
                        print "Close the lid."
                        time.sleep(1)

                    except IOError:				# Print "Error" if communication error encountered
                        print ("Error")
            except TypeError:
                print ("Error")
            except IOError:
                print ("Error")
            except KeyboardInterrupt:
                digitalWrite(rled,0)
                digitalWrite(buzzer,0)
                break
Ejemplo n.º 5
0
    def demoRange(self):
        while True:
            try:
                # Read distance value from Ultrasonic
                print (grovepi.ultrasonicRead(ultrasonic_ranger))

            except TypeError:
                print ("Error")
            except IOError:
                print ("Error")
            except KeyboardInterrupt:
                break
def read_sensor():
        try:
                light = grovepi.analogRead(light_sensor)
                distance = grovepi.ultrasonicRead(ultrasonic_ranger)
                [temp, humidity] = grovepi.dht(temp_humidity_sensor, blue)
                #Return -1 in case of bad temp/humidity sensor reading
                if math.isnan(temp) or math.isnan(humidity):
                        return [-1, -1, -1, -1]
                return [light, distance, temp, humidity]
        
        except IOError as TypeError:
                return [-1, -1, -1, -1]
Ejemplo n.º 7
0
def readData():
    try:
        json_obj = json.dumps({
                'temp' : grovepi.dht(DHT_pin,1)[0],
                'hum' : grovepi.dht(DHT_pin,1)[1],
                'lum' : grovepi.analogRead(0),
                'dist' : grovepi.ultrasonicRead(US_pin),
                'pot' : grovepi.analogRead(1),
                'pir' : grovepi.digitalRead(PIR_pin)
                }) 
        return json_obj
    except IOError:
        print "Erreur d'entrée/sortie"
Ejemplo n.º 8
0
def ultrasonicF():
	time.sleep(0.50)
	try:
		#ultrasonic
		range= int(grovepi.ultrasonicRead(ultrasonic_ranger))
		#int(str(range) + " cm")

		if range<=500:
			client.publish("range", str(range))
			

	except (IOError,TypeError) as ex:
		error="Error: " + str(ex)
Ejemplo n.º 9
0
def handlerequests(req):
    if req.operation==0:
        pin = req.pin.split("Pin")[1]
        grovepi.pinMode(int(pin), "INPUT")
        try:
            sensorval = grovepi.digitalRead(int(pin))
        except:
            sensorval =0
        msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation)
        sys.stdout.write(json.dumps(msgtx.__dict__)+"\n")
    elif req.operation == 1:
        pin = req.pin.split("Pin")[1]
        grovepi.pinMode(int(pin), "OUTPUT")
        try:
            grovepi.digitalWrite(int(pin), int(req.payload))
        except:
            grovepi.digitalWrite(int(pin), int(req.payload))
    elif req.operation == 2:
        pin = req.pin.split("Pin")[1]
        grovepi.pinMode(int(pin), "INPUT")
        try:
            sensorval = grovepi.analogRead(int(pin))
        except:
            sensorval = 0
        msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation)
        sys.stdout.write(json.dumps(msgtx.__dict__)+"\n")
    elif req.operation ==4:
        pin = req.pin.split("Pin")[1]
        try:
            [temp,humidity] = grovepi.dht(int(pin),1)
        except:
            temp=0
            humidity =0
        a= json.dumps({'temp':temp,'humidity':humidity})
        msgtx = Python2Sharp(msg.isRequest,msg.watcherid,msg.syncid,a,msg.operation)
        sys.stdout.write(json.dumps(msgtx.__dict__)+"\n")
    elif req.operation == 5:
        pin = req.pin.split("Pin")[1]
        try:
            sensorval=grovepi.ultrasonicRead(int(pin))
        except:
            sensorval=0
        msgtx = Python2Sharp(msg.isRequest, msg.watcherid, msg.syncid, str(sensorval), msg.operation)
        sys.stdout.write(json.dumps(msgtx.__dict__)+"\n")
    elif req.operation == 6:
        try:
            setRGB(0,128,64)
            setText(req.payload)
        except:
            pass
Ejemplo n.º 10
0
def sensor_read_ultrasonic():
	retry = 3
	while retry > 0:
		try:
			status = grovepi.ultrasonicRead(ultrasonic_ranger)
			time.sleep(.01)
			break
		except:
			print 'can not read ultrasonic, retry again'
			retry = retry - 1
			time.sleep(.1)

	if retry == 0:
		return -1
	else:
		return status
Ejemplo n.º 11
0
def candy_detection():
	global candy_count
	dist = 100
	try:
		while dist > 8:
			# Read distance value from Ultrasonic
			# print(grovepi.ultrasonicRead(ultrasonic_ranger))
			dist = grovepi.ultrasonicRead(ultrasonic_ranger)
			random_bar()
			led_random()
		print("Distance Detected: " + str(dist))
		candy_count = candy_count + 1
		thanks = "Thank you for the candy! " + "I now have " + str(candy_count) + " pieces of candy!"
		lcd_rgb(str(thanks))
		led_random()
		sound(thanks)
	except TypeError:
		print ("Ultrasonic Error! Error!")
	except IOError:
		print ("Ultrasonic Error! Error!")
Ejemplo n.º 12
0
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import grovepi

# Connect the Grove Ultrasonic Ranger to digital port D4
# SIG,NC,VCC,GND
ultrasonic_ranger = 4

while True:
    try:
        # Read distance value from Ultrasonic
        print(grovepi.ultrasonicRead(ultrasonic_ranger))

    except TypeError:
        print ("Error")
    except IOError:
        print ("Error")
Ejemplo n.º 13
0
Archivo: main.py Proyecto: rvu95/rpi
#!/usr/bin/env python

import grovepi
import urllib2
import json

ultrasonic_ranger = 4

while True:
  try:
        value = grovepi.ultrasonicRead(ultrasonic_ranger) 
	data = {"Level":value}
	url = 'https://chocolate-furry.herokuapp.com/level	'
	req = urllib2.Request(url,json.dumps(data),{'Content-Type': 'application/json'})
	f = urllib2.urlopen(req)
	for x in f:
		print(x)
	f.close
	print (value)

  except TypeError:
        print ("Error")
  except IOError:
        print ("Error")
Ejemplo n.º 14
0
def show_ultrasonic_distance():
	#LCD_show("Head : " + str(grovepi.ultrasonicRead(ultrasonic_ranger_left)))
	print "head : ", str(grovepi.ultrasonicRead(ultrasonic_ranger_head)),"right : ", str(grovepi.ultrasonicRead(ultrasonic_ranger_right)),"left : ", str(grovepi.ultrasonicRead(ultrasonic_ranger_left))
Ejemplo n.º 15
0
 def check_distance(self):
     dist = grovepi.ultrasonicRead(self.ULTRASONIC)
     print('Distance: ', dist)
     return dist
Ejemplo n.º 16
0
# Connect two Grove Ultrasonic Rangers to digital ports D3 and D2
# SIG,NC,VCC,GND
ultrasonic_ranger1 = 3 # Ultrasonic Ranger at D3
ultrasonic_ranger2 = 2 # Ultrasonic Ranger at D2

sleepTime = int(sys.argv[1])	#sys.argv[1] is the first and only argument

t_end = time.time() + sleepTime

with picamera.PiCamera() as camera:
        camera.hflip = True
        camera.vflip = True
        camera.start_preview()
        camera.preview.alpha = 230

        while time.time() < t_end:

                try:
                    # Get distance value
                    distance1 = grovepi.ultrasonicRead(ultrasonic_ranger1)
                    distance2 = grovepi.ultrasonicRead(ultrasonic_ranger2)
                    R = min(distance1, distance2)
                    R = str(R)
                    camera.annotate_text = R
                    time.sleep(.5)
                    
                except (IOError,TypeError) as e:
                            print "Error"
                    
        camera.stop_preview()
Ejemplo n.º 17
0
def main():
    global isConnected
    # Create an MQTT client for connecting to AWS IoT via MQTT.
    client = mqtt.Client(deviceName + "_sr")  # Client ID must be unique because AWS will disconnect any duplicates.
    client.on_connect = on_connect  # When connected, call on_connect.
    client.on_message = on_message  # When message received, call on_message.
    client.on_log = on_log  # When logging debug messages, call on_log.

    # Set the certificates and private key for connecting to AWS IoT.  TLS 1.2 is mandatory for AWS IoT and is supported
    # only in Python 3.4 and later, compiled with OpenSSL 1.0.1 and later.
    client.tls_set(awsCert, deviceCertificate, devicePrivateKey, ssl.CERT_REQUIRED, ssl.PROTOCOL_TLSv1_2)

    # Connect to AWS IoT server.  Use AWS command line "aws iot describe-endpoint" to get the address.
    print("Connecting to AWS IoT...")
    client.connect("A1P01IYM2DOZA0.iot.us-west-2.amazonaws.com", 8883, 60)

    # Start a background thread to process the MQTT network commands concurrently, including auto-reconnection.
    client.loop_start()

    # Configure the Grove LED port for output.
    grovepi.pinMode(led, "OUTPUT")
    time.sleep(1)

    # Loop forever.
    while True:
        try:
            # If we are not connected yet to AWS IoT, wait 1 second and try again.
            if not isConnected:
                time.sleep(1)
                continue
            # read temperature
            temp = grovepi.temp(temp_sensor,'1.1')
            distance_in_cm = grovepi.ultrasonicRead(ultrasonic_ranger)
           

            if distance_in_cm > 3 and distance_in_cm < 7 :
               grovepi.digitalWrite(led,1)  
               grovepi.digitalWrite(buzzer,0)
               msg = "Distance between bike and ground is more than 20 cm  ->Led on} : value of distance is %d " %distance_in_cm
            elif  distance_in_cm >= 7 :
               grovepi.digitalWrite(led, 1)
               grovepi.digitalWrite(buzzer,1)
               msg = "To much gap between bike and ground :->led on/buzzer on : value of distance is %d" %distance_in_cm
            else: 
               grovepi.digitalWrite(led,0)  
               grovepi.digitalWrite(buzzer,0)
               msg = "OK : distance is less than 20 cm: value of distance is %d" %distance_in_cm 

        #except KeyboardInterrupt:
        #    break
        #except IOError:
        #    print("error");
 
            #Get light sensor(LDR)/Sound_sensor value
            light_sensor_value = grovepi.analogRead(light_sensor)
            loudness_sensor_value = grovepi.analogRead(sound_sensor)
            axes = adxl345.getAxes(True)
            
            #time.sleep(1)
            # led off - buzzer off
            #grovepi.digitalWrite(led,0) 
            #grovepi.digitalWrite(buzzer,0)
            #time.sleep(1)
        
               # print ("temp =", temp)
                # Prepare our sample data in JSON format.
            payload = {
                "state": {
                    "reported": {
                        "temperature": temp,
                        "humidity": 55,
                        "light_level": light_sensor_value,
                        "sound_level": loudness_sensor_value,
                        "message": msg,
                        "distance":distance_in_cm,
                        "accelerometer":axes, 
                        "timestamp": datetime.datetime.now().isoformat()
                    }
                }
            }
            print("Sending sensor data to AWS IoT...\n" +
                  json.dumps(payload, indent=4, separators=(',', ': ')))

            # Publish our sensor data to AWS IoT via the MQTT topic, also known as updating our "Thing Shadow".
            client.publish("$aws/things/" + deviceName + "/shadow/update", json.dumps(payload))
            print("Sent to AWS IoT")

            # Wait 30 seconds before sending the next set of sensor data.
            time.sleep(0.5)

        except KeyboardInterrupt:
            # Stop the program when we press Ctrl-C.
            break
        except IOError:
            # Some I/O problem happened.
            print("I/O Error")
            continue
        except:
            # For all other errors, we wait a while and resume.
            time.sleep(10)
            continue
Ejemplo n.º 18
0
# some thresholds
THRESHOLD_DOOR_OPEN_ULTRASOUND=50
THRESHOLD_DOOR_OPEN_ROTATION=400

#variable which stores the current state
currentState=STATE_UNKNOWN

# we only change state when we've seen the sensors for a 5 seconds - this avoids fluctuating if there is noise
change_state_counter=0

# CSV header
print "ultrasound,rotation,currentState,change_state_counter"

while True:
    # first read the sensors
    ultrasound=grovepi.ultrasonicRead(ULTRASOUND_PIN)
    rotation=grovepi.analogRead(ROTATION_SENSOR_PIN)
    print "%d,%d,%d,%d"%(ultrasound,rotation,currentState,change_state_counter)
    
    # for each current state, check the sensors and decide whether to change state
    if currentState==STATE_UNKNOWN:
        # inital unknown state - guess from the current sensors
        if ultrasound > THRESHOLD_DOOR_OPEN_ULTRASOUND and rotation>THRESHOLD_DOOR_OPEN_ROTATION:
            # door is open
            currentState=STATE_DOOR_OPEN
        elif ultrasound< THRESHOLD_DOOR_OPEN_ULTRASOUND and rotation<THRESHOLD_DOOR_OPEN_ROTATION:
            # door is closed
            currentState=STATE_DOOR_CLOSED
        else:
            # the thresholds are each on the opposite directions, wait until the sensors die down before we decide on a state
            pass
Ejemplo n.º 19
0
led_status = 3
relay = 2
buzzer = 5

SMTP_USERNAME = ''  # Mail id of the sender
SMTP_PASSWORD = ''  # Pasword of the sender
SMTP_RECIPIENT = ''  # Mail id of the reciever
SMTP_SERVER = 'smtp.gmail.com'  # Address of the SMTP server
SSL_PORT = 465

while True:  # in case of IO error, restart
    try:
        grovepi.pinMode(switch, "INPUT")
        while True:
            if grovepi.digitalRead(switch) == 1:  # If the system is ON
                if grovepi.ultrasonicRead(
                ) < 100:  # If a person walks through the door
                    print "Welcome"
                    grovepi.analogWrite(buzzer,
                                        100)  # Make a sound on the Buzzer
                    time.sleep(.5)
                    grovepi.analogWrite(buzzer, 0)  # Turn off the Buzzer
                    grovepi.digitalWrite(
                        led_status, 1
                    )  # Turn on the status LED to indicate that someone has arrived
                    grovepi.digitalWrite(
                        relay, 1
                    )  # turn on the Relay to activate an electrical device

                    # Take a picture from the Raspberry Pi camera
                    call(["raspistill -o i1.jpg -w 640 -h 480 -t 0"],
                         shell=True)
Ejemplo n.º 20
0
def backUp(): 
    timeStart = time.time()
    while(grovepi.ultrasonicRead(ultrasonic_sensor_port1) < 15 and (grovepi.ultrasonicRead(ultrasonic_sensor_port3) < 15)):
        BP.set_motor_power(BP.PORT_A + BP.PORT_D, 30)
Ejemplo n.º 21
0
        BP.set_motor_power(BP.PORT_D,30)

def turnRight(): # if there's a wall in front, will need to implement check left or right to determine to turn left or right after encountering an obstacle
    timeStart = time.time()
    while(timeStart + 3 >= time.time()):
        BP.set_motor_power(BP.PORT_A,-30)
        BP.set_motor_power(BP.PORT_D,30)

def backUp(): 
    timeStart = time.time()
    while(grovepi.ultrasonicRead(ultrasonic_sensor_port1) < 15 and (grovepi.ultrasonicRead(ultrasonic_sensor_port3) < 15)):
        BP.set_motor_power(BP.PORT_A + BP.PORT_D, 30)

try:
    while True:
        if(grovepi.ultrasonicRead(ultrasonic_sensor_port2) < 21):
           if(grovepi.ultrasonicRead(ultrasonic_sensor_port1) < 15 and (grovepi.ultrasonicRead(ultrasonic_sensor_port3) < 15)):
               backUp()
           elif (grovepi.ultrasonicRead(ultrasonic_sensor_port3) < 15):
               turnRight()
           elif (grovepi.ultrasonicRead(ultrasonic_sensor_port1) < 15):
               turnLeft()
           break
        else:
            BP.set_motor_power(BP.PORT_A + BP.PORT_D, -30)
            
        checKMap()
        
except KeyboardInterrupt: # except the program gets interrupted by Ctrl+C on the keyboard.
    print(mazeMap[0], "\n", mazeMap[1], "\n", mazeMap[2], "\n", mazeMap[3], "\n", mazeMap[4], "\n", mazeMap[5], "\n", mazeMap[6], "\n")
    BP.reset_all()
Ejemplo n.º 22
0
                print msg
                print "temp: ", temp

        elif msg[:8].lower() == "humidity".lower():
            if en_grovepi:
                port = int(msg[8:])
                [temp, humidity] = grovepi.dht(port, 0)
                s.sensorupdate({'humidity': humidity})
            if en_debug:
                print msg
                print "humidity:", humidity

        elif msg[:8].lower() == "distance".lower():
            if en_grovepi:
                port = int(msg[8:])
                dist = grovepi.ultrasonicRead(port)
                s.sensorupdate({'distance': dist})
            if en_debug:
                print msg
                print "distance=", dist

        elif msg[:3].lower() == "lcd".lower():
            if en_grovepi:
                if en_debug:
                    print msg[:3], msg[3:6], msg[6:]
                import grove_rgb_lcd
                if msg[3:6].lower() == "col".lower(
                ):  #lower() added just for consistency. Not really needed
                    rgb = []
                    for i in range(0, 6, 2):
                        rgb.append(int(
Ejemplo n.º 23
0
import grovepi
from grove_rgb_lcd import *
"""This if-statement checks if you are running this python file directly. That 
is, if you run `python3 grovepi_sensors.py` in terminal, this if-statement will 
be true"""
if __name__ == '__main__':
    PORT = 4  # D4
    pot = 0  #A0

    setText("Start Measurement")
    setRGB(0, 128, 64)
    setText(" ")
    buf = " "

    while True:
        #So we do not poll the sensors too quickly which may introduce noise,
        #sleep for a reasonable time of 200ms between each iteration.
        pot_value = grovepi.analogRead(pot)
        read = grovepi.ultrasonicRead(PORT)

        if (read < pot_value):
            buf = " OBJ PRES"
            setRGB(255, 0, 0)
        else:
            buf = " "
            setRGB(0, 255, 0)

        setText_norefresh("{:<6} {:>9}\n{:<6}".format(
            str(pot_value) + "cm", buf,
            str(read) + "cm"))
Ejemplo n.º 24
0
import grovepi
import grovelcd
import grove6axis
import grovenfctag
import time

print "timestamp,button,temperature,ultrasound"
while True:
    button = grovepi.digitalRead(2)
    temperature = grovepi.analogRead(0)
    ultrasound = grovepi.ultrasonicRead(7)
    print time.time(), ",", button, ",", temperature, ",", ultrasound
Ejemplo n.º 25
0
  /usr/lib/python3.5
  /usr/local/lib/python3.5/dist-packages

The `sys` module, however, is a builtin that is written in and compiled in C for
performance. Because of this, you will not find this in the default directories.
"""
import sys
import time
# By appending the folder of all the GrovePi libraries to the system path here,
# we are successfully `import grovepi`
sys.path.append('../../Software/Python/')
# This append is to support importing the LCD library.
sys.path.append('../../Software/Python/grove_rgb_lcd')

import grovepi

"""This if-statement checks if you are running this python file directly. That 
is, if you run `python3 grovepi_sensors.py` in terminal, this if-statement will 
be true"""
if __name__ == '__main__':
    PORT = 4    # D4

    while True:
        #So we do not poll the sensors too quickly which may introduce noise,
        #sleep for a reasonable time of 200ms between each iteration.
        time.sleep(0.2)

        print(grovepi.ultrasonicRead(PORT))
	print ("EE250 Session 1 Complete")
    	print("Hello World")
Ejemplo n.º 26
0
led_status = 3
relay = 2
buzzer = 5

SMTP_USERNAME = ''  # Mail id of the sender
SMTP_PASSWORD = ''  # Pasword of the sender
SMTP_RECIPIENT = '' # Mail id of the reciever
SMTP_SERVER = 'smtp.gmail.com'  # Address of the SMTP server
SSL_PORT = 465

while True:     # in case of IO error, restart
    try:
        grovepi.pinMode(switch,"INPUT")
        while True:
            if grovepi.digitalRead(switch) == 1:    # If the system is ON
                if grovepi.ultrasonicRead() < 100:  # If a person walks through the door
                    print "Welcome"
                    grovepi.analogWrite(buzzer,100) # Make a sound on the Buzzer
                    time.sleep(.5)
                    grovepi.analogWrite(buzzer,0)       # Turn off the Buzzer
                    grovepi.digitalWrite(led_status,1)  # Turn on the status LED to indicate that someone has arrived
                    grovepi.digitalWrite(relay,1)       # turn on the Relay to activate an electrical device

                    # Take a picture from the Raspberry Pi camera
                    call (["raspistill -o i1.jpg -w 640 -h 480 -t 0"], shell=True)
                    print "Image Shot"
                    p = subprocess.Popen(["runlevel"], stdout=subprocess.PIPE)
                    out, err=p.communicate()    # Connect to the mail server
                    if out[2] == '0':
                        print 'Halt detected'
                        exit(0)
Ejemplo n.º 27
0
 def read(self):
     self.value = grovepi.ultrasonicRead(self.port)
     return self.value
Ejemplo n.º 28
0
# Connect two Grove Ultrasonic Rangers to digital ports D3 and D2
# SIG,NC,VCC,GND
ultrasonic_ranger1 = 3  # Ultrasonic Ranger at D3
ultrasonic_ranger2 = 2  # Ultrasonic Ranger at D2

sleepTime = int(sys.argv[1])  #sys.argv[1] is the first and only argument

t_end = time.time() + sleepTime

with picamera.PiCamera() as camera:
    camera.hflip = True
    camera.vflip = True
    camera.start_preview()
    camera.preview.alpha = 230

    while time.time() < t_end:

        try:
            # Get distance value
            distance1 = grovepi.ultrasonicRead(ultrasonic_ranger1)
            distance2 = grovepi.ultrasonicRead(ultrasonic_ranger2)
            R = min(distance1, distance2)
            R = str(R)
            camera.annotate_text = R
            time.sleep(.5)

        except (IOError, TypeError) as e:
            print "Error"

    camera.stop_preview()
Ejemplo n.º 29
0
grovepi.dust_sensor_en()
grovepi.setDustSensorInterval(5000)
grovepi.ir_recv_pin(ir)
# grovepi.ledBar_init(ledbar, 0)

data = {
    'sound': 0,
    'light': 0,
    'button': 0,
    'temp': 0,
    'humidity': 0,
    'prox': 0,
    'dust': 0,
    'ir': 3 * [0]
}

while True:
    data['sound'] = grovepi.analogRead(sound_sensor)
    data['light'] = grovepi.analogRead(light_sensor)
    # [data['temp'],data['humidity']] = grovepi.dht(dht_sensor,0)
    data['button'] = grovepi.digitalRead(button)
    data['prox'] = grovepi.ultrasonicRead(ultrasonic_ranger)
    data['dust'] = grovepi.dustSensorRead()
    grovepi.analogWrite(led, val % 256)
    # grovepi.ledBar_setBits(ledbar, val % 1024)
    if grovepi.ir_is_data():
        data['ir'] = list(grovepi.ir_read_signal())
    val += 10
    print(json.dumps(data))
    time.sleep(0.2)
Ejemplo n.º 30
0
# wallstop.py
import time
import brickpi3
import grovepi

BP = brickpi3.BrickPi3()

ultrasonic_sensor_port = 4

try:
    while grovepi.ultrasonicRead(ultrasonic_sensor_port) > 15:
        print("Sensor: %6d Motor A: %6d  B: %6d  C: %6d  D: %6d" \
         % (grovepi.ultrasonicRead(ultrasonic_sensor_port), \
          BP.get_motor_encoder(BP.PORT_A), \
          BP.get_motor_encoder(BP.PORT_B), \
          BP.get_motor_encoder(BP.PORT_C), \
          BP.get_motor_encoder(BP.PORT_D)))
        BP.set_motor_power(BP.PORT_A + BP.PORT_D, 30)
except IOError as error:
    print(error)
except TypeError as error:
    print(error)
except KeyboardInterrupt:
    print("You pressed ctrl+C...")

BP.offset_motor_encoder(BP.PORT_A, BP.get_motor_encoder(BP.PORT_A))
BP.offset_motor_encoder(BP.PORT_B, BP.get_motor_encoder(BP.PORT_B))
BP.offset_motor_encoder(BP.PORT_C, BP.get_motor_encoder(BP.PORT_C))
BP.offset_motor_encoder(BP.PORT_D, BP.get_motor_encoder(BP.PORT_D))

BP.reset_all()
Ejemplo n.º 31
0
def navigate():
    # algorithm information
    # uses PID control to maintain in the center of the lane
    # when it approaches a wall in front of it, it first checks if there is a wall to the left of it
    # if there is not, it turns left and moves forward without PID control until the left ultrasonic sensor reads values indicating the presence of a wall
    # if there is, it checks if there is a wall to the right of it
    # if there is not, it turns right and moves forward without PID control until the right ultrasonic sensor reads values indicating the presence of a wall
    # if there is, it turns 180 degrees
    # GEARS then resumes using PID control to maintain its position in the center of the lane

    global magValue
    global irValue
    global initGyro
    global solved
    global maxSideUltra
    global maxSingleSide
    global minFrontUltra
    global maxFrontUltra
    global tileSize

    KP = 0.25
    KI = 0.05
    KD = 0.02

    P = 0.0
    I = 0.0
    D = 0.0
    e = 0.0

    #e_prev = 0

    # check magnetic and IR values
    # Set origin and direction in mappingInit
    # Enable magnet and IR checking
    # Update tileSize global variable
    # Update origin x, origin y in mappingInit and BOTH mappingFinals

    mappingInit(3, 0, 0)
    # mappingInit(x-origin, y-origin, 0 N; 1 W; 2 S; 3 E)
    BP.offset_motor_encoder(leftMotor, BP.get_motor_encoder(leftMotor))
    while (solved == 0):
        while (grovepi.ultrasonicRead(ultrasonicLeft) +
               grovepi.ultrasonicRead(ultrasonicRight) > maxSideUltra):
            BP.set_motor_power(rightMotor, 13)
            BP.set_motor_power(leftMotor, -14)
        BP.set_motor_power(rightMotor, 0)
        BP.set_motor_power(leftMotor, 0)
        initGyro = BP.get_sensor(gyroscope)[0]
        e_prev = grovepi.ultrasonicRead(
            ultrasonicLeft) - grovepi.ultrasonicRead(ultrasonicRight)
        # keep and rather than or to support 4-way turning
        while (magValue == 0 and irValue == 0
               and grovepi.ultrasonicRead(ultrasonicLeft) +
               grovepi.ultrasonicRead(ultrasonicRight) < maxSideUltra
               and BP.get_sensor(ultrasonicFront) > minFrontUltra):
            time.sleep(timeStep)
            e = (grovepi.ultrasonicRead(ultrasonicLeft) -
                 grovepi.ultrasonicRead(ultrasonicRight)) + (
                     0.6 * (BP.get_sensor(gyroscope)[0] - initGyro))
            #print("e: " + str(e))
            if (abs(e) > 20
                    or grovepi.ultrasonicRead(ultrasonicLeft) > maxSingleSide
                    or
                    grovepi.ultrasonicRead(ultrasonicRight) > maxSingleSide):
                e = 0
            #print("Front: ")
            #print(BP.get_sensor(ultrasonicFront))
            #print("Left: ")
            #print(grovepi.ultrasonicRead(ultrasonicLeft))
            #print("Right: ")
            #print(grovepi.ultrasonicRead(ultrasonicRight))               # positive e means GEARS is too far right, negative e means GEARS is too far left
            P = KP * e
            I += KI * e * (timeStep * 20) / 2
            D = KD * (e - e_prev) / (timeStep * 20)
            powerModifier = P + I + D
            if (e > 0 and powerModifier < 0):
                powerModifier *= -1
            elif (e < 0 and powerModifier > 0):
                powerModifier *= -1
            #print("Power: " + str(powerModifier))
            BP.set_motor_power(rightMotor, 20 + powerModifier)
            BP.set_motor_power(leftMotor, -20 + powerModifier)
            e_prev = e
            identifyMagnet()
            identifyIR()
            time.sleep(timeStep * 55)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            mappingTrack(BP.get_motor_encoder(leftMotor), 0, tileSize)
        BP.set_motor_power(rightMotor, 0)
        BP.set_motor_power(leftMotor, 0)
        mazeTurn()
    cargo(1)
    cargo(0)
    mappingFinal(3, 0, 6, tileSize, 1)
Ejemplo n.º 32
0
sys.path.append('../../Software/Python/')
# This append is to support importing the LCD library.
sys.path.append('../../Software/Python/grove_rgb_lcd')
import grovepi

ultPrt = 4 # D4 is the port for ultrasonic ranger
           
# Moving average of distance values from USR 
t = 10
fs = 20
distance_window = []
ts = []

for i in range(t * fs):
    # Poll USR value   
    time.sleep(0.05)
    distance_window.append(grovepi.ultrasonicRead(ultPrt))
    ts.append(i)
    print(distance_window[i])
            
# Publish user's average distance over 10 seconds sampled at 20Hz to /users
avg_distance = sum(distance_window[:]) / len(distance_window)
print(len(ts))
print(len(distance_window))
print(avg_distance)

plt.scatter(ts, distance_window)
plt.show() 

Ejemplo n.º 33
0
def main():
    global isConnected
    # Create an MQTT client for connecting to AWS IoT via MQTT.
    client = mqtt.Client(deviceName + "_sr")  # Client ID must be unique because AWS will disconnect any duplicates.
    client.on_connect = on_connect  # When connected, call on_connect.
    client.on_message = on_message  # When message received, call on_message.
    client.on_log = on_log  # When logging debug messages, call on_log.

    # Set the certificates and private key for connecting to AWS IoT.  TLS 1.2 is mandatory for AWS IoT and is supported
    # only in Python 3.4 and later, compiled with OpenSSL 1.0.1 and later.
    client.tls_set(awsCert, deviceCertificate, devicePrivateKey, ssl.CERT_REQUIRED, ssl.PROTOCOL_TLSv1_2)

    # Connect to AWS IoT server.  Use AWS command line "aws iot describe-endpoint" to get the address.
    print("Connecting to AWS IoT...")
    client.connect("A1P01IYM2DOZA0.iot.us-west-2.amazonaws.com", 8883, 60)

    # Start a background thread to process the MQTT network commands concurrently, including auto-reconnection.
    client.loop_start()

    # Create the beacon service for scanning beacons.
    beacon_service = ble.BeaconService()

    # Loop forever.
    while True:
        try:
            # If we are not connected yet to AWS IoT, wait 1 second and try again.
            if not isConnected:
                time.sleep(1)
                continue

            # Scan for beacons and add to the sensor data payload.
            beacons = {}
            # Nick: Added to initialise beacon_id value
            beacon_id = ""
            beacons_detected = beacon_service.scan(2)
            for beacon_address, beacon_info in list(beacons_detected.items()):
                # For each beacon found, add to the payload. Need to flip the bytes.
                beacon = {
                    "uuid": beacon_info[0].replace('-', ''),
                    "major": (beacon_info[1] % 256) * 256 + beacon_info[1] // 256,
                    "minor": (beacon_info[2] % 256) * 256 + beacon_info[2] // 256,
                    "power": beacon_info[3],
                    "rssi": beacon_info[4],
                    "address": beacon_address
                }
                # Beacon ID is B_(uuid)_(major)_(minor). This format allows us
                # to match beacon IDs within IoT rules. Prepad major and minor
                # with 0s to max length, so that we can slice beacons by fixed
                # length in IoT rules. Sample beacon ID:
                # "B_b9407f30f5f8466eaff925556b57fe6d_00602_29434"
                beacon_id = "B_" + beacon["uuid"] + "_" + \
                            str(beacon["major"]).rjust(5, '0') + "_" + \
                            str(beacon["minor"]).rjust(5, '0')
                # Nick: Originally beacon["id"] = beacons
                beacon["id"] = beacon_id
                beacons[beacon_id] = beacon

            # Prepare our sensor data in JSON format.
            # Nick: For beacon, only send beacon_id since it is uniquely identifiable incl. UUID+major+minor
            payload = {
                "state": {
                    "reported": {
                        "cplot": "lot1",
                        "beacons": beacon_id,
                        "distance": grovepi.ultrasonicRead(ultrasonic_ranger),
                        "timestamp": datetime.datetime.now().isoformat()
                    }
                }
            }


            print("Sending sensor data to AWS IoT...\n" +
                  json.dumps(payload, indent=4, separators=(',', ': ')))

            # Publish our sensor data to AWS IoT via the MQTT topic, also known as updating our "Thing Shadow".
            client.publish("$aws/things/" + deviceName + "/shadow/update", json.dumps(payload))
            print("Sent to AWS IoT")

            # Wait 30 seconds before sending the next set of sensor data.
            time.sleep(30)

        except KeyboardInterrupt:
            # Stop the program when we press Ctrl-C.
            break
        except Exception as e:
            # For all other errors, we wait a while and resume.
            print("Exception: " + str(e))
            time.sleep(10)
            continue
Ejemplo n.º 34
0
        if timeTick == timeCycle:
            timeTick = 0
            cursor = homeonDB.find({"name": "desk_light_0"})
            for document in cursor:
                if (document["status"]["power"] == "on"):
                    isLightUp = True
                else:
                    isLightUp = False

                if (document["mode"] == "auto"):
                    auto_mode = True
                else:
                    auto_mode = False

            if auto_mode:
                ul1 = grovepi.ultrasonicRead(ultrasonic_ranger)
                time.sleep(0.5)
                ul2 = grovepi.ultrasonicRead(ultrasonic_ranger)
                time.sleep(0.5)
                ul3 = grovepi.ultrasonicRead(ultrasonic_ranger)
                if ul1 > 100 and ul2 > 100 and ul3 > 100:
                    now = datetime.datetime.now()
                    datetime_string = str(now.year) + "" + str(now.strftime('%m')) + "" + str(now.strftime('%d')) + "-" + str(now.strftime('%H')) + "" + str(now.strftime('%M')) + "" + str(now.strftime('%S'))
                    print(datetime_string + ": No body is here. Ultrasonic sensed: " + str(ul1) + " " + str(ul2) + " " + str(ul3))
                    if isLightUp and auto_mode:
                        print(datetime_string + ": Light is on, auto mode is on. Turn light off.")
                        # loop through pins and set them up
                        for i in pinList:
                            GPIO.setup(i, GPIO.OUT)
                        GPIO.output(24, GPIO.HIGH)
                        homeonDB.update_one(
        # Detect motion and log when there are changes
        if grovepi.digitalRead(PIR_SENSOR_PIN):
            if lastValue != "active":
                lastValue = "active"
                streamer.log (ROOM_NAME + " Motion", lastValue)
                streamer.flush()
                print 'Motion Detected'
        else:
            if lastValue != "inactive":
                lastValue = "inactive"
                streamer.log (ROOM_NAME + " Motion", lastValue)
                streamer.flush()
                print '-'
 
        # If distance value from Ultrasonic is less than 60 cm, log it
        proximity = grovepi.ultrasonicRead(USR_SENSOR_PIN)
        if proximity < 60:
            if proximity != lastProximity:
                if not compromised:
                    streamer.log(OBJECT_NAME + " Compromised", OBJECT_EMOJI_TOKEN)
                    compromised = True
                streamer.log ("Proximity to " + OBJECT_NAME + "(cm)", proximity)
                streamer.flush()
                print proximity
                lastProximity = proximity
        # Safe distance away
        else:
            proximity = 1000
            compromised = False
            if lastProximity != 1000:
                streamer.log ("Proximity to " + OBJECT_NAME + "(cm)", proximity)
Ejemplo n.º 36
0
    print("on_message: " + msg.topic + " " + str(msg.payload, "utf-8"))


if __name__ == '__main__':
    print("test")
    ultrasonic_ranger = 4 
    client = mqtt.Client()  
    client.on_message = on_message 
    client.on_connect = on_connect
    client.connect(host="eclipse.usc.edu", port=11000, keepalive=60) 
    client.loop_start() 
    while True:
        
        with i2c_lock: 
            try:
                ultrasonic_value = grovepi.ultrasonicRead(ultrasonic_ranger) 
                print(str(ultrasonic_value))
                if ultrasonic_value < 200:
                    state = 1
                    sensorstring = str(ultrasonic_value)
                    client.publish("avipi/targetAcquired", "target acquired at " +
                    sensorstring)
                    while True:
                        ultrasonic_value = grovepi.ultrasonicRead(ultrasonic_ranger) 
                        if ultrasonic_value > 350:
                            state = 0
                            client.publish("avipi/targetAcquired", "target lost")
                            break
            except KeyboardInterrupt: 
                break
            except IOError:
Ejemplo n.º 37
0
    ori_list = list(ori)
    # x = ori_list[0] * 180.0 / math.pi
    y = ori_list[1] * 180.0 / math.pi
    # z = ori_list[2] * 180.0 / math.pi
    # returns orientation as yaw,pitch,roll
    # ori_list = list(ori)
    # pitch = ori_list[2] * 180.0 / math.pi
    a = grove6axis.getAccel()
    a_list = list(a)
    # x_a = accel_list[0]
    y_a = a_list[1]
    # z_a = accel_list[2]

    motion = grovepi.digitalRead(3)
    # read from Ultrasonic sensor on input D3
    ultra = grovepi.ultrasonicRead(4)
    # Filter1 De-trending / high pass filter:
    # it removes long term bias and drift & show short term variations
    ultra_high = constant * (ultra_high + ultra - ultra_last)
    ultra_last = ultra
    # Filter2 Smoothing / low pass filter:
    # it removes random noise & shows longer term variations
    ultra_low = ultra_low * (1.0 - constant) + ultra * constant
    # Filter3 Median / Non linear filter
    historyBuffer.append(ultra)
    orderedHistory = sorted(historyBuffer)
    ultra_median = orderedHistory[int(len(orderedHistory) / 2)]

    #output the data
    print(time, y, y_a, motion, ultra, ultra_high, ultra_low, ultra_median)
    # returns orientation as yaw,pitch,roll
Ejemplo n.º 38
0
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import grovepi

# Connect the Grove Ultrasonic Ranger to digital port D4
# SIG,NC,VCC,GND
ultrasonic_ranger = 4

while True:
    try:
        # Read distance value from Ultrasonic
        print((grovepi.ultrasonicRead(ultrasonic_ranger)))

    except TypeError:
        print ("Error")
    except IOError:
        print ("Error")
Ejemplo n.º 39
0
try:
	options = {
	"org": "z4cnep",
	"type": "RaspberryPi",
	"id": "000000001bb887a7",
	"auth-method": "token",
	"auth-token": "6xzR?XvuXGVd2+k?qq"
	}
	client = ibmiotf.device.Client(options)
	client.connect()

	ultrasonic_ranger = 4
	while True:
		try:
		  # Read distance value from Ultrasonic
		  myData={'distance' : grovepi.ultrasonicRead(ultrasonic_ranger)}
		  client.publishEvent("status", "json", myData)
		  time.sleep(10)
		except:
			print ("Error reading ultrasonic")
			

except ibmiotf.ConnectionException  as e:
	print(e)


def sendRequest(reading):
	headers = {"Contect-type": "application/x-www-form-urlencoded"}
	conn = httplib.HTTPConnection("knuckleballers.mybluemix.net")
	conn.request("POST", "/server_post", "reading=" +readings, headers)
	repsonse = conn.getresponse()
Ejemplo n.º 40
0
import grovepi
import grovelcd
import time

grovepi.pinMode(3,"OUTPUT")

print "time,ultra,analog"
while True:
    ultra=grovepi.ultrasonicRead(2)
    ana=grovepi.analogRead(0)
    digi=grovepi.digitalRead(4)
    grovepi.analogWrite(3,ultra/2)
    grovelcd.setRGB(ultra/2,200-ultra/2,0)
    txt="%d - %d\n wooo yay"%(digi, ana)
    grovelcd.setText(txt,True)
    print "%f,%d,%d"%(time.time(),ultra,ana)
    time.sleep(0.1)
Ejemplo n.º 41
0
def mazeTurn():
    # turning algorithm for GEARS turning within the maze
    global magValue
    global irValue
    global initGyro
    global solved
    global maxSideUltra
    global maxSingleSide
    global minFrontUltra
    global maxFrontUltra
    global tileSize

    BP.set_motor_power(rightMotor, 13)
    BP.set_motor_power(leftMotor, -13)
    time.sleep(.85)
    BP.set_motor_power(rightMotor, 0)
    BP.set_motor_power(leftMotor, -0)

    # and rather than or allows 4-way intersection support
    if (magValue == 0 and irValue == 0
            and grovepi.ultrasonicRead(ultrasonicLeft) +
            grovepi.ultrasonicRead(ultrasonicRight) < maxSideUltra
            and BP.get_sensor(ultrasonicFront) > minFrontUltra):
        time.sleep(timeStep)
    elif (grovepi.ultrasonicRead(ultrasonicLeft) > maxSingleSide):
        mappingTrack(0, -1, tileSize)
        turnToPoint(initGyro)
        initGyro -= 90
        # if there isn't a wall 40 cm or less away from the left of GEARS
        time.sleep(timeStep * 4)
        if (BP.get_sensor(ultrasonicFront) < 40):
            # 3-way intersection
            time.sleep(timeStep * 4)
            while (BP.get_sensor(ultrasonicFront) > maxFrontUltra):
                time.sleep(timeStep * 4)
                BP.set_motor_power(rightMotor, 12)
                BP.set_motor_power(leftMotor, -15)
                time.sleep(timeStep * 10)
                BP.set_motor_power(rightMotor, 0)
                BP.set_motor_power(leftMotor, 0)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            centerPointTurning(90, 0)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            elapsed = 0
            start = time.time()
            while (grovepi.ultrasonicRead(ultrasonicLeft) > maxSingleSide
                   and grovepi.ultrasonicRead(ultrasonicRight) > maxSingleSide
                   and elapsed < 5):
                BP.set_motor_power(rightMotor, 12)
                BP.set_motor_power(leftMotor, -15)
                time.sleep(timeStep * 4)
                end = time.time()
                elapsed = end - start
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            # complete maze condition
            if (elapsed >= 5):
                BP.set_motor_power(rightMotor, -12)
                BP.set_motor_power(leftMotor, 15)
                time.sleep(5)
                BP.set_motor_power(rightMotor, 0)
                BP.set_motor_power(leftMotor, 0)
                solved = 1
        else:
            # 4-way intersection
            BP.offset_motor_encoder(leftMotor, BP.get_motor_encoder(leftMotor))
            while (BP.get_motor_encoder(leftMotor) > -185):
                BP.set_motor_power(rightMotor, 9)
                BP.set_motor_power(leftMotor, -11)
                time.sleep(timeStep * 4)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            centerPointTurning(90, 0)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            elapsed = 0
            start = time.time()
            while (grovepi.ultrasonicRead(ultrasonicLeft) > maxSingleSide
                   and grovepi.ultrasonicRead(ultrasonicRight) > maxSingleSide
                   and elapsed < 5):
                BP.set_motor_power(rightMotor, 9)
                BP.set_motor_power(leftMotor, -11)
                time.sleep(timeStep * 4)
                end = time.time()
                elapsed = end - start
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            # complete maze condition
            if (elapsed >= 5):
                BP.set_motor_power(rightMotor, -9)
                BP.set_motor_power(leftMotor, 11)
                time.sleep(5)
                BP.set_motor_power(rightMotor, 0)
                BP.set_motor_power(leftMotor, 0)
                solved = 1
    elif (grovepi.ultrasonicRead(ultrasonicRight) > maxSingleSide
          and BP.get_sensor(ultrasonicFront) < 40):
        mappingTrack(0, -1, tileSize)
        turnToPoint(initGyro)
        initGyro += 90
        # if there isn't a wall 40 cm or less away from the right of GEARS
        time.sleep(timeStep * 4)
        if (BP.get_sensor(ultrasonicFront) < 40):
            # 3-way intersection
            time.sleep(timeStep * 4)
            while (BP.get_sensor(ultrasonicFront) > maxFrontUltra):
                BP.set_motor_power(rightMotor, 11)
                BP.set_motor_power(leftMotor, -9)
                time.sleep(timeStep * 10)
                BP.set_motor_power(rightMotor, 0)
                BP.set_motor_power(leftMotor, 0)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            centerPointTurning(90, 1)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            while (grovepi.ultrasonicRead(ultrasonicLeft) > maxSingleSide and
                   grovepi.ultrasonicRead(ultrasonicRight) > maxSingleSide):
                BP.set_motor_power(rightMotor, 9)
                BP.set_motor_power(leftMotor, -11)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
        else:
            # 4-way intersection
            BP.offset_motor_encoder(leftMotor, BP.get_motor_encoder(leftMotor))
            while (BP.get_motor_encoder(leftMotor) > -185):
                BP.set_motor_power(rightMotor, 9)
                BP.set_motor_power(leftMotor, -11)
                time.sleep(timeStep * 4)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            centerPointTurning(90, 1)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
            while (grovepi.ultrasonicRead(ultrasonicLeft) > maxSingleSide and
                   grovepi.ultrasonicRead(ultrasonicRight) > maxSingleSide):
                time.sleep(timeStep * 4)
                BP.set_motor_power(rightMotor, 9)
                BP.set_motor_power(leftMotor, -11)
                time.sleep(timeStep * 10)
                BP.set_motor_power(rightMotor, 0)
                BP.set_motor_power(leftMotor, 0)
            BP.set_motor_power(rightMotor, 0)
            BP.set_motor_power(leftMotor, 0)
    elif (BP.get_sensor(ultrasonicFront) > minFrontUltra):
        time.sleep(timeStep)
    else:
        # walls are present both to the left and right of GEARS
        turnToPoint(initGyro)
        initGyro += 180
        centerPointTurning(180, 1)
Ejemplo n.º 42
0
import time
import grovepi
import httplib



ultrasonic_ranger = 4
while True:
	try:
	  # Read distance value from Ultrasonic
	  sendRequest(str(grovepi.ultrasonicRead(ultrasonic_ranger)))
	except:
		print ("Error reading ultrasonic")
		time.sleep(10)
			




def sendRequest(reading):
	headers = {"Contect-type": "application/x-www-form-urlencoded"}
	conn = httplib.HTTPConnection("knuckleballers.mybluemix.net")
	conn.request("POST", "/server_post", "reading=" +readings, headers)
	repsonse = conn.getresponse()
	print response.status, response.reason
	data = response.read()
	conn.close()


# Eric's change is here!
Ejemplo n.º 43
0

import time
import picamera
import sys

import grovepi
from grovepi import *

sleepTime = float(sys.argv[1])	#sys.argv[1] is the first and only argument

# Connect the Grove Ultrasonic Ranger to digital port D3
# SIG,NC,VCC,GND
ultrasonic_ranger = 3

with picamera.PiCamera() as camera:
    camera.hflip = True
    camera.vflip = False    
    camera.start_preview()
    while True:
	try:
                
                # Get distance value
                distance = grovepi.ultrasonicRead(ultrasonic_ranger)
                L = str(distance)
                
                camera.annotate_text = L
                camera.preview.alpha = 230
    time.sleep(sleepTime)
    camera.stop_preview()
Ejemplo n.º 44
0
try:
    while True:
        #PID control
        dist_front = BP.get_sensor(us_front)
        e = target - dist_front
        print("%d cm from the wall " % dist_front)

        P = KP * e
        I += KI * e * dT / 2
        D = KD * (e - e_prev) / dT

        power_in = P + I + D
        e_prev = e
        BP.set_motor_power(BP.PORT_B + BP.PORT_C, -power_in)

        #left/right sensors
        dist_left = grovepi.ultrasonicRead(us_left)
        if (dist_left > 50):
            dist_left = 50
        dist_right = grovepi.ultrasonicRead(us_right)
        if (dist_right > 50):
            dist_right = 50
        print("left: %d right: %d" % (dist_left, dist_right))

        time.sleep(dT)

except KeyboardInterrupt:  # except the program gets interrupted by Ctrl+C on the keyboard.
    print('You pressed ctrl+c..')
    BP.set_motor_power(BP.PORT_B + BP.PORT_C, 0)
    BP.reset_all()
Ejemplo n.º 45
0
import grovepi
import urllib2
import json
import time
import requests
import lcd

#ports for buttons that will be updating values in the database
sensor1 = 2
sensor2 = 3

button1 = 0
button2 = 0

piID = 2
lcd.setText("Hi, I'm pi number" + str(piID))
while (true):
    if (grovepi.ultrasonicRead(sensor1) <= 10)
        button1 = 1
    if (grovepi.ultrasonicRead(sensor2) <= 10)
        button2 = 1

    #if the value isnt already one, set it to one when the corresponding button's pressed
    if (json.loads(urllib2.urlopen("http://andrew.local:1337/pull/?id=").read())["response"]["sensors"]["button1"]["value"] == 0):
        requests.post("http://andrew.local:1337/push/?id=" + piID + "&name=button1&value=" + button1)
    if (json.loads(urllib2.urlopen("http://andrew.local:1337/pull/?id=").read())["response"]["sensors"]["button2"]["value"] == 0):
        requests.post("http://andrew.local:1337/push/?id=" + piID + "&name=button2&value=" + button2)
    time.sleep(.1)
Ejemplo n.º 46
0
name = "Distance"                      # Descriptive name for your device, put '+' for space char

# Sensor settings
ranger = 4                             # Ultrasonic Ranger is connected to port D4

# Other global variables
baseurl = "http://piland.socialdevices.io"
baseurl = baseurl + "/" + str(room) + "/write/" + str(slot) + "?name=" + name + "&value="

while True:
  
  try:

    # Read the ultrasonic ranger distance

    distance_cm = grovepi.ultrasonicRead(ranger)

    url = baseurl + "%d" % distance_cm + "+cm"

    print url

    requests.get(url)    # write data

    time.sleep(2.0)      # 2 second delay

  except KeyboardInterrupt:
    print "Terminating"
    break
  except IOError:
    print "IOError"
  except:
Ejemplo n.º 47
0
SMTP_PASSWORD = '******'  # Password of the sender
SMTP_RECIPIENT = '*****@*****.**'  # Mail id of the reciever
SMTP_SERVER = 'mail.myserverhere.com'  # Address of the SMTP server
SSL_PORT = 465
FTP_SITE = 'someserver.com'
FTP_USER = '******'
FTP_PASSWORD = '******'

while True:  # in case of IO error, restart
    try:
        grovepi.pinMode(switch, "INPUT")
        while True:
            if grovepi.digitalRead(switch) == 1:  # If the system is ON
                # by Mister Ed - added ranger variable to pass, otherwise fatal errors
                if grovepi.ultrasonicRead(
                        ultrasonic_ranger
                ) < 5:  # If a person walks through the door
                    print("Welcome")
                    grovepi.analogWrite(buzzer,
                                        100)  # Make a sound on the Buzzer
                    time.sleep(.5)
                    grovepi.analogWrite(buzzer, 0)  # Turn off the Buzzer
                    grovepi.digitalWrite(
                        led_status, 1
                    )  # Turn on the status LED to indicate that someone has arrived
                    grovepi.digitalWrite(
                        relay, 1
                    )  # turn on the Relay to activate an electrical device

                    # Take a picture from the Raspberry Pi camera
                    # Mister Ed -- edited delay to take snap shot to lowest value but still reliable
Ejemplo n.º 48
0
    parser.add_argument("-u", "--ultrasonicranger",
        help = "Specify which ultrasonic ranger to subscribe to (1 or 2)",
                            default = 1) 
    args = parser.parse_args()

    distance = 0

    if args.ultrasonicranger == '1':
        topic = ultrasonic_ranger1_topic
    elif args.ultrasonicranger == '2':
        topic = ultrasonic_ranger2_topic

    client = mqtt.Client()
    client.on_message = on_message
    client.on_connect = on_connect
    client.connect(mqtt_broker_hostname, mqtt_broker_port, keepalive=60)
    # have paho.mqtt spawn a background thread for us
    client.loop_start()

    while True:
        if TEST:
            distance = (distance + 1) % 10
            time.sleep(0.2)
        else:
            #ultrasonicRead() has a 60ms delay
            distance = grovepi.ultrasonicRead(grovepi_digital_port) 
            time.sleep(0.130)

        print("topic: " + topic + ", distance (cm): " + str(distance))
        client.publish(topic, distance)
Ejemplo n.º 49
0
def main():
    global isConnected
    # Create an MQTT client for connecting to AWS IoT via MQTT.
    client = mqtt.Client(deviceName + "_sr")  # Client ID must be unique because AWS will disconnect any duplicates.
    client.on_connect = on_connect  # When connected, call on_connect.
    client.on_message = on_message  # When message received, call on_message.
    client.on_log = on_log          # When logging debug messages, call on_log.

    # Set the certificates and private key for connecting to AWS IoT.  TLS 1.2 is mandatory for AWS IoT and is supported
    # only in Python 3.4 and later, compiled with OpenSSL 1.0.1 and later.
    client.tls_set(awsCert, deviceCertificate, devicePrivateKey, ssl.CERT_REQUIRED, ssl.PROTOCOL_TLSv1_2)

    # Connect to AWS IoT server.  Use AWS command line "aws iot describe-endpoint" to get the address.
    print("Connecting to AWS IoT...")
    client.connect("A1P01IYM2DOZA0.iot.us-west-2.amazonaws.com", 8883, 60)

    # Start a background thread to process the MQTT network commands concurrently, including auto-reconnection.
    client.loop_start()

    # Configure the Grove LED port for output.
    grovepi.pinMode(led, "OUTPUT")
    time.sleep(1)

    detected=0

    # Loop forever.
    while True:
        try:
            # If we are not connected yet to AWS IoT, wait 1 second and try again.
            if not isConnected:
                time.sleep(1)
                continue

            # Scanning mode - 
            while (grovepi.ultrasonicRead(ultrasonic_ranger)>Dist_Thres):
                print("[Sensor] no detection @ "+datetime.datetime.now().isoformat())
                time.sleep(3)

            # Verification mode - 
            detected=1
            for i in range(1,10):
                if (grovepi.ultrasonicRead(ultrasonic_ranger)<Dist_Thres):
                    print("[Sensor] possible detection? @ "+datetime.datetime.now().isoformat())
                    grovepi.digitalWrite(led,1)
                    grovepi.digitalWrite(led,0)
                else:
                    detected=0
                    break

            if (detected==1):
                # Read Grove sensor values. Prepare our sensor data in JSON format.
                print("[Sensor] confirmed detection!")
                postToSlack(device, "Detection at " + device_loc)
                grovepi.digitalWrite(led,1)
                payload = {
                    "state": {
                        "reported": {
                            "timestamp": datetime.datetime.now().isoformat(),
                            "distance": grovepi.ultrasonicRead(ultrasonic_ranger)
                        }
                    }
                }
                print("Sending sensor data to AWS IoT...\n" +
                      json.dumps(payload, indent=4, separators=(',', ': ')))

                # Publish our sensor data to AWS IoT via the MQTT topic, also known as updating our "Thing Shadow".
                client.publish("$aws/things/" + deviceName + "/shadow/update", json.dumps(payload))
                print("Sent to AWS IoT")

                while (grovepi.ultrasonicRead(ultrasonic_ranger)<Dist_Thres):
                    print("[Sensor] detection still positive ...")
                grovepi.digitalWrite(led,0)
                print("[Sensor] no detection!")
                postToSlack(device, "No more detection at " + device_loc)

        except KeyboardInterrupt:
            break
        except IOError:
            print("Error")
Ejemplo n.º 50
0
    print( 'ioType: ' + ioType )

    grovepi.digitalWrite( int(port), int(value) )
    
    return "Success\n"

#Adding capabilities
requests.post("http://andrew.local:1337/add_capability/?moteId=" + id + "&name=led&ioType=" + str(2) + "&port=" + str(red))
requests.post("http://andrew.local:1337/add_capability/?moteId=" + id + "&name=led&ioType=" + str(2) + "&port=" + str(blue))

#Main loop of game
while True:
	lcd.setText("Play Simon!");
	lcd.setRGB(128,128,128)

	readyToPlay = (grovepi.ultrasonicRead(redSens) < 200) or (grovepi.ultrasonicRead(blueSens) < 200)
	if readyToPlay:
		lcd.setText("Let's play!")
		lcd.setRGB(255,0,255)

		#Tells server game is started
		requests.post("http://andrew.local:1337/user_interaction/?id=13371c825290295966131f43f818ecca")
		lost = False
		try:
			#establish light colors
			for item in range(0,gameLength):
				if random.randint(1, 2) == 1:
					selectionLog[item] = 0
				else: 
					selectionLog[item] = 1
Ejemplo n.º 51
0
				print msg
				print "temp: ",temp
		
		elif msg[:8].lower()=="humidity".lower():
			if en_grovepi:
				port=int(msg[8:])
				[temp,humidity] = grovepi.dht(port,0)
				s.sensorupdate({'humidity':humidity})
			if en_debug:
				print msg
				print "humidity:",humidity
		
		elif msg[:8].lower()=="distance".lower():
			if en_grovepi:
				port=int(msg[8:])
				dist=grovepi.ultrasonicRead(port)
				s.sensorupdate({'distance':dist})
			if en_debug:
				print msg
				print "distance=",dist	
		
		elif msg[:3].lower()=="lcd".lower():
			if en_grovepi:
				if en_debug:
					print msg[:3], msg[3:6],msg[6:]
				import grove_rgb_lcd 
				if msg[3:6].lower() == "col".lower():
					rgb = []
					for i in range(0,6,2): 
						rgb.append(int(msg[6:][i:i+2],16))  # convert from one hex string to three ints
					if en_debug:
Ejemplo n.º 52
0
import grovepi
import time
while True:
    #read from 6-Axis Accelerometer&Compass sensor on input
    #read from Tilt sensor on input D4
    #d4= grovepi.digitalRead(4)

    #read from Ultrasonic sensor on input D3
    d3 = grovepi.ultrasonicRead(3)
    #output the data
    print("Ultrasonic_Distance:", d3)
    # Read roughly 10 times a second
    #  - n.b. analog read takes time to do also
    #  set the time for 1s to display data
    time.sleep(2)