Python 3 CSV整数到字节+\n

2024-04-18 23:18:05 发布

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

我正在尝试用python中的串行通信与Arduino通信。有一个来自arduino https://www.arduino.cc/en/Tutorial/ReadASCIIString的程序。只需发送一个“120200100”来控制3个LED。当我用python编写数据到arduino时

你知道吗arduino.write公司(b'120,10244\n')

而且很有效。但我的主要问题是,如果我把这些值赋给一个变量,这个变量通过GUI得到更改,例如我计划在其上实现的PyQT滑块,我应该怎么做呢?你知道吗

如何输出分配给变量的3个整数->;到csv->;字节+\n

例如

P1=self.pwm1水平滑块.value()#假设值为120

P2=self.pwm2水平滑块.value()#假设值为200

P3=self.pwm3水平滑块.value()#假设值为100

进入b'120200100\n'

读取ASCII字符串代码

// pins for the LEDs:
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // make the pins outputs:
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);

}

void loop() {
  // if there's any serial available, read it:
  while (Serial.available() > 0) {

    // look for the next valid integer in the incoming serial stream:
    int red = Serial.parseInt();
    // do it again:
    int green = Serial.parseInt();
    // do it again:
    int blue = Serial.parseInt();

    // look for the newline. That's the end of your sentence:
    if (Serial.read() == '\n') {
      // constrain the values to 0 - 255 and invert
      // if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
      red = 255 - constrain(red, 0, 255);
      green = 255 - constrain(green, 0, 255);
      blue = 255 - constrain(blue, 0, 255);

      // fade the red, green, and blue legs of the LED:
      analogWrite(redPin, red);
      analogWrite(greenPin, green);
      analogWrite(bluePin, blue);

      // print the three numbers in one string as hexadecimal:
      Serial.print(red, HEX);
      Serial.print(green, HEX);
      Serial.println(blue, HEX);
    }
  }
}

Tags: theselfforledvalueserial水平green
1条回答
网友
1楼 · 发布于 2024-04-18 23:18:05

为了回答您的问题,在示例之外:

p1 = 120
p2 = 200
p3 = 100

the_bytes = bytes(f'{p1},{p2},{p3}\n', 'utf-8')

这是假设您希望字节使用UTF-8作为编码,这是常见的,但是您需要检查一些内容。它也可以是cp1252——这里更多https://docs.python.org/3/library/codecs.html#standard-encodings

然后您可以将the_bytes发送到需要它们的任何地方。你知道吗

相关问题 更多 >