Python 3 CSV integers to bytes + \n [closed]

天涯浪子 提交于 2019-12-13 03:57:59

问题


I'am Trying to Communicate with Arduino using serial communication in python. There is this program from arduino https://www.arduino.cc/en/Tutorial/ReadASCIIString . Simply sending a " 120,200,100" to control 3 LEDS. When I tried it in python writing data to the arduino so simply

arduino.write(b'120,10,244\n')

and it works. But my main problem is that if I assigned those values to a variable which gets change through a GUI for example a PyQT slider which I'am planning to implement it on, How should I go about this?

How to output 3 integers assigned to variables->to csv -> bytes +\n

For example

P1 = self.PWM1horizontalSlider.value() # ASSUMING a value of 120

P2 = self.PWM2horizontalSlider.value() # ASSUMING a value of 200

P3 = self.PWM3horizontalSlider.value() # ASSUMING a value of 100

into b'120,200,100\n'

Read ASCII String Code

// 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);
    }
  }
}

回答1:


To answer your question, outside of the example:

p1 = 120
p2 = 200
p3 = 100

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

This is assuming you want the bytes to use UTF-8 as an encoding, which is common, but something you'd want to check. It could also be something like cp1252 - more here https://docs.python.org/3/library/codecs.html#standard-encodings

You could then send the_bytes wherever you need them.



来源:https://stackoverflow.com/questions/54917671/python-3-csv-integers-to-bytes-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!