【问题标题】:Processing blocks drawing function while writing to the serial port写入串行端口时处理块绘图功能
【发布时间】:2015-07-14 21:50:54
【问题描述】:

在处理中,我编写了一个简单的程序,它获取图像的所有像素并将其值发送到串行端口。这是在draw函数内部完成的,它在每个draw事件中遍历像素数组。

因此,对于 200 x 200 的图像,有 40000 个像素,并且绘制函数被调用了 40000 次。但我没有看到我在此处理过程中所做的任何更改的结果。 30 秒后数据被序列化,然后所有更改才可见。

在写入连载期间,我需要什么才能立即绘制并查看结果?异步线程可以成为解决方案吗?我也试过这个,并调用 redraw 方法,但似乎没有任何帮助。

【问题讨论】:

  • 你能发一个MCVE 来说明你在说什么吗?
  • 我仍在努力解决这个问题。似乎提供的所有想法都不起作用。但是一旦我找到解决方案,我就会在这里发布。

标签: java arduino processing


【解决方案1】:

对于 200x200 的图像,您将循环遍历 40000 像素,但您不需要经常调用 draw() 函数。您可以在每次 draw() 调用时为每个像素运行一次循环,以防像素实际发生变化,否则,您可以在 setup() 中缓存像素值一次

关于写入串行,它不应该太复杂。 这是一个概念验证草图,说明了一种编写并行写入串行的线程的方法:

import processing.serial.*;

int w = 200;
int h = 200;
int np = w*h;//total number of pixels

PImage image;

SerialThread serial;

void setup(){
  image = createImage(w,h,ALPHA);
  //draw a test pattern
  for(int i = 0 ; i < np; i++) image.pixels[i] = color(tan(i) * 127);
  //setup serial 
  serial = new SerialThread(this,Serial.list()[0],115200);
}
void draw(){
  image(image,0,0);
}
void mousePressed(){
  println("writing pixel data to serial port");
  for(int i = 0 ; i < np; i++) serial.write((int)brightness(image.pixels[i]));
}
//implement runnable - can run as thread, alternatively extend Thread
class SerialThread implements Runnable{

  Serial serial;

  boolean running = false;//keep the tread running

  int data;//store a byte to send
  boolean hasData;//keep track if the most recent data was written

  SerialThread(PApplet parent,String port,int baudrate){
    try{
      //setup serial
      this.serial = new Serial(parent,port,baudrate);
      //setup thread
      running = true;
      new Thread(this).start();
    }catch(Exception e){
      System.err.println("error opening serial port! please check settings (port/baudrate) and the usb cable");
      e.printStackTrace();
    } 
  }
  //handled
  public void run(){
    while(running){//endless loop to keep the thread running
      if(hasData){//if there is data to write
        if(serial != null) serial.write(data); //send it via serial, if the port is open
        hasData = false;//mark that the data was sent
      }
    }
  }

  public void write(int data){
    this.data = data;
    hasData = true;
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多