arduino python interface with multiple variables

2019-09-11 08:36发布

问题:

I want to bring 3 sensor variables that change all the time to my python interface.

I am trying with this test code, it does not work, what am I doing wrong?

Arduino:

void setup() {
  Serial.begin (9600);
}

void loop() {
  Serial.print(random(1,3)); 
  Serial.print(random(3,5));
  Serial.print(random(5,7)); 
}

Python:

canvas.create_text(190, 150, text=ser.readline(1), fill="gray", font="Helvetica 45 bold",tag="T1")

How can I get multiple variables updating all the time? right now I am just getting the first one, and it is not updating

回答1:

Why are you using the readline function to read just one byte? Since you want multiple values, separate the variables with (for instance) a space, then use readline to store them all and split to separate them:

PS: note that the last one is actually a println

Arduino:

void loop() {
  Serial.print(random(1,3));
  Serial.print(" "); 
  Serial.print(random(3,5));
  Serial.print(" ");
  Serial.println(random(5,7)); 
}

Python:

allitems=ser.readline()
separateditems=allitems.split();
canvas.create_text(190, 150, " - ".join(separateditems), fill="gray", font="Helvetica 45 bold",tag="T1")

In this example I put the items in the separateditems list (so separateditems[0] is equal to random(1,3), separateditems[1] is equal to random(3,5) and separateditems[2] is equal to random(5,7)). Then I joined them to display "random(1,3) - random(3,5) - random(5,7)". Anyway you can do whatever you want with the collected data.

Then I HIGHLY suggest you to put a delay inside the loop, to avoid sending too many data. I suggest putting a delay(100); at the end or, if you need to do other things while waiting, see the "Bounce without delay" example.