树莓派python 控制GPIO

sudo pip install rpi.gpio

 

#!/usr/bin/env python
# encoding: utf-8

import RPi.GPIO as GPIO
import time

# 指定GPIO口的选定模式为GPIO引脚编号模式
GPIO.setmode(GPIO.BCM)

# 指定GPIO14的模式为输出模式,且初始状态为低电平。
# 如果上面GPIO口的选定模式指定为主板模式的话,这里就应该指定8号而不是14号。
GPIO.setup(14, GPIO.OUT,initial = GPIO.LOW)

# 循环10次
for i in range(0, 10):
    # 让GPIO14输出高电平(LED灯亮)
    GPIO.output(14, True)
    # 持续一段时间
    time.sleep(0.5)
    # 让GPIO14输出低电平(LED灯灭)
    GPIO.output(14, False)
    # 持续一段时间
    time.sleep(0.5)

GPIO.cleanup()
# 清理GPIO口

  

 

 

#!/usr/bin/env python
# encoding: utf-8
import time
import RPi.GPIO as GPIO

GPIO.cleanup()

GPIO.setmode(GPIO.BCM)

btn_input = 27;
LED_output = 17;

# GPIO btn_input set up as input.
GPIO.setup(btn_input, GPIO.IN)
GPIO.setup(LED_output, GPIO.OUT)

# handle the button event
def buttonEventHandler_rising (pin):
    # turn LED on
    print('buttonEventHandler_rising',pin)
    GPIO.output(LED_output,True)
    

	
GPIO.add_event_detect(btn_input, GPIO.RISING , callback=buttonEventHandler_rising, bouncetime=200) 

try:  
    while True : time.sleep(0.1)  
finally:
    GPIO.remove_event_detect(btn_input)
    GPIO.cleanup()

  

#!/usr/bin/python
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|-|S|p|y|.|c|o|.|u|k|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# ultrasonic_1.py
# Measure distance using an ultrasonic module
#
# Author : Matt Hawkins
# Date   : 09/01/2013

# Import required Python libraries
import time
import RPi.GPIO as GPIO

# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)

# Define GPIO to use on Pi
GPIO_TRIGGER = 23
GPIO_ECHO    = 24

print "Ultrasonic Measurement"

# Set pins as output and input
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  # Trigger
GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

while 1==1:

  # Set trigger to False (Low)
  GPIO.output(GPIO_TRIGGER, False)
  
  # Allow module to settle
  time.sleep(0.5)
  
  # Send 10us pulse to trigger
  GPIO.output(GPIO_TRIGGER, True)
  time.sleep(0.00001)
  GPIO.output(GPIO_TRIGGER, False)
  start = time.time()
  
  
  while GPIO.input(GPIO_ECHO)==0:
    start = time.time()
  
  while GPIO.input(GPIO_ECHO)==1:
    stop = time.time()
  
  # Calculate pulse length
  elapsed = stop-start
  
  # Distance pulse travelled in that time is time
  # multiplied by the speed of sound (cm/s)
  distance = elapsed * 34300
  
  # That was the distance there and back so halve the value
  distance = distance / 2
  
  print "Distance : %.1f" % distance
  
  # Reset GPIO settings
GPIO.cleanup()

  

转载于:https://www.cnblogs.com/ahuo/p/10868816.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值