Ejemplo n.º 1
0
def main():
	wm=wimote.connect(Led)
	while True:
		button=wimote.whichbutton(wm)
		time.sleep(0.05)
		wm.rumble=False
	
			
		#Moving Forwards		
		if button==3:
			distance_front = usonic.reading(Trigger_front,Echo_front)
			print distance_front
			if distance_front < Collision:
				wm.rumble=True
				#led.off(Led)
				motor.stop()
			elif distance_front >= Collision:
				#led.on(Led)
				motor.forward()
		#Reverse
		if button==4:
			motor.reverse()
		if button==7:
			motor.cleanup()
			led.cleanup()
			usonic.cleanup()
			sys.exit()
		if button==None:
			led.off(Led)
			motor.stop()
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
def initialize():
    start_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    led.blink(1000, 100)
    print "pixhawk..."

    serial_ok = False

    if os.path.exists("/log/.factory") or os.path.exists(
            "/log/updates/FACTORYRESET") or os.path.exists(
                "/log/updates/UPDATE") or os.path.exists(
                    "/log/updates/RESETSETTINGS"):
        os.system("rm -f /log/.factory")
    else:
        serial_ok = checkArduCopter()

        # if we're in factory reset, just reset parameters and exit
        if recoveryCheck() and serial_ok:
            resetParameters()
        else:
            # find and load ArduCopter FW
            if doFirmware():
                serial_ok = checkArduCopter()

            # reset ArduCopter parameters if tagged
            if os.path.exists("/firmware/resetParams") and serial_ok:
                resetParameters()
                os.remove("/firmware/resetParams")

    led.off()
    end_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    logger.debug("pixhawk initialization took %0.3f sec",
                 (end_us - start_us) / 1000000.0)
Ejemplo n.º 4
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
Ejemplo n.º 5
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()
Ejemplo n.º 6
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()
Ejemplo n.º 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)
Ejemplo n.º 8
0
    def _Led_OFF(self):

        self._head_html()
        resposta = """
                <html>
                <head>
                <meta http-equiv="refresh" content="0; url=http://pi.g2.asi.itic.cat:808/led_off.html">
                </head>
                </html>
                """
        self.wfile.write(resposta)
        led.off()
Ejemplo n.º 9
0
def button():
    delta = 0
    if (GPIO.input(5) == GPIO.LOW):
        startTime = time.perf_counter()
        while GPIO.input(5) == GPIO.LOW:
            pass
        delta = time.perf_counter() - startTime
    if (delta < 0.5 and delta > 0.05):
        buttonPressed()
    elif (delta >= 0.5):
        led.off()
        time.sleep(1)
Ejemplo n.º 10
0
        def _Led_OFF(self):

                self._head_html()
		resposta =  """
                <html>
                <head>
                <meta http-equiv="refresh" content="0; url=http://pi.g2.asi.itic.cat:808/led_off.html">
                </head>
                </html>
                """
                self.wfile.write(resposta)
                led.off()
Ejemplo n.º 11
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
Ejemplo n.º 12
0
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
Ejemplo n.º 13
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()
Ejemplo n.º 14
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')
Ejemplo n.º 15
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)
Ejemplo n.º 16
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))
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
    def sendAt(self, command, success='OK', error='ERROR', wait=2):
        """
		Function to send AT commands
		to GSM Module
		"""
        if not self.stopEvent.isSet():
            print '{0:20}'.format(command),

            try:
                self.obj.write(command + '\r\n')
            except Exception as e:
                self.gsm_init('sendAt(): ' + str(e))

            time.sleep(0.25)

            self.status = self.checkStatus(success, error, wait)

            if 'Success' in self.status:
                led.blink_slow(led.pin['at'])
                return 'Success'

            elif 'Timeout' in self.status:
                debugLog.error('TIMEOUT=> ' + command)
                errTime.setBit(command)
                return 'ErrorTimeout'

            elif 'Error' in self.status:
                debugLog.error('ERROR=> ' + command)
                errGsm.setBit(command)
                led.off(led.pin['at'])
                return 'Error'

            else:
                debugLog.error('OTHER=> ' + command)
                errUnknown.setBit(command)
                led.off(led.pin['at'])
                return 'Other'
Ejemplo n.º 19
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())
Ejemplo n.º 20
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)
Ejemplo n.º 21
0
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()
    #added 2017-1105
    max_row -= 1
    if max_row <1:
        #restart rows
Ejemplo n.º 22
0
def initialize():
    global cube_version
    firmware_path = None
    paramsAfterLoad = False

    start_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    led.blink(1000, 100)
    print "pixhawk..."
    baud = get_baud()
    if baud == None:
        print "pixhawk: ERROR checking baud"
        logger.error("finding baud")
        logger.error("pixhawk status: no response")
        # pixhawk might be stuck in bootloader

    # If we're in a factory reset, we just need to reset the pixhawk.
    # If we've just completed the clean install, load the appropriate ArduCopter FW and reset the pixhawk
    # Otherwise, just look in /firmware and load whatever is there.
    if recoveryCheck():
        resetParameters()
        rebootPixhawk()
    else:
        if (os.path.isdir("/firmware/3dr")
                or os.path.isdir("/firmware/green")) and checkPixhawkVersion():
            # This must be a clean install if the initial FW directories are here.
            paramsAfterLoad = True
            if cube_version == 'cube_20':
                (firmware_path,
                 firmware_version) = find_firmware(firmware_root_3dr)
            elif cube_version == 'cube_21':
                (firmware_path,
                 firmware_version) = find_firmware(firmware_root_green)
        else:
            # Not a clean install, look for FW in the normal location
            (firmware_path, firmware_version) = find_firmware(firmware_root)

    if firmware_path is None:
        logger.info("no new firmware file")
    elif os.path.exists("/log/.factory") and (baud
                                              is not None) and verify_usb():
        logger.info("pixhawk: factory - not loading firmware")
    else:
        print "pixhawk: loading firmware"
        logger.info("%s:", firmware_path)
        for v in firmware_version:
            logger.info("%-20s %s", v, firmware_version[v])
        if load(firmware_path):
            move_firmware(firmware_path)
            os.system("rm -rf /firmware/3dr")
            os.system("rm -rf /firmware/green")
            os.system("rm -rf /firmware/wipe")
            if paramsAfterLoad:
                logger.info("Executing post-install parameter reset...")
                resetParameters()
                rebootPixhawk()
                logger.info("...Reset complete")
        else:
            print "pixhawk: ERROR loading firmware"
            logger.error("pixhawk status: can't load")

    os.system("rm -f /log/.factory")

    running_version = get_version()
    logger.info(running_version)

    logger.info("now running:")
    for component in [
            "build_version", "ardupilot_git_hash", "px4_git_hash",
            "nuttx_git_hash"
    ]:
        if component in running_version:
            version = running_version[component]
        else:
            version = "unknown"
        logger.info("%-20s %s", component, version)
    write_version_file(running_version)
    if "build_version" in running_version \
        and running_version["build_version"] != "unknown":
        logger.info("pixhawk status: ready")
        print "pixhawk: running %s" % running_version["build_version"]
    else:
        print "pixhawk: ERROR checking version"
    led.off()
    end_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    logger.debug("pixhawk initialization took %0.3f sec",
                 (end_us - start_us) / 1000000.0)
Ejemplo n.º 23
0
def o():  # 字符o的莫尔斯码表示
    for i in range(3):  # 哒循环三次
        music.pitch(1000, 150, wait=0)  # 蜂鸣 频率 持续时间 等待时间
        led.on()  # 点亮led
        sleep(50)  # 延迟50毫秒
        led.off()  # 关闭led
Ejemplo n.º 24
0
# 电位器控制灯泡-改进2

# 硬件模块:
# micro:bit×1;主板×1
# 模块×2:电位器、LED灯泡

# 简介:
# 根据电位器读数设置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()
Ejemplo n.º 25
0
def reset_lights():
    led.off(0)
    led.off(1)
    led.off(2)
    led.off(3)
    led.off(4)
    led.off(5)
    led.off(6)
    led.off(7)
    led.off(8)
Ejemplo n.º 26
0
def initialize():
    start_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    led.blink(1000, 100)
    print "pixhawk..."
    baud = get_baud()
    if baud == None:
        print "pixhawk: ERROR checking baud"
        logger.error("finding baud")
        logger.error("pixhawk status: no response")
        # pixhawk might be stuck in bootloader

    # try to load if we have firmware, whether we found the baud or not

    (firmware_path, firmware_version) = find_firmware()
    if firmware_path is None:
        logger.info("no new firmware file")
        # Another backup would be to look in /firmware/loaded and load
        # whatever's there if we did not get a heartbeat. Getting stuck in
        # the bootloader has so far only been observed to happen when a
        # programming is interrupted, in which case the firmware we were
        # loading is still in /firmware.
    elif os.path.exists("/log/.factory") and \
         (baud is not None) and \
         verify_usb():
        logger.info("pixhawk: factory - not loading firmware")
        move_firmware(firmware_path)
    else:
        print "pixhawk: loading firmware"
        logger.info("%s:", firmware_path)
        for v in firmware_version:
            logger.info("%-20s %s", v, firmware_version[v])
        if load(firmware_path):
            move_firmware(firmware_path)
        else:
            print "pixhawk: ERROR loading firmware"
            logger.error("pixhawk status: can't load")

    # If .factory exists, we either found a baud, passed USB, and skipped
    # loading pixhawk, or either did not find a baud or USB heartbeat, and
    # loaded pixhawk.
    os.system("rm -f /log/.factory")

    # We have followed some combination of these to get here:
    #   * found baud | did not find baud
    #   * no firmware | firmware and flashed it | firmware and error flashing
    #
    # The cases that are known to happen:
    #   Normal cases
    #   * Found baud, there was no new firmware
    #   * Found baud, there was new firmware, flashed it
    #   Error cases
    #   * Did not find baud, there was new firmware, flashed it
    #
    # Other cases should "never" happen (and have not been observed):
    #   * Did not find baud, there was no new firmware
    #       The only known way to not find the baud is if pixhawk is stuck in
    #       its bootloader, which happens because flashing was interrupted,
    #       which means there is new firmware available.
    #   * Found baud, there was new firmware, error flashing it
    #   * Did not find baud, there was new firmware, error flashing it
    #       Should "never" fail to flash pixhawk when we try to.

    # This should work for any of the three known-to-happen cases. For the
    # error cases, running_version will be set to an empty dictionary, and
    # write_version_file will write "unknown" for all the versions.
    # get_version() can return None if the configuration is corrupt, but in
    # that case we have far deeper problems (an md5 has just succeeded).
    running_version = get_version()

    logger.info("now running:")
    for component in [
            "build_version", "ardupilot_git_hash", "px4_git_hash",
            "nuttx_git_hash"
    ]:
        if component in running_version:
            version = running_version[component]
        else:
            version = "unknown"
        logger.info("%-20s %s", component, version)
    write_version_file(running_version)
    if "build_version" in running_version \
        and running_version["build_version"] != "unknown":
        logger.info("pixhawk status: ready")
        print "pixhawk: running %s" % running_version["build_version"]
    else:
        print "pixhawk: ERROR checking version"
    led.off()
    end_us = clock.gettime_us(clock.CLOCK_MONOTONIC)
    logger.debug("pixhawk initialization took %0.3f sec",
                 (end_us - start_us) / 1000000.0)
Ejemplo n.º 27
0
# 主节点读取子节点上传感器的读数并将结果显示在自身的元件上:
# 温湿度传感器的读数将直接显示于OLED显示屏内,光敏电阻则会在光强低于一定阈值时点亮LED灯泡,在光强高于阈值时则熄灭

# 硬件模块:
# micro:bit×2;主板×2
# 模块×4:(主节点)OLED显示屏、LED灯泡;(子节点)温湿度传感器、光敏电阻

import mb,oled,light,led,temp_humi # 主板、模块控制库
from microbit import *
import music

# 初始化
mb.remote_on()# 启动远程模式
led_on=0
oled.clear()
led.off()
timer=0
light_read=0
tmp,hum='--','--'
while True:
    timer+=1

    # 每500帧更新温湿度读数
    if timer>500:
        timer-=500
        t,h=temp_humi.temp_humi()
        if t!=None:
            tmp,hum=t,h
        oled.clear()
        oled.show(1,8,b'\xce\xc2\xb6\xc8\xa3\xba%s\xa1\xe6'%tmp)
        oled.show(4,8,b'\xca\xaa\xb6\xc8\xa3\xba%s\xa3\xa5'%hum)
Ejemplo n.º 28
0
 def _Led_OFF(self):
     self._head_html()
     resposta = "Off"
     self.wfile.write(resposta)
     led.off(ser)
Ejemplo n.º 29
0
import sensor, avi, time, led
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)
Ejemplo n.º 30
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
Ejemplo n.º 31
0
 def _Led_OFF(self):
         self._head_html()
         resposta ="Off"
         self.wfile.write(resposta)
         led.off(ser)
Ejemplo n.º 32
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)