Example #1
0
def deng(text):
    if text[0].__eq__("开") and text[1].__eq__("灯"):
        led.on()
    elif text[0].__eq__("关") and text[1].__eq__("灯"):
        led.off()
    else:
        return has_weather(text)
Example #2
0
def main():
    trigger = 26.0
    lcd.setup()
    lcd.initDisplay()
    file = open('/home/pi/temp.txt', 'a')
    led.setup()
    led.off(led.green)
    led.off(led.yellow)
    last = 0.0
    while 1:
        t = return_temp_from_file('/sys/bus/w1/devices/')
        lcd.clearLCD()
        lcd.write('Temp: ')
        tc = str(float(t) / 1000)
        lcd.write(tc + ' ')
        lcd.cmd8b(0b11011111, True)
        lcd.write('C')
        file.write(time.strftime('%d.%m.%Y') + '; ' +
                   time.strftime('%H:%M:%S') + '; ' + tc + '\n')
        file.flush()
        tt = float(tc)
        if tt < trigger and last >= trigger:
            led.off(led.yellow)
            led.on(led.green)
        elif tt >= trigger and last < trigger:
            led.off(led.green)
            led.on(led.yellow)
        last = tt
Example #3
0
def recordAudio(device):
        if(device!=1):  led.on()
	print colored("\n**start record**\n",'magenta')
	# only records for 5 second, as hardcoded value
	with sr.Microphone() as source: audio = r.record(source, duration=5)
	print colored("\n**end record**\n",'magenta')
	if(device!=1):  led.off()
	return audio
Example #4
0
def adc_thread():
    while True:
        time.sleep_ms(100)  #线程每100毫秒检测一次按键是否被按下
        val = adc.get()
        if val > 0 and val < 1000:  #过滤掉启动和无按键被按下时的值
            led.on()  #有按键按下,我们让led亮
            print("val:", val)  #打印采集值
        else:
            led.off()
Example #5
0
def on_message(client,userdata,msg):
	cmd1=msg.payload              # cmd1 is a live command(might be out of order)
	print cmd1
	db_obj.insert(cmd1)
	cmdx=db_obj.fetch()				#cmdx is fetched from db order by time
	if cmdx=="on":
		led.on()
	else:
		led.off()
Example #6
0
        def _Led_ON(self):
                
                self._head_html()
		resposta ="""
                <html>
                <head>
                <meta http-equiv="refresh" content="0; url=http://pi.g2.asi.itic.cat:808/led_on.html">
                </head>
                </html>
                """
                self.wfile.write(resposta)
                led.on()
Example #7
0
def serialDisplay(dt=2.0):
    import time
    import utime
    while True:
        led.on()
        
         timestamp = utime.localtime()
        #print('{0},{1},{2},{3},{4},{5},{6},{7:0.2f}'.format(_LOCATION, timestamp[0],timestamp[1],timestamp[2],_tc(timestamp[3]),timestamp[4],timestamp[5],temp))
        print( temp_record(timestamp, temp) )
        
        led.off()
        time.sleep(dt)
Example #8
0
    def _Led_ON(self):

        self._head_html()
        resposta = """
                <html>
                <head>
                <meta http-equiv="refresh" content="0; url=http://pi.g2.asi.itic.cat:808/led_on.html">
                </head>
                </html>
                """
        self.wfile.write(resposta)
        led.on()
Example #9
0
def main():
    reset_lights()
    count = 0  #slows down the loop
    pin = 0  #pin number of LED to light
    old_pin = 0
    idle()
    while True:
        count += 1

        #start the game sequence
        if is_button_pressed() == 0:
            print(game_state)
            if game_state == "idle":
                game()
                sound("game")

            #check results of game
            elif game_state == "game":
                end_game(pin)
            time.sleep(.5)

        #Game blinks at higher rate
        if count == 25 or count == 50 or count == 75:
            if game_state == "game":
                old_pin = pin
                pin = non_repeating_random(pin)
                #print("blink "+str(pin))
                led.blink(old_pin, pin)

        if count > 100:
            count = 0

            #once ambient sound complete and state is idle pick another song
            if pygame.mixer.music.get_busy() == 0:
                if game_state == "idle":
                    music()
                elif game_state == "game":
                    end_game(pin)

            #depending on state blink lights
            if game_state == "game":
                old_pin = pin
                pin = non_repeating_random(pin)
                #print("blink "+ str(pin))
                led.blink(old_pin, pin)
            elif game_state == "idle":
                pin = non_repeating_random(pin)
                #print("fade "+str(pin))
                led.on(pin)
                led.fade(pin)
        time.sleep(.01)  #slow loop down a bit
def connect(Led):
	while True:
		try:	
			print 'Press Button 1 and 2 on the remote'
			led.on(Led)
			time.sleep(1)
			wm=cwiid.Wiimote()
		except RuntimeError:
			continue
		break
	print 'Remote Connected'
	led.off(Led)
	time.sleep(1)

	Rumble = False
	wm.rpt_mode=cwiid.RPT_BTN
	return wm
Example #11
0
    def handle_read(self):
        try:
            data = self.recv(1024)
            if not data:
                return

            lf_char_index = data.find('\n')

            if lf_char_index == -1:
                # No new line character in data, so we append all.
                self.data += data
            else:
                # We see a new line character in data, so append rest and handle.
                self.data += data[:lf_char_index]

                if self.data == "blink":
                    print "blink start"
                    led.blink(led_pin, 1, 1, 5)
                    print "blink end"

                elif self.data == "turn LED on":
                    print "turning on LED"
                    self.send("turning on LED")
                    led.on(led_pin)

                elif self.data == "turn LED off":
                    print "turning off LED"
                    self.send("turning off LED")
                    led.off(led_pin)

                elif self.data == "read adc":
                    read_value = adc.read0()
                    print "ADC 0 value read: " + str(read_value)
                    self.send(str(read_value) + '\n')

                else:
                    print "received [%s]" % self.data
                    self.send(self.data + '\n')

                # Clear the buffer
                self.data = ""
        except Exception as e:
            BTError.print_error(handler=self, error=BTError.ERR_READ, error_message=repr(e))
            self.data = ""
            self.handle_close()
Example #12
0
def index():
    if request.method == 'POST':
        if request.form['state_button'] == 'On':
            led.on()
        elif request.form['state_button'] == 'Off':
            led.off()
        elif request.form['state_button'] == 'Red':
            led.colour('Red')
        elif request.form['state_button'] == 'Blue':
            led.colour('Blue')
        elif request.form['state_button'] == 'Green':
            led.colour('Green')
        elif request.form['state_button'] == 'Fade':
            led.fade()

        slider = request.form["brightnessSlider"]
        print(slider)
    return render_template('index.html')
Example #13
0
def temperatureStore(dt=2.0):
    import time
    import utime
    
    # helper function to add sensor data record to file
    def write_record(timestamp, temp):
        f = open('temperature.txt', 'a') #append mode
        #data = '{0},{1},{2},{3},{4},{5},{6},{7:0.2f}\n'.format(_LOCATION, timestamp[0],timestamp[1],timestamp[2],_tc(timestamp[3]),timestamp[4],timestamp[5],temp)
        f.write( temp_record(timestamp, temp) )
        f.close()

    while True:
        led.on()
        
        temp = ds18b20.temperature(ds)
        timestamp = utime.localtime()
        write_record(timestamp, temp)
        
        led.off()
        time.sleep(dt)
Example #14
0
def run():
    r = 0  # To ensure it will loop
    x_angle = sensor.get_x_rotation()
    log.current("The x angle is {}".format(x_angle))
    try:
        while r == 0:
            x_angle = sensor.get_x_rotation()
            if x_angle < 0:
                log.current("the x angle is {}".format(x_angle))
                motor.run_motor(direction="clockwise")
                led.on()
                sleep(0.5)
                led.off()
            elif x_angle > 0:
                log.current("the x angle is {}".format(x_angle))
                motor.run_motor(direction="anti")
                led.on()
                sleep(0.5)
                led.off()
            else:
                log.current("the x angle is {}".format(x_angle))
                led.on()
                sleep(0.5)
                led.off()
        log.records("program loop ran successfully.")
    except Exception as error:
        log.records("program loop stopped because of {}.".format(error))
Example #15
0
def temperatureStore(dt=2.0):
    import time
    import utime

    def write_record(timestamp, temp):
        f = open('temperature.txt', 'a') #append mode
        data = '{0},{1},{2},{3},{4},{5},{6},{7:0.2f}\n'.format(_LOCATION,timestamp[0],timestamp[1],timestamp[2],timestamp[3]+2,timestamp[4],timestamp[5],temp)
        f.write(data)
        f.close()

    while True:
        led.on()
        temp = ds18b20.temperature(ds)
        timestamp = utime.localtime()
        print('{0},{1},{2},{3},{4},{5},{6},{7:0.2f}'.format(_LOCATION,timestamp[0],timestamp[1],timestamp[2],timestamp[3]+2,timestamp[4],timestamp[5],temp))
        write_record(timestamp, temp)
        #f = open('temperature.txt', 'a') #append mode
        #data = '{0},{1},{2},{3},{4},{5},{6},{7:0.2f}\n'.format(_LOCATION,timestamp[0],timestamp[1],timestamp[2],timestamp[3]+2,timestamp[4],timestamp[5],temp)
        #f.write(data)
        #f.close()
        led.off()
        time.sleep(dt)
Example #16
0
 def _Led_ON(self):
         self._head_html()
         resposta ="On"
         self.wfile.write(resposta)
         led.on(ser)
Example #17
0
import led, time
while (vcp_is_connected()==False):
   led.on(led.BLUE)
   time.sleep(150)
   led.off(led.BLUE)
   time.sleep(100)
   led.on(led.BLUE)
   time.sleep(150)
   led.off(led.BLUE)
   time.sleep(600)
Example #18
0
def o():  # 字符o的莫尔斯码表示
    for i in range(3):  # 哒循环三次
        music.pitch(1000, 150, wait=0)  # 蜂鸣 频率 持续时间 等待时间
        led.on()  # 点亮led
        sleep(50)  # 延迟50毫秒
        led.off()  # 关闭led
Example #19
0
# 根据电位器读数设置LED灯泡状态
# 加入记录LED状态的变量以防止重复发出指令
# 在micro:bit显示屏上增加对电位器示数的显示

import poten, led  # 导入模块控制库
from microbit import sleep, display

is_on = False  # 记录LED当前状态,防止重复操作
led.off()  # 确保初始LED为关闭状态

# 循环进行
while True:
    # 读取电位器位置(0-4095)
    pv = poten.value()

    # 根据读数设置LED灯状态
    if pv < 2048:
        if is_on:
            led.off()
            is_on = False
    elif not is_on:
        is_on = True
        led.on()

    # 计算并设置点亮像素位置
    pos = int(pv * 25 / 4100)
    display.clear()
    display.set_pixel(pos % 5, pos // 5, 9)

    # 等待0.2秒后进行下一次读数
    sleep(200)
Example #20
0
#alert led - #added 2017-1105
import led
led = led.setup() #default pin WeMOS D1 mini: GPIO12

import socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.bind(addr)
s.listen(1)

print('listening on', addr)
rows = [] #empty rows #added 2017-1105
max_row = 12 #added 2017-1105
while True:
    led.on() #show I'm alive
    cl, addr = s.accept() #wait for client

    print('client connected from', addr)
    led.off() #client connected
    cl_file = cl.makefile('rwb', 0)
    while True:
        line = cl_file.readline()
        if not line or line == b'\r\n':
            break
    #rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins]
    #OK: rows += ['<tr><td> %s </td></tr>' % str((ds18b20.temperature(ds)))]
    rows += ['<tr><td> {0:4.1f} </td></tr>'.format(ds18b20.temperature(ds))]
    response = html % '\n'.join(rows)
    cl.send(response)
    cl.close()
Example #21
0
    # Take snapshot
    image = sensor.snapshot()

    # Threshold image with RGB
    binary  = image.threshold([(255, 0, 0),
                               (0, 255,  0),
                               (0, 0, 255)], 80)

    # Image closing
    binary.dilate(3)
    binary.erode(3)

    # Detect blobs in image
    blobs = binary.find_blobs()

    led.off(led.RED)
    led.off(led.GREEN)
    led.off(led.BLUE)

    # Draw rectangles around detected blobs
    for r in blobs:
        if r[5]==1:
            led.on(led.RED)
        if r[5]==2:
            led.on(led.GREEN)
        if r[5]==3:
            led.on(led.BLUE)
        image.draw_rectangle(r[0:4])

    print(clock.fps())
Example #22
0
 def _Led_ON(self):
     self._head_html()
     resposta = "On"
     self.wfile.write(resposta)
     led.on(ser)
Example #23
0
def main():
    t1 = backFill(event, stopEvent)
    t2 = live(event, stopEvent)

    threadPool.append(t1)
    threadPool.append(t2)

    t1.start()
    t2.start()


if __name__ == '__main__':
    stopEvent = threading.Event()
    threadPool = []
    led.on(led.pin['code'])

    modem_ok_q = queue()

    modemThread = led.modem_ok_th(modem_ok_q, stopEvent)
    #threadPool.append(modemThread)
    modemThread.start()

    #try:
    #	os.system("clear")
    #except :
    #	pass

    #debugLog    = log.debugLog('./log/dredger2_debug')         # Code for PC
    #liveLog     = log.liveLog('./log/dredger2_live')
    #backLog     = log.backfillLog('./log/dredger2_backfill')
Example #24
0
'''
    Simple echo server
'''
import wlan
import socket
import select
import led, time

SSID = ''  # Network SSID
KEY = ''  # Network key
HOST = ''  # Use first available interface
PORT = 8000  # Arbitrary non-privileged port

led.off(led.RED)
led.off(led.BLUE)
led.on(led.GREEN)

# Init wlan module and connect to network
wlan.init()
wlan.connect(SSID, sec=wlan.WPA2, key=KEY)
led.off(led.GREEN)

# Wait for connection to be established
while (True):
    led.toggle(led.BLUE)
    time.sleep(250)
    led.toggle(led.BLUE)
    time.sleep(250)
    if wlan.connected():
        led.on(led.BLUE)
        break
Example #25
0
REC_LENGTH = 10  # recording length in seconds

# Set sensor parameters
sensor.reset()
sensor.set_contrast(2)
sensor.set_framesize(sensor.VGA)
sensor.set_pixformat(sensor.JPEG)
sensor.set_quality(95)

led.off(led.RED)
time.sleep(5 * 1000)

path = "%d.mjpeg" % random(0, 1000)
vid = avi.AVI(path, 640, 480)

led.on(led.RED)
clock = time.clock()
start = time.ticks()
while ((time.ticks() - start) < (REC_LENGTH * 1000)):
    clock.tick()
    image = sensor.snapshot()
    vid.add_frame(image)

vid.flush(int(clock.fps()))
led.off(led.RED)

while (True):
    led.toggle(led.BLUE)
    time.sleep(500)
    led.toggle(led.BLUE)
    time.sleep(500)
Example #26
0
import led, time
while (vcp_is_connected() == False):
    led.on(led.BLUE)
    time.sleep(150)
    led.off(led.BLUE)
    time.sleep(100)
    led.on(led.BLUE)
    time.sleep(150)
    led.off(led.BLUE)
    time.sleep(600)