Processing摸索前行(3)

前面两篇文章,是初步熟悉一下这个软件在可视化功能上的应用,那么,我们主要想要把他用在实战中。比如,我们接下来要介绍的Processing与Arduino的互动中。比如在Processing中展示Arduino上传过来的数据。

一、如何调用串口并取得通讯
调用串口的第一步就是要引入串口的文件资源,这个和Java的调用方式是一直的,只不过,我们可以通过菜单直接来完成:
在这里插入图片描述
在代码中自动插入:
import processing.serial.*;
这里,我们首先实现从串口获取数据:

import processing.serial.*;
Serial sp;
int val;

void setup()
{
  size(400,300);
  line(40,50,200,200);
  sp=new Serial(this,"com3",9600);
}

void draw()
{

   while(sp.available()>0)
   {    
   val=sp.read();
   print(val);
   }
  
  
}

在Arduino端,我们只要简单的实现串口的发送即可,具体Arduino的串口设置,这里不赘述,代码如下


int val=13;
void setup() {
   Serial.begin(9600);
}

void loop() {
   delay(200);
   Serial.println(val);
   //Serial.write(val);
   delay(200);
}

以上的代码已经实现了最基本的串口通讯功能。也仅仅是Processing能够从Arduino中获取数据了。下面我们将要对这些数据进行图形显示。

二、正确获取串口通讯数据
以下程序完成通过在arduino板的模拟口接入变阻器,通过串口发送变阻器数据到Processing,在Processing中呈现图像的功能。

arduino端

int ledpin=13;
int pot=0;

void setup() {
  // put your setup code here, to run once:
   Serial.begin(9600);
   pinMode(ledpin,OUTPUT);
 
}
void loop() {
  // put your main code here, to run repeatedly:
  int val;
  int percent;
  val=analogRead(pot);
  percent=map(val,0,680,0,254);
     Serial.write(percent);
  
}

Processing端

import processing.serial.*;
Serial myport;
int portCount=0;
float val,data;
void setup()
{
  size(400,320);
  portCount=Serial.list().length;
  println();
  println("Connecting to ->"+ Serial.list()[portCount-1]);
  myport=new Serial(this,Serial.list()[portCount-1],9600);
  val=0;
  
  frameRate(10);
}
void draw()
{
  while(myport.available()>0)
  {
    
   //对应的arduino端使用Serial.println
   // String inBuffer = myport.readString();   
   // if (inBuffer != null) {
  //  println(inBuffer);
   // }
         
    //对应的arduino端使用Serial.write
     val=myport.read();
     println(val);
     fill(204, 102, 0);
     rect(10,40,380,250);
    
     if(val>0)
     {
       rect(10,290,380,val-250);
       rect(10,40,380,250-val); 
     }
  }
  
}

随着电位器的值变化,Processing图中的两条下的距离发生变化,形成开合的图形效果。运行效果如下:

有关arduino通过串口发送数据,在Processing中的显示不正确的解决方案,我在下面的文章中已经阐述清楚:
关于arduino通过串口发送到processing的数据混乱(错误\显示不正确)的问题解答
如果您是通过搜索引起直接阅读的本章节,可以通过连接来回顾前面的内容:
Processing摸索前行(1)
Processing摸索前行(2)

猜你喜欢

转载自blog.csdn.net/haigear/article/details/84558651