def ADC_Read(channel):
value = 0;
for i in range(0,4):
if((channel >> (3 - i)) & 0x01):
GPIO.output(Address,GPIO.HIGH)
else:
GPIO.output(Address,GPIO.LOW)
GPIO.output(Clock,GPIO.HIGH)
GPIO.output(Clock,GPIO.LOW)
for i in range(0,6):
GPIO.output(Clock,GPIO.HIGH)
GPIO.output(Clock,GPIO.LOW)
time.sleep(0.001)
for i in range(0,10):
GPIO.output(Clock,GPIO.HIGH)
value <<= 1
if(GPIO.input(DataOut)):
value |= 0x01
GPIO.output(Clock,GPIO.LOW)
return value
python类input()的实例源码
def detect_distance():
# ??????
GPIO.output(TRIG_CHANNEL, GPIO.HIGH)
# ??10us??
time.sleep(0.000015)
GPIO.output(TRIG_CHANNEL, GPIO.LOW)
while GPIO.input(ECHO_CHANNEL) == GPIO.LOW:
pass
# ???????????
t1 = time.time()
while GPIO.input(ECHO_CHANNEL) == GPIO.HIGH:
pass
# ??????????
t2 = time.time()
# ?????????
return (t2-t1)*340/2
def jsonstatus():
status = {}
for pin in pinLEDs:
status[pinLEDs[pin]] = str(GPIO.input(pin))
status['distance'] = str(round(MeasureDistance() * 100, 1)) + ' cm'
status['surface'] = BlackOrWhite()
# JSON encode and transmit response
response = json.dumps(status)
client_sock.send(response)
return
#
# main loop
#
# add serial port service
def get_status_string():
with thermostatLock:
sched = "None"
if holdControl.state == "down":
sched = "Hold"
elif useTestSchedule:
sched = "Test"
elif heatControl.state == "down":
sched = "Heat"
elif coolControl.state == "down":
sched = "Cool"
return "[b]System:[/b]\n " + \
"Heat: " + ( "[color=00ff00][b]On[/b][/color]" if GPIO.input( heatPin ) else "Off" ) + "\n " + \
"Cool: " + ( "[color=00ff00][b]On[/b][/color]" if GPIO.input( coolPin ) else "Off" ) + "\n " + \
"Fan: " + ( "[color=00ff00][b]On[/b][/color]" if GPIO.input( fanPin ) else "Auto" ) + "\n " + \
"Sched: " + sched
def ShowPhoto(photoFile):
screen = pygameEngine.GetScreen()
image = pygame.image.load(photoFile).convert()
image = pygame.transform.scale(image, (config.WIDTH,config.HEIGHT))
screen.blit(image, (0,0))
pygame.display.update()
sleep(1)
pygameEngine.ShowNavButtons()
i = 0
while True:
# get one pygame event
event = pygame.event.poll()
# handle events
# Button 1 = Quit
if (event.type == pygame.MOUSEBUTTONUP and event.button == 1) or (event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE) or GPIO.input(config.GPIO_NUMBER_BUTTON_1):
return -1
# Button 2 = Cycle old photos
if (event.type == pygame.MOUSEBUTTONUP and event.button == 3) or (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN) or GPIO.input(config.GPIO_NUMBER_BUTTON_2):
return 1
# Button Esc or Q = Quit keys
if event.type == pygame.KEYDOWN and (event.key == pygame.K_ESCAPE or event.key == pygame.K_q) :
return -1
def button_pressed(self, channel):
# Debouncing
time.sleep(0.05)
if (GPIO.input(channel) == 0):
# Find out which button was pressed
for button in self.buttons:
if (channel == self.buttons[button]):
# Change screen
if (button == 'MODE_BUTTON'):
if (self.display != False):
self.display.change_screen()
# Toggle backlight
elif (button == 'PAUSE_BUTTON'):
if (self.display != False):
self.display.toggle_backlight()
# Send command to MPD client
elif (self.mpd != False):
self.mpd.commands(button.replace('_BUTTON', ''))
def lowBattery(channel):
#Checking for LED bounce for the duration of the battery Timeout
for bounceSample in range(1, int(round(batteryTimeout / sampleRate))):
time.sleep(sampleRate)
if GPIO.input(batteryGPIO) is 1:
break
global playerFlag
while playerFlag is 1:
time.sleep(1)
#If the LED is a solid for more than 10% of the timeout, we know that the battery is getting low. Launch the Low Battery alert.
if bounceSample > int(round(batteryTimeout / sampleRate * 0.1)):
playerFlag = 1
os.system("/usr/bin/omxplayer --no-osd --layer 999999 " + lowalertVideo + " --alpha 160;");
playerFlag = 0
#Discovered a bug with the Python GPIO library and threaded events. Need to unbind and rebind after a System Call or the program will crash
GPIO.remove_event_detect(batteryGPIO)
GPIO.add_event_detect(batteryGPIO, GPIO.FALLING, callback=lowBattery, bouncetime=300)
def powerSwitch(channel):
#Checking for LED bounce for the duration of the Power Timeout
for bounceSample in range(1, int(round(powerTimeout / sampleRate))):
time.sleep(sampleRate)
if GPIO.input(powerGPIO) is 0:
break
if bounceSample is int(round(powerTimeout / sampleRate)) - 1:
#When the Power Switch is placed in the off position with no bounce for the duration of the Power Timeout, we immediately shutdown
os.system("sudo shutdown -h now")
try:
sys.stdout.close()
except:
pass
try:
sys.stderr.close()
except:
pass
sys.exit(0)
def main():
#if the Low Battery LED is active when the program launches, handle it
if GPIO.input(batteryGPIO) is 0:
lowBattery(batteryGPIO)
#if the Power Switch is active when the program launches, handle it
if GPIO.input(powerGPIO) is 1:
powerSwitch(powerGPIO)
#Add threaded event listeners for the Low Battery and Power Switch
try:
GPIO.remove_event_detect(batteryGPIO)
GPIO.add_event_detect(batteryGPIO, GPIO.FALLING, callback=lowBattery, bouncetime=300)
GPIO.remove_event_detect(powerGPIO)
GPIO.add_event_detect(powerGPIO, GPIO.RISING, callback=powerSwitch, bouncetime=300)
except KeyboardInterrupt:
GPIO.cleanup()
def read(self):
self.waitForReady()
unsignedValue = 0
for i in range(0, self.readBits):
GPIO.output(self.PD_SCK, True)
unsignedValue = unsignedValue << 1
GPIO.output(self.PD_SCK, False)
bit = GPIO.input(self.DOUT)
if (bit):
unsignedValue = unsignedValue | 1
self.setChannelGainFactor()
signedValue = self.correctForTwosComplement(unsignedValue)
self.lastVal = signedValue
return self.lastVal
def set(self):
parser = argparse.ArgumentParser(
description='Set zone state high=1 or low=0')
parser.add_argument('--zone', help='Set zone 1/2/3/4/5 or *', required=False)
parser.add_argument('--state',help='Set state high=1 or low=0', required=False)
args = parser.parse_args(sys.argv[2:])
if args.zone:
for zone in self.data["zones"]:
if zone["id"]==int(args.zone):
GPIO.setup(zone["boardOut"], GPIO.OUT)
GPIO.output(zone["boardOut"], int(args.state))
zone["value"] = GPIO.input(int(zone["boardOut"]))
print zone
else:
self.setAll(args.state)
def get(self):
parser = argparse.ArgumentParser(
description='Set zone state high=1 or low=0')
parser.add_argument('--zone', help='Set zone 1/2/3/4/5 or *', required=False)
args = parser.parse_args(sys.argv[2:])
if args.zone:
for zone in self.data["zones"]:
if zone["id"]==int(args.zone):
GPIO.setup(zone["boardOut"], GPIO.OUT)
zone["value"]=GPIO.input(int(zone["boardOut"]))
print zone
else:
print self.getAll()
def value(self, v=None):
if v is None:
return GPIO.input(self.gpio_no)
GPIO.output(self.gpio_no, v)
print("GPIO ########## GPIO.output({},{})={}".format(self.gpio_no,v,GPIO.input(self.gpio_no)))
def accState(roomNumber, accNumber):
if roomNumber == 0:
if GPIO.input(outPin[roomNumber][accNumber]) is 1:
return 'containerOff'
else:
return 'containerOn'
elif roomNumber > 0:
#get the state of other accesories in other rooms
return 'containerOff'
def buttonStates():
accState=[]
for i in range(len(outPin)):
accState.append([])
for j in range(len(outPin[i])):
accState[i].append(1 - GPIO.input(outPin[i][j]))
return json.dumps(accState)
def toggle(roomNumber, accNumber):
if len(outPin[roomNumber]) != 0:
state= 1 - GPIO.input(outPin[roomNumber][accNumber])
GPIO.output(outPin[roomNumber][accNumber], state)
#subprocess.call(['./echo.sh'], shell=True)
else:
#action for other rooms
subprocess.call(['./echo.sh'], shell=True)
#print(roomNumber, accNumber)
buttonHtmlName = accName[roomNumber][accNumber].replace(" ", "<br>")
passer="<button class='%s' onclick='toggle(%d,%d)'>%s</button>" % (accState(roomNumber,accNumber), roomNumber, accNumber, buttonHtmlName)
return passer
def getio(self, io_number):
if self.importlib is not None:
return GPIO.input(io_number)
def main():
read_25 = GPIO.input(25)
print(read_25)
GPIO.cleanup()
###
#############################
def get_state(sleep_time=wheel_pulse):
# clear trigger sensor
gpio.output(trigger, False)
time.sleep(sleep_time)
# send trigger pulse
gpio.output(trigger, True)
time.sleep(0.00001)
gpio.output(trigger, False)
while gpio.input(echo) == 0:
pulse_start = time.time()
while gpio.input(echo) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 343 * 100 / 2. # speed of sound m/s * m to cm / round trip
if distance > 2 and distance < 400: # sensor range
distance = distance + distance_from_sensor_to_car_front
# don't worry about things further 4'
# this also reduces the size of the state machine
if distance >= max_distance:
distance = max_distance - 1
return int(distance)
##############################################################################
# perform action
##############################################################################
def get_distance(self):
# clear trigger
gpio.output(self.trigger, False)
time.sleep(0.1)
print('checking.....')
# send pulse to trigger
gpio.output(self.trigger, True)
time.sleep(0.00001)
gpio.output(self.trigger, False)
# check echo for return signal
while gpio.input(self.echo) == 0:
self.pulse_start = time.time()
while gpio.input(self.echo) == 1:
self.pulse_end = time.time()
pulse_duration = self.pulse_end - self.pulse_start
distance = self.speed_of_sound / 2. * pulse_duration
distance = round(distance, 2)
distance /= 2.54 # inches
# filter out things far away
if distance > self.max_distance:
distance = self.max_distance
# filter out junk
if distance < self.min_distance:
disance = self.min_distance
return distance