Project Detail: I have a pushbutton and as I press it I am increasing a value and sending it over to python. However, no matter what I do, I can not get consistent data when it gets to Python.
Arduino Code:
void button(){
int buttonState = digitalRead(buttonPin);
if (buttonState == HIGH){
index += 1;
Serial.print("{" + String(index) + "}" + "\n");
delay(1000);
Serial.flush();
}
}
Python Code:
def arduinoButton(newData):
inProgress = False
line = []
while arduino.readline() != None and newData == False:
rc = arduino.readline()
print("rc", rc)
for c in rc:
print(c)
if inProgress == True:
if c != "}":
line.append(c)
else:
inProgress = False
newData = True
print(line)
return line
elif c == "{":
inProgress = True
while True:
newData = False
num = arduinoButton(newData)
This is what is being received:
However, what I am hoping for is getting {index} each time
This is what I have used to read a line of input from Arduino a line at a time.
Put a small delay in the Arduino sending code so only one line is sent at a time.
p.s. this is slightly edited from what I actually used
def haveLineOfData():
# returns True if have received non-empty msg else False
global receivedText, charsReceived, timeLastMsgRecived, clearToSendFlag
receivedText = ""
if serialPort.inWaiting() == 0:
return False
foundEOL = False
while serialPort.inWaiting() > 0: # have something to read
x = serialPort.read().decode("utf-8") # decode needed for Python3
if x == '\n':
foundEOL = True
break
else:
charsReceived += x
if foundEOL:
#clear out any following data
while serialPort.inWaiting() > 0: # have something to read
serialPort.read()
if len(charsReceived) == 0:
return False # empty msg returns False
# else have non-empy msg and are connected
receivedText = charsReceived
charsReceived = ""
return True
# else still waiting for whole line
return False
#==================
First step is to reduce the complexity of your "system" to the lowest possible level.
In this case this means instead of receiving the serial data in your python-script.
recieve the serial data in the serial monitor of the Arduino-IDE.
And look what data do you receive.
Next step is to use a minimalistic arduino-program that does send a fixed string to your python script testing if your python-script is able to receive this data.
Then adding a button to your Arduino-code sending a fixed text and again printing to the serial monitor of the Arduino-IDE. To test if your button is working as expected.
The more complexity to put together untested the more time you need to go through all the possabilities that might cause the problem. This time increases expontentially with the complexity.
So in the end you finish yor project faster by using really small tiny test-programs.