串行通信PySerial我得到奇怪的字符(可能是ASCII?)我无法解码我

2024-10-01 15:44:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在Arduino和Python之间通信串行数据。我得到这个字符列表,但我不能把它们转换成整数。我没有通过解码来运行它:当我发送0-255的值时,它就工作了。。。你知道吗

我使用的是python3.7

y.encode('utf-8').strip()

Python代码

import serial
import numpy as np

barr = [4]

ser = serial.Serial(
    port='COM12',\
    baudrate=56000,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=5)

print("connected to: " + ser.portstr)
count=0

while True:

    y = ser.readline(512)
    print(y)

Python输出:

b'\x9a1\x9aX\x9a\x7f\x9a\xa6\x9c\xce\x9a\xf5\x9a\x1c\x9aC\x9cj\x9a\x91\x9a\xb8\x9a\xdf\x9c\x06\x9a-\x9cT\x9a{\x9c\xa2\x9c\xc9\x9a\xf0\x9a\x17\x9c>\x9af\x9a\x8d\x9a\xb4\x9a\xdb\x9a\x02\ and it goes one....

你知道吗串行写入Arduino代码的一部分:

for (unsigned short int nIndexStep = 0; nIndexStep<g_objRF.getConfiguration()->getFreqSpectrumSteps(); nIndexStep++)
  {

    //Print every step of sweep data onto display
    int stepFreq = g_objRF.getSweepData()->getFrequencyKHZ(nIndexStep);
    int stepAmp  = g_objRF.getSweepData()->getAmplitudeDBM(nIndexStep);
    delay(serialdelay);

    Serial.write(stepFreq);
    delay(serialdelay);
    Serial.write(stepAmp);
    if (stepAmp <= (TopLevel -90))
    {
      stepAmp = TopLevel -90;
    }
    if (stepAmp > TopLevel)
    {
      stepAmp = TopLevel;
    }
    //Serial.print(stepAmp);
    //Serial.print(", ");
    comp2 = stepAmp;
    comp1 = max(comp1, comp2);




    {

    }

  }



      }
      Serial.write("\n");



Tags: 代码importserialarduinoserwriteintprint
1条回答
网友
1楼 · 发布于 2024-10-01 15:44:50

与串行写入可以发送字节、字符串或字节数组。不能发送整数。你知道吗

如果要发送整数,必须先将其转换为字节数组。你知道吗

有无数种方法可以做到这一点。位掩码,投射指针,联合体。。。只要在网上搜索并选择你最喜欢的。你知道吗

https://www.arduino.cc/reference/en/language/functions/communication/serial/write/

相关问题 更多 >

    热门问题