# 接线图
# 树莓派管脚图
# 代码
| #include <stdio.h> |
| #include <wiringPi.h> |
| #include <pcf8591.h> |
| |
| #define PCF 120 |
| #define uchar unsigned char |
| |
| int AIN0 = PCF + 0; |
| int AIN1 = PCF + 1; |
| int AIN2 = PCF + 2; |
| |
| char *state[6] = {"home", "up", "down", "left", "right", "pressed"}; |
| |
| int direction(){ |
| int x, y, b; |
| int tmp; |
| x = analogRead(AIN1); |
| y = analogRead(AIN0); |
| b = analogRead(AIN2); |
| if (y == 0) |
| tmp = 1; |
| if (y == 255) |
| tmp = 2; |
| |
| if (x == 255) |
| tmp = 3; |
| if (x == 0) |
| tmp = 4; |
| |
| if (b == 0) |
| tmp = 5; |
| if (x-125<15 && x-125>-15 && y-125<15 && y-125>-15 && b == 255) |
| tmp = 0; |
| |
| return tmp; |
| } |
| |
| int main (void) |
| { |
| int tmp; |
| int status = 0; |
| wiringPiSetup (); |
| |
| pcf8591Setup (PCF, 0x48); |
| while(1) |
| { |
| tmp = direction(); |
| if (tmp != status) |
| { |
| printf("%s\n", state[tmp]); |
| status = tmp; |
| } |
| } |
| return 0 ; |
| } |
编译命令: gcc joystick_PS2.c -o joystick_PS2 -lwiringPi
# Python
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| import PCF8591 as ADC |
| import time |
| |
| def setup(): |
| ADC.setup(0x48) |
| global state |
| |
| def direction(): |
| state = ['home', 'up', 'down', 'left', 'right', 'pressed'] |
| i = 0 |
| |
| if ADC.read(0) <= 5: |
| i = 1 |
| if ADC.read(0) >= 250: |
| i = 2 |
| |
| if ADC.read(1) >= 250: |
| i = 3 |
| if ADC.read(1) <= 5: |
| i = 4 |
| |
| if ADC.read(2) == 0: |
| i = 5 |
| |
| if ADC.read(0) - 125 < 15 and ADC.read(0) - 125 > -15 and ADC.read(1) - 125 < 15 and ADC.read(1) - 125 > -15 and ADC.read(2) == 255: |
| i = 0 |
| |
| return state[i] |
| |
| def loop(): |
| status = '' |
| while True: |
| tmp = direction() |
| if tmp != None and tmp != status: |
| print tmp |
| status = tmp |
| |
| def destroy(): |
| pass |
| |
| if __name__ == '__main__': |
| setup() |
| try: |
| loop() |
| except KeyboardInterrupt: |
| destroy() |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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) |
| |