我正在尝试使用python中的串行通信与Arduino进行通信。 arduino https://www.arduino.cc/en/Tutorial/ReadASCIIString有这个程序。只需发送“ 120,200,100”即可控制3个LED。当我在python中尝试将数据写入arduino时
arduino.write(b'120,10,244 \ n')
,并且有效。但是我的主要问题是,如果我将这些值分配给通过GUI进行更改的变量(例如,我计划在其上实现的PyQT滑块),我应该怎么做?
如何输出分配给变量的3个整数->到csv->字节+ \ n
例如
P1 = self.PWM1horizontalSlider.value()#假设值为120
P2 = self.PWM2horizontalSlider.value()#假定值为200
P3 = self.PWM3horizontalSlider.value()#假定值为100
变成b'120,200,100 \ 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);
}
}
}
答案 0 :(得分:0)
要回答您的问题,请在示例之外:
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
。