I am new to Python and programming in general.
I am in the process of making a remote control for Spotify using an Arduino and python.
Whenever a button is pressed on the Arduino, a single character is sent via serial. There is a python script listening for this character and based on what the character is it executes a command. The problem that I am having is that the spotify.playpause() works every time its respective button is pressed, but all the other commands require multiple button presses. I am sure it is not an issue with the Arduino because I have confirmed via multiple serial monitors that the character is being sent correctly, so I believe that it is an issue with the Python loop.
EDIT: Just adding more information, it seems that different combinations of serial.read() or serial.readline on the python side and Serial.print or Serial.println on the Arduino side have no effect on the issue
TL;DR The loop doesn’t fully execute, what’s wrong with it.
Here is the code:
import serial
from pytify import Spotify
spotify = Spotify()
connected = False
ser = serial.Serial("COM3", 57600)
while not connected:
serin = ser.read()
connected = True
while True:
if ser.read() == '0':
spotify.playpause()
elif ser.read() == '1':
spotify.volumeUp()
elif ser.read() == '2':
spotify.volumeDown()
elif ser.read() == '3':
spotify.previous()
elif ser.read() == '4':
spotify.next()
else :
pass
Your problem is that you keep calling ser.read for each if/elif case, so you are discarding the value each time your comparison fails. You need to call ser.read only once, then compare that result using a local var, like this: