def main(): ip = get_ip_address() hostname = socket.gethostname() sensor = LIS3DH() sensor.setRange(LIS3DH.RANGE_2G) data = {} while True: x = sensor.getX() y = sensor.getY() z = sensor.getZ() button_pressed = GPIO.input(BUTTON_PIN) == 1 light_level = sensor.getADC(sensor.ADC_1) humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, dht_pin) if humidity is not None and temperature is not None: data['temperature'] = str(round(temperature, 2)) data['humidity'] = str(round(humidity, 2)) else: data['temperature'] = 0 data['humidity'] = 0 data['button_pressed'] = button_pressed data['orientation'] = {'x': x, 'y': y, 'z': z} data['ip_address'] = ip data['hostname'] = hostname print(data) time.sleep(.2)
def main(): ip = get_ip_address() hostname = socket.gethostname() with open('/home/pi/deviceinfo.json') as json_data: device_config = json.load(json_data) client = pubsub.Client(project="iot-tech-bootcamp") topic = client.topic("bootcamp") sensor = LIS3DH() sensor.setRange(LIS3DH.RANGE_2G) data = {} while True: d = datetime.utcnow() x = sensor.getX() y = sensor.getY() z = sensor.getZ() button_pressed = GPIO.input(BUTTON_PIN) == 1 # We "invert" the value by subtracting from 2700 # and convert to integer light_level = 2700 - int(sensor.getADC(sensor.ADC_1)) # get data from the dht22 sensor humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, dht_pin) data['device_id'] = device_config['id'] data['city'] = device_config['city'] data['country'] = device_config['country'] data['region'] = device_config['region'] data['lat'] = device_config['lat'] data['long'] = device_config['lng'] data["timestamp"] = d.isoformat("T") + "Z" data['light_level'] = light_level data['button_pressed'] = button_pressed data['orientation'] = {'x': x, 'y': y, 'z': z} if humidity is not None and temperature is not None: data['temperature'] = str(round(temperature, 2)) data['humidity'] = str(round(humidity, 2)) else: data['temperature'] = 0 data['humidity'] = 0 data['ip_address'] = ip data['hostname'] = hostname print(data) try: topic.publish(json.dumps(data).encode('utf-8'), timestamp=data["timestamp"]) except: print("Failed to submit to PubSub. Trying again...") pass time.sleep(1)
def Accelerometer_sensor(self, serial, timer, reed_input, movingcar, last_alert, start_program, lastx, lasty, lastz): Accelerometer = LIS3DH() reed_bit = 0 x = Accelerometer.getX() y = Accelerometer.getY() z = Accelerometer.getZ() if start_program == 0: #prevents false acceleration alerts i = 0 start_program = 1 lastx = x lasty = y lastz = z #print("\rnewlastX: %.6f\tnewlastY: %.6f\tnewlastZ: %.6f \t m/s^2" % (x, y, z)) # Display results (acceleration is measured in m/s^2) print("\rX: %.6f\tY: %.6f\tZ: %.6f \td m/s^2" % (x, y, z)) #print("\rlastX: %.6f\tlastY: %.6f\tlastZ: %.6f \t m/s^2" % (lastx, lasty, lastz)) if reed_input == 1: #check if child is buckled print("Seat belt buckled") else: print("Seat unbuckled") if accelerometer_sensor.rateAccel(self, movingcar, x, y, z, lastx, lasty, lastz) == 1: #if car is moving if reed_input == 0: #if seat is unbuckled update last_alert if last_alert == 0: #If parent hasn't been notified last_alert = timer #Update last_alert time reed_bit = 1 #trigger danger_temp_alert() SMS warning if ( timer - last_alert ) > 60 * 5: #If it's been more than 5 minutes since the last alert send another last_alert = timer #Update last_alert time reed_bit = 1 #trigger danger_temp_alert() SMS warning #start_program = 0 #reset program values #Update coordinate values lastx = x lasty = y lastz = z return { "reed_bit": reed_bit, "last_alert": last_alert, "start_program": start_program, "lastx": lastx, "lasty": lasty, "lastz": lastz }
def main(): sensor = LIS3DH() sensor.setRange(LIS3DH.RANGE_2G) while True: x = sensor.getX() y = sensor.getY() z = sensor.getZ() print("X = " + x) print("Y = " + y) print("Z = " + z) sleep(0.5)
def main(): sensor = LIS3DH() sensor.setRange(LIS3DH.RANGE_2G) while True: x = sensor.getX() y = sensor.getY() z = sensor.getZ() button_pressed = GPIO.input(BUTTON_PIN) == 1 print("button: %s orientation: X: %.6f\tY: %.6f\tZ: %.6f" % (button_pressed, x, y, z)) time.sleep(.2)
def acquire_data(q, fs, T_D_new): sensor = LIS3DH(debug=True) sensor.setRange(LIS3DH.RANGE_8G) data = numpy.zeros((fs * T_D_new, 3)) while True: # when there's no hardware for i in range(T_D_new * fs): data[i, 0] = sensor.getX() data[i, 1] = sensor.getY() data[i, 2] - sensor.getZ() data = numpy.random.rand(100, 3) q.put(data)
def Accelerometer_sensor(self, timer, reed_input, movingcar, last_alert, start_program, lastx, lasty, lastz): Accelerometer = LIS3DH() reed_bit = 0 x = Accelerometer.getX() y = Accelerometer.getY() z = Accelerometer.getZ() if start_program == 0: #prevents false acceleration alerts i = 0 start_program = 1 lastx = x lasty = y lastz = z if reed_input == 1: #check if child is buckled print("Seat belt buckled") else: print("Seat unbuckled") if accelerometer_sensor.rateAccel(self, movingcar, x, y, z, lastx, lasty, lastz) == 1: #if car is moving if reed_input == 0: #if seat is unbuckled update last_alert if last_alert == 0: #If parent hasn't been notified last_alert = timer #Update last_alert time reed_bit = 1 #trigger seat_belt_alert() SMS warning if ( timer - last_alert ) > 60 * 5: #If it's been more than 5 minutes since the last alert send another last_alert = timer #Update last_alert time reed_bit = 1 #trigger seat_belt_alert() SMS warning #Update coordinate values lastx = x lasty = y lastz = z return { "reed_bit": reed_bit, "last_alert": last_alert, "start_program": start_program, "lastx": lastx, "lasty": lasty, "lastz": lastz }
def main(): sensor = LIS3DH() sensor.setRange(LIS3DH.RANGE_2G) while True: x = sensor.getX() y = sensor.getY() z = sensor.getZ() button_pressed = GPIO.input(BUTTON_PIN) == 1 light_level = sensor.getADC(sensor.ADC_1) humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, pin) if humidity is not None and temperature is not None: print('temp={0:0.1f}*C humidity={1:0.1f}% '.format( temperature, humidity)) print( "light: %.6f\t button: %s orientation: X: %.6f\tY: %.6f\tZ: %.6f" % (light_level, button_pressed, x, y, z)) time.sleep(.2)
def main(): #User Configuration# throwThreshold = 0.7 #Sensitivity for catch detaction, larger number = less sensitive catchRepeat=3 #Number of times the ball should repeat a word in catch mode tagRepeat=0 #Number of times the ball should repeat a word in RFID mode #End user configuration pyglet.options["audio"] = ('openal', 'pulse', 'directsound','silent') catchCount=0 tagCount=0 sensor = LIS3DH() sensor.setRange(LIS3DH.RANGE_2G) reader = SimpleMFRC522.SimpleMFRC522() rfidList, rfidIndex = fileList("./rfidSounds") catchList, catchIndex = fileList("./catchSounds") while True: average = readAccel(sensor) RFIDTag = readRFID(reader) if average>throwThreshold: pyPlayer = pyglet.resource.media(catchList[catchIndex]) pyPlayer.play() print("Caught!") sleep(3) catchCount+=1 if catchCount == catchRepeat: catchCount=0 catchIndex = updateIndex(catchList, catchIndex) if RFIDTag != None: pyPlayer = pyglet.resource.media(rfidList[rfidIndex]) pyPlayer.play() print(RFIDTag) tagCount+=1 if tagCount == tagRepeat: tagCount=0 rfidIndex = updateIndex(rfidList,rfidIndex) sleep(0.1)
def __init__(self, address=0x18, bus=1, frequency_seconds=1, sensitivity=(0.05, 0.05, 0.05), auto_calibrate=True, auto_sensitivity=1.0, threshold_per_minute=1, vibration_callback=None, steady_vibration_callback=None): GPIO.setmode(GPIO.BCM) self.meter = Meter() self.frequency_seconds = frequency_seconds self.sensitivity = sensitivity self.auto_calibrate = auto_calibrate self.auto_sensitivity = auto_sensitivity self.threshold_per_minute = threshold_per_minute self.calibration = (0.0, 0.0, 0.0) self.sensor = LIS3DH(address=address, bus=bus) if self.auto_calibrate: self._calibrate() super(VibrationSensor, self).__init__(vibration_callback, steady_vibration_callback)
dig_P5 -= 65536 dig_P6 = b1[17] * 256 + b1[16] if dig_P6 > 32767 : dig_P6 -= 65536 dig_P7 = b1[19] * 256 + b1[18] if dig_P7 > 32767 : dig_P7 -= 65536 dig_P8 = b1[21] * 256 + b1[20] if dig_P8 > 32767 : dig_P8 -= 65536 dig_P9 = b1[23] * 256 + b1[22] if dig_P9 > 32767 : dig_P9 -= 65536 if __name__ == '__main__': sensor = LIS3DH(debug = False) sensor.setRange(LIS3DH.RANGE_16G) sensor.setDataRate(LIS3DH.DATARATE_400HZ) #sensor.setHighResolution() while(1==1): # BMP280 address, 0x76(118) # Read data back from 0xF7(247), 8 bytes # Pressure MSB, Pressure LSB, Pressure xLSB, Temperature MSB, Temperature LSB # Temperature xLSB, Humidity MSB, Humidity LSB data = bus.read_i2c_block_data(0x77, 0xF7, 8) # Convert pressure and temperature data to 19-bits adc_p = ((data[0] * 65536) + (data[1] * 256) + (data[2] & 0xF0)) / 16 adc_t = ((data[3] * 65536) + (data[4] * 256) + (data[5] & 0xF0)) / 16
def clickcallback(channel): # interrupt handler callback print("Interrupt detected") click = sensor.getClick() print("Click detected (0x%2X)" % (click)) if (click & 0x10): print(" single click") if (click & 0x20): print(" double click") if __name__ == '__main__': testADC = True sensor = LIS3DH(debug=True, enableADC=testADC) sensor.setRange(LIS3DH.RANGE_2G) sensor.setClick(LIS3DH.CLK_DOUBLE, 200, mycallback=clickcallback) # second accelerometer # s2 = LIS3DH(address=0x19, debug=True) print("Starting stream") while True: x = sensor.getX() y = sensor.getY() z = sensor.getZ() a = sensor.getChan1() b = sensor.getChan2() c = sensor.getChan3()
#!/usr/bin/python import RPi.GPIO as GPIO import serial import subprocess from LIS3DH import LIS3DH import TempHeader1 import time ############################################################################# accelerometer = LIS3DH() accel_sensor = TempHeader1.accelerometer_sensor() alert = TempHeader1.alert() ############################################################################# ############################################################################# movingcar = .1 # max aceleration in m/s^2 lastx = 0 #last known X Coordinates lasty = 0 #last known Y Coordinates lastz = 0 #last known Z Coordinates differencex = 0 # difference between current and last known X Coordinates differencey = 0 # difference between current and last known Y Coordinates differencez = 0 # difference between current and last known Z Coordinates update_time = 1 #check reed sensor every second start_program = 0 reed_pin = 36 timer = 0 #initiate timer timer_speed = 1 last_alert = 0 reed_bit = 0 # seat belt check. 1 = unbuckled, 0 = buckled ############################################################################
#!/usr/bin/python from LIS3DH import LIS3DH from TempHeader1 import temp_sensor import time sensor = LIS3DH() movingcar = 1 # max aceleration in m/s^2 lastx = 0 #last known X Coordinates lasty = 0 #last known Y Coordinates lastz = 0 #last known Z Coordinates differencex = 0 # difference between current and last known X Coordinates differencey = 0 # difference between current and last known Y Coordinates differencez = 0 # difference between current and last known Z Coordinates update_time = 1 #check reed sensor every second start_program = 0 print("Starting stream") def rateAccel(float currentx, float currenty, float currentz) : differencex = currentx - lastx differencey = currenty - lasty differencez = currentz - lastz print("\rdifferenceX: %.6f\tdifferenceY: %.6f\tdifferenceZ: %.6f \t m/s^2" % (differencex, differencey, differencez)) if (abs(differencex)>movingcar) | (abs(differencey)>movingcar) | (abs(differencez)>movingcar) : print("You're moving!") checkReed();
from time import sleep def clickcallback(channel): # interrupt handler callback print("Interrupt detected") click = sensor.getClick() print("Click detected (0x%2X)" % (click)) if (click & 0x10): print(" single click") if (click & 0x20): print(" double click") if __name__ == '__main__': sensor = LIS3DH(debug=True, datarate=DATARATE_LOWPOWER_5KHZ) sensor.setRange(LIS3DH.RANGE_2G) sensor.setClick(LIS3DH.CLK_DOUBLE, 200, mycallback=clickcallback) # second accelerometer # s2 = LIS3DH(address=0x19, debug=True) fd = open("data.csv", "w") #will overwrite existing file print("Starting stream") while True: x = sensor.getX() y = sensor.getY() z = sensor.getZ()
def main(): ip = get_ip_address() hostname = socket.gethostname() client = pubsub.Client(project="google.com:iot-bootcamp") topic = client.topic("bootcamp") sensor = LIS3DH() sensor.setRange(LIS3DH.RANGE_2G) data = {} while True: region = random.choice(['emea', 'amer', 'apac']) files = os.listdir(os.path.join(infobase, region)) file_int = randint(1, len(files)) file_int = file_int - 1 #print(file_int) to_move = os.path.join(infobase, region, files[file_int]) with open(to_move) as jfile: device_config = json.load(jfile) d = datetime.utcnow() x = sensor.getX() y = sensor.getY() z = sensor.getZ() button_pressed = GPIO.input(BUTTON_PIN) == 1 # We "invert" the value by subtracting from 2700 # and convert to integer light_level = 2700 - int(sensor.getADC(sensor.ADC_1)) # get data from the dht22 sensor humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, pin) data['device_id'] = device_config['id'] if ip is not None: data['ip'] = ip else: data['ip'] = "Unknown" data['city'] = device_config['city'] data['country'] = device_config['country'] data['region'] = device_config['region'] data['lat'] = device_config['lat'] data['long'] = device_config['lng'] data["timestamp"] = d.isoformat("T") + "Z" data['light_level'] = light_level data['button_pressed'] = button_pressed data['orientation'] = {'x': x, 'y': y, 'z': z} if humidity is not None and temperature is not None: data['temperature'] = str(round(temperature, 2)) data['humidity'] = str(round(humidity, 2)) else: data['temperature'] = 0 data['humidity'] = 0 if data['lat'] < 10: data['temperature'] = float(data['temperature']) + round( random.uniform(10, 40), 1) data['humidity'] = float(data['humidity']) + round( random.uniform(10, 38), 1) else: data['temperature'] = float(data['temperature']) - round( random.uniform(5, 20), 1) data['humidity'] = float(data['humidity']) - round( random.uniform(10, 25), 1) data['ip_address'] = ip data['hostname'] = hostname lcd.clear() lcd.message('IP%s\n' % (data['ip'])) lcd.message('H:%s' % (data['hostname'])) time.sleep(4) lcd.clear() lcd.message('%s %s\n' % (data['city'], data['region'])) lcd.message('%s\n' % (data['country'])) time.sleep(4) lcd.clear() lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) lcd.message('T %s H %s' % (data['temperature'], data['humidity'])) time.sleep(4) lcd.clear() lcd.message('Light %s\n' % (str(round(light_level, 0)))) lcd.message('%s %s %s' % (str(round(x, 2)), str(round(y, 2)), str(round(z, 2)))) time.sleep(4) lcd.clear() lcd.message('Button %s\n' % (data['button_pressed'])) lcd.message('LT:%s LG:%s' % (str(round(data['lat'], 1)), str(round(data['long'], 1)))) print(data) try: topic.publish(json.dumps(data).encode('utf-8'), timestamp=data["timestamp"]) except: print("Failed to submit to PubSub. Trying again...") pass time.sleep(1)
#def clickcallback(channel): # interrupt handler callback # print("Interrupt detected") # click = sensor.getClick() # print("Click detected (0x%2X)" % (click)) # if (click & 0x10): # print(" single click") # if (click & 0x20): # print(" double click") if __name__ == '__main__': sensor = LIS3DH(debug=True,datarate=LIS3DH.DATARATE_400HZ) sensor.setRange(LIS3DH.RANGE_8G) #sensor.setClick(LIS3DH.CLK_DOUBLE, 200, mycallback=clickcallback) # second accelerometer # s2 = LIS3DH(address=0x19, debug=True) print("Starting stream") acc_data = Acc_data() while True: x = sensor.getX() y = sensor.getY() z = sensor.getZ() item = {'x':x,'y':y,'z':z}
from LIS3DH import LIS3DH from time import sleep def clickcallback(channel): # interrupt handler callback print "Interrupt detected" click = sensor.getClick() print "Click detected (0x%2X)" % (click) if (click & 0x10): print " single click" if (click & 0x20): print " double click" if __name__ == '__main__': sensor = LIS3DH(debug=True) sensor.setRange(LIS3DH.RANGE_2G) sensor.setClick(LIS3DH.CLK_SINGLE, 80, mycallback=clickcallback) print "Starting stream" while True: x = sensor.getX() y = sensor.getY() z = sensor.getZ() # raw values print "\rX: %.6f\tY: %.6f\tZ: %.6f" % (x, y, z) sleep(0.1) # click sensor if polling & not using interrupt
#!/usr/bin/python from LIS3DH import LIS3DH import time import math # sensor_a will be the sensor on the handle bars # debug=False just turns off the verbose output when initializing sensor_a = LIS3DH(address=0x18, debug=False) # This sets the range to 16G because you're biking # allowed options are: 2G(default), 4G, 8G, 16G sensor_a.setRange(LIS3DH.RANGE_16G) # set up the second sensor(mount this one on the lower fork arm) sensor_b = LIS3DH(address=0x19, debug=False) sensor_b.setRange(LIS3DH.RANGE_16G) if __name__ == '__main__': with open("/home/pi/bike_accel/python-lis3dh/bike_data.csv", "a") as log: # You could read a button input here to wait until triggered to start logging while True: # This order helps to align readings as close as possible ax = sensor_a.getX() bx = sensor_b.getX() ay = sensor_a.getY() by = sensor_b.getY() az = sensor_a.getZ() bz = sensor_b.getZ() # this calculates the magnitude of the accelerometers magnitude_a = math.sqrt( math.pow(ax, 2) + math.pow(ay, 2) + math.pow(az, 2))