C语言编程
本次的C语言程序也并不难,一开始定义3个引脚,两个为输出引脚,用来控制双色LED,一个为输入引脚,用来读取按键开关的高低电位,根据电为的变化调整LED灯的颜色,按键为什么会有delay(10)
是为了检测当前按键是否按压后抬起。
#include <wiringPi.h>
#include <stdio.h>
#define BtnPin 0
#define Gpin 1
#define Rpin 2
void LED(char* color)
{
pinMode(Gpin, OUTPUT);
pinMode(Rpin, OUTPUT);
if (color == "RED")
{
digitalWrite(Rpin, HIGH);
digitalWrite(Gpin, LOW);
}
else if (color == "GREEN")
{
digitalWrite(Rpin, LOW);
digitalWrite(Gpin, HIGH);
}
else
printf("LED Error");
}
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
pinMode(BtnPin, INPUT);
LED("GREEN");
while(1){
if(0 == digitalRead(BtnPin)){
delay(10);
if(0 == digitalRead(BtnPin)){
LED("RED");
printf("Button is pressed\n");
}
}
else if(1 == digitalRead(BtnPin)){
delay(10);
if(1 == digitalRead(BtnPin)){
while(!digitalRead(BtnPin));
LED("GREEN");
}
}
}
return 0;
}
Python编程
#!/usr/bin/env python
import RPi.GPIO as GPIO
BtnPin = 11
Gpin = 12
Rpin = 13
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output
GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V)
GPIO.add_event_detect(BtnPin, GPIO.BOTH, callback=detect, bouncetime=200)
def Led(x):
if x == 0:
GPIO.output(Rpin, 1)
GPIO.output(Gpin, 0)
if x == 1:
GPIO.output(Rpin, 0)
GPIO.output(Gpin, 1)
def Print(x):
if x == 0:
print ' ***********************'
print ' * Button Pressed! *'
print ' ***********************'
def detect(chn):
Led(GPIO.input(BtnPin))
Print(GPIO.input(BtnPin))
def loop():
while True:
pass
def destroy():
GPIO.output(Gpin, GPIO.HIGH) # Green led off
GPIO.output(Rpin, GPIO.HIGH) # Red led off
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
PS:Python中GPIO控制的初始化控制-------两种
在python的GPIO初始化上可以用GPIO.setup(pinx,GPIO.IN,pull_up_down=GPIO.PUD_UP/GPIO.DOWN)
来控制上下拉。原代码中使用的是初始化上拉。
PS:添加临界检测
GPIO.add_event_detect(channel, GPIO.RISING, callback=my_callback)
在通道上添加上升临界值检测
Pass的作用
大家可以看到loop()
下的pass。
pass的作用是在编写代码时只写框架思路,具体实现还未编写就可以用 pass 进行占位,使程序不报错,不会进行任何操作。
还有非常重要的一点,我们怎么让我们设置的电频可以从高到低或者从低到高呢?
wait_for_edge() #函数
event_detected() #函数
(1) wait_for_edge()
函数是为了阻止程序的执行,直到检测到边缘为止。
GPIO.wait_for_edge(channel, GPIO_RISING, timeout=5000)
注意检测的边缘参数有
GPIO.RISING, GPIO.FALLING , GPIO.BOTH
(上升沿, 下降沿 或 升降沿), 这样用几乎不占用CPU,如果你只希望在,使用 timeout
参数确定的时间段内查询
(2)event_detected()
函数被设计用来与其他事物一起在循环中使用,它不会在CPU忙于处理其他事物时错过输入状态的变化。这使得使用Pygame 或 PyQt 时非常有用,因为其中有一个主循环监听和及时响应GUI事件的基础。
只要检测到指定参数的边缘事件(上升沿, 下降沿 或 升降沿)发生时,调用GPIO.event_detected(channel)的值就为"ture"(真)。
GPIO.add_event_detect(BtnPin, GPIO.BOTH, callback=detect, bouncetime=200)
PS给回调函数添加一个弹跳时间的参数( bouncetime= )