Arduino
//Analog Hall Sensor
//using an LM393 Low Power Low Offset Valtage Dual Comparator
/**********************************
* Analog Hall Sensor Uno3
* A0 A0
* D0 7
* VCC 5V
* GND GND
*********************************/
const int ledPin = 13;//the led attach to pin13
int sensorPin = A0; //Select the input pin for the Sensor
int digitalPin = 7; //D0 attach to pin7
int sensorValue = 0; //variable to store the value coming from A0
boolean digitalValue = 0; //variable to store the value coming from pin7
void setup()
{
pinMode(digitalPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop()
{
sensorValue = analogRead(sensorPin); //read the value of A0
digitalValue = digitalRead(digitalPin); //read the value of D0
Serial.print("Sensor Value ");
Serial.println(sensorValue); //A0
Serial.print("Digital Value ");
Serial.println(digitalValue);
if (digitalValue == HIGH) //if value of D0 is HIGH
{
digitalWrite(ledPin, LOW); //turn off the led
}
if (digitalValue == LOW)
{
digitalWrite(ledPin, HIGH); //turn on the led
}
delay(1000);
}
树莓派
C
#include <stdio.h>
#include <wiringPi.h>
#include <pcf8591.h>
#define PCF 120
int main (void)
{
int res, tmp, status;
wiringPiSetup();
pcf8591Setup(PCF, 0x48); //Setup pcf8591 on base pin 120, and address 0x48
status = 0;
while(1) //loop forever
{
res = analogRead(PCF + 0);
printf("Current intensity of magnetic field: %d\n", res);
if (res-133 < 5 || res-133 > -5)
tmp = 0;
if (res < 128) tmp = -1;
if (res > 138) tmp = 1;
if (tmp != status)
{
switch(tmp)
{
case 0:
printf("\n****************\n");
printf("* Magnet: None. *\n");
printf("*****************\n\n");
break;
case -1:
printf("\n****************\n");
printf("* Magnet: North. *\n");
printf("******************\n\n");
break;
case 1:
printf("\n****************\n");
printf("* Magnet: South. *\n");
printf("******************\n\n");
break;
}
status = tmp;
}
delay(200);
}
return 0;
}
python
#!/usr/bin/env python
import RPi.GPIO as GPIO
import PCF8591 as ADC
import time
def setup():
ADC.setup(0x48)
def Print(x):
if x == 0:
print('*************')
print('* No Magnet *')
print('*************')
print('')
if x == 1:
print('****************')
print('* Magnet North *')
print('****************')
print('')
if x == -1:
print('****************')
print('* Magnet South *')
print('****************')
print('')
def loop():
status = 0
while True:
res = ADC.read(0)
print('Current intensity of magentic field: ', res)
if res-133 < 5 and res-133 > -5:
tmp = 0
if res < 128:
tmp = -1
if res > 138:
tmp = 1
if tmp != status:
Print(tmp)
status = tmp
time.sleep(0.2)
if __name__ == '__main__':
setup()
loop()
网友评论