倾斜传感器利用传感器倾斜程度,实现开关功能,原理如同轻触开关,我们代码的主要任务也是利用引脚接收到高低信号,然后根据接收结果控制两个输出电位高低,控制双色LED。
#include <wiringPi.h>
#include <stdio.h>#define TiltPin 0
#define Gpin 1
#define Rpin 2void 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);}elseprintf("LED Error");
}int main(void)
{if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screenprintf("setup wiringPi failed !");return 1; }pinMode(TiltPin, INPUT);LED("GREEN");while(1){if(0 == digitalRead(TiltPin)){delay(10);if(0 == digitalRead(TiltPin)){LED("RED");printf("Tilt!n");}}else if(1 == digitalRead(TiltPin)){delay(10);if(1 == digitalRead(TiltPin)){while(!digitalRead(TiltPin));LED("GREEN");}}}return 0;
}
#!/usr/bin/env python
import RPi.GPIO as GPIOTiltPin = 11
Gpin = 12
Rpin = 13def setup():GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical locationGPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to outputGPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to outputGPIO.setup(TiltPin, 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(TiltPin, 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 ' * Tilt! *'print ' *************'def detect(chn):Led(GPIO.input(TiltPin))Print(GPIO.input(TiltPin))def loop():while True:passdef destroy():GPIO.output(Gpin, GPIO.HIGH) # Green led offGPIO.output(Rpin, GPIO.HIGH) # Red led offGPIO.cleanup() # Release resourceif __name__ == '__main__': # Program start from heresetup()try:loop()except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.destroy()
**PS:**python编程也如之前的轻触开关一样,也是用电为升降,不过python中利用了GPIO.add_event_detect
函数比较高级而已
本文发布于:2024-01-28 12:51:55,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17064175207552.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |