def __init__(self, service): Thread.__init__(self) #This is the library used by Grove to capture the values in the 3 axes self.adxl345 = ADXL345() self.service = service self.running = True
def __init__(self, bus, gyro_address, accel_address, compass_address, name, gyro_scale=L3G4200D.FS_2000, accel_scale=ADXL345.AFS_16g): self.bus = bus self.gyro_address = gyro_address self.accel_address = accel_address self.name = name self.gyro_scale = gyro_scale self.accel_scale = accel_scale self.accelerometer = ADXL345(bus, accel_address, name + "-accelerometer", accel_scale) self.gyroscope = L3G4200D(bus, gyro_address, name + "-gyroscope", gyro_scale) self.compass = HMC5883L(bus, compass_address, name + "-compass") self.last_time = time.time() self.time_diff = 0 self.pitch = 0 self.roll = 0 # take a reading from the device to allow it to settle after config changes self.read_all() # now take another to act a starting value self.read_all() self.pitch = self.rotation_x self.roll = self.rotation_y
def thread(): #p1 = Process(target=camera.record) print('\nBuckle up, butter cup. You just flipped my bitch switch\n') GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(10, GPIO.LOW) print('Set-up Pin 10\n') GPIO.setup(21, GPIO.LOW) GPIO.output(21, GPIO.HIGH) print('Set-up Pin 21\n') adxl = ADXL345() print('Set-up ADXL345\n') GPIO.output(10, GPIO.HIGH) while True: axes = adxl.getAxes(True) xyforce = math.sqrt(axes['x']**2 + axes['y']**2) netforce = math.sqrt(xyforce**2 + axes['z']**2) if (netforce >= 7): time.sleep(0.25) if (netforce >= 7): GPIO.output(10, GPIO.LOW) print('LAUNCH LAUNCH LAUNCH LAUNCH LAUNCH') break camera.record()
def listen_capteur(self, s): sensor = 4 button = 3 i = 0 m = False while True: adxl345 = ADXL345() #print(CapteurService.getDoorState(self)) #print(CapteurService.getAccelerometerState(self)) #print(CapteurService.getButtonState(self)) self.stateDoor = grovepi.digitalRead(sensor) axes = adxl345.getAxes(True) self.stateAccelerometer = axes['z'] first = axes['z'] self.stateButton = grovepi.digitalRead(button) time.sleep(.1) axes = adxl345.getAxes(True) second = axes['z'] res = int(abs(first - second) * 100) if (res > 10): self.stateMailing = True m = True if (m == True): i = i + 1 if (i >= 5): self.stateMailing = False m = False i = 0
def main(): global this global acquire_data global get_altitude global find_floor_from_range global set_position_as_floor from bmp388 import BMP388 from VL53L0X import VL53L0X from adxl345 import ADXL345 from accelerometer import ACCELEROMETER from distance import HeightTiltCompensator # I2C Object if 'i2c' not in globals(): from machine import I2C, Pin i2c = I2C(0, scl=Pin(22), sda=Pin(21)) adxl = ADXL345(i2c, 83) accelerometer = ACCELEROMETER(adxl, 'adxl345_calibration_2point') tof = VL53L0X(i2c, 41) distance_fusion = HeightTiltCompensator(accelerometer, tof) barometer = BMP388(i2c) this = ALTITUDE(barometer, distance_fusion) this.sr.offset = -40.0 acquire_data = this.acquire_data get_altitude = this.get_altitude find_floor_from_range = this.find_floor_from_range set_position_as_floor = this.set_position_as_floor
def __init__(self): hardwarebase.__init__(self, 'ACCELEROMETER') self.payload = acceleropayload() self.serial0 = None #self.lcd.data_print("RFID Initialize..",0,1) time.sleep(1) self.adxl345 = ADXL345()
def get_accelerometer(self): """Return the current acceleration""" try: import grovepi from adxl345 import ADXL345 except ImportError: return '{"x":0,"y":0,"z":0}' adxl = ADXL345() return adxl.getAxes(True)
def __init__(self): # initialize the accellerometer self.adxl345 = ADXL345() self.stopped = False self.results = [] self.t_start = time() self.count = 0 self.elapsed = 0 signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop)
def isUsed() : print "isUsed()" adxl345 = ADXL345() axes = adxl345.getAxes(True) forces = measureForce() print "isUsed()\t[ Z Acceleration : %.3fG ]" % ( axes['z'] ) print "isUsed()\t[ F sensitivity : %d ]" % ( forces ) if float(axes['z']) > 0.8 and forces < 10 : return False else : return True
def main(): print('program start') # initialize gpio GPIO.setmode(GPIO.BCM) GPIO.setup(PIN_BEEP, GPIO.OUT) GPIO.setup(PIN_STARTSW, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) # initialize accerelation sensor adxl345 = ADXL345() filtered_acc = [None for i in range(BUF_SIZE)] filtered_index = 0 filtered_acc[0] = adxl345.getAxes(True) index = 1 # measure try: while(True): if (GPIO.input(PIN_STARTSW) == 1): break else: sleep(0.2) print('いただきます!') try: eating_id = start_eating() except: print('server down?') hayagui_count = 0 while(True): acc = adxl345.getAxes(True) if (index == 0): filtered_acc[0] = lowpass3d(filtered_acc[BUF_SIZE - 1], acc) else: filtered_acc[index] = lowpass3d(filtered_acc[index - 1], acc) abs_acc = abs3d(filtered_acc[index]) if (abs_acc > (1 + THRESHOLD) or abs_acc < (1 - THRESHOLD)): GPIO.output(PIN_BEEP, 1) sleep(0.3) GPIO.output(PIN_BEEP, 0) hayagui_count += 1 print('HAYAGUI NOW!') else: GPIO.output(PIN_BEEP, 0) # print('x: {0:.3f}'.format(filtered_acc[index]['x'])) # print('y: {0:.3f}'.format(filtered_acc[index]['y'])) # print('z: {0:.3f}'.format(filtered_acc[index]['z'])) index = (index + 1) % BUF_SIZE sleep(0.2) if (GPIO.input(PIN_STARTSW) == 1): try: print('ごちそうさまでした!') finish_eating(eating_id, hayagui_count) except: print('server down?') break finally: GPIO.cleanup()
def get_graph_data(): adxl345 = ADXL345() axes = adxl345.getAxes(True) graph_to_send = json.dumps({ 'x':axes['x'], 'y':axes['y'], 'z':axes['z'] }) return graph_to_send
def accReading(self): device_acc = ADXL345() i = self.numRecord while (i > 0): device_acc.read_data() self.accx, self.accy, self.accz = device_acc.getAcc() print("x = %.4f (m/s)" % (self.accx)) print("y = %.4f (m/s)" % (self.accy)) print("z = %.4f (m/s)" % (self.accz)) print("\n") time.sleep(self.timeInteration) i -= 1
def init(self): print "Initializing ADXL345 Accelerometer" adxl345 = ADXL345() print "ADXL345 Initialized" readings = [0.0, 0.0, 0.0, 0.0, 0.0] i = 0 while True: readings[i] = adxl345.read()[1] i = (i + 1) % 5 time.sleep(0.0001) if i == 0: globals.ACCEL = (sum(readings) / float(len(readings)))
def __init__(self): # Total watch duration (seconds) self.watch_duration = 3 # Interrupt watch interval (interrupts/second) self.watch_interval = 1 # Consecutive interrupt threshold for suspicious motion (interrupts) self.trig_int_threshold = self.watch_duration * self.watch_interval # Consecutive interrupt counter (interrupts) self.trig_int_count = 0 # Setup ADXL345 self.adxl345 = ADXL345()
def getAngle(): adxl345 = ADXL345() #while(1): axes = adxl345.getAxes(True) #print("ADXL345 on address 0x%x:" % (adxl345.address)) #print(" x = %.3fG" % ( axes['x'] )) #print(" y = %.3fG" % ( axes['y'] )) #print(" z = %.3fG" % ( axes['z'] )) angle = orentation(axes['x'], axes['y'], axes['z']) #time.sleep(1.0) return angle
def accel(): adxl345 = ADXL345() axes = adxl345.getAxes(True) # return {'status':'online', 'servertime':time.time()} # response = "ADXL345 on address 0x%x:" % (adxl345.address) # response += " x = %.3fG" % (axes['x']) # response += " y = %.3fG" % (axes['y']) # response += " z = %.3fG" % (axes['z']) response = axes return response
def get_graph_data(): global sample sample += 1 adxl345 = ADXL345() axes = adxl345.getAxes(True) graph_to_send = json.dumps({ 'x': axes['x'], 'y': axes['y'], 'z': axes['z'], 's': sample }) return graph_to_send
def __init__(self, bus=None): if bus is None: bus = smbus.SMBus(i2c_banana_pi_bus_number()) #Default ADXL345 range +/- 2g is ideal for telescope use self.accel = ADXL345(bus, 0x53, name="accel") self.gyro = L3G4200D(bus, 0x69, name="gyro") self.compass = HMC5883L(bus, 0x1e, name="compass") self.barometer = BMP085(bus, 0x77, name="barometer") self._last_gyro_time = 0 #needed for interpreting gyro self.read_gyro_delta() #Discard first reading q_start = self.current_orientation_quaternion_mag_acc_only() self._q_start = q_start self._current_hybrid_orientation_q = q_start self._current_gyro_only_q = q_start
def __init__(self, bus=None): if bus is None: bus = smbus.SMBus(1) # ADXL345 accelerometer range, 2g is ideal for telescope use. Allowed values : 2g, 4g, 8g, 16g self.accel = ADXL345(bus, 0x53, name="accel", scale="8g") # L3G4200D gyroscope range, 250 is ideal for telescope use. Allowed values : 250, 500, 2000 self.gyro = L3G4200D(bus, 0x69, name="gyro", scale=250) self.compass = HMC5883L(bus, 0x1e, name="compass") self.barometer = BMP085(bus, 0x77, name="barometer") self._last_gyro_time = 0 #needed for interpreting gyro self.read_gyro_delta() #Discard first reading q_start = self.current_orientation_quaternion_mag_acc_only() self._q_start = q_start self._current_hybrid_orientation_q = q_start self._current_gyro_only_q = q_start
def __init__(self, adxl345_address=0x53): self.r = redis.Redis(db=2) self.adxl345 = ADXL345(adxl345_address) dbprint("ADXL345 on address 0x%x" % (self.adxl345.address)) self.adxl345.setFIFOmode(self.adxl345.FIFO_BYPASS, self.adxl345.FIFO_TRIGGER_INT2, 2) self.adxl345.setFIFOmode(self.adxl345.FIFO_FIFO, self.adxl345.FIFO_TRIGGER_INT2, 2) self.hmc5883l = hmc5883l(gauss=4.7, declination=(-2, 5)) dbprint("HMC5883L on address 0x%x" % (self.hmc5883l.address)) self.l3g4200 = l3g4200(1) dbprint("L3G4200 on address 0x%x" % (self.l3g4200.address)) self.r.delete(ACCEL_REDIS_QUEUE, COMPASS_REDIS_QUEUE, GYRO_REDIS_QUEUE, TEMPERATURE_REDIS_QUEUE)
def try_io(tries=10): assert tries > 0 error = None adxl345 = None while tries: try: adxl345 = ADXL345() except IOError as e: error = e tries -= 1 else: break if not tries: raise error return adxl345
def record(): shutil.rmtree('/home/pi/images/') os.mkdir('/home/pi/images') folder = '/home/pi/images/' timeStamp = str(time.time()) clock = 0 camera = PiCamera() camera.resolution = (640, 480) camera.framerate = 30 rawCapture = PiRGBArray(camera, size=(640, 480)) startTime = time.clock() frames_record_time = time.time() frame_count = 0 adxl = ADXL345() while True: axes = adxl.getAxes(True) xyforce = math.sqrt(axes['x'] ** 2 + axes['y'] ** 2) netforce = math.sqrt(xyforce ** 2 + axes['z'] ** 2) if(netforce >= 2): print('LAUNCH LAUNCH LAUNCH LAUNCH LAUNCH') break for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): image = frame.array timeStamp = str(time.time()) cv2.imwrite(folder + timeStamp + ".jpg", image) frame_count += 1 clock = time.clock() - startTime print('time: ' + str(clock)) print('the ' + timeStamp + '.jpg frame has been taken and recorded \n') rawCapture.truncate(0) if clock > 10: print('Camera Done ' + str(clock) +'s\n') rawCapture.close() camera.close() break frames_record_time = time.time() - frames_record_time print(str(frame_count) + ' frames done in ' + str(frames_record_time) + ' seconds for the camera recording')
def thread(): p1 = Process(target=camera.record) p2 = Process(target=dc.anal_video) print('Buckle up, butter cup. You just flipped my bitch switch\n') p1.start() adxl = ADXL345() while True: axes = adxl.getAxes(True) xyforce = math.sqrt(axes['x']**2 + axes['y']**2) netforce = math.sqrt(xyforce**2 + axes['z']**2) if (netforce >= 2): print('LAUNCH LAUNCH LAUNCH LAUNCH LAUNCH') break time.sleep(2) p2.start()
def main_loop(): adxl345 = ADXL345() axes = adxl345.getAxes(True) print "ADXL345 on address 0x%x:" % (adxl345.address) print " x = %.3fG" % (axes['x']) print " y = %.3fG" % (axes['y']) print " z = %.3fG" % (axes['z']) oldaxes = dict(axes) start_time = time.time() results = {'force': 0, 'bumps': 0, 'bumpforce': 0} subprocess.Popen( ["sudo", "-E", "python", "/home/pi/toaster/adxl345-python/startup.py"]) while True: diff_time = time.time() - start_time if diff_time >= 60.0: print datetime.now() start_time = time.time() subprocess.Popen([ "sudo", "-E", "python", "/home/pi/toaster/adxl345-python/logger.py", str(results['force']), str(results['bumps']), str(results['bumpforce']) ]) results = {'force': 0, 'bumps': 0, 'bumpforce': 0} axes = adxl345.getAxes(True) deltas = {k: abs(v - oldaxes[k]) for k, v in axes.items()} total_force = sum(deltas.values()) results['force'] += total_force if total_force > 0.1: results['bumpforce'] += total_force results['bumps'] += 1 oldaxes = dict(axes) return True
def accelerometer_sensor(frequence, port, tsk_id, enrollment, sensor, sensor_name): while True: try: adxl345 = ADXL345() client = mqtt.Client() client.connect(server, 1883, 60) # sensor_value = ultrasonic.read_sensor(sensor_port) axes = adxl345.getAxes(True) # print(( axes['x'] ),"\t",( axes['y'] ),"\t",( axes['z'] )) # if sensor_value != 0: #setup the topic #pub_light = myserial + ':' + tsk_id + ':' + port pub_topic = enrollment + ':' + myserial + ':' + sensor + ':' + sensor_name # #public message client.publish(pub_topic, "%s@%s" % (axes, datetime.datetime.now()), 1) time.sleep(frequence) except (IOError, TypeError) as e: print "Error"
def _init_sensor(self): from adxl345 import ADXL345 self._adxl345 = ADXL345()
help='The IP address of the server', dest='address', default="192.168.0.5", type=str) parser.add_option('--port', help='The server port', dest='port', default=8089, type=int) opts, args = parser.parse_args() ''' By default the range is set to 2G, which is good for most applications. ''' adxl345 = ADXL345() def get_axes(): axes = adxl345.getAxes(gforce=True) ''' We send 4 pieces of information, the current time (which can be used to work out the lag) and the x, y, z readings from the accelerometer ''' x = "{},{},{},{}".format(time.time(), axes['x'], axes['y'], axes['z']) return x client = EstimSocket(address=opts.address, port=opts.port) client.client_connect()
global connAccel connAccel = OpenAccelConnection() cursorAccel = SetCursor(connAccel) uploading = False #variables for GPS sensor library global gpsd gpsd = None os.system('sudo gpsd /dev/ttyUSB0 -F /var/run/gpsd.sock') #ensuring gpsd is pointed to the right USB GPS receiver gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info current_value = None running = True #setting the thread running to true adxl345 = ADXL345() #initialize library for accelerometer # hardcoded userId reflects who is the volunteer, 99 is for administrator userId = User.id uploadInterval = 60 #in seconds frequency = 10 #no of times per while loop for accelerometer #searches for internet connection & upload data to database in intervals def OnInterval(): global uploading threading.Timer(uploadInterval,OnInterval).start() try: if uploading != True:
def __init__(self): self.adxl345 = ADXL345() self.y = np.zeros(2000) self.sampleCount = 0
import math from multiprocessing import Process, Queue, Lock from adxl345 import ADXL345 import RPi.GPIO as GPIO def thread(): #p1 = Process(target=camera.record) print('Buckle up, butter cup. You just flipped my bitch switch\n') GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(10, GPIO.LOW) GPIO.setup(21, GPIO.LOW) GPIO.output(21, GPIO.HIGH) adxl = ADXL345() GPIO.output(10, GPIO.HIGH) while True: axes = adxl.getAxes(True) xyforce = math.sqrt(axes['x'] ** 2 + axes['y'] ** 2) netforce = math.sqrt(xyforce ** 2 + axes['z'] ** 2) if(netforce >= 3): GPIO.output(10, GPIO.LOW) print('LAUNCH LAUNCH LAUNCH LAUNCH LAUNCH') break camera.record() #p1.start()