振动传感器

电路图:
树梅派学习 11. 振动传感器实验和干簧管传感器_#define

接线图:
树梅派学习 11. 振动传感器实验和干簧管传感器_git_02

实体接线图:

程序:

#include <wiringPi.h>
#include <stdio.h>

#define VibratePin 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)
{
int status = 0;
int tmp = 0;
int value = 1;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}

pinMode(VibratePin, INPUT);

while(1){
value = digitalRead(VibratePin);
if (tmp != value){
status ++;
if (status > 1){
status = 0;
}
LED(status);
Print(status);
delay(1000);
}
}
return 0;
}

干簧管传感器

线路图:
树梅派学习 11. 振动传感器实验和干簧管传感器_git_03
代码:

#include <wiringPi.h>
#include <stdio.h>

#define ReedPin 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(ReedPin, INPUT);
LED("GREEN");

while(1){
if(0 == digitalRead(ReedPin)){
delay(10);
if(0 == digitalRead(ReedPin)){
LED("RED");
printf("Detected Magnetic Material!\n");
}
}
else if(1 == digitalRead(ReedPin)){
delay(10);
if(1 == digitalRead(ReedPin)){
while(!digitalRead(ReedPin));
LED("GREEN");
}
}
}
return 0;
}