首先你for
環和if
statment使用錯在這裏,他們是不需要的。該while
迴路可以equivently rewriten爲:
a = "0x750x010x010x060x000x08"
b = a.replace("0x", " ")
while True:
port.write("\r\n"+b)
你的主要misanderstanding是,你認爲Python的理解要遍歷十六進制數。但事實並非如此。在你原來的循環中,它只是逐字逐字地循環訪問a
字符串。實際上,在for
循環的每次迭代中,您只需將原始a
字符串更改爲「75 01 01 06 00 08」並將其作爲字符串發送。
如果你需要發送字節,你應該把你的字符串分成單獨的記錄,每個字節的信息並將這些記錄轉換爲字節。 下面是在評論認爲
a = "0x750x010x010x060x000x08"
b1 = a.split("0x")
# b1 is ["", "75", "01", "01", "06", "00", "08"], the values are still strings
b2 = [int(x, 16) for x in b1[1:]]
# b2 is a list of integers, the values calculated from strings assuming they are hex (16-bit) numbers
# use b1[1:] to cut the first blank string
b = str(bytearray(b2))
#b joins values list into a bytes string (each interger transformed into one byte)
while True:
port.write("\r\n" + b)
更新問題的代碼: 如果a
格式是這樣「0x750101060008」,您只需2個字母把它分解:
b1 = [a[2*i:2*i+2] for i in range(len(a)/2)]
感謝ü阿布舍克..但這會在樹莓派終端輸出...我希望通過在uart終端中選擇十六進制選項在uart終端輸出 –
請解釋整個場景,以便我可以幫到你 –
我附上了終端窗口輸出的快照...你可以看到在我編輯的問題..我可以看到,我已經選擇了ASCII我的選擇,但即時通訊選擇十六進制選項時,它不會給這個輸出...我希望同樣的輸出,當我選擇十六進制選項,我不想這個輸出在ASCII選項 –