Ejemplo n.º 1
2
class Display(base_display.DisplayBase):

    """
    Control Raspberry Pi Sense Hat LED Matrix
    """

    def __init__(self):
        self.sense = SenseHat()
        self.defer = None

    def cb_show_text(self, *args, **kwargs):
        self.defer = None

    def show_text(self, text):
        self.show(text, None, None)
        
    def show(self, text, textcolor, bgcolor):
        if not textcolor:
            textcolor = (0xff,0xff,0xff)
        if not bgcolor:
            bgcolor = (0,0,0)
            
        if self.defer is None:
            self.sense.set_rotation(90, False)
            self.defer = threads.defer_to_thread(self.sense.show_message, text, text_colour=textcolor, back_colour=bgcolor)
            self.defer.addCallback(self.cb_show_text)
            self.defer.addErrback(self.cb_show_text)

    def clear(self):
        self.sense.clear()
Ejemplo n.º 2
0
class RunTime:
    def __init__(self):
        self.apps = []
        self.apps.append(Clock())
        self.sense = SenseHat()

    def start(self):
        pygame.init()
        pygame.display.set_mode((640, 480))
        running = True
        icon = self.apps[0].get_icon()
        self.display_icon(icon)
        """
		while running:
			for event in pygame.event.get():
				if event.type == QUIT:
					running = False
				else:
					if event.key == K_RIGHT:
						self.sense.clear()
					elif event.key == K_LEFT:
						self.display_icon(icon)
					else:
						running = False
		"""

    def display_icon(self, icon):
        e = [0, 0, 0]
        padded_icon = []
        for i in range(0, len(icon)):
            padded_icon.append(e)
            padded_icon.extend(icon[i])
            padded_icon.append(e)
        padded_icon.extend([e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e])
        self.sense.set_pixels(padded_icon)
Ejemplo n.º 3
0
def main():

	#initialize Pygame which handles joystick inputs on SenseHat
	pygame.init()
	pygame.display.set_mode((640, 480))

	subprocess.call(["mpc","clear"])
	subprocess.call(["mpc","load","playlist1"])
	subprocess.call(["mpc","enable","1"])


	# SenseHat initialization and configuration
	sense = SenseHat()
	sense.low_light = True
	sense.rotation = 90

	#initialize last weather update time
	last_update_time = 0

	#Main loop

	while True:  

		#Handle Senshat Joystick inputs
		for event in pygame.event.get():
			#if event.type == KEYDOWN:
				#radio_commands(event)
				#print('DN')
			if event.type == KEYUP:
				radio_commands(event)
				print('SenseHat Input')
def get_sensors(precision):
	sense = SenseHat()
	data = {}
	data['temperature'] = round(sense.get_temperature(), precision)
	data['pressure'] = round(sense.get_pressure(), precision)
	data['humidity'] = round(sense.get_humidity(), precision)
	return data
class SensorHatLogger:

    """
    Logs the hostname, time (unixtime), temperature, humidity, and pressure to Kafka in JSON format. The data is
    generated by a Raspberry Pi with a Sense Hat: https://www.raspberrypi.org/products/sense-hat/
    
    This captures a read approx. every 10 seconds.

    TODO: https://github.com/initialstate/wunderground-sensehat/wiki/Part-3.-Sense-HAT-Temperature-Correction
    
    """

    def __init__(self):
        self.producer = KafkaProducer(bootstrap_servers='hdp01.woolford.io:6667')
        self.sense = SenseHat()
        self.sensor_record = dict()

    def read_values_from_sensor(self):
        self.sensor_record['host'] = socket.gethostname()
        self.sensor_record['timestamp'] = int(time.time())
        self.sensor_record['temperature'] = self.sense.get_temperature()
        self.sensor_record['humidity'] = self.sense.get_humidity()
        self.sensor_record['pressure'] = self.sense.get_pressure()

    def send_record_to_kafka(self):
        sensor_record_json = json.dumps(self.sensor_record)
        self.producer.send("temperature_humidity_json", sensor_record_json)

    def run(self):
        self.read_values_from_sensor()
        self.send_record_to_kafka()
Ejemplo n.º 6
0
def interp(doc):
        ''' boilermake
	devices.setup()
        devices.set_in('Button',devices.Button(16, GPIO.PUD_DOWN))
	devices.set_in('TempSensor',devices.TemperatureHumiditySensor(7))
	devices.set_out('Servo', devices.Servo(12))
	devices.set_out('RgbLed', devices.RgbLed(11, 13, 15, 100))
	devices.set_out('BlueLed', devices.Led(19,120))
	devices.set_out('GreenLed', devices.Led(18,120))
	devices.set_out('RedLed', devices.Led(22, 120))
        '''
	try:
		global page_decls
		page_decls = {}
                global sense
                sense = SenseHat()
		if 'Pages' not in doc:
			raise Exception("Malformed doc {}".format(json.dumps(doc)))
		for page_doc in doc['Pages']:
			page_decl = translate_page_decl(page_doc)
			page_decls[page_decl.name] = page_decl
		if 'Main' not in page_decls:
			raise Exception('Malformed doc - no main {}'.format(json.dumps(doc)))
		page_decls['Main'].interp()
		sense.clear()
                #devices.cleanup()
	except Exception as e:
                if sense:
                    sense.clear()
		#devices.cleanup()
		raise e
Ejemplo n.º 7
0
def music():
    root = tkinter.Tk()
    root.geometry("150x150")
    root.wm_title("Music")
    b1 = ttk.Button(root, text = 'V+', command = vdown)
    b2 = ttk.Button(root, text = 'V-', command = vup)
    b3 = ttk.Button(root, text = 'Next', command = nextm)
    b4 = ttk.Button(root, text = 'Previous', command = previousm)
    b5 = ttk.Button(root, text = 'On/Off', command = moff)
    b1.pack()
    b2.pack()
    b3.pack()
    b4.pack()
    b5.pack()
    sense = SenseHat()
    sense.clear()
    pygame.init()
    pygame.display.set_mode((15, 15))
    mixer.init()
    #music
    global path
    path = "/home/pi/Desktop/Smart House/Music"
    global mfiles
    mfiles = [f for f in os.listdir(path) if f.endswith('.mp3')]
    global abc
    abc = 2
    global state
    state = "Off"
Ejemplo n.º 8
0
def index():
    user = {'nickname': 'Miguel'}  # fake user
    sense = SenseHat()
    sense.show_message("Hello world!")
    return render_template('index.html',
                           title='Home',
                           user=user)
Ejemplo n.º 9
0
def main(frames=FRAMES):
    """Show the frames on the sense hat."""
    sense = SenseHat()

    for frame in frames:
        sense.set_pixels(frame)
        time.sleep(0.25)
Ejemplo n.º 10
0
	def readSensor(self):
		from sense_hat import SenseHat
		senseHat = SenseHat()
		self.humidity   = senseHat.get_humidity()
		self.tempH      = senseHat.get_temperature_from_humidity()
		self.pressure   = senseHat.get_pressure() + PRESSURE_OFFSET
		self.tempP      = senseHat.get_temperature_from_pressure()
		self.mesureTime = time.time()
Ejemplo n.º 11
0
class Sensor :
    def __init__(self) :
        self.sensor_id = "sensor hat"
        self.fileplace = 'tempplace.conf'
        self.total_count = 0
        self.device_file = "/dev/null"
        self.sense = SenseHat()
        self.place = self.readplacename()

    def reinit(self) :
        self.__init__()

    def sensorid(self) :
        return self.sensor_id

    def total_count(self) :
        return self.total_count

    def placename(self):
        return self.place

    def setplacename(self, name):
        self.place = setplace_db(name)

    def readplacename(self):
        self.place = getplace_db()
        return self.place

    def read_temp(self):
        temp = "null"
        tt = self.sense.get_temperature()
        th = self.sense.get_temperature_from_humidity()
        tf = self.sense.get_temperature_from_pressure()

        tf = float(tt)
        tf = tf - 10.0 # Fattore di correzione
        tt = round(tt, 2)
        tc = round(tf, 2)
        th = round(th, 2)
        tf = round(tf, 2)

        self.total_count += 1
        return str(tc)

    def read_pressure(self):
        p = self.sense.get_pressure()
        p = round(p, 2)
        self.total_count += 1
        return str(p)

    def read_humidity(self):
        h = self.sense.get_humidity()
        h = round(h, 2)
        self.total_count += 1
        return str(h)

    def sensordebug(self):
        return 'Sense Hat'
Ejemplo n.º 12
0
def get_press(altitude):
 # enable SenseHat modules
    from sense_hat import SenseHat
    
    sense=SenseHat()
    raw_pressure = sense.get_pressure()
    pressure = raw_pressure/math.pow(1 - 0.0065*altitude/288.15,5.25588)
    #print(pressure)
    return pressure
Ejemplo n.º 13
0
class Screen:
    def __init__(self):
        self.sense = SenseHat()
        self.general_level = 0
        self.wait_time = 4
        self.cur_time = 0
        self.clear()
        self.balance = 0

    def clear(self):
        for i in range(SIZE):
            for j in range(SIZE):
                self.sense.set_pixel(i, j, BLACK)

    def clear_col(self, x):
        for i in range(0, 7):
            self.sense.set_pixel(x, i, BLACK)

    def plot_bar(self, x, height, colors=None):
        if colors is None:
            colors = BAR_COLORS
        self.clear_col(x)
        for i in range(height):
            self.sense.set_pixel(x, 7 - i, colors[7 - i])

    def plot_balance(self):
        for i in range(SIZE):
            self.plot_bar(i, max(1, self.general_level), BAR_COLORS)

    def show_amount(self):
        self.show_message(str(self.balance), color=list(BAR_COLORS[min(7, 8 - self.general_level)]))

    def show_message(self, message, speed=0.1, color=[255, 255, 255]):
        self.sense.show_message(message, speed, color)
        self.plot_balance()

    """ Parses an input in the form:
        balance percentage """

    def parse_input(self, line):
        self.cur_time = 0
        # Split balance and percentage.
        [self.balance, percent] = [float(x) for x in line.split()]
        self.general_level = int(round(min(max(0, percent), 100) / 100.0 * SIZE))
        self.draw_check()

    def draw_check(self):
        types = [BLACK, GREEN]
        pixels = [types[CHECK[i / SIZE][i % SIZE]] for i in range(SIZE * SIZE)]
        self.sense.set_pixels(pixels)

    def no_text(self):
        self.cur_time += SLEEP_TIME
        if self.cur_time > self.wait_time:
            self.cur_time = 0
            self.show_amount()
Ejemplo n.º 14
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        sense = SenseHat()
        sense.show_message("Hello {}!".format(form.openid.data))
        #flash('Login requested for OpenID="{}", remember_me={}'.format(form.openid.data, form.remember_me.data))
        return redirect('/index')
    return render_template('login.html', 
                           title='Sign In',
                           form=form)
Ejemplo n.º 15
0
def SH_show_colour(): # Thread to update colour on LED matrix
    sh = SenseHat()
    global running
    while running:
        red_val =red_var.get()
        green_val =green_var.get()
        blue_val =blue_var.get()
        time.sleep(0.05)
        sh.clear(red_val,green_val,blue_val)
    sh.clear([0,0,0])
Ejemplo n.º 16
0
Archivo: hat.py Proyecto: sli/sensed
class Hat(object):
    ''' `sensed` sensor module for the Raspberry Pi Sense HAT. This
        module returns a dictionary of all built in sensors. '''

    def __init__(self, config: DotMap) -> None:
        if config.sensed.test is not True:
            from sense_hat import SenseHat
            self.sense = SenseHat()

    def get_data(self) -> dict:
        # Environmental sensors
        humid = self.sense.humidity
        temp = self.sense.temperature
        temp_h = self.sense.get_temperature_from_humidity()
        temp_p = self.sense.get_temperature_from_pressure()
        press = self.sense.pressure

        # IMU (inertial measurement unit) sensors
        orient_r = self.sense.orientation_radians
        orient_d = self.sense.orientation
        compass = self.sense.compass
        compass_r = self.sense.compass_raw
        gyro = self.sense.gyroscope
        gyro_r = self.sense.gyroscope_raw
        accel = self.sense.accelerometer
        accel_r = self.sense.accelerometer_raw

        return {'environment': {'humidity': humid,
                                'temperature': temp,
                                'temperature_h': temp_h,
                                'temperature_p': temp_p,
                                'pressure': press},
                'imu': {'orientation_rad': orient_r,
                        'orientation_deg': orient_d,
                        'compass': compass,
                        'compass_r': compass_r,
                        'gyroscope': gyro,
                        'gyroscope_r': gyro_r,
                        'accelerometer': accel,
                        'accelerometer_raw': accel_r}}

    def test(self) -> dict:
        return {'environment': {'humidity': 1,
                                'temperature': 2,
                                'temperature_h': 3,
                                'temperature_p': 4,
                                'pressure': 5},
                'imu': {'orientation_rad': 6,
                        'orientation_deg': 7,
                        'compass': 8,
                        'compass_r': 9,
                        'gyroscope': 10,
                        'gyroscope_r': 11,
                        'accelerometer': 12,
                        'accelerometer_raw': 13}}
Ejemplo n.º 17
0
class SensorClient(object):

	def __init__(self, broker, broker_port):
		self.sense=SenseHat()
		self.broker=broker
		self.broker_port=broker_port
		self.client_id=uname()[1]
		
		sub_topics=	{	"temperature"	:	lambda: self.sense.get_temperature(),
					"humidity"	:	lambda: self.sense.get_humidity(),
					"pressure"	:	lambda:	self.sense.get_pressure() }

		self.topics={}
		root_topic="%s/sensehat"%self.client_id
		for sub_topic in sub_topics.keys():
			topic="%s/%s"%(root_topic, sub_topic)
			self.topics[topic]=sub_topics[sub_topic]
			

	def on_connect(self, client, userdate, flags, rc):
		for topic in sorted(self.topics):
			print "Subscribing to %s"%(topic)
			client.subscribe( topic )
		self.publish_sensor_topics()

	# If we recieve the payload of '?' (question-mark)
	# Then publish the value to the topic
	def on_message(self, client, userdata, msg):
		if msg.payload=="?":
			try:
				self.publish_topic( msg.topic )
			except Exception as e:
				print "Error when trying to publish '%s' ?"%msg.topic
		else:
			print "Ignoring message %s=%s"%(msg.topic, msg.payload)
		
	
	def publish_topic( self, topic ):
		topic_value=self.topics[topic]() # execute the Lambda to fetch value
		print "Publishing %s=%s"%(topic, topic_value)
		self.mqtt_client.publish( topic, topic_value )

	# Publish all topics (called when we first connect)
	def publish_sensor_topics(self):
		for topic in sorted(self.topics):
			self.publish_topic( topic )

	def run(self):
		self.mqtt_client=mqtt.Client( self.client_id )
		self.mqtt_client.on_message=self.on_message
		self.mqtt_client.on_connect=self.on_connect
		self.mqtt_client.connect(broker, broker_port)
		self.mqtt_client.loop_forever()
Ejemplo n.º 18
0
def main(v):
	if v is None:
		v=0.5
	else:
		v=float(v)
	sense=SenseHat()
	for i in range(8):
 		for j in range(8):
    			(h,s,v)=XY_to_HSV(i,j,v)
    			(r,g,b)=HSV_to_RGB(h,s,v)
    			#print (i,j,int(r),int(g),int(b),int(h),int(s),int(v))
    			sense.set_pixel(i,j,int(r),int(g),int(b))
Ejemplo n.º 19
0
 def update(self):
     """Get the latest data from Sense HAT."""
     from sense_hat import SenseHat
     sense = SenseHat()
     temp_from_h = sense.get_temperature_from_humidity()
     temp_from_p = sense.get_temperature_from_pressure()
     t_cpu = get_cpu_temp()
     t_total = (temp_from_h + temp_from_p) / 2
     t_correct = t_total - ((t_cpu - t_total) / 1.5)
     t_correct = get_average(t_correct)
     self.temperature = t_correct
     self.humidity = sense.get_humidity()
     self.pressure = sense.get_pressure()
Ejemplo n.º 20
0
def gyroGame(maxDegs):
	sense = SenseHat()
	while 1:
		orientation = sense.get_orientation_degrees()
		if orientation['pitch'] < maxDegs:
			realpitch=orientation['pitch']
		else:
			realpitch=-1*(360-orientation['pitch'])
			
		if orientation['roll'] < maxDegs:
			realroll=orientation['roll']
		else:
			realroll=-1*(360-orientation['roll'])
		
		x_pos=7-int(round(((maxDegs+realpitch)/(2.0*maxDegs))*8.0,0))
		y_pos=int(round(((maxDegs+realroll)/(2.0*maxDegs))*8.0,0))
		
		if x_pos > 7:
			x_pos = 7
		if x_pos < 0:
			x_pos = 0
		if y_pos > 7:
			y_pos = 7
		if y_pos < 0:
			y_pos = 0
			
		sense.clear()
		
		if (1 <= x_pos <=6)  and (1 <= y_pos <=6):
			sense.set_pixel(x_pos,y_pos,0,0,255)
		else:
			sense.set_pixel(x_pos,y_pos,255,0,0)
Ejemplo n.º 21
0
def lab_temp(): 
	import sys 
	from sense_hat import SenseHat

	sense = SenseHat()

	temperature = sense.get_temperature()
	pressure = sense.get_pressure()
	humidity = sense.get_humidity()

	if temperature is not None and pressure is not None and humidity is not None: 
		return render_template("lab_temp.html",temp=temperature, pres=pressure, hum=int(humidity)) 
	else: 
		return render_template("no_sensor.html") 
Ejemplo n.º 22
0
def monitor_pass(pass_details):
    sense = SenseHat()
    sense.clear()

    p = pass_details
    
    t0 = p.StartTime
    t1 = p.HighTime
    t2 = p.EndTime

    pixels = [C.K] * 64

    nx, ny = 0, 0
    while True:
        time.sleep(0.1)
        t = datetime.utcnow()
        if t >= t0: break

        pixels[8 * ny + nx] = C.K
        nx, ny = border(Azimuth.from_string('N'))
        pixels[8 * ny + nx] = C.B

        sense.set_pixels(pixels)

    while True:
        time.sleep(0.1)
        t = datetime.utcnow()
        if t > t2: break

        if t < t1:
            x = (t - t0).total_seconds() / (t1 - t0).total_seconds()
            a = x * p.HighAzimuth + (1 - x) * p.StartAzimuth
            if a > 180:
                a = a - 360
        else:
            x = (t2 - t).total_seconds() / (t2 - t1).total_seconds()
            a = x * p.HighAzimuth + (1 - x) * p.EndAzimuth
            if a > 180:
                a = a - 360

        #print('{0:0.3f} {1:0.3f}'.format(x, distinv(x)))
        #pixels = spot(x, distinv)
        #pixels = spiral(x, ramp)
        pixels = spot(x, Tween.distinv)

        nx, ny = border(Azimuth.from_string('N'))
        pixels[8 * ny + nx] = C.B

        px, py = border(a)
        pixels[8 * py + px] = C.R

        sense.set_pixels(pixels)

    sense.clear()
Ejemplo n.º 23
0
def draw_bluetooth():
    B = [0, 0, 255]  # Blue
    O = [255, 255, 255]  # White
    sense = SenseHat()
    bluetooth_logo = [
        O, O, O, O, O, O, O, O,
        O, O, O, B, O, O, O, O,
        O, O, O, B, B, O, O, O,
        O, B, O, B, O, B, O, O,
        O, O, B, B, B, O, O, O,
        O, B, O, B, O, B, O, O,
        O, O, O, B, B, O, O, O,
        O, O, O, B, O, O, O, O
    ]
    sense.set_pixels(bluetooth_logo)
Ejemplo n.º 24
0
def get_press(altitude):

 # enable SenseHat modules
    from sense_hat import SenseHat
    
    sense=SenseHat()
    raw_pressure1 = sense.get_pressure()
    time.sleep(0.1) 
    raw_pressure2 = sense.get_pressure()
    time.sleep(0.1) 
    raw_pressure3 = sense.get_pressure()
    raw_pressure=(raw_pressure1+raw_pressure2+raw_pressure3)/3
    pressure = raw_pressure/math.pow(1 - 0.0065*altitude/288.15,5.25588)
    #print(pressure)
    return pressure
class Sens_data():
    def __init__(self):
        self.sense = SenseHat()

    def get_temperature(self):
        return "%.2f" % self.sense.get_temperature()

    def get_humidity(self):
        return "%.2f" % self.sense.get_humidity()

    def get_pressure(self):
        return "%.2f" % self.sense.get_pressure()

    def get_timestamp(self):
        return str(int(time.time()))
Ejemplo n.º 26
0
def main():
    sense = SenseHat()
    sense.low_light = True
    print( "<---- ImageDisplay ---->\n" )
    if len( sys.argv ) != 2:
        print( "There must be exactly one argument, the path of the to be displayed image" )
        return 0
    else:
        print( "Displaying \'{0}\'".format( sys.argv[ 1 ] ) )
    onOffMatrix = senseSuppLib.LoadPixelStatusFromBIDF( sys.argv[ 1 ] )
    senseSuppLib.UpdateScreen( [ 255, 255, 255 ], onOffMatrix, sense )
    time.sleep( 3 )
    sense.clear()

    return 0
Ejemplo n.º 27
0
def get_metrics():

    if settings.SENSE_HAT:
        try:
            from sense_hat import SenseHat
        except ImportError:
            raise SystemExit('[ERROR] Please make sure sense_hat is installed properly')

    sense = SenseHat()
    data = {}
    data['temperature'] = sense.get_temperature();
    data['humidity'] = sense.get_humidity();
    data['pressure'] = sense.get_pressure();

    return data;
Ejemplo n.º 28
0
    def __init__(self) :
        self.sensor_id = "unknown"
        self.total_count = 0
        base_dir = '/sys/bus/w1/devices/'
        try:
            device_folder = glob.glob(base_dir + '28*')[0]
        except:
            device_folder = '/tmp'

        pos = device_folder.rfind('-')
        if pos > 0:
           self.sensor_id = device_folder[pos+1:]
        self.device_file = device_folder + '/w1_slave'

        if os.path.isfile(self.device_file) :
            print self.device_file
        else:
            self.device_file = "/dev/null"

        self.place = self.readplacename()
        try:
            from sense_hat import SenseHat
            self.sensehat = SenseHat()
	except:
            self.sensehat = None
Ejemplo n.º 29
0
    def __init__(self):
        super(AbstractRenderer,self).__init__()

        os.environ['SDL_VIDEODRIVER'] = 'dummy'
        pygame.init()
        pygame.display.set_mode((1,1))
        self.sense = SenseHat()
Ejemplo n.º 30
0
import ssl
import json
import time
from sense_hat import SenseHat

connflag = False

def on_connect(client, userdata, flags, rc):
    global connflag
    connflag = True
    if rc==0:
        print ("Connection status: successful")
    elif rc==1:
        print ("Connection status: Connection refused")

sense = SenseHat()

mqttc = paho.Client()
mqttc.on_connect = on_connect

awshost = "a16qzy7tmyv2qb.iot.eu-west-1.amazonaws.com"
awsport = 8883
clientId = "pi-garage"
thingName = "pi-garage"
caPath = "root-CA.crt"
certPath = "pi-garage.cert.pem"
keyPath = "pi-garage.private.key"

mqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
mqttc.connect(awshost, awsport, keepalive=60)
Ejemplo n.º 31
0
from sense_hat import SenseHat

# Grab the orientation of R-Pi
# https://astro-pi.org/wp-content/uploads/2015/10/orientation.png
sense = SenseHat()
orientation = sense.get_orientation()
yaw = orientation['yaw']
roll = orientation['roll']
pitch = orientation['pitch']

print("yaw: " + str(yaw))
print("roll: " + str(roll))
print("pitch: " + str(pitch))

# Is R-Pi perpendicular to the ground?
# If so, use yaw to determine which way is up
# If not, then it's impossible to orient so drop through
if roll < 300 and roll > 80:
    if yaw >= 315 or yaw <= 45:
        sense.set_rotation(90)
    elif yaw >= 225 and yaw < 315:
        sense.set_rotation(0)
    elif yaw >= 135 and yaw < 225:
        sense.set_rotation(270)
    elif yaw > 45 and yaw < 135:
        sense.set_rotation(180)

# Color constants
r = (255, 0, 100)  # raspberry
w = (255, 255, 255)  # white
import threading
import time
from random import randint
from sense_hat import SenseHat
sense = SenseHat()

# Define the colours red and green
red = (255, 0, 0)
green = (0, 255, 0)
black = (0,0,0)
orange = (255, 255, 0)
white = (255,255,255)

# Definizione del lock per sincronizzazione e avvio sequenziale
threadLock = threading.Lock()
 
class MyThread (threading.Thread):
   def __init__(self, nome, durata):
      threading.Thread.__init__(self)
      self.nome = nome
      self.durata = durata
   def run(self):
      # Acquisizione del lock 
      threadLock.acquire()
      time.sleep(self.durata)
      print ("Thread '" + self.name + "' terminato")
      # Rilascio del lock
      threadLock.release()

# Definizione variabili
tempo1 = 25
Ejemplo n.º 33
0
class TwoPlayerGame():
    sense = SenseHat()
    player1_score = 0
    player2_score = 0
    rollDice = RollDice()
    game_goal = 30
    text_speed = 0.04
    playerTurn = 0
    p1 = Player()
    p2 = Player()

    def __init__(self, player1, player2):
        self.p1.name = player1
        self.p2.name = player2


    def Start_Game(self):
        self.rollDice.sense.clear()
        self.sense.show_message("2_plyrs_take_turns_to_shake_PI", self.text_speed)
        self.sense.show_message("1st_over_" + str(self.game_goal) + "_pts_wins!", self.text_speed)
        gameInPlay = True
        while gameInPlay:
            self.player_turn()

            if self.p1.score>self.game_goal or self.p2.score>self.game_goal:
                self.end_game()
                gameInPlay = False



    def player_turn(self):
        currPlayer = Player()
        if(self.playerTurn%2==0):
            currPlayer = self.p1
        else:
            currPlayer = self.p2

        self.sense.show_message(currPlayer.name + "_Shake", self.text_speed)
        score = self.rollDice.detect_shake()
        currPlayer.score+=score
        self.sense.show_message(str(currPlayer.score) + " pts", self.text_speed)
        print("Rolled:", score)
        print(self.p1.name, "has a score of", self.p1.score)
        print(self.p2.name, "has a score of", self.p2.score)
        print()

        self.playerTurn+=1

    def end_game(self):
        self.sense.show_message("Game_over_:(", self.text_speed)
        winner = Player()
        now = datetime.now()
        winning_time = now.strftime("%H:%M:%S")
        if self.p1.score>self.p2.score:
            winner = self.p1
        else:
            winner = self.p2
        self.sense.show_message(winner.name + " won:)", self.text_speed)
        print("Game over - see winner.csv for results")

        with open('winner.csv', 'a+', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(["Winner: ", winner.name, "Score: ", winner.score, "Time: ",  winning_time, "Shakes: ", self.playerTurn])
        file.close()
Ejemplo n.º 34
0
from sense_hat import SenseHat

sense = SenseHat()

sense.set_rotation(180)

red = [255, 0, 0]
green = [0,255,0]
blue = [0,0,255]
<<<<<<< HEAD
color = str(raw_input('indique el color de la temperatura'))


def probando():
    temp = round(sense.get_temperature(),2)
    temp_str = 'Temp: ' + str(temp)

    sense.show_message(temp_str,0.1,color,blue)

    pressure = sense.get_pressure()
    press_str = 'Press: ' + str(pressure)

    sense.show_message(press_str,0.1,blue)

probando()
=======


temp = round(sense.get_temperature(),2)
temp_str = 'Temp: ' + str(temp)
Ejemplo n.º 35
0
#!/usr/bin/env python3
# import specific object from the sense hat package
from sense_hat import SenseHat
sense = SenseHat()
sense.clear()

temp = sense.get_temperature()
sense.show_message('Temp: {0:0.1f} *c'.format(temp), scroll_speed=0.05)
sense.clear()
Ejemplo n.º 36
0
from sense_hat import SenseHat
import sys
import time
import random

sense = SenseHat()
sense.set_imu_config(False, False, False)


def main():
    text = "NMD"
    while True:
        for x in text:
            rnd1 = random.randrange(0, 255)
            rnd2 = random.randrange(0, 255)
            rnd3 = random.randrange(0, 255)
            sense.set_rotation(180)
            sense.show_letter(x, [rnd1, rnd2, rnd3], [0, 0, 0])
            time.sleep(1)
            sense.clear()
        time.sleep(3)


try:
    main()
except (KeyboardInterrupt, SystemExit):
    print('Programma sluiten')
finally:
    print('Opkuisen van de matrix')
    sense.clear()
    sys.exit()
Ejemplo n.º 37
0
from sense_hat import SenseHat
import datetime
import time

sense = SenseHat()
now = datetime.datetime.now()

zero = [[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]
one = [[0, 1, 1, 0], [1, 0, 1, 0], [0, 0, 1, 0], [1, 1, 1, 1]]
two = [[0, 1, 1, 0], [1, 0, 0, 1], [0, 0, 1, 0], [1, 1, 0, 1]]
three = [[1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1], [1, 1, 1, 1]]
four = [[1, 0, 0, 1], [1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1]]
five = [[1, 1, 1, 1], [1, 0, 0, 0], [0, 1, 1, 1], [1, 1, 1, 1]]
six = [[0, 1, 1, 0], [1, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1]]
seven = [[1, 1, 1, 1], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]]
eight = [[1, 1, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 1]]
nine = [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1], [0, 0, 0, 1]]

b = [0, 0, 255]
g = [0, 255, 0]
p = [255, 0, 255]
o = [255, 150, 0]
e = [0, 0, 0]


def num_to_arr(n):
    if n == 0:
        return zero
    elif n == 1:
        return one
    elif n == 2:
Ejemplo n.º 38
0
import params as p
# if you are executing the code from your raspberry with a cam module and a SenseHat connected set simulation = False, otherwise use the simulation mode
simulation_mode = False

from imutils.video import VideoStream
import numpy as np
import cv2
import numpy as np
import time
import pygame
if not simulation_mode:
    from sense_hat import SenseHat
else:
    from sense_emu import SenseHat

sense = SenseHat()
sense.clear()

vs = VideoStream(usePiCamera=not simulation_mode).start()
time.sleep(1.0)

cv2.namedWindow("ROV", cv2.WINDOW_NORMAL)
cv2.resizeWindow('ROV', 600, 600)
pygame.init()

auto = False
use_keyboard = True
use_controller = False

telemetry_dict = {'light': 'OFF'}
Ejemplo n.º 39
0
#!/usr/bin/python
import termios, fcntl, sys, os
from sense_hat import SenseHat
import random

sense = SenseHat()
sense.clear()

fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            c = sys.stdin.read(1)
            print "Got character {} with colour R:{}, G:{}, B:{}".format(
                repr(c), r, g, b)
            sense.show_letter(str(c), text_colour=[r, g, b])
        except IOError:
            pass
finally:
def main():
    sensehat = SenseHat()
    sensehat.set_imu_config(True, True, True)
    velocityMatrix = [0.0, 0.0, 0.0]

    resultMatrixKeys = ['x', 'y', 'z']

    velocityMatrix = dict(zip(resultMatrixKeys, velocityMatrix))
    displacementX = 0
    displacementY = 0
    displacementZ = 0

    sensehat.show_message("calibrating", 0.1, [100, 0, 0])
    sensehat.show_letter('!', [100, 0, 0])
    gCoeff = calculateGCoeff(sensehat)
    sensehat.show_message("Complete", 0.1, [0, 100, 0])
    flag = True
    while flag:
        starttime = time.time()
        '''get raw data'''
        accel_raw = sensehat.get_accelerometer_raw()
        orient_rad = sensehat.get_orientation_radians()
        orient_deg = sensehat.get_orientation_degrees()

        external_temp = sensehat.get_temperature()
        pressure = sensehat.get_pressure()

        eulermatrixtrans = createTransformMatrix(orient_rad)

        accel_procc = removeGravity(accel_raw, eulermatrixtrans, gCoeff)

        accel_real = matrixMultiply3x9(accel_procc, eulermatrixtrans)

        endtime = time.time()
        '''calculate velocity change and displacement'''
        total_time = starttime - endtime
        '''if motion is detected we output distance moved'''
        if abs(accel_procc[0]) > 0.03 or abs(accel_procc[1]) > 0.03 or abs(
                accel_procc[2]) > 0.03:
            print(
                ("acceleration x = {0},y={1},z={2}, degrees to north = {3},{4}"
                 .format(accel_real['x'], accel_real['y'], accel_real['z'],
                         orient_rad, orient_deg)))

        config = {
            "apiKey": "AIzaSyA20qu9ddnRJPAQgGpn9ySQLuqjLH2WWPI",
            "authDomain": "firefightingmonitoringsystem.firebaseapp.com",
            "databaseURL":
            "https://firefightingmonitoringsystem.firebaseio.com/",
            "storageBucket": "firefightingmonitoringsystem.appspot.com"
        }

        fireBase = pyrebase.initialize_app(config)
        db = firebase.database()
        '''Need to add acceleration data'''
        data = {
            "external_temp": external_temp,
            "pressure": pressure,
        }

        results = db.push(data)
        print(results)

    return
Ejemplo n.º 41
0
from sense_hat import SenseHat
from datetime import datetime

sense = SenseHat()


def get_sense_data():
    sense_data = []
    sense_data.append(sense.get_temperature())
    sense_data.append(sense.get_pressure())
    sense_data.append(sense.get_humidity())

    return sense_data


def get_sense_data():
    sense_data = []
    sense_data.append(sense.get_temperature())
    sense_data.append(sense.get_pressure())
    sense_data.append(sense.get_humidity())

    return sense_data


while True:
    print(get_sense_data())
Ejemplo n.º 42
0
# import the SenseHat library
from sense_hat import SenseHat
from time import sleep
from random import randint

sense = SenseHat()

while True:
    # Border (random color)
    X = (randint(0, 255), randint(0, 255), randint(0, 255))
    # No fill
    O = [0, 0, 0]  # Black

    # 4 rectangles of different sizes
    rect1 = [
        X,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
        O,
Ejemplo n.º 43
0
from sense_hat import SenseHat
import time

hat = SenseHat()
hat.set_rotation(180)
hat.low_light = True

blue = (0, 0, 127)
r = (255, 0, 0)
o = (0, 0, 0)
heart = [
    o, r, o, o, o, o, r, o, r, o, r, o, o, r, o, r, r, o, o, r, r, o, o, r, r,
    o, o, o, o, o, o, r, o, r, o, o, o, o, r, o, o, o, r, o, o, r, o, o, o, o,
    o, r, r, o, o, o, o, o, o, o, o, o, o, o
]

# hat.show_message("I Hello World", text_colour=r)
hat.show_letter("I")
time.sleep(2)
hat.set_pixels(heart)
time.sleep(2)
hat.show_message("You")
Ejemplo n.º 44
0
#!/usr/bin/python
from sense_hat import SenseHat
import time

ap = SenseHat()
ho = ap.get_temperature()
uj = ho-10.5
par = ap.get_humidity()
leg = ap.get_pressure()


#print("Homerseklet: %s C" % temp)               # Homerseklet konzolon kiirasa
#print("Paratartalom: %s %%rH" % humidity)        # Paratartalom konzolon kiirasa
#print("Legnyomas: %s Millibars" % pressure)    # Legnyomas konzolon kiirasa

ap.set_rotation(180)        # LED matrix jobbrol balra forgatasa
              
ap.show_message("%.1f C" % uj, scroll_speed=0.10, text_colour=[0, 255, 0])

time.sleep(1)           # 1s varakozas

ap.show_message("%.1f %%rH" % leg, scroll_speed=0.10, text_colour=[255, 0, 0]) 

time.sleep(1)      # 1s varakozas

ap.show_message("%.1f Millibars" % par, scroll_speed=0.10, text_colour=[0, 0, 255])

ap.clear()      # LEDek kikapcsolasa
Ejemplo n.º 45
0
#!/usr/bin/env python
#this script will show a scrolling message on the Pi HAT
from sense_hat import SenseHat
sense = SenseHat()

sense.show_message("Hello, World!")
Ejemplo n.º 46
0
from sense_hat import SenseHat
from time import sleep
from PIL import Image
import numpy as np
import scipy.io


def load_image(values, sense):
    for i in range(0, 7):
        for j in range(0, 7):
            sense.set_pixel(i, j, values[i][j])


def clear_leds(sense):
    sense.clear()


path_to_file = "image"
im = Image.open(path_to_file)
rgb_im = im.convert('RGB')
valyes = np.array(rgb_im)

sense = SenseHat()

clear_leds(sense)

load_image(values, sense)

sense.flip_v()
sense.set_rotation(270)
import time
from sense_hat import SenseHat


COLOR = {
    'white': (255,255,255),
    'half_white':(128,128,128),
    'red': (255,0,0),
    'green': (0,255,0),
    'blue': (0,0,255),
    'off': (0,0,0),
    }

sense = SenseHat()

for i in range(64):
    sense.set_pixel(i%8,int(i/8),i*4+3,i*4+3,i*4+3)

sense.low_light=True
time.sleep(2)
sense.low_light=False
time.sleep(2)

sense.clear()
import pygame

from pygame.locals import *
from sense_hat import SenseHat

pygame.init()
pygame.display.set_mode((320, 240))

sense = SenseHat()
sense.clear()

running = True

x = 0
y = 0

cursor = [200, 0, 200]
blank = [0, 0, 0]

# Use a nice pink colour for the cursor
sense.set_pixel(x, y, cursor)

# The following Dictionary makes up solution to task (2)
color = {
    "red": [255, 0, 0],
    "blue": [0, 0, 248],
    "green": [0, 255, 0],
    "yellow": [255, 255, 0],  # as [R,G,B]
    "cyan": [0, 255, 255],
    "white": [248, 252, 248],
    "black": [0, 0, 0],
Ejemplo n.º 49
0
    parser.add_argument('-start-http-server',
                        '--start-http-server',
                        default=False,
                        action="store_true",
                        help="Start server.")

    parser.add_argument('-kill-http-server',
                        '--kill-http-server',
                        default=False,
                        action="store_true",
                        help="Start server.")

    args = parser.parse_args()

    reflection = Reflection()
    sense = SenseHat()

    cls_client = reflection.get_class(args.link_module, args.client)
    client = cls_client(args.client_settings_file)

    #cls_server = reflection.get_class(args.link_module,args.server)
    #server = cls_server(args.server_settings_file)

    tmux = TmuxHandler()
    if args.start_http_server == True:
        print("Starting http server in tmux mode...")
        name = args.name + "_http"
        cmd = "python start_http_server.py -name " + name + " -server " + args.server + " -server-settings-file " + args.server_settings_file
        cmds = tmux.create_tmux_commands(name, cmd)
        os.system("\n".join(cmds))
        os.system("sleep 2")
Ejemplo n.º 50
0
# Show Message Example 
#This program will let you display a scrolling message on the LED matrix of the SenseHat

#import senseHat library
from sense_hat import SenseHat
# a library is a set of code that can be referenced in a program. It has books (functions) that can be opened to help with tasks. 

#we have to declare how we want to call the libary we imported. This will allow the program to use the books (functions) that are in the library
sense = SenseHat()
#createa  blue variable
b= (0,0,0) #hold the color black
w=(255,255,255)
l= (0,0,255) #holds the color blue
p = (255,128,128)
o = (233,133,0)
#now use the sense libary we will use the set_pixel to make two blue pixels
sense.clear()
texas = [
b,b,o,o,b,b,b,b,
b,b,o,o,b,b,b,b,
b,b,o,o,o,o,o,o,
o,o,o,o,o,o,o,o,
b,o,o,o,o,o,o,o,
b,b,b,o,o,o,o,b,
b,b,b,o,o,b,b,b,
b,b,b,b,o,b,b,b
	]
sense.set_pixels(texas)
Ejemplo n.º 51
0
import time

from sense_hat import SenseHat

sense = SenseHat()
sense.clear()
Ejemplo n.º 52
0
from sense_hat import SenseHat
from time import sleep
import vision_lib

if __name__ == '__main__':

    sense = SenseHat()

    #add your colors
r = (255, 0, 0)
g = (0, 255, 0)
b = (0, 0, 255)
k = (0, 0, 0)
w = (255, 255, 255)
c = (0, 255, 255)
y = (255, 255, 0)
o = (255, 128, 0)
n = (255, 128, 128)
p = (128, 0, 128)
d = (255, 0, 128)
l = (128, 255, 128)

#add your Raspimon lists, the first is an egg

#raspimon_egg =  [(128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (255, 255, 255), (255, 255, 255), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (255, 255, 255), (255, 255, 255), (255, 255, 255), (255, 255, 255), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (255, 255, 255), (255, 255, 255), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128), (128, 0, 128)]

open_eyes = [
    k, k, d, d, d, d, k, k, k, d, d, w, d, w, d, k, d, d, d, k, d, k, d, d, d,
    d, r, d, d, d, r, d, p, p, d, d, k, d, d, p, k, r, r, d, d, d, p, k, r, r,
    r, r, p, p, p, p, k, k, k, k, k, k, k, k
]
	def __init__(self):
		self.sense = SenseHat()
		self.cpu_temp = 0
		self.sensor_temp = 0
		self.room_temp = 0
Ejemplo n.º 54
0
import time
from sense_hat import SenseHat

sense = SenseHat()

pixels = [[255, 0, 0], [255, 0, 0], [255, 87, 0], [255, 196, 0], [205, 255, 0],
          [95, 255, 0], [0, 255, 13], [0, 255, 122], [255, 0, 0], [255, 96, 0],
          [255, 205, 0], [196, 255, 0], [87, 255, 0], [0, 255, 22],
          [0, 255, 131], [0, 255, 240], [255, 105, 0], [255, 214, 0],
          [187, 255, 0], [78, 255, 0], [0, 255, 30], [0, 255, 140],
          [0, 255, 248], [0, 152, 255], [255, 223, 0], [178, 255, 0],
          [70, 255, 0], [0, 255, 40], [0, 255, 148], [0, 253, 255],
          [0, 144, 255], [0, 34, 255], [170, 255, 0], [61, 255,
                                                       0], [0, 255, 48],
          [0, 255, 157], [0, 243, 255], [0, 134, 255], [0, 26, 255],
          [83, 0, 255], [52, 255, 0], [0, 255, 57],
          [0, 255, 166], [0, 235, 255], [0, 126, 255], [0, 17, 255],
          [92, 0, 255], [201, 0, 255], [0, 255, 66], [0, 255, 174],
          [0, 226, 255], [0, 117, 255], [0, 8, 255], [100, 0, 255],
          [210, 0, 255], [255, 0, 192], [0, 255, 183], [0, 217, 255],
          [0, 109, 255], [0, 0, 255], [110, 0, 255], [218, 0, 255],
          [255, 0, 183], [255, 0, 74]]

msleep = lambda x: time.sleep(x / 1000.0)


def next_colour(pix):
    r = pix[0]
    g = pix[1]
    b = pix[2]
Ejemplo n.º 55
0
# 
# 
# 

# In[12]:


# gpio_blink.py
# 

import RPi.GPIO as GPIO # requires install on env-> pip install RPi.GPIO
import time
from sense_hat import SenseHat

# sense hat setup
sh = SenseHat()
sh.clear()
sh.show_message(ini_msg,scroll_speed=0.1, text_colour = [100, 100, 100], back_colour = [0, 0, 0])

ALARM_LED_X = 1
ALARM_LED_Y = 1
ALARM_LED_COLOUR =  [255, 0, 0] # RED

# RPI GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.OUT)
GPIO.setup(20, GPIO.OUT)
GPIO.setup(13, GPIO.IN)

state = True
Ejemplo n.º 56
0
from sense_hat import SenseHat
import time
from random import randint

sense = SenseHat()

letters = "NMD"

#While loop altijd laten doorlopen
while True:
    for letter in letters:
        #Array doorlopen en willekeurige kleur meegeven
        sense.show_letter(
            letter,
            text_colour=[randint(0, 255),
                         randint(0, 255),
                         randint(0, 255)])
        #Na iedere loop een seconde pauzeren
        time.sleep(1)
Ejemplo n.º 57
0
from sense_hat import SenseHat
import time
import random

sense = SenseHat()
sense.set_rotation(270)

#sense.show_message("hello", text_colour=(0, 250, 0), back_colour=(255, 165, 0)) 

for i in range(100):
  xpos = random.randint(0, 7)
  ypos = random.randint(0, 7)
  kleur = random.randint(1, 3)
  if (kleur == 1):
    sense.set_pixel(xpos, ypos, (0, random.randint(100, 255), random.randint(100, 255)))
  elif (kleur == 2):
    sense.set_pixel(xpos, ypos, (random.randint(100, 255), 0, random.randint(100, 255))) 
  else:
    sense.set_pixel(xpos, ypos, (random.randint(100, 255), random.randint(100, 255), 0))
  time.sleep(0.02)
Ejemplo n.º 58
0
def major_colour_range(start, end, steps):
    step = (end - start) // steps
    while True:
        colour = start
        while start < end:
            for i in range(steps):
                yield colour
            colour += step


def pixel_range(red_range, blue_range, green_range):
    yield (next(red_range), next(blue_range), next(green_range))


sense = SenseHat()

green_range = colour_range(50, 255, 7)
blue_range = colour_range(50, 255, 7)

for x in range(8):
    g = next(green_range)
    for y in range(8):
        ##        print(x, y, 0, g, b)
        b = next(blue_range)
        sense.set_pixel(x, y, 0, g, b)

sleep(1)

red_range = colour_range(50, 255, 7)
Ejemplo n.º 59
0
#!?usr/bin/env python 
# this script will display letters with random colors on the Pi HAT
from sense_hat import SenseHat
import time
import random
sense = SenseHat()
# asssign random interger between 0 and 255 to a variable named r
r = random.randint (0,255)
print("the random number is"), r, ("this time")

sense.show_letter("H", (r, 0, 0))
time.sleep(1)
sense.show_letter("i", (0, r, 0))
time.sleep(1)
sense.show_letter("!", (0, 0, r))
time.sleep(1)
sense.clear()

print("done")
Ejemplo n.º 60
-1
class VibrateSensor(object):
    """Vibration Sensor"""

    def __init__(self):
        from sense_hat import SenseHat
        self.movement_threshold = 0.05
        self.sensor = SenseHat()
        self.current_reading = self.sensor.get_accelerometer_raw()
        self.last_reading = self.current_reading

    def read_sensor(self):
        """Set last_reading to prevous sensor reading, and read again"""
        self.last_reading = self.current_reading
        self.current_reading = self.sensor.get_accelerometer_raw()

    def motion_detected(self):
        """Returns True if there has been movement since the last read"""
        self.read_sensor()
        x_movement = abs(self.last_reading['x'] - self.current_reading['x'])
        y_movement = abs(self.last_reading['y'] - self.current_reading['y'])
        z_movement = abs(self.last_reading['z'] - self.current_reading['z'])
        if (x_movement > self.movement_threshold) \
                or (y_movement > self.movement_threshold) \
                or (z_movement > self.movement_threshold):
            return True
        else:
            return False