arduino python interface with multiple variables

眉间皱痕 提交于 2019-12-12 02:39:45

问题


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.



来源:https://stackoverflow.com/questions/33380721/arduino-python-interface-with-multiple-variables

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