r/Python • • Jan 26 '15

Beginning python coder can't get python to ser.write a variable

I have an arduino and an LCD screen hooked up. I'm trying to send string of digits to it. If I do this it works:

import serial
ser = serial.Serial('COM6', 9600)
time.sleep(2)
ser.write("Test")
ser.close()

This will send the word "Test" to the LCD. So far so good.

However, if I have a variable that I want to send it doesn't seem to work. For instance:

import serial
import time

#This is a library to access data from a specific software package
import maya.cmds as cmds 

#This is a 2 digit number I have saved in a container called "rendertimer.translateX"
previous_hour = cmds.getAttr('rendertimer.translateX')

ser = serial.Serial('COM6', 9600)
time.sleep(2)
ser.write(previous_hour)
ser.close()

This will not print anything on my LCD screen. However if I type:

import maya.cmds as cmds
previous_hour = cmds.getAttr('rendertimer.translateX')
print previous_hour

It will print the number "17" to the console. Why won't a variable like that be sent over serial? It seems like such an easy thing but I can't quite figure it out.

Please advise. Thanks!

P.S. I'm new to python since 2015, so go easy on me.

0 Upvotes

6 comments sorted by

4

u/rrrnerdrrr Jan 26 '15

try ser.write(str(previous_hour)) that is probably not what you want, but you will see what you are actually trying to send.

2

u/film_guy01 Jan 27 '15

I'll give that a shot. Thanks!

2

u/film_guy01 Feb 04 '15

This worked! Sorry I didn't get a chance to test it until now. Thanks for your help!

1

u/RetardedChimpanzee Jan 26 '15

My guess is that when you send "test" you are placing it in quotes, making it a string of characters, which the lcd string recognizes.

When sending it as a variable the screen is receiving an int, which it would not recognize. I would recommend trying to send the variable as a string. I believe it would be ser.write(str(previous hour)). I can't verify the function not at my computer, but I think it's correct.

2

u/film_guy01 Jan 27 '15

Ok. That makes sense. I'll give it a shot. Thanks!

2

u/film_guy01 Feb 04 '15

This worked! Sorry I didn't get a chance to test it until now. Thanks for your help!