简体   繁体   中英

How to use an Arduino joystick button with Pyfirmata

I made a program that uses PyFirmata with a joystick in Arduino. Everything was working properly except for the button. I understand it to the point that I know that I need to write a voltage first but then after that when I read the value it just stays at 1 no matter what. To make sure my board or joystick or something was not faulty I ran it using c++ the default Arduino language and it worked. Please note I am new to Arduino so keep that in mind. Here is my code:

from pyfirmata import Arduino
from pyfirmata.util import Iterator
import time

# Setup
try:
    board = Arduino('COM6')
    iterator = Iterator(board)
    iterator.start()
    print("Successfully Connected to Arduino Board")
except:
    print("ERROR: Could Not Connect to Arduino Board")
    board = None
    exit()

joystick_x = board.get_pin("a:0:i")
joystick_y = board.get_pin("a:1:i")
joystick_switch = board.digital[3]

dt = 0.1
val_x, val_y, val_s = .5, .5, 0

joystick_switch.write(1)

while True:
    time.sleep(dt)
    val_x = joystick_x.read()
    val_y = joystick_y.read()
    val_s = joystick_switch.read()
    print(val_s)

I figured out the Answer. With PyFirmata when you write you cant correctly read it again. Though in c++ you can. So to get around this I edited my circuit so that I write to another pin then have the joystick switch between them and finally do an analog read. I have to do an analog read because some of the current will make it through. To fix this I used the floor function from the math library to get the correct value. Thank you to everyone who tried to help. Here is the code for anyone who wants to view it:

from pyfirmata import Arduino, PWM, INPUT, OUTPUT
from pyfirmata.util import Iterator
import time
from math import floor

# Setup
try:
    board = Arduino('COM6')
    print("here")
    iterator = Iterator(board)
    iterator.start()
    print("Successfully Connected to Arduino Board")
except:
    print("ERROR: Could Not Connect to Arduino Board")
    board = None
    exit()

joystick_x = board.get_pin("a:0:i")
joystick_y = board.get_pin("a:1:i")
joystick_x.enable_reporting()
joystick_y.enable_reporting()
joystick_switch = board.get_pin("a:3:i")
joystick_switch2 = board.digital[2]
joystick_switch.enable_reporting()

dt = 0.1
val_x, val_y, val_s = .5, .5, 0

joystick_switch2.write(1)

while True:
    time.sleep(dt)
    val_x = joystick_x.read()
    val_y = joystick_y.read()
    val_s = floor(joystick_switch.read())
    # if val_x is None or val_y is None or val_s:
    #     val_x, val_y, val_s = .5, .5, 0
    print(val_s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM