回転する磁場の速度を調整するプログラムを作成しています。基本的に、私はちょうどユーザーの意図された速度を表すためにシリアルポートを介してフロートを送信しようとしています。しかし、私は本当に意味をなさないエラーが発生しています。私はずっと小さな部分でエラーを分離しました。PySerial:TypeError: 'float'オブジェクトが反復不可能です
コード:私は、スクリプトを実行する場合、これは誤りである
import serial #imports PySerial Library
#Function allows for user input and conversion to float.
#If not float, "Invalid" is printed to the console, and input is requested again
def get_float(prompt):
while True: #Main Loop
try:
response = raw_input(prompt) #User inputs
return float(response) #Conversion is attempted
except:
print("Invalid") #If conversion fails
def magnet_speed():
input = get_float('Enter a speed in rpm to immediately change rotation speed\n>> ')
print input
arduino.write(input) #send to arduino
arduino = serial.Serial('/dev/ttyACM0', 9600) #declares which serial port the arduino is con$
magnet_speed()
exit()
:
Enter a speed in rpm to immediately change rotation speed
>> a
Invalid
Enter a speed in rpm to immediately change rotation speed
>> 4
4.0
Traceback (most recent call last):
File "magnet_speed.py", line 22, in <module>
magnet_speed()
File "magnet_speed.py", line 16, in magnet_speed
arduino.write(input) #send to arduino
File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 498, in write
d = to_bytes(data)
File "/usr/local/lib/python2.7/dist-packages/serial/serialutil.py", line 66, in to_bytes
for item in seq:
TypeError: 'float' object is not iterable
私の唯一の考えは、私がget_float()
右からfloatを返すいないよ場合、または私はありません変数input
が正しく定義されています。 get_float()
関数は、pythonシェルで実行すると、入力された数値を単独で出力することは間違いありません。
arduino.write(出力)には繰り返し可能なアイテムが必要です。試してみてくださいarduino.write([出力]) – galaxyan
@ galaxyan:シリアルポート*バイト文字列を扱う*。 Pythonではiterableです。 –
@MartijnPietersは理にかなっています。ありがとうございます。 – galaxyan