jped
jped

Reputation: 486

How to convert ASCII characterers to Strings in Python

I am trying to compare an ASCII character that I am receiving from the serial port with a string. I am not able to do that, even though it seems like I have converted the inputs successfully. Here is my code

import serial
import time 
port="/dev/ttyUSB0"
serialArduino= serial.Serial(port,9600)
serialArduino.flushInput()
inputs=""
while True:
    inputsp=serialArduion.readline()
    for letter in inputsp:
        inputs=inputs+ str(letter)
   print inputs
   if inputs=="DOWN":
       print "APPLES"
   elif inputs=="UP"
       print "Bannana"

ok so even though the input sometimes equals UP OR DOWN it still does not print out APPLES or Bannana

Upvotes: 1

Views: 1953

Answers (2)

falsetru
falsetru

Reputation: 368944

The return value of readline() contains newline. You need to strip newline.

import serial
import time 
port="/dev/ttyUSB0"
serialArduino= serial.Serial(port,9600)
serialArduino.flushInput()

while True:
    inputs = serialArduion.readline().rstrip()
    if inputs == "DOWN":
        print "APPLES"
    elif inputs == "UP"
        print "Bannana"

Upvotes: 2

rajpy
rajpy

Reputation: 2476

try this:

while True:
    inputsp=serialArduion.readline()
    for letter in inputsp:
        inputs=inputs+ chr(letter)
   print inputs
   if inputs.lower() =="down":
       print "APPLES"
   elif inputs.lower() =="up":
       print "Bannana"

Just changed 'str' to 'chr', which converts ASCII to a character. Other than this modification, strip off any other characters coming from input stream.

Upvotes: 0

Related Questions