# 接线图
# 树莓派管脚图
# 代码
| #include <stdio.h> |
| #include <wiringPi.h> |
| #include <pcf8591.h> |
| |
| #define PCF 120 |
| |
| int main (void) |
| { |
| int res, tmp, status; |
| wiringPiSetup (); |
| |
| pcf8591Setup (PCF, 0x48); |
| status = 0; |
| while(1) |
| { |
| 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 ; |
| } |
编译命令: gcc analog_hall_switch.c -o analog_hall_switch -lwiringPi
# 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 '*************' |
| print '* No Magnet *' |
| print '*************' |
| print '' |
| if x == 1: |
| print '' |
| print '****************' |
| print '* Magnet North *' |
| print '****************' |
| print '' |
| if x == -1: |
| print '' |
| print '****************' |
| print '* Magnet South *' |
| print '****************' |
| print '' |
| |
| def loop(): |
| status = 0 |
| while True: |
| res = ADC.read(0) |
| print 'Current intensity of magnetic 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() |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| import smbus |
| import time |
| |
| |
| bus = smbus.SMBus(1) |
| |
| |
| def setup(Addr): |
| global address |
| address = Addr |
| |
| def read(chn): |
| if chn == 0: |
| bus.write_byte(address,0x40) |
| if chn == 1: |
| bus.write_byte(address,0x41) |
| if chn == 2: |
| bus.write_byte(address,0x42) |
| if chn == 3: |
| bus.write_byte(address,0x43) |
| bus.read_byte(address) |
| return bus.read_byte(address) |
| |
| def write(val): |
| temp = val |
| temp = int(temp) |
| |
| bus.write_byte_data(address, 0x40, temp) |
| |
| if __name__ == "__main__": |
| setup(0x48) |
| while True: |
| print 'AIN0 = ', read(0) |
| print 'AIN1 = ', read(1) |
| tmp = read(0) |
| tmp = tmp*(255-125)/255+125 |
| write(tmp) |
| |