【树莓派+arduino实验记录17】金属触摸传感器
2020-09-09 本文已影响0人
Geekero
Arduino
/*****************************
* name:Touch Switch
* function:
* ***********************************/
const int SensorPin = 7;
const int ledPin = 13;
int SensorState = 0;
void setup()
{
pinMode(SensorPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
SensorState = digitalRead(SensorPin);
Serial.println(SensorState);
if (SensorState == HIGH)
{
digitalWrite(ledPin, LOW); //turn off
}
else
{
digitalWrite(ledPin, HIGH); //turn on
}
}
树莓派
C
#include <wiringPi.h>
#include <stdio.h>
#define TouchPin 0
#define Gpin 1
#define Rpin 2
int tmp = 0;
void LED(int color)
{
pinMode(Gpin, OUTPUT);
pinMode(Rpin, OUTPUT);
if (color == 0)
{
digitalWrite(Rpin, HIGH);
digitalWrite(Gpin, LOW);
}
else if (color == 1)
{
digitalWrite(Rpin, LOW);
digitalWrite(Gpin, HIGH);
}
else
{
printf("LED ERROR");
}
}
void Print(int x)
{
if (x != tmp){
if (x == 0)
printf("...ON\n");
if (x == 1)
printf("...OFF\n");
tmp = x;
}
}
int main(void)
{
if (wiringPiSetup() == -1){
printf("setup wiringPi failed !\n");
return 1;
}
pinMode(TouchPin, INPUT);
while(1){
LED(digitalRead(TouchPin));
Print(digitalRead(TouchPin));
}
return 0;
}
Python
#!/usr/bin/env python
import RPi.GPIO as GPIO
TouchPin = 11
Gpin = 12
Rpin = 13
tmp = 0
def setup():
GPIO.setmode(GPIO.BOARD) #Numbers GPIOs by physical location
GPIO.setup(Gpin, GPIO.OUT)
GPIO.setup(Rpin, GPIO.OUT)
GPIO.setup(TouchPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #Set BtnPin's mode is input, and pull up to high level(3.3V)
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):
global tmp
if x != tmp:
if x == 0:
print('')
print('********')
print('* ON *')
print('********')
if x == 1:
print('')
print('********')
print('* OFF *')
print('********')
tmp = x
def loop():
while True:
Led(GPIO.input(TouchPin))
Print(GPIO.input(TouchPin))
def destroy():
GPIO.output(Gpin, GPIO.HIGH) #Green led off
GPIO.output(Rpin, GPIO.HIGH) #Red led off
GPIO.cleanup()
if __name__ == '__main__':
setup()
try:
loop()
except KeyboardInterrupt:
destroy()