<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
      <title>Tagged with write() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=write%28%29</link>
      <pubDate>Sun, 08 Aug 2021 18:50:52 +0000</pubDate>
         <description>Tagged with write() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggedwrite%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>How to auto submit the change in text field? Currently need to press "enter" key</title>
      <link>https://forum.processing.org/two/discussion/25239/how-to-auto-submit-the-change-in-text-field-currently-need-to-press-enter-key</link>
      <pubDate>Mon, 27 Nov 2017 21:57:20 +0000</pubDate>
      <dc:creator>mohsin95</dc:creator>
      <guid isPermaLink="false">25239@/two/discussions</guid>
      <description><![CDATA[<p>I am using ControlP5 GUI library text fields to make a GUI compatible with Arduino.
The gui works fine for now but if I need to a new value in the textfield, I have to press "enter" key after typing in the new value. It is getting quite irritating since the gui shows the new value but does not gets transmitted through serial on the backend.</p>

<p>Here is the code I am using to process the textfields:</p>

<p><code>Textfield paperLengthTextField = jControl.addTextfield("Desired Paper Length (inches):")
                                           .setPosition(280, 180)
                                           .setSize(200, 40)
                                           .setText("1")
                                           .setFont(font)
                                           .setAutoClear(false);</code></p>

<p>and using this function to send the new entered data to the arduino through serial:</p>

<p><code>public void controlEvent(ControlEvent theEvent) {
  String msg = theEvent.getController().getName();
  switch(msg) {
    case "Desired Paper Length (inches):":
      println("Desired Paper Length: " + theEvent.getStringValue());
      myPort.write('i' + theEvent.getStringValue());
      break;
    case "Number of Pages to Cut:":
      println("Number of Pieces to Cut: " + theEvent.getStringValue());
      myPort.write('c' + theEvent.getStringValue());
      break;
  }   
}</code></p>
]]></description>
   </item>
   <item>
      <title>How to send multiple PWM values from Processing to Arduino?</title>
      <link>https://forum.processing.org/two/discussion/24916/how-to-send-multiple-pwm-values-from-processing-to-arduino</link>
      <pubDate>Wed, 08 Nov 2017 17:42:34 +0000</pubDate>
      <dc:creator>hoodihoo</dc:creator>
      <guid isPermaLink="false">24916@/two/discussions</guid>
      <description><![CDATA[<p>Hi all,</p>

<p>For a while I've been looking to control several banks of LED lights independently by using a GUI with a couple sliding bars. The idea is by moving each sliding bar around, the PWM value of the corresponding LED bank would change and the LEDs would get brighter or darker. Through this forum and other resources I have been able to accomplish this with one slider bar and one bank of LEDs. However, I am struggling to scale this project up because I don't know how to send and read multiple PWM values from several slider bars. I've seen some people mentioning splitting up the communication into several bits and then reading each bit in Arduino to correspond to each LED bank. I do not know how to accomplish this with the slider bars though. If you do have a solution, please by thorough. My Processing and Arduino code is below (currently aimed at using 2 slider bars for 2 corresponding LED banks), thanks in advance.</p>

<p><strong>Processing</strong></p>

<pre><code>import controlP5.*;

import processing.serial.*;

ControlP5 cp5;

Serial port;

PFont font, font2;


int Brightness_1 = 0;

int Brightness_2 = 0;

void setup() 
{

 size(450, 200);

 String portName = Serial.list()[0];

 port = new Serial(this, "COM9", 9600);

  cp5 = new ControlP5(this);

 font = createFont("calibri light", 20);

 font2 = createFont("calibri light", 12);

  cp5.addSlider("Brightness_1", 0, 255, 0, 50, 125, 255, 12)
     .setPosition(50,125)
     .setSize(255,12)
     .setRange(0,255)
     .setFont(font);

  cp5.addSlider("Brightness_2", 0, 255, 0, 50, 125, 255, 12)
     .setPosition(50,125)
     .setSize(255,12)
     .setRange(0,255)
     .setFont(font);
}

void draw() 
{
  background(200, 10, 30);
  fill(100, 0, 150);
  textFont(font);

  text(Brightness_1, 25, 50);

  port.write(Brightness_1);

  port.write(Brightness_2);



}
</code></pre>

<p><strong>Arduino</strong></p>

<pre><code>int incomingData;

void setup()
{

pinMode(4, OUTPUT);   //set pin4 as output 

pinMode(5, OUTPUT);   //set pin5 as output 

//pinMode(6, OUTPUT);   //set pin6 as output

Serial.begin(9600);

}

void loop()
{
if(Serial.available())

 {
    incomingData = Serial.read();

    analogWrite(4, incomingData);

    analogWrite(5, incomingData);

      }


  }
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to improve OpenCV performance on ARM?</title>
      <link>https://forum.processing.org/two/discussion/24529/how-to-improve-opencv-performance-on-arm</link>
      <pubDate>Fri, 13 Oct 2017 16:00:05 +0000</pubDate>
      <dc:creator>Isaac96</dc:creator>
      <guid isPermaLink="false">24529@/two/discussions</guid>
      <description><![CDATA[<p>Hi guys</p>

<p>I am making a face-tracking Nerf blaster using OpenCV on the Raspberry Pi. I am using a Microsoft LifeCam webcam for capture input and the SoftwareServo class for blaster control. However, my code runs at 1-2 FPS on the Pi (Pi 3 model B). I am currently using scale to improve performance, but the code still runs at 1 FPS. Additionally, the servos are extremely jittery. I am powering the servos using a 2A 5V regulator. The Pi is powered off a 2A USB supply. The grounds <em>are</em> connected. Does anyone know how to improve performance? Maybe a different CV library?</p>

<p>Thanks for input!
Code:</p>

<pre><code>import processing.io.*;
import gab.opencv.*;
import processing.video.*;
import java.awt.*; 

PImage img;
Rectangle[] faceRect; 

Capture cam;
OpenCV opencv; 
SoftwareServo panServo;
SoftwareServo trigServo;

int widthCapture=320; 
int heightCapture=240;
int fpsCapture=30; 
int panpos=90;
int firePos = 80;
int readyPos = 0;
long time;
int wait = 500;

int targetCenterX;
int targetCenterY;

int threshold = 20;
int thresholdLeft;
int thresholdRight;
int moveIncrement = 2;


int circleExpand = 20;
int circleWidth = 3;

boolean isFiring = false;
boolean isFound = false;
boolean manual = false;

void setup()
{ 
  size (320, 240); 
  frameRate(fpsCapture); 
  background(0);
  panServo = new SoftwareServo(this);
  trigServo = new SoftwareServo(this);
  panServo.attach(17);
  trigServo.attach(4);

  cam = new Capture(this, widthCapture, heightCapture);
  cam.start(); 

  opencv = new OpenCV(this, widthCapture, heightCapture); 
  opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE);
}

void  draw() 
{
  if (millis() - time &gt;= wait)
  {
    trigServo.write(readyPos);
    isFiring = false;
  }
  if (isFiring) 
  {
    trigServo.write(firePos);
    tint(255, 0, 0);
  } else
  {
    trigServo.write(readyPos);
    noTint();
  }
  if (cam.available() == true) 
  { 
    cam.read();  
    img = cam.get(); 

    opencv.loadImage(img);

    image(img, 0, 0);
    blend(img, 0, 0, widthCapture, heightCapture, 0, 0, widthCapture, heightCapture, HARD_LIGHT);
    faceRect = opencv.detect();
  }

  stroke(255, 255, 255);
  strokeWeight(1);
  thresholdLeft = (widthCapture/2)-threshold;
  thresholdRight =  (widthCapture/2)+threshold;

  stroke(255, 255, 255, 128);
  strokeWeight(1);
  line(thresholdLeft, 0, thresholdLeft, heightCapture); //left line
  line(thresholdRight, 0, thresholdRight, heightCapture); //right line

  if ((faceRect != null) &amp;&amp; (faceRect.length != 0))
  {
    isFound = true;
    //Get center point of identified target
    targetCenterX = faceRect[0].x + (faceRect[0].width/2);
    targetCenterY = faceRect[0].y + (faceRect[0].height/2);    

    //Draw circle around face
    noFill();
    strokeWeight(circleWidth);
    stroke(255, 255, 255);
    ellipse(targetCenterX, targetCenterY, faceRect[0].width+circleExpand, faceRect[0].height+circleExpand);
    if (!manual) {
      //Handle rotation
      if (targetCenterX &lt; thresholdLeft)
      {
        panpos -=  moveIncrement;
        //delay(70);
      }
      if (targetCenterX &gt; thresholdRight)
      {
        panpos+=  moveIncrement;
        //delay(70);
      }

      //Fire
      if ((targetCenterX &gt;= thresholdLeft) &amp;&amp; (targetCenterX &lt;= thresholdRight))
      {
        isFiring = true;
        println("Gotem");
        noFill();
      }
    }
  }
}
void keyPressed() {
  if (key == 'm') {
    manual = !manual;
    println("manual mode toggled");
    isFiring = false;
  } else if (key == 'a' &amp;&amp; manual) {
    panpos-= moveIncrement;
    println("left");
  } else if (key == 'f' &amp;&amp; manual) {
    isFiring = !isFiring;
  } else if (key == 'd' &amp;&amp; manual) {
    panpos+= moveIncrement;
    println("right");
  } else if (key == 'c' )
  {
    panServo.write(90);
  } else {
    println(key);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>i have been problem with incopatible librery</title>
      <link>https://forum.processing.org/two/discussion/24457/i-have-been-problem-with-incopatible-librery</link>
      <pubDate>Sun, 08 Oct 2017 19:51:51 +0000</pubDate>
      <dc:creator>helias21</dc:creator>
      <guid isPermaLink="false">24457@/two/discussions</guid>
      <description><![CDATA[<p>import codeanticode.gsvideo.*;
import processing.serial.*;</p>

<p>//objects
PFont f;
GSCapture cam;
Serial myPort;
PrintWriter output;</p>

<p>//colors
color black=color(0);
color white=color(255);</p>

<p>//variables
int itr; //iteration
float pixBright;
float maxBright=0;
int maxBrightPos=0;
int prevMaxBrightPos;
int cntr=1;
int row;
int col;</p>

<p>//scanner parameters
float odl = 210;  //distance between webcam and turning axle, [milimeter], not used yet
float etap = 120;  //number of phases profiling per revolution
float katLaser = 25<em>PI/180;  //angle between laser and camera [radian]
float katOperacji=2</em>PI/etap;  //angle between 2 profiles [radian]</p>

<p>//coordinates
float x, y, z;  //cartesian cords., [milimeter]
float ro;  //first of polar coordinate, [milimeter]
float fi; //second of polar coordinate, [radian]
float b; //distance between brightest pixel and middle of photo [pixel]
float pxmmpoz = 5; //pixels per milimeter horizontally 1px=0.2mm
float pxmmpion = 5; //pixels per milimeter vertically 1px=0.2mm</p>

<p>//================= CONFIG ===================</p>

<p>void setup() {
  size(800, 600);
  strokeWeight(1);
  smooth();
  background(0);</p>

<p>//fonts
  f=createFont("Arial",16,true);</p>

<p>//camera conf.
  String[] avcams=GSCapture.list();
  if (avcams.length==0){
    println("There are no cameras available for capture.");
    textFont(f,12);
    fill(255,0,0);
    text("Camera not ready",680,32);
  }
  else{
    println("Available cameras:");
    for (int i = 0; i &lt; avcams.length; i++) {
      println(avcams[i]);
    }
    textFont(f,12);
    fill(0,255,0);
    text("Camera ready",680,32);
    cam=new GSCapture(this, 640, 480,avcams[0]);
    cam.start();
  }</p>

<p>//Serial (COM) conf.
  printArray(Serial.list());
  myPort=new Serial(this, Serial.list()[0], 9600);</p>

<p>//output file
  output=createWriter("skan.asc");  //plik wynikowy *.asc</p>

<p>}</p>

<p>//============== MAIN PROGRAM =================</p>

<p>void draw() {</p>

<p>PImage zdjecie=createImage(cam.width,cam.height,RGB);
  cam.read();
  delay(2000);
  for (itr=0;itr&lt;etap;itr++) {
    cam.read();
    zdjecie.loadPixels();
    cam.loadPixels();
    for (int n=0;n&lt;zdjecie.width*zdjecie.height;n++){
      zdjecie.pixels[n]=cam.pixels[n];
    }
    zdjecie.updatePixels();
    set(20,20,cam);
    String nazwaPliku="zdjecie-"+nf(itr+1, 3)+".png";
    zdjecie.save(nazwaPliku);
    obroc();
    delay(500);
  }
  obroc();
  licz();
  noLoop();</p>

<p>}</p>

<p>void licz(){
  for (itr=0; itr&lt;etap; itr++){</p>

<pre><code>String nazwaPliku="zdjecie-"+nf(itr+1, 3)+".png";
PImage skan=loadImage(nazwaPliku);
String nazwaPliku2="odzw-"+nf(itr+1, 3)+".png";
PImage odwz=createImage(skan.width, skan.height, RGB);
skan.loadPixels();
odwz.loadPixels();
int currentPos;
fi=itr*katOperacji;
println(fi);

for(row=0; row&lt;skan.height; row++){  //starting row analysis
maxBrightPos=0;
maxBright=0;
  for(col=0; col&lt;skan.width; col++){
    currentPos = row * skan.width + col;
    pixBright=brightness(skan.pixels[currentPos]);
    if(pixBright&gt;maxBright){
      maxBright=pixBright;
      maxBrightPos=currentPos;
    }
    odwz.pixels[currentPos]=black; //setting all pixels black
  }

  odwz.pixels[maxBrightPos]=white; //setting brightest pixel white

  b=((maxBrightPos+1-row*skan.width)-skan.width/2)/pxmmpoz;
  ro=b/sin(katLaser);
  //output.println(b + ", " + prevMaxBrightPos + ", " + maxBrightPos); //I used this for debugging

  x=ro * cos(fi);  //changing polar coords to kartesian
  y=ro * sin(fi);
  z=row/pxmmpion;

  if( (ro&gt;=-30) &amp;&amp; (ro&lt;=60) ){ //printing coordinates
    output.println(x + "," + y + "," + z);
  }

}//end of row analysis

odwz.updatePixels();
odwz.save(nazwaPliku2);
</code></pre>

<p>}
  output.flush();
  output.close();
}</p>

<p>void obroc() {  //sending command to turn
  myPort.write('S');
  delay(50);
  myPort.write('K');
}</p>

<p>this code i get on this page <a href="https://www.instructables.com/id/Lets-cook-3D-scanner-based-on-Arduino-and-Proces/" target="_blank" rel="nofollow">https://www.instructables.com/id/Lets-cook-3D-scanner-based-on-Arduino-and-Proces/</a>   because i ve tryed to build a 3d scanner to calculate the volumen of some object</p>

<p>when i compile the code has a error on this line:
cam=new GSCapture(this, 640, 480,avcams[0]);</p>

<p>on the serial monitor of prossesing this show me all the cameras but when the code arrive on this line the compilator show me this error on this line cam=new GSCapture(this, 640, 480,avcams[0]);</p>

<p>i dont know why</p>

<p>i have a prossesing version 3.3.6</p>
]]></description>
   </item>
   <item>
      <title>Why can't I get the option pane to show.</title>
      <link>https://forum.processing.org/two/discussion/24430/why-can-t-i-get-the-option-pane-to-show</link>
      <pubDate>Sat, 07 Oct 2017 12:29:01 +0000</pubDate>
      <dc:creator>stumped1</dc:creator>
      <guid isPermaLink="false">24430@/two/discussions</guid>
      <description><![CDATA[<p>A newby and my first time using Processing and I can't see how I can resolve this. I'm trying to set up a CNC drawing setup in arduino uno and the Processing option pane is not displaying correctly. I've attached a screenshot and it appears a fault is shown at line 31. 
Would greatly appreciate any help<img src="https://forum.processing.org/two/uploads/imageupload/412/C67EN4DZYET8.png" alt="Screenshot (5)" title="Screenshot (5)" /></p>
]]></description>
   </item>
   <item>
      <title>[SOLVED] serial.write triggers serialEvent and sends data to it?</title>
      <link>https://forum.processing.org/two/discussion/24245/solved-serial-write-triggers-serialevent-and-sends-data-to-it</link>
      <pubDate>Sun, 24 Sep 2017 20:31:22 +0000</pubDate>
      <dc:creator>vagos21</dc:creator>
      <guid isPermaLink="false">24245@/two/discussions</guid>
      <description><![CDATA[<p>Hello again, after working successfully for a couple of days on the serial comm between arduino and the pi3, (receiving data) i stumbled upon this problem accidentally... i use the serial event to parse incoming data, which is in a sligtly format than the outgoing data. for example, to receive a "setpoint" variable my arduino sends this on serial with println:</p>

<p>SP2</p>

<p>the raspberry parses succesfully and sets the SP value to 2
changing the value of SP to 3 on the arduino it expects to see this on its serial port:</p>

<p>SP;3</p>

<p>so on the raspberry side i do
myPort.write("SP;3\n")</p>

<p>and i get a serialevent parse error, after doing some debug prints, i see that the data is not at all sent to the arduino, but the write command triggers the serialevent which catches the "SP;3" command!!</p>

<p>is this a bug? is the serialevent supposed to be triggered upon the write command? i'm so puzzled, if this is so how can i send out data through my serial at all? Could this be a hardware connection issue? i'm using this voltage divider:</p>

<p><a rel="nofollow" href="https://oscarliang.com/ctt/uploads/2013/05/arduino-raspberry-pi-serial-connect-schematics.jpg">https://oscarliang.com/ctt/uploads/2013/05/arduino-raspberry-pi-serial-connect-schematics.jpg</a></p>

<p>thank you,
Vangelis</p>
]]></description>
   </item>
   <item>
      <title>Program freezing when using Serial out</title>
      <link>https://forum.processing.org/two/discussion/23387/program-freezing-when-using-serial-out</link>
      <pubDate>Mon, 10 Jul 2017 11:28:59 +0000</pubDate>
      <dc:creator>eugval</dc:creator>
      <guid isPermaLink="false">23387@/two/discussions</guid>
      <description><![CDATA[<p>Hi guys,</p>

<p>This program I've made is designed to read data from a csv file and output it to an arduino (which will in turn eventually output it to a motor). Strangely, it runs just fine without the Arduino plugged in, but with the Arduino plugged in it starts freezing every one or two seconds after the first eight seconds or so. I presume some buffer somewhere is being filled up and is not clearing itself fast enough, but I have no idea where. Any thoughts?</p>

<pre><code>/*  CSV_READER
    Version 3.4

    Improvements from last version:
    - 

    Improvements to be made:
    - Begins to freeze when Arduino plugged in

*/

import processing.serial.*;

int xpos=90; // set x servo's value to mid point (0-180);
int ypos=90; // and the same here
Serial port; // The serial port we will be using
Table table;
final int motorPulley = 17; //number of teeth on the pulley
final int enginePulley = 51;
final int calibrationFactor = (2880 * (enginePulley/motorPulley))/360; //2880 = max rpm of motor
int rowCount = 1;
int timeResolution; //the time interval in ms of the chosen data file
boolean fileSelected = false;
boolean run = false;
boolean pause = false;
boolean stop = false;
int time, rpm;
boolean debounce = true; //ensures button is released before it can be pressed again
int stopCount = 0; //how long before program closes
int timeRunning = 0; //time the program has spent running
int timePaused = 0;
String fileName;

void setup() 
{
  size(360, 360, P2D);
  background(50);

  selectInput("Select a file to process:", "fileSelected");
  //table = loadTable(file, "header");

  frameRate(1000); //sets framerate

  //println(Serial.list()); // List COM-ports
  port = new Serial(this, Serial.list()[5], 9600);


}

void fileSelected(File selection) //selects the file
{
  if (selection == null) 
  {
    println("Window was closed or the user hit cancel.");
  } 
  else 
  {
    println("User selected " + selection.getAbsolutePath());
    fileName = selection.getName();
    table = loadTable(selection.getAbsolutePath(), "header");
    fileSelected = true;
    TableRow row1 = table.getRow(1);
    TableRow row2 = table.getRow(2);
    int time1 = row1.getInt("time");
    int time2 = row2.getInt("time");
    timeResolution = time2 - time1;
  }
}

void draw() 
{
  while (fileSelected == false) //Does not run unti a file has actually been selected
  {
    delay(1);
  }

  clear();
  //println(frameRate); //use for testing a specific variable

  if (stop == false) //normal running section of program
  {
      if (run == true) //loads row data
      {
        timeRunning = millis() - timePaused;
        nextRow();
      }

      else
      {
        timePaused = millis() - timeRunning;
      }

      //println(rpm);
      update(0, rpm/calibrationFactor); //update serial signal being sent to arduino

      strokeWeight(10);
      stroke(0, 191, 255);
      fill(0, 0, 0);
      //ellipse(180, 180, rpm/24,rpm/24);
      arc(180,180,180,180, 0, radians(rpm/24)); //draws an arc whic represents the rpm value
      fill(255);
      text(rpm, 163, 185);
      text("rpm",166,195);
      text((float) time/1000, 30, 230);
      text("time (s)", 30, 240); //displays the time and rpm values
      text(fileName,30,30);
      text("timeR: " + (float) timeRunning/1000, 30, 260);

      if (run == false) //displays start button
      {
       strokeWeight(0);
        fill(51,255,51);
       rect(160,320,50,20);
       fill(0);
       text("START",165,332);


      }

      if (run == true) //displays pause button
      {
        strokeWeight(0);
        fill(255,153,51);
       rect(160,320,50,20);
       fill(0);
       text("PAUSE",165,332);

      }

      strokeWeight(0);
        fill(255,0,0);
       rect(230,320,50,20);
       fill(0);
       text("STOP",235,332);  

      if (mousePressed &amp;&amp; overRect(160,320,50,20) &amp;&amp; debounce) //detects if start/pause button has been pressed
       {
         debounce = false;
         if (run == false)
           run = true;
         else if (run == true)
           run = false;
        }

      if (mousePressed &amp;&amp; overRect(230,320,50,20) &amp;&amp; debounce)
      {
        stop = true;
      }

      if (rowCount &gt;= table.getRowCount()) //end program when end of file is reached
      {
        stop = true;
      }
  }

  else if (stop == true)
  {

    fill(255);
    text("Run finished",150,160);
    stopCount++;
    if (stopCount &gt;= 500)
      exit();
  }
}

boolean overRect(int x, int y, int width, int height) //checks to see if the mouse is over the defined rectangle
{
  if (mouseX &gt;= x &amp;&amp; mouseX &lt;= x+width &amp;&amp; 
      mouseY &gt;= y &amp;&amp; mouseY &lt;= y+height) {
    return true;
  } 
  else 
  {
    return false;
  }
}

void nextRow() //loads data from the next row in the table
{
  TableRow row = table.getRow(rowCount);
  time = row.getInt("time");
  if (time &lt;= timeRunning) //loads new rpm if we have reached that time
  {
    rpm = row.getInt("rpm"); 
    rowCount++;
  }
  if(time + timeResolution &lt; timeRunning) //catches up if it falls behind
  {
     rowCount++; 
     println(rowCount);
  }

}

void mouseReleased() //ensures mouse is released before it can be pressed again
{
   debounce = true; 
}

void update(int x) //updates output to arduino
{
  //Calculate servo postion from mouseX
  xpos= x/2;
  ypos = y/2;
  //Output the servo position ( from 0 to 180)
  port.write(xpos+"x");
  port.write(ypos+"y");
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>very basic/stupid serial question (i hope)</title>
      <link>https://forum.processing.org/two/discussion/23054/very-basic-stupid-serial-question-i-hope</link>
      <pubDate>Tue, 13 Jun 2017 13:23:05 +0000</pubDate>
      <dc:creator>mala</dc:creator>
      <guid isPermaLink="false">23054@/two/discussions</guid>
      <description><![CDATA[<p>when using  <code>serial.write(byte[])</code>    is the whole array sent out ?</p>

<p>for example lets say I have  <code>out_byteBuffer[128]</code> and sometimes I'm only storing two of bytes to the buffer and then I go   <code>serial.write(out_byteBuffer)</code> i presume it writes the whole array out even if 126 of the bytes are null ?</p>

<p>and if you want to write out a certain fixed number(maxWrite) of bytes from the byte array you would do this ? :</p>

<pre><code>        for(int i = 0; &lt; maxWrite; i++){
        serial.write(out_byteBuffer[i]);
        }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Loading a random image from an array</title>
      <link>https://forum.processing.org/two/discussion/22926/loading-a-random-image-from-an-array</link>
      <pubDate>Sun, 04 Jun 2017 22:25:04 +0000</pubDate>
      <dc:creator>iossiiiffff</dc:creator>
      <guid isPermaLink="false">22926@/two/discussions</guid>
      <description><![CDATA[<p>Hi,
Sorry for the basic question but I'm new in Processing. I've found this piece of code on the internet that converts images and sends them to a receipt printer through a FTDI serial connector. The thing is I wanted to adapt it a bit in order to load a random image from an array. I've looked it up and found some related answers but still no luck... :( Thank you</p>

<p>this is the code:</p>

<pre><code>import processing.serial.*;

Serial myPort;
String portName = "";
PImage img;

int one_byte = 0;
int[] eight_pixels = new int[8];

void setup() 
{
  size(200, 200);
  String[] ports = Serial.list();
  for(int i = 0; i &lt; ports.length; i++){
    if(ports[i].indexOf("usbserial")!=-1){
      portName = Serial.list()[i];
    }
  }
  if(portName!=""){
    myPort = new Serial(this, portName, 19200);
    myPort.bufferUntil(10);
    println(portName);
  }else{
    println("plug in the USB cable");
  }

  myPort.write(27);
  myPort.write(55);
  myPort.write(7); // 8*(x+1)
  myPort.write(160); // x*10 us
  myPort.write(2); // x*10 us

  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);

  img = loadImage("source_image4.jpg");

  img.resize(384, 0);
  img.loadPixels();

  for (int y = 0; y &lt; img.height; y++) {
    myPort.write(18);
    myPort.write(42);
    myPort.write(1);
    myPort.write(48);
     for (int x = 0; x &lt; 384; x++) {
         int loc = x + y*384;

         float r = red(img.pixels[loc]);
         float g = green(img.pixels[loc]);
         float b = blue(img.pixels[loc]);

         int rgb = int(r+g+b);

         if(rgb &gt; 382){
            eight_pixels[7-(x%8)] = 0;
         }else{
            eight_pixels[7-(x%8)] = 1;
         }
         if((x+1)%8==0){
           one_byte = eight_pixels[0] | (eight_pixels[1] &lt;&lt; 1) | (eight_pixels[2] &lt;&lt; 2) | (eight_pixels[3] &lt;&lt; 3) | (eight_pixels[4] &lt;&lt; 4) | (eight_pixels[5] &lt;&lt; 5) | (eight_pixels[6] &lt;&lt; 6) | (eight_pixels[7] &lt;&lt; 7);
           myPort.write((byte)one_byte);
           delay(1);
         }
     }
     delay(10);
  }

  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
}

void draw() {

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Send two vectors from Processing to Arduino</title>
      <link>https://forum.processing.org/two/discussion/22356/send-two-vectors-from-processing-to-arduino</link>
      <pubDate>Wed, 03 May 2017 07:05:08 +0000</pubDate>
      <dc:creator>NicholasASR</dc:creator>
      <guid isPermaLink="false">22356@/two/discussions</guid>
      <description><![CDATA[<p>Hi, i have a big problem.. I'm trying to send two int vectors from Processing to Arduino but when i run processing and also arduino, it says that the Serial Port is busy. I first tried for one vector but it doesn't work...</p>
]]></description>
   </item>
   <item>
      <title>How to translate byte[] to PImage?</title>
      <link>https://forum.processing.org/two/discussion/14814/how-to-translate-byte-to-pimage</link>
      <pubDate>Mon, 08 Feb 2016 10:34:01 +0000</pubDate>
      <dc:creator>czerny</dc:creator>
      <guid isPermaLink="false">14814@/two/discussions</guid>
      <description><![CDATA[<p>in Server sketch, i take a picture with Processing’s Video library and send a byte array to client’s buffer</p>

<p>like this,,</p>

<pre><code>/**
void mousePressed() {
 capture.save(“temp.jpg");
 byte[] b=loadBytes(“temp.jpg");
 server.write(b);
} 
*/
</code></pre>

<p>but i have no idea how to convert this byte array to PImage format in Client’s sketch.</p>

<p>is there any byte[] to Pimage converting method in processing???</p>
]]></description>
   </item>
   <item>
      <title>[ControlP5 + Serial] Serial input to textfield controller</title>
      <link>https://forum.processing.org/two/discussion/22224/controlp5-serial-serial-input-to-textfield-controller</link>
      <pubDate>Wed, 26 Apr 2017 13:50:03 +0000</pubDate>
      <dc:creator>Blad2021</dc:creator>
      <guid isPermaLink="false">22224@/two/discussions</guid>
      <description><![CDATA[<p>Hi all,</p>

<p>So going to do my best to describe this, it might sound a bit more complicated then intended.  I'm trying to set the value of a textfield controller (using ControlP5 library) with input from the Serial.  I could do this now by using a bunch of if statements but thats not very attractive therefore I want a function.  I have everything setup on my serial to ouput the following:</p>

<p>SEN.x.y</p>

<p>"SEN" being what it reads for to determine the function.<br />
(x) - The textfield ID to change
(y) - The value to change the textfield to.</p>

<p>My code so far:</p>

<pre><code>import processing.serial.*;
import controlP5.*;

Serial myPort;  // Create object from Serial class**
String inByte;**
String s;**
ControlP5 cp5;
String temp;
String endchar = "\n";
Textarea consoletext;
Textfield Timer1;
Println console;
//Variables
boolean firstContact = false;
boolean globalState [] = {false, false, false, false, false, false, false, false};
int pin [] = {22, 24, 26, 28, 30, 32, 34, 36};

void setup() 
{  
  size(800,500);
  cp5 = new ControlP5(this);
  cp5.enableShortcuts();

  cp5.addTextfield("console")
    .setSize(360,35)
    .setCaptionLabel("Console Injection Module")
    .setPosition(20,430)
    .setFont(createFont("arial",14))
    .setAutoClear(true)
    ;

  cp5.addTextfield("Timer1")
    .setId(1)
    .setPosition(20,70)
    .setSize(200,35)
    .setFont(createFont("arial",12))
    .setAutoClear(true)
    .setCaptionLabel("EEPROM: Timer 1")
    ;
  cp5.addTextfield("Timer2")
    .setId(2)
    .setPosition(20,130)
    .setSize(200,35)
    .setFont(createFont("arial",12))
    .setAutoClear(true)
    .setCaptionLabel("EEPROM: Timer 2")
    ;
  cp5.addTextfield("Timer3")
    .setId(3)
    .setPosition(20,190)
    .setSize(200,35)
    .setFont(createFont("arial",12))
    .setAutoClear(true)
    .setCaptionLabel("EEPROM: Timer 3")
    ;
  cp5.addTextfield("Timer4")
    .setId(4)
    .setPosition(20,250)
    .setSize(200,35)
    .setFont(createFont("arial",12))
    .setAutoClear(false)
    .setCaptionLabel("EEPROM: Timer 4")
    ;
  cp5.addTextfield("Timer5")
    .setId(5)
    .setPosition(20,310)
    .setSize(200,35)
    .setFont(createFont("arial",12))
    .setAutoClear(false)
    .setCaptionLabel("EEPROM: Timer 5")
    ;
  cp5.addTextfield("Timer6")
    .setId(6)
    .setPosition(20,370)
    .setSize(200,35)
    .setFont(createFont("arial",12))
    .setAutoClear(false)
    .setCaptionLabel("EEPROM: Timer 6")
    ;
  cp5.addButton("button1")
    .setSize(60,20)
    .setCaptionLabel("LED On")
    .setPosition(235,70)
    ;
  cp5.addButton("button2")
    .setSize(60,20)
    .setCaptionLabel("LED Off")
    .setPosition(235,100)
    ;
  cp5.addButton("button4")
    .setSize(60,20)
    .setCaptionLabel("Relays On")
    .setPosition(235,130)
    ;
  cp5.addButton("button3")
    .setSize(60,20)
    .setCaptionLabel("Relays Off")
    .setPosition(235,160)
    ;
  cp5.addBang("Relay1")
     .setPosition(310,50)
     .setId(1)
     .setSize(60,30)
     .setCaptionLabel("relay1")
     ;

  cp5.addBang("Relay2")
     .setPosition(310,95)
     .setSize(60,30)
     .setId(2)
     .setCaptionLabel("Relay 2")
     ;

  cp5.addBang("Relay3")
     .setPosition(310,140)
     .setSize(60,30)
     .setId(3)
     .setCaptionLabel("Relay 3")
     ;

  cp5.addBang("Relay4")
     .setPosition(310,185)
     .setSize(60,30)
     .setId(4)
     .setCaptionLabel("Relay 4")
     ;

  cp5.addBang("Relay5")
     .setPosition(310,230)
     .setSize(60,30)
     .setId(5)
     .setCaptionLabel("Relay 5")
     ;
  cp5.addBang("Relay6")
     .setPosition(310,275)
     .setSize(60,30)
     .setId(6)
     .setCaptionLabel("Relay 6")
     ;
  cp5.addBang("Relay7")
     .setPosition(310,320)
     .setSize(60,30)
     .setId(7)
     .setCaptionLabel("Relay 7")
     ;
  cp5.addBang("Relay8")
     .setPosition(310,365)
     .setSize(60,30)
     .setId(8)
     .setCaptionLabel("Relay 8")
     ;
consoletext = cp5.addTextarea("txt")
  .setPosition(440,20)
  .setSize(350, 465)
  .setFont(createFont("", 12))
  .setLineHeight(14)
  .setColor(color(255, 255, 255, 255))
  .setColorBackground(color(100, 100))
  .setColorForeground(color(255, 100));
  ;
  cp5.addTextlabel("ctext")
    .setText("Console")
    .setPosition(436,3)
    .setColorValue(255)
    .setFont(createFont("Arial",14));
  cp5.addTextlabel("stitle")
    .setText("Machine Serial")
    .setPosition(10,10)
    .setColorValue(color(200, 17, 0, 255))
    .setFont(createFont("Arial",24));
  cp5.addTextlabel("subtitle")
    .setText("Control Panel")
    .setPosition(30,35)
    .setColorValue(200)
    .setFont(createFont("Arial",16));

  console = cp5.addConsole(consoletext);


  //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, "COM3", 9600);
  myPort.bufferUntil('\n');

}

void draw() {
  background(0);
  fill(255);
  for (int i=0;i&lt;globalState.length;i++){
    if (globalState[i] == false){
      fill(color(200, 20, 0, 255));
      rect(385, 50+i*45, 30, 30);
    }
    else{
      fill(color(123, 255, 0, 255));
      rect(385, 50+i*45, 30, 30);
    }
  }
}
void controlEvent(ControlEvent test) {
  if(test.isAssignableFrom(Textfield.class)){
    if("console".equals(test.getName())){
      temp = test.getStringValue();
      if("LED On".equals(temp)){
        myPort.write("2");
        println("Sent: LED ON");
      }else if("LED Off".equals(temp)){
        myPort.write("1");
        println("Sent: LED OFF");
      }else if("help".equals(temp)){
        println("Help:");
        println("/  Commands:");
        println("/  - Update.x.y - Updates control pin layout.");
        println("     (x) - Array location  (y) - PIN");
        println("    Starts at 0!");
        println("/  - EEPROM.x.y - Updates EEPROM address (x) with value (y)");
        println("/  - PIN.x.y - Updates PIN (x) with value of (y)"); 
        println("/    [ Value should be 0 or 1 ONLY!]");
        println("/  - Call.x - Calls current value of position (x) in array");
        println("/  - Varu.x.y - Updates the position (x) with value of (y) in array");
        println("/");
        println("/");
        println("/  Timer values should stay within value of 5100");
        println("/");
      }else {
        String result = temp.substring(0,6);
      //if(temp.contains("Update"){
        if("Update".equals(result)){
          String apple = temp.substring(7,8);
          String pear = temp.substring(9,temp.length());
          int orange = Integer.parseInt(apple);
          int grape = Integer.parseInt(pear);
          pin[orange] = grape;
        } else {
          myPort.write(temp.toUpperCase() + '\n');
          println("Sent: " +temp.toUpperCase());
        }
      }
    }
    boolean StrTest = test.getName().startsWith("Timer");

    if(StrTest == true){
      println("Sending EEPROM Update to controller");
      println("Updating Timer: " +test.getId() +" to Value: " +test.getStringValue());
      Timefunc(test.getId()-1, test.getStringValue());
    }
  }
}
public void button1(){
  println("Sent: pin.10.1");
  myPort.write("PIN.10.1" +endchar);
}
public void button2(){
  println("Sent: pin.10.0");
  myPort.write("PIN.10.0" +endchar);
}
public void button3(){
  println("SYSTEM: Relays On");
  myPort.write("PIN.22.0" +endchar);
  myPort.write("PIN.24.0" +endchar);
  myPort.write("PIN.26.0" +endchar);
  myPort.write("PIN.28.0" +endchar);
  myPort.write("PIN.30.0" +endchar);
  myPort.write("PIN.32.0" +endchar);
  myPort.write("PIN.34.0" +endchar);
  myPort.write("PIN.36.0" +endchar);
}
public void button4(){
  println("SYSTEM: Relays Off");
  myPort.write("PIN.22.1" +endchar);
  myPort.write("PIN.24.1" +endchar);
  myPort.write("PIN.26.1" +endchar);
  myPort.write("PIN.28.1" +endchar);
  myPort.write("PIN.30.1" +endchar);
  myPort.write("PIN.32.1" +endchar);
  myPort.write("PIN.34.1" +endchar);
  myPort.write("PIN.36.1" +endchar);
}
public void Relay1(){
  RelayControl(pin[0], !globalState[0]);
}
public void Relay2(){
  RelayControl(pin[1], !globalState[1]);
}
public void Relay3(){
  RelayControl(pin[2], !globalState[2]);
}
public void Relay4(){
  RelayControl(pin[3], !globalState[3]);
}
public void Relay5(){
  RelayControl(pin[4], !globalState[4]);
}
public void Relay6(){
  RelayControl(pin[5], !globalState[5]);
}
public void Relay7(){
  RelayControl(pin[6], !globalState[6]);
}
public void Relay8(){
  RelayControl(pin[7], !globalState[7]);
}
public void RelayControl(int Id, boolean Flag){
  byte status = 0;
  if(Flag == true){
    status = 1;
  } else {
    status = 0;
  }
  myPort.write("PIN." +Id +'.' +status +endchar);
}

void SensorCheck(int value){
 myPort.write("SC." +value +endchar);
}

public void Timefunc(int Id, String value){
  byte overboard = 0;
  int control = Integer.parseInt(value);
  if(control &gt; 5100){
    control=5100; 
  }
  control = control/10;
  if(control &gt;= 256){
    overboard = 1;
  }
  if(overboard == 0){
    myPort.write("EEPROM." +Id +'.' +control +endchar);
    Id++;
    myPort.write("EEPROM." +Id +'.' +"0" +endchar);
  }
  if(overboard == 1){
    control = control - 255;
    myPort.write("EEPROM." +Id +'.' +"255" +endchar);
    Id++;
    myPort.write("EEPROM." +Id +'.' +control +endchar);
  }
}

void serialEvent(Serial myPort) {
  inByte = myPort.readStringUntil('\n');
  if (inByte != null){
    inByte = trim(inByte);
    println("Recieved: " +inByte);
    if(inByte.contains("PIN.")){
      String result = inByte.substring(4,6);
      char state = inByte.charAt(7);
      boolean isOn;
      if(state == '1'){
        isOn = true;
      }
      else{
       isOn = false; 
      }
      int endresult = parseInt(result);
      for(int i = 0;i&lt;pin.length;i++){
        if (endresult == pin[i]){
          globalState[i] = isOn;
        }
      }
      delay(10);
    }//End of PIN Function
    if(inByte.contains("SEN.")){
      char firstvalue = inByte.charAt(5);
      char secondvalue = inByte.charAt(7);
      int fvresult = parseInt(firstvalue);
      int svresult = parseInt(secondvalue);
      cp5.getId(fvresult);
    }

    if (firstContact == false) {
      if (inByte.equals("&lt;Controller is ready&gt;")) {
        myPort.clear();
        firstContact = true;
        //myPort.write("A");
        println("SYSTEM: Contact Made");
        delay(100);
        println("Control ready!");
      }
    }
  }
}
</code></pre>

<p>The issue resides with this line: 
cp5.getId(fvresult);</p>

<p>How can I format this to send the information to the Textfield controller when it doesn't go thorugh the ControlEvent function?</p>

<p>edit: fixed spelling mistakes.</p>

<p>edit: I have a working example below.  Its just not a "universal" function:</p>

<pre><code>if(inByte.contains("SEN.")){
  char firstvalue = inByte.charAt(5);
  String secondvalue = inByte.substring(6,inByte.length());
  //int fvresult = Integer.parseInt(firstvalue);
  int svresult = Integer.parseInt(secondvalue);
  println(svresult);
  Timer1.setText(secondvalue);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Detecting CTRL+C keyboard combo and sending over serial</title>
      <link>https://forum.processing.org/two/discussion/9335/detecting-ctrl-c-keyboard-combo-and-sending-over-serial</link>
      <pubDate>Sun, 08 Feb 2015 10:33:46 +0000</pubDate>
      <dc:creator>anjchang</dc:creator>
      <guid isPermaLink="false">9335@/two/discussions</guid>
      <description><![CDATA[<p>Just a quick question-- Is there any way to get Processing to detect that you've hit "CTRL+C" in the keyboard and then send it out over serial?
I'm trying to do this while communicating to an MSP430 but it doesn't seem to be working.
      if (typedCharacterString.indexOf("ctrl")==0) {
        port.write(0x03);
        port.write(0x10);
      }
?? Thanks for any suggestions. anj</p>
]]></description>
   </item>
   <item>
      <title>processing write several time to arduino</title>
      <link>https://forum.processing.org/two/discussion/22037/processing-write-several-time-to-arduino</link>
      <pubDate>Sun, 16 Apr 2017 20:43:45 +0000</pubDate>
      <dc:creator>Maxwell11</dc:creator>
      <guid isPermaLink="false">22037@/two/discussions</guid>
      <description><![CDATA[<p>I have a problem is that when i use serial.write() in processing to send value to arduino it actually send it several times which leads to problems with my project is there any idea how to fix such problem?</p>
]]></description>
   </item>
   <item>
      <title>About using different mods of webcam.</title>
      <link>https://forum.processing.org/two/discussion/21507/about-using-different-mods-of-webcam</link>
      <pubDate>Mon, 20 Mar 2017 17:31:48 +0000</pubDate>
      <dc:creator>nikoches</dc:creator>
      <guid isPermaLink="false">21507@/two/discussions</guid>
      <description><![CDATA[<p>Hello everyone!I ran into a problem with using different mods in processing.I use standard library VIdeo <a rel="nofollow" href="https://processing.org/reference/libraries/video/index.html">https://processing.org/reference/libraries/video/index.html</a>, to grab video from webcam, and i want to switch video mode at the time of shooting a video, you know, like changes resolutions and fps.Is it real?Also i use Control iP5 to make GUI, and i need to change this in listbox(Control iP5),In which all modes are presented.Really need your help.Thanks in advance.</p>

<pre><code>``    import controlP5.*;
    import processing.serial.*;
    import processing.video.*;
    Serial serial;
    String received;
    ControlP5 cp5;
    Capture cam;
    int a;
    int cnt = 0;
    boolean C = false;
    int i=0; ``
  ``  Textlabel myTextlabelA;
    ListBox l;
    Textlabel myTextlabelB;
    void setup() {
    String[] cameras = Capture.list();
    cp5 = new ControlP5(this);
    size(640, 480);
    noStroke(); 
     //String port = Serial.list()[0];
    //serial = new Serial(this, port, 9600);
   cam = new Capture(this, 320, 240, cameras[1]);
   cam.start();
   myTextlabelA = cp5.addTextlabel("label")
   .setText("water="+a)
   .setPosition(400, 40)
   .setColorValue(#000000)
   .setFont(createFont("Georgia", 20))
    ;
    myTextlabelB = cp5.addTextlabel("label1")
    .setText("HC-SR04="+a+"m")
    .setPosition(400, 80)
    .setColorValue(#000000)
    .setFont(createFont("Georgia", 20))
    ;``   
   `` l = cp5.addListBox("m")
    .setPosition(400, 120)
    .setSize(140, 140)
    .setItemHeight(24)
    .setBarHeight(25)
    .setColorBackground(color(#ff8800))
    .setColorActive(color(0))
    .setColorForeground(color(255, 100, 0))
    //.setFont(createFont("Times New Roman",14))
   .setColorValue(#000000)
   .setOpen(false)
   .setWidth(230)
    ;

     l.getCaptionLabel().toUpperCase(true);
     l.getCaptionLabel().set("Cameras");
     l.getCaptionLabel().setColor(#000000);
     l.setHeight(250);
     l.getCaptionLabel().setSize(15);
     l.getCaptionLabel().setWidth(200);
     for (i=0; i&lt;cameras.length; i++) {
     l.addItem(cameras[i], "ID="+i);
     l.getItem(i).put("color", new CColor().setBackground(0xffff0000).setBackground(0xffff8800));
     }
     //Описание кнопок
     cp5.addButton("Forward")
      .setPosition(560, 400)
      .updateSize()
        ;  


 ``      cp5.addButton("stop") 

       .setPosition(560, 420) 

       .updateSize()
        ;
       cp5.addButton("Backward")
       .setPosition(560, 440)

        .updateSize()
         ;
         cp5.addButton("Turn on Lights")
         .setPosition(20, 400)

          .updateSize()
           ;  ``
          cp5.addButton("Turn off Lights")
          .setPosition(20, 420)

           .updateSize() ``
            ;
           cp5.addButton("Move up")
          .setPosition(100, 400)

           .updateSize()
            ;
          cp5.addButton("Move Down")
          .setPosition(100, 420)

           .updateSize() 
            ;   ``
  ``       //Список доступных режимов камеры в консоли
           println("Available cameras:");
            for (int i = 0; i &lt; cameras.length; i++) {
            println(cameras[i], "ID=", i);
             }
           }
           void draw() {
           background(255, 204, 0);
          //Чтение камеры,если доступно
           if (cam.available() == true) {
            cam.read();
              }
           image(cam, 20, 20);
               }
         //Функции Кнопок
           public  void controlEvent(ControlEvent theEvent) {
           println(theEvent.getController().getName());
           println(l.getItem(i));
              }
            public void Forward() {
            serial.write('3');
               }
             public void stop() {
             serial.write('1');
                }
             public void Backward() {
             serial.write('2');
                 }
             //Определение нажатий
                 public void keyPressed() {
                 if ( key == CODED ) {
                 if ( keyCode == RIGHT ) {
                     a=10;
                     serial.write('1');
                     } else if ( keyCode == LEFT ) { 
                     a= 10;
                      serial.write('2');
                      } else if ( keyCode == UP ) { 
                      a -= 10;
                       serial.write('0');
                     } else if ( keyCode == DOWN ) { 
                        a += 10;
                        stop();
                               }
                            }
                        }  ``
</code></pre>

<p>p.s. 
If it's not difficult for you to express yourself simpler please, because my English is terrible(as you see).</p>
]]></description>
   </item>
   <item>
      <title>No stable recieving of Data from two MPU 6050</title>
      <link>https://forum.processing.org/two/discussion/20657/no-stable-recieving-of-data-from-two-mpu-6050</link>
      <pubDate>Sun, 05 Feb 2017 13:56:48 +0000</pubDate>
      <dc:creator>Patrik9</dc:creator>
      <guid isPermaLink="false">20657@/two/discussions</guid>
      <description><![CDATA[<p>Hi,</p>

<p>i'm interested in displaying the roll and pitch angles in processing. My Arduino code is from</p>

<p><a rel="nofollow" href="https://github.com/eadf/MPU6050_DMP6_Multiple">https://github.com/eadf/MPU6050_DMP6_Multiple</a></p>

<p>According to that I defined the output of the <strong>arduino code</strong> and in the serial monitor everything looks fine :).  I deleted the line OUTPUT_SERIAL.print("pr:"); so that just a 0 or 1 is send for the identification of the mpu, then TAB Angle1 for current mpu, TAB Angle2 for current mpu:</p>

<pre><code> OUTPUT_SERIAL.print(mpu); OUTPUT_SERIAL.print("\t");
 OUTPUT_SERIAL.print(ypr[1] * 180 / M_PI);
 OUTPUT_SERIAL.print("\t");
 OUTPUT_SERIAL.println(ypr[2] * 180 / M_PI);
</code></pre>

<p>(Interrupt pins not used as recommended by the way)</p>

<p>The <strong>Code for Processing is below</strong> . I just want to print the values in the console first, sometimes the real values are printed sometimes just zeros appear. Is the Problem the Character which needs to send to start the DMPs or something else (Transmitting led of the arduino not blinking in the case of zeros)?</p>

<pre><code>import processing.serial.*;
Serial myPort;  // Create object from Serial class
String inString;     // Data received from the serial port
int interval = 0;
int     lf = 10; 

float imu0[] = new float[2];
float imu1[] = new float[2];

void setup()
{

  size(800, 600);
  String portName = "COM3";
  myPort = new Serial(this, portName, 115200);
  myPort.clear();
  myPort.bufferUntil(lf);
  myPort.write('r');
}

void draw()
{ background(25);

 if (millis() - interval &gt; 1000) {
        // resend single character to trigger DMP init/start
        // in case the MPU is halted/reset while applet is running
        myPort.write('r');
        interval = millis();}


println(imu0[0]);
println(imu0[1]);
println(imu1[0]);
println(imu1[1]);

}

void serialEvent(Serial p) {
  inString = myPort.readString();

  try {
    // Parse the data
    //println(inString);
    String[] dataStrings = split(inString, '\t');
    if (dataStrings.length == 3) {
      if (dataStrings[0].equals("0")) {
        for (int i = 0; i &lt; dataStrings.length - 1; i++) {
          imu0[i] = float(dataStrings[i+1]);
        }
      } else if (dataStrings[0].equals("1")) {
        for (int i = 0; i &lt; dataStrings.length - 1; i++) {
          imu1[i] = float(dataStrings[i+1]);
        }        
      } else {
        println(inString);
      }
    }
  } catch (Exception e) {
    println("Caught Exception");
  }

}
</code></pre>

<p>If you don't know but have a stable example of recieving data from two mpu 6050 that would be also a big help
Thank you</p>
]]></description>
   </item>
   <item>
      <title>How to send the hex values from processing through serial ?.</title>
      <link>https://forum.processing.org/two/discussion/19940/how-to-send-the-hex-values-from-processing-through-serial</link>
      <pubDate>Tue, 27 Dec 2016 09:49:33 +0000</pubDate>
      <dc:creator>msureshkumar2610</dc:creator>
      <guid isPermaLink="false">19940@/two/discussions</guid>
      <description><![CDATA[<p>I need to send this 11 Series bytes(0xEF,0x01,0xFF,0xFF,0xFF,0xFF,0x01,0x00,0x03,0x01,0x00,0x05) from processing to serial.</p>

<pre><code>import processing.serial.*;
int value = 0;
Serial myPort;  
int val;        
byte collect[] = {0xEF,0x01,0xFF,0xFF,0xFF,0xFF,0x01,0x00,0x03,0x01,0x00,0x05};

void setup() 
{
  size(200, 200);
  myPort = new Serial(this, "COM6", 57600);
}

void draw() {
  fill(value,0,255);
  rect(25, 25, 50, 50);
}

void mouseClicked() {
  if (value == 0) {
    value = 255;
    for(int i=0;i&lt;=11;i++){
      myPort.write(collect[i]);
    }
  } else {
    value = 0;
  }
}
</code></pre>

<p>I got error while using this byte data type</p>

<p>Which data type I need to use for this kind of HEX values ?.</p>
]]></description>
   </item>
   <item>
      <title>Kinect with grid</title>
      <link>https://forum.processing.org/two/discussion/19864/kinect-with-grid</link>
      <pubDate>Wed, 21 Dec 2016 12:11:47 +0000</pubDate>
      <dc:creator>inxsght</dc:creator>
      <guid isPermaLink="false">19864@/two/discussions</guid>
      <description><![CDATA[<p>Im new with processing, im trying to make a fade background and as the user move the movement will stay on the grid.</p>

<p>So i have made a grid, where i move the can see my body movement on the grid.</p>

<blockquote class="Quote">
  <p>1) how do i make the movement stay in grid after i move.</p>
  
  <p>2) how do i make ... example = player 1 = red, player 2 = green.</p>
  
  <p>3)background color fade random rgb.</p>
</blockquote>

<pre><code>import processing.serial.*;
import KinectPV2.*;


Serial myPort;
KinectPV2 kinect;

boolean foundUsers = false;

int matrixSizeWidth = 14;
int matrixSizeHeight = 18;

void setup() {
  size(1024, 424);
  frameRate(200);

  //String portName = "COM5";
 // myPort = new Serial(this, portName, 115200);

  kinect = new KinectPV2(this);

  //kinect.enableDepthImg(true);
  kinect.enableBodyTrackImg(true);

  kinect.init();

  delay(6000);
}

void draw() {
  clear();
  background(255);

  PImage kinectImg = kinect.getBodyTrackImage();

  image(kinectImg, 512, 0);

  int [] rawData = kinect.getRawBodyTrack();

  foundUsers = false;
  //iterate through 1/5th of the data
  for(int i = 0; i &lt; rawData.length; i+=5){
    if(rawData[i] != 255){
     //found something
     foundUsers = true;
     break;
    }
  }
 // print(rawData);

  int totalPixels = 0;

  //if (foundUsers)
  //{
   // myPort.clear();

    int row = 0;

    //color toColor = -(int)random(255*255*255);
    color thatColor = -(int)random(255*255*255);

    for (int y = 10; y &lt; 414; y += matrixSizeHeight){
      int col = 0;

      for (int x = 10; x &lt; 500; x += matrixSizeWidth) {
        color c = kinectImg.pixels[x + y*kinectImg.width];

        // print(c);

        if(c &lt; -1)
        {
        //c = toColor;
        }
        else{
        c = thatColor;
        }

        print(c);

        fill(c);
        stroke(0);
        strokeWeight(1);
        rect(x, y, matrixSizeWidth, matrixSizeHeight);

        //if (totalPixels &lt; 105)
        //{
          if (c != -1)
          {
            //print(1);
           // myPort.write("H");
            totalPixels++;
            //myPort.write(totalPixels);
          }
          else
          {
            //print(0);
           // myPort.write("L");
          }
        //}


        col++;
      }

      row++;
    }


   // myPort.write("C");

  fill(0);
  textSize(14);
  text(kinect.getNumOfUsers(), 10, 30);
  text("Found User: "+foundUsers, 10, 50);
  text(frameRate, 10, 70);
  text("Total Pixels: " + totalPixels, 10, 90);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Lockup with Game Control Plus by Quark</title>
      <link>https://forum.processing.org/two/discussion/19272/lockup-with-game-control-plus-by-quark</link>
      <pubDate>Thu, 24 Nov 2016 17:09:09 +0000</pubDate>
      <dc:creator>house231</dc:creator>
      <guid isPermaLink="false">19272@/two/discussions</guid>
      <description><![CDATA[<p>I am using the GC+ library to get Windows 7 joystick movements to processing. I then use the processing program to communicate with my Arduino microprocessor.  Its a great library, awesome tutorials and documentation.  My problem is it works for about 5 minutes flawlessly then my processing programs totally locks up.  I cannot get the program to run again unless I reboot my computer.   I am sorry I cannot follow the directions for posting code.  Wow what I mess I am.</p>

<pre><code> /**
 Demonstration of using a joystick for Game Control Plus

 When this sketch runs it will try and find
 a game device that matches the configuration
 file 'joystick' int the data file of the processing folder.  if it can't match this device
 then it will present you with a list of devices
 you might try and use.  Use the configurator in the Processing--&gt;Files--&gt;examples--&gt;GC+ to write a data file that is included into the procesing
 folder.  You keymap and name various functions.  These are then written down below in a code. (get matched
 device and get slider).

 The chosen device requires 2 sliders and 2 buttons.
 */

import org.gamecontrolplus.gui.*;
import org.gamecontrolplus.*;
import net.java.games.input.*;

import processing.serial.*;

ControlIO control;
ControlDevice stick;
float px, py, pz, pzz;
Serial myPort;  // Create object from Serial class

public void setup() {
  myPort = new Serial(this, "COM4", 9600);//this port can be different on even the same PC.
  size(400, 400);
  // Initialise the ControlIO
  control = ControlIO.getInstance(this);
  // Find a device that matches the configuration file
  stick = control.getMatchedDevice("XBOX4"); // the device is named in the config file made by GC+ ap
  if (stick == null) {
    println("No suitable device configured");
    System.exit(-1); // End the program NOW!
  }
}

public void draw() {
  px = stick.getSlider("STEERING").getValue(); //these values are named in the config file made by  GC+ ap
  py = stick.getSlider("THROTTLE").getValue();
  pz = stick.getSlider("BRAKE").getValue();  

  px=map(px,-1,1,0,255);//data from game control is usually -1.0000 to + 1.0000///PWM of Arduino requires 0-255 for analogWrite output.
  px = int(px);
  py=map(py,-1,1,127,255);
  py=int(py);
  pz=map(pz,-1,1,127,0);
  pz=int(pz);

  pzz=py-(127-pz);

delay(100);
    myPort.write("H" + int(px) + "," + int(pzz) + "\n");    //Arduino is looking for H255,255\n (can be any non numberical value to stop must be H to start)
    background(255, 255, 240);
fill(255, 0, 0);
textSize(25);
text(int(px), 75, 100);//do not write to Processing monitor it takes too long, better to write to GUI.
text(int(pzz),75,200);

}
</code></pre>

<p>``</p>
]]></description>
   </item>
   <item>
      <title>difficulty connecting arduino to processing &amp; difficulty in servo control T_T</title>
      <link>https://forum.processing.org/two/discussion/19079/difficulty-connecting-arduino-to-processing-difficulty-in-servo-control-t-t</link>
      <pubDate>Wed, 16 Nov 2016 22:20:00 +0000</pubDate>
      <dc:creator>vapeur</dc:creator>
      <guid isPermaLink="false">19079@/two/discussions</guid>
      <description><![CDATA[<p>Hi there,</p>

<p>Recently I want to make a project using processing to capture mind wave and send 0, 1, 2 to Arduino to control a servo.
I encountered 3 problems:</p>

<p>1, Processing's serial cannot transmit to Arduino, but it can send 0 at 1st time, and then nothing works.</p>

<p>2, My servo does not stick to the angle I wrote to him. It keeps spinning around and around..</p>

<p>3, I intend to make servo turn clock wise when receiving '1', and anticlockwise receiving '2', but it dose not do anticlockwise all the time, it turns anticlockwise for 3seconds, and then turn clockwise, and repeat.....</p>

<p>Following are my codes. Each of the problems being solved can save me a step from the fire of July.......</p>

<p>Processing:</p>

<pre><code>//Thinkgear
import neurosky.*;
import org.json.*;

//Arduino
import cc.arduino.*;
import org.firmata.*;
import processing.serial.*;

ThinkGearSocket neuroSocket;
int attention=10;
int meditation=10;
int attentionBrightness = 0;

int attentionValue = 40;
int meditationValue = 40;

Arduino arduino;
Serial myPort;  // Create object from Serial class
int ledPin = 3;
int servoPin = 9;



void setup() 
{
  size(600,600); 

  //ThinkGear Connection
  ThinkGearSocket neuroSocket = new ThinkGearSocket(this);
  try {neuroSocket.start();}
  catch (Exception e) {println("Is Thinkgear running?");}
  smooth();
  frameRate(10);

  //Arduino Connection 
  String portName = Serial.list()[5]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
  printArray(Serial.list());
}


void draw() {

  visualisation();

  //case 0: halt &amp; LED BLINK 
  if (attention&lt;attentionValue)  
    {
      if(meditation&lt;=meditationValue)
      { myPort.write('0');  println("0"); } 

   //case 1:  close &amp; LED OFF
      else if (meditation&gt;meditationValue)
     { myPort.write('1');   println("1"); }   
    }

  //case 2:  open &amp; LED ON
  else if (attention&gt;attentionValue)
  { myPort.write('2');  println("2"); }
}


////alternative test
//   if (mousePressed == true) 
//   { myPort.write('0');  println("0"); } 

//   //case 1:  close &amp; LED OFF
//   if (mousePressed==false &amp;&amp; keyPressed==false)
//   { myPort.write('1');   println("1"); }   

//  //case 2:  open &amp; LED ON
//  if (keyPressed==true)
//  { myPort.write('2');  println("2");}
//}


void poorSignalEvent(int sig) {
  println("SignalEvent "+sig);
}

public void attentionEvent(int attentionLevel) 
{
  println("Attention Level: " + attentionLevel);
  attention = attentionLevel;
}


void meditationEvent(int meditationLevel) 
{
  println("Meditation Level: " + meditationLevel);
  meditation = meditationLevel;
}

void stop() {
  neuroSocket.stop();
  super.stop();
}
</code></pre>

<p>and Arduino,</p>

<pre><code>#include &lt;VarSpeedServo.h&gt;

//initiate
VarSpeedServo myservo;                            
int pos = 0;    
int servoPin = 9;
int ledPin = 3;


//conncect to processing
char val;


void setup() 
{ 
  //led
  pinMode(ledPin,OUTPUT);

  //servo
  myservo.attach(servoPin);  
  myservo.write(0,255,true);  //reset position
  delay(1000);
  Serial.begin(9600);
} 

void loop() 
{ 
  if (Serial.available())
  val = Serial.read();
  if(val =='1')
  {
  digitalWrite(ledPin,LOW);
  myservo.attach(servoPin);  
  int pos=0;
  while(pos &lt; 90)        // from 0 to 180   
  {                                                  
    myservo.write(pos,10,true);        
    Serial.println(myservo.read());
    delay(5);    
    pos += 1;                      
  } 

//  digitalWrite(servoPin,LOW);
  delay(20);
  }

  if (val =='2')
  {
  digitalWrite(ledPin,HIGH);
  myservo.attach(servoPin);  
  int pos = 90;
  while(pos&gt;=1)   //from 180 to 0  
  {                                
    myservo.write(pos,10,true);         
    Serial.println(myservo.read());
    pos-=1;
   digitalWrite(servoPin, HIGH);
   delay(20); 
  } 
  }

  else if (val == '0')
  {
  digitalWrite(ledPin, HIGH);  
  delay(1000);              
  digitalWrite(ledPin, LOW);    
  delay(1000);              
  myservo.detach();
  }
  }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Port.write question</title>
      <link>https://forum.processing.org/two/discussion/19173/port-write-question</link>
      <pubDate>Sun, 20 Nov 2016 05:04:08 +0000</pubDate>
      <dc:creator>house231</dc:creator>
      <guid isPermaLink="false">19173@/two/discussions</guid>
      <description><![CDATA[<p>I am trying to send the following:    H254,254\n.   I am not sure I am formatting it correctly in the write statement.  Any help would be so appreciated!!!!</p>

<p>value1=254;
    value2=254;
    myPort.write("H" + value1 + value2 + "\n");</p>
]]></description>
   </item>
   <item>
      <title>Turning on relays via serial port,building the GUI</title>
      <link>https://forum.processing.org/two/discussion/18593/turning-on-relays-via-serial-port-building-the-gui</link>
      <pubDate>Mon, 17 Oct 2016 12:13:56 +0000</pubDate>
      <dc:creator>Yami89</dc:creator>
      <guid isPermaLink="false">18593@/two/discussions</guid>
      <description><![CDATA[<p>I've made a small program to turn on and off relays via ardiuno and it works. Now I would like to make a proper interface so basically have rectangle on screen and show which button/light is turned on. So when I press 1 the rectangle labled light 1 should turn red and go back to the when I release the key. the problem i'm having is that when the rectangle turns red it stays red without going back even when key is release. I could use the keyReleased function but then how would I include that into my current program?</p>

<pre><code>import processing.serial.*;

Serial myPort;  // Create object from Serial class

void setup() 
{
  size(200, 200); 
  String portName = Serial.list()[5]; 
  myPort = new Serial(this, portName, 9600);
  printArray(Serial.list());
}
void draw() {
  if ((keyPressed == true)&amp;&amp;(key == '1'))
  { 
    myPort.write('a');         
    println("1");
  } else if ((keyPressed == true)&amp;&amp;(key == '2')) {
    myPort.write('b');
    println("2");
  } else if ((keyPressed == true)&amp;&amp;(key == '3')) {
    myPort.write('c');
    println("3");
  } else if ((keyPressed == true)&amp;&amp;(key == '4')) {
    myPort.write('d');
    println("4");
  } else if ((keyPressed == true)&amp;&amp;(key == '5')) {
    myPort.write('e');
    println("5");
  } else 
  {                          
    myPort.write('0');
  }
}
</code></pre>

<p>Here is the code showing the idea about the rectangle turning red I've used ellipse just to show you the idea.</p>

<pre><code>void setup(){
          size(400,400);
          ellipse(20,20,20,20);



        }
        void draw(){
        if((keyPressed == true)&amp;&amp;(key == '1')){
          ellipse(20,20,20,20);
          fill(255,0,0);


        }





        }                       
</code></pre>
]]></description>
   </item>
   <item>
      <title>convert float string to string</title>
      <link>https://forum.processing.org/two/discussion/18679/convert-float-string-to-string</link>
      <pubDate>Mon, 24 Oct 2016 00:49:20 +0000</pubDate>
      <dc:creator>allcc</dc:creator>
      <guid isPermaLink="false">18679@/two/discussions</guid>
      <description><![CDATA[<p>I'm communicating with a microcontroller using the serial port using a demo I found and it works great. The issue is I do not want a floating point number to go to the microcontroller. Right now it does, using the code below.</p>

<p>What I would like to do is drop the decimal (or round off) "subtext[counter]" before sending via myPort.write. I have tried converting it to an int, but then myport.write doesn't like it. If there is a way to send an INT via myPort.write that would also be a good solution.</p>

<p>if(counter&lt;subtext.length){</p>

<p>pan = Float.valueOf(subtext[counter]);</p>

<p>pan = (pan + 0.01) * 11.2;</p>

<p>(subtext[counter]) = Float.toString(pan);</p>

<p>myPort.write(subtext[counter]);</p>
]]></description>
   </item>
   <item>
      <title>7 Segment Up/Down Counter controlled by Processing Program</title>
      <link>https://forum.processing.org/two/discussion/18716/7-segment-up-down-counter-controlled-by-processing-program</link>
      <pubDate>Wed, 26 Oct 2016 03:48:27 +0000</pubDate>
      <dc:creator>lucassantos212</dc:creator>
      <guid isPermaLink="false">18716@/two/discussions</guid>
      <description><![CDATA[<p>Hi! The activity involves me having to create an up/down counter using an Arduino and controlled by processing. My idea is that there are buttons in the processing program that when hovered over, sends a signal to the arduino program signifying a process. So hovering over the first square, makes it count down, the second square, stop, and the last square resets it. If it is not over any square, it sends a '0', making it continue counting up.</p>

<p>This is the working arduino code. I have pushbuttons that does the processes mentioned.</p>

<pre><code>    `

    unsigned char digit_1 = 7;
    unsigned char digit_2 = 8;
    unsigned char digit_3 = 10;

    int num1 = 0;
    int num2 = 0;
    int num3 = 0;
    int state = 0;
    int halt = 0;
    char val; //data received from serial port
    void setup()
    {
      Serial.begin(9600);
      for (int x = 11; x &lt; 19; x++)
      {
        pinMode (x, OUTPUT);
      }

      pinMode (digit_1, OUTPUT);
      pinMode (digit_2, OUTPUT);
      pinMode (digit_3, OUTPUT);
     //  attachInterrupt(0, s1_press, RISING);
     //  attachInterrupt(1, s2_press, RISING);

    }


    void loop()
    {
      while (Serial.available())
      { val = Serial.read();
      }
      if (val == 1)
      {
        state = 1;
      }
      else //if (val == 0)
      {
        state = 0;
        halt = 0;
      }
      if (val == 2)
      {
        halt = 1;
      }
      else
      {
        state = 0;
        halt = 0;
      }

      if (halt == 0) {
        if (state == 0) {
          num3++;
          if (num3 == 10) {
            num3 = 0;
            num2++;
          }
          if (num2 == 10) {
            num2 = 0;
            num1++;
          }
          if (num1 == 10) {
            num1 = 0;
            num2 = 0;
            num3 = 0;
          }
        }

        if (state == 1) {
          num3--;
          if (num3 == -1) {
            num3 = 9;
            num2--;
          }
          if (num2 == -1) {
            num2 = 9;
            num1--;
          }
          if (num1 == -1) {
            num3 = 9;
            num2 = 9;
            num1 = 9;
          }
        }
      }
      for (int x = 0; x &lt; 80; x++) {
        digitalWrite (digit_3, HIGH);
        digitalWrite (digit_2, LOW);
        digitalWrite (digit_1, LOW);
       display_ (num1);
        delay(1);
        digitalWrite (digit_3, LOW);
        digitalWrite (digit_2, HIGH);
        digitalWrite (digit_1, LOW);
        display_ (num2);
        delay(1);
        digitalWrite (digit_3, LOW);
        digitalWrite (digit_2, LOW);
        digitalWrite (digit_1, HIGH);
        display_ (num3);
        delay(1);
      }

    }




    void display_ (unsigned char num)
    {
      switch (num)
      {
        case 0:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, HIGH);
            digitalWrite (16, HIGH);
            digitalWrite (17, LOW);
            digitalWrite (18, LOW);

            break;
          }
        case 1:
          {
            digitalWrite (11, LOW);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, LOW);
            digitalWrite (15, LOW);
            digitalWrite (16, LOW);
            digitalWrite (17, LOW);
            digitalWrite (18, LOW);

            break;
          }
        case 2:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, LOW);
            digitalWrite (14, HIGH);
            digitalWrite (15, HIGH);
            digitalWrite (16, LOW);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);
             break;
          }
        case 3:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, LOW);
            digitalWrite (16, LOW);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);
           break;
          }
        case 4:
          {
            digitalWrite (11, LOW);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, LOW);
            digitalWrite (15, LOW);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
        case 5:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, LOW);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, LOW);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
        case 6:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, LOW);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, HIGH);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
        case 7:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, LOW);
            digitalWrite (15, LOW);
            digitalWrite (16, LOW);
            digitalWrite (17, LOW);
            digitalWrite (18, LOW);


            break;
          }
        case 8:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, HIGH);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
        case 9:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, LOW);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
      }
    }


    void s1_press() {
      if (state == 0)
        state = 1;
      else if (state == 1)
        state = 0;
      delay (100);
    }

    void s2_press() {
      if (halt == 0)
        halt = 1;
      else
        halt = 0;
      delay(100);
    }
</code></pre>

<p>Here is my intended implementation of the processing code based on the serial write example;</p>

<p>`
    import processing.serial.*;</p>

<pre><code>Serial myPort;  // Create object from Serial class
int val;        // Data received from the serial port
color c1 = #75C58E;
color c2 = #75C5FF;
color c3 = #D07633;
void setup() 
{
  size(420, 200);
  String portName = Serial.list()[1];
  myPort = new Serial(this, portName, 9600);
}

//0 - count up and start
//1 - count down
//2 - stop
//3 - reset

void draw() {
  background(255);
  if (mouseOverRect() == true) {  // If mouse is over square,
    fill(c1);                    // change color and
    myPort.write('1');              // send a '1' to indicate mouse is over square
  } else                          //will be equivalent to the count up/count down trigger
  {
    fill(0);
    myPort.write('0');
  }
  rect(50, 50, 100, 100);         // Draw a square

  if (mouseOverRect2() == true) {  // If mouse is over square,
    fill(c2);                    // change color and
    myPort.write('2');              // send a 2 to indicate mouse is over square
  } else                        //stop trigger
  {
    fill(0);
    myPort.write('0');
  }
  rect(160, 50, 100, 100);

    if (mouseOverRect3() == true) {  // If mouse is over square,
    fill(c3);                    // change color and
    myPort.write('3');              // send a '3' to indicate mouse is over square
  } else                      //reset
  {
    fill(0);
    myPort.write('0');
  }
  rect(270, 50, 100, 100);
}


boolean mouseOverRect() { // Test if mouse is over square
  return ((mouseX &gt;= 50) &amp;&amp; (mouseX &lt;= 150) &amp;&amp; (mouseY &gt;= 50) &amp;&amp; (mouseY &lt;= 150));
}
boolean mouseOverRect2() { // Test if mouse is over square
  return ((mouseX &gt;= 160) &amp;&amp; (mouseX &lt;= 260) &amp;&amp; (mouseY &gt;= 50) &amp;&amp; (mouseY &lt;= 150));
}
boolean mouseOverRect3() { // Test if mouse is over square
  return ((mouseX &gt;= 270) &amp;&amp; (mouseX &lt;= 370) &amp;&amp; (mouseY &gt;= 50) &amp;&amp; (mouseY &lt;= 150));
}
</code></pre>

<p>`</p>

<p>Any tips on how this could be implemented? My implementation doesn't seem to affect the arduino program in any way.</p>
]]></description>
   </item>
   <item>
      <title>Arduino Serial  to Processing Serial Problem with Bluetooth :(</title>
      <link>https://forum.processing.org/two/discussion/18580/arduino-serial-to-processing-serial-problem-with-bluetooth</link>
      <pubDate>Sun, 16 Oct 2016 16:01:42 +0000</pubDate>
      <dc:creator>jeremy_wilde</dc:creator>
      <guid isPermaLink="false">18580@/two/discussions</guid>
      <description><![CDATA[<p>With HC-SR04 sensor, I'm trying to put Arduino Serial output to Processing with Bluetooth</p>

<p>On Arduino, I can get perfect distance output on serial monitor (like 2~30)</p>

<p>However, When I try to transport that serial to Processing with Bluetooth</p>

<p>It turns to someting like -1, 55, 54 on Processing Serial monitor</p>

<p>This is my Arduino code</p>

<pre><code>int trigPin = A5;
int echoPin = A4;
void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
long duration, distance;
  digitalWrite(trigPin, HIGH);
  delay(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  distance = ((float)(340 * duration) / 10000) / 2;

  Serial.print(distance);
  delay(500);
  if (Serial.available() &gt; 0) {
    Serial.read();
    Serial.write(distance);
  }
}
</code></pre>

<p>This is Processing code</p>

<pre><code>    import processing.serial.*;

    Serial serial;

    void setup() {
      size(400, 400);  

     // println(Serial.list());
      serial = new Serial(this, Serial.list()[1], 9600);
      int start = millis();
      while (millis() &lt; start + 4000) {
      }
      serial.write(1);
     frameRate(10);
    }

    void draw() {
      if (serial.available() &gt; 0) {
        background(serial.read(),0,0);
        serial.write(1);
      }
          println(serial.read());
    }
</code></pre>

<p>Can you help me?</p>
]]></description>
   </item>
   <item>
      <title>How to send data of type double over a Server. (server.write(double))</title>
      <link>https://forum.processing.org/two/discussion/5486/how-to-send-data-of-type-double-over-a-server-server-write-double</link>
      <pubDate>Sat, 31 May 2014 01:56:29 +0000</pubDate>
      <dc:creator>everittmatt</dc:creator>
      <guid isPermaLink="false">5486@/two/discussions</guid>
      <description><![CDATA[<p>Hey there, I am working on a project that sends data from Processing to Houdini( a procedural modelling program).
Houdini needs to receive the data in 8 byte chunks of type <em>int</em> and <em>double</em>.</p>

<p>In my code below I am successfully sending the cmdType and channels <em>ints</em> by packing them out. However, the structure of a double cannot be simply packed out and the server.write() will on use int, char and byte.</p>

<p>Is there a way I can send a double or convert it to bytes/bits?</p>

<pre><code>import processing.net.*;
Server myServer;
int val = 0;
int cmdType = 1;
int channels = 3;
double[] samples = {5.3,2.3,1.2};

void setup() {
  size(200, 200);
  // Starts a myServer on port 5204
  myServer = new Server(this, 5204);
  frameRate(5);
  sendReset();
}

void draw() {
  val = (val + 1) % 255;
  background(val);
  sendSetup(cmdType);
  sendSetup(channels);
  sendSamples(samples);
}

void sendSetup(int d){
  myServer.write(0);
  myServer.write(0);
  myServer.write(0);
  myServer.write(0);
  myServer.write(0);
  myServer.write(0);
  myServer.write(0);
  myServer.write(d);
}

void sendSamples(double[] sample){
  for(int i = 0; i &lt; sample.length; i++){
    myServer.write(sample[i]);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Has anyone here tried an Arduino connection to Android using Processing</title>
      <link>https://forum.processing.org/two/discussion/17695/has-anyone-here-tried-an-arduino-connection-to-android-using-processing</link>
      <pubDate>Fri, 29 Jul 2016 12:49:37 +0000</pubDate>
      <dc:creator>nanakesewaa</dc:creator>
      <guid isPermaLink="false">17695@/two/discussions</guid>
      <description><![CDATA[<p>Hello I have been having some struggles with displaying flowers on my Android. This is what my code does. I have two sensors on the Arduino, photoresistor and motion detector, they both work  and what Processing does is to display different modes of a colored flower based on the state of the sensors. I want to create a sort of energy conscious display so people know what is wrong in a room based on the color of the flower. A connection between Processing and Android works(only a test of flower display), so does the connection between Processing and Arduino work(it runs and I see the flower states).
How can I get the Android to display my flowers, it seems to me the problem might be from reading the Serial connections....any help?</p>

<p>Android Sketch</p>

<pre><code>#define PIR 3
#define LED 2

int pirState;
int ldrValue;

void setup() {
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
  pinMode(PIR, INPUT);
  digitalWrite(LED, LOW);

}

void loop(){
pirState = digitalRead(PIR);
ldrValue = analogRead(LDR)/4;
Serial.write(pirState);
Serial.write(ldrValue);
delay(1000);
}
</code></pre>

<p>Processing Sketch
//</p>

<pre><code>import processing.serial.*; 

Serial port;  // Create object from Serial class

int pirState;
int ldrValue;

void setup(){
fullScreen();
noStroke();
frameRate(15);
printArray(Serial.list());
port= new Serial(this, Serial.list()[0],9600);

}

void draw(){
  if (port.available() &gt; 0) {  // If data is available to read,
    pirState = port.read();
    ldrValue = port.read();            // read it and store it in val
    println(pirState, "and", ldrValue);
    delay(10);
  } 
  background(255); // Clear background
    //set center point
    translate(width/2, height/2);
    //rotate canvas using frame count
   // rotate(radians(frameCount+mouseX));
    //draw 5 petals, rotating after each one
    for(int i=0; i&lt;5; i++){
        if (pirState == 0 &amp;&amp; ldrValue &lt;= 128) { // no one is in and light is off
        fill(#00ff00);//green
        ellipse(0,-80,100,100);
        rotate(radians(72));
        println("no one is and light is off");
        }
        else if(pirState == 0 &amp;&amp; ldrValue &gt; 128){//no one is in and light is on
           fill(#FF0000);//red
        ellipse(0,-80,100,100);
        rotate(radians(72));
        println("no one is and light is on");
        }
         else if(pirState == 1 &amp;&amp; ldrValue &gt; 128) { // one is in and light is on
       fill(#FFAA0D);//orange
        ellipse(0,-80,100,100);
        rotate(radians(72));
        println("one is and light is on");
        }
        else if(pirState == 1 &amp;&amp; ldrValue &lt;= 128){ //if one is in and light is off
        fill(#00AAFF);//blue
        ellipse(0,-80,100,100);
        rotate(radians(72));
        println("one is and light is off");

    }
    //center circle
    fill(#fff9bb);
    ellipse(0,0,100,100);
 }
</code></pre>

<p>How can I connect my Processing output to the Android.</p>
]]></description>
   </item>
   <item>
      <title>Android processing app crashes when using usb / processing serial library (Serial.list(this)) probs</title>
      <link>https://forum.processing.org/two/discussion/17375/android-processing-app-crashes-when-using-usb-processing-serial-library-serial-list-this-probs</link>
      <pubDate>Thu, 30 Jun 2016 19:56:51 +0000</pubDate>
      <dc:creator>gabriellalevine</dc:creator>
      <guid isPermaLink="false">17375@/two/discussions</guid>
      <description><![CDATA[<p>hi - I'm having trouble debugging why my android app is crashing when trying to use <a rel="nofollow" href="https://github.com/inventit/processing-android-serial">processing android serial</a> to talk via Processing android app to arduino. i can successfully install and launch the app on android, but the app keeps crashing. I'm using really simple code just to see if I can talk via an OTG cable via serial from Android to Arduino via processing app. But when I plug in the OTG USB cable that's plugged into arduino UNO, I can choose the android app to open up that I have installed from Processing to android, but right away it says "Unfortunately, this app has stopped".</p>

<p>I'm wondering how to go about debugging this. Is it the wrong port (Serial.list(this)[0]) that is doing this? or something else? I'm not sure how to debug why the app's crashing. I just recently started using Processing 0251 for Android. Even just the line "println(Serial.list(this));" triggers the app to shut down.</p>

<p>Thanks in advance!</p>

<p>I used this <a rel="nofollow" href="http://journeytounknownsoundscapes.blogspot.com/2013/12/how-to-arduino-with-android-really-good.html">link</a> to help getting set up:</p>

<p>Processing code in Android mode:</p>

<pre><code>import com.yourinventit.processing.android.serial.*;

Serial SerialPort;
boolean Toggle;

void setup()    
{fullScreen();
background(255,0,0);
  println(Serial.list(this)); //this line alone makes the app crash even if i dont have any other code
  SerialPort = new Serial(this, Serial.list(this)[0], 9600);
}

void draw()
{
}

void mousePressed() {    
  Toggle = !Toggle;
    // while (SerialPort.available() &gt; 0) {
  SerialPort.write( Toggle?"1":"0");
    // }
}
</code></pre>

<p>Arduino Code:</p>

<pre><code>    #define NUMBER_OF_CHANNELS 8
    #define PINLED1 13
    volatile char lastReceivedCharFromSerialIn = '\0';

    void setup() {
      pinMode(PINLED1, OUTPUT);
      Serial.begin(9600);    
    }

    void loop() {
      digitalWrite( PINLED1, lastReceivedCharFromSerialIn == '1');
    }

    void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        lastReceivedCharFromSerialIn = (char)Serial.read(); 
      }
    }
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to send data from arduino after mousepressed()?</title>
      <link>https://forum.processing.org/two/discussion/17515/how-to-send-data-from-arduino-after-mousepressed</link>
      <pubDate>Wed, 13 Jul 2016 14:44:31 +0000</pubDate>
      <dc:creator>rojascan</dc:creator>
      <guid isPermaLink="false">17515@/two/discussions</guid>
      <description><![CDATA[<p>Basically what I want to do is to send values of a potentiometer to the processing and show them in the console after I press a button in the processing program. However, I'm not getting what I want.</p>

<p>My program does a few things that already worked. It has three different modes to move a servo and those are in the main screen of my program. And I've got another screen when I press the button and some of the values of the potentiometer are shown. However, those values don't keep showing unless I press the button again.</p>

<p>This is the relevant arduino code:</p>

<pre><code>void loop ()
{

  if (Serial.available()) {
    val = Serial.read();
  }
 //val is send from processing to the arduino to change modes 
  switch (val) {
    //-------------------------- Close Modes----------------------//
    case 0:
        digitalWrite(ledPot, LOW);
        digitalWrite(ledCPM, LOW);
        digitalWrite(ledFSR, LOW);
      break;
    //--------------------------CPM Mode----------------------//
    case 1:
        cpmMovement();
        digitalWrite(ledCPM, HIGH);
        digitalWrite(ledPot, LOW);
        digitalWrite(ledFSR, LOW);
      break;
    //--------------------------POT Mode----------------------//
    case 2:
        digitalWrite(ledPot, HIGH);
        digitalWrite(ledCPM, LOW);
        digitalWrite(ledFSR, LOW);
        potMovement();
      break;
    //--------------------------FSR Mode----------------------//
    case 3:
        digitalWrite(ledPot, LOW);
        digitalWrite(ledCPM, LOW);
        digitalWrite(ledFSR, HIGH);
        fsrMovement();
      break;
    //---------------------Calibration Mode-----------------------//
    case 4:
        digitalWrite(ledPot, HIGH);
        digitalWrite(ledCPM, HIGH);
        digitalWrite(ledFSR, HIGH);
      break;
    //----------------Sending Values--------------------//  This is the relevant block
    case 5:
        digitalWrite(ledPot, LOW);
        digitalWrite(ledCPM, LOW);
        digitalWrite(ledFSR, HIGH);
        stateCAL == true;
        while(stateCAL == true){
        sendMaxValue();
        }
     break; 

  }
}

void sendMaxValue(){ //Function which sends the values to the console
  unsigned long startTime = millis();
  long calibrationTime = 3000;

  while(millis() - startTime &lt;= calibrationTime) {
    maxforce = analogRead(Pot)/4;
    if (maxforce &gt; maxReading) maxReading = maxforce;
    Serial.print(maxReading);         
    Serial.print('\t');         
    Serial.print(maxforce);
    Serial.print('\t');         
    Serial.print(startTime);
    Serial.print('\t');         
    Serial.println(millis() - startTime);

  }

  if (millis() - startTime &gt; calibrationTime){
    stateCAL = false;
    Serial.println("Falso");
    Serial.print("After 5 seconds, the maximum reading was: ");
    Serial.println(maxReading);
    maxReading = 0;
  } 

}
</code></pre>

<p>And this is the relevant processing code:</p>

<pre><code>void mousePressed() {
  println("Coordinates: "  + mouseX + "," + mouseY);
  if (pressedCPMButton &amp;&amp; currentColorCPM==butColor) { //Changing color CPM to pressed button color
    currentColorCPM = butpreColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(1);   //Send 1 to port
    println(1);
  } else if (pressedCPMButton &amp;&amp; currentColorCPM==butpreColor) {
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(0);   //Send 1 to port
    println(0);
  }
  if (pressedPOTButton &amp;&amp; currentColorPOT==butColor) {
    currentColorCPM = butColor;
    currentColorPOT = butpreColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(2);   //Send 1 to port
    println(2);                                    //Send 2 to port
  } else if (pressedPOTButton &amp;&amp; currentColorPOT==butpreColor) {
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(0);   //Send 1 to port
    println(0);
  }
  if (pressedFSRButton &amp;&amp; currentColorFSR==butColor) {
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butpreColor;
    currentColorCAL = butColor;
    myPort.write(3);   //Send 1 to port
    println(3);                                  //Send 3 to port
  } else if (pressedFSRButton &amp;&amp; currentColorFSR==butpreColor) {
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(0);   //Send 1 to port
    println(0);
  }
  if (pressedCALButton &amp;&amp; currentColorCAL==butColor) {
    currentScreen = 1;
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butpreColor;
    myPort.write(4);   //Send 1 to port
    println(4);                                  //Send 4 to port
  } else if (pressedBACKButton) {
    currentScreen = 0;
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(0);   //Send 1 to port
    println(0);
  }

  if (pressedSTARTCALButton) {     //This is the bit that isn't working well.
    if(myPort.available() &gt; 0){
    }
    myPort.write(5);     //Send 5 to port
    println(5);
    valforce = myPort.readString();
    println(valforce);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>serial.write() five sensors of Arduino and Processing</title>
      <link>https://forum.processing.org/two/discussion/17213/serial-write-five-sensors-of-arduino-and-processing</link>
      <pubDate>Sun, 19 Jun 2016 14:25:15 +0000</pubDate>
      <dc:creator>goldi</dc:creator>
      <guid isPermaLink="false">17213@/two/discussions</guid>
      <description><![CDATA[<p>Hi I'm very new to all of this, hope to formulate the question right.</p>

<p>In my project I have 5 sensors connected to Arduino, which I want to interpret via Seria.write() --&gt; Processing.</p>

<p>Arduino:</p>

<pre><code>firstSens = 100 + (155 * digitalRead(8));
secondSens = analogRead(A1)/4;
thirdSens = analogRead(A2)/4;
fourthSens = humData;
fifthSens = tempData;

int sensData[6] = {firstSens, secondSens, thirdSens, fourthSens, fifthSens};

int i;
for (i = 0; i &lt; 5; i = i + 1) {
  Serial.write(sensData[i]);
}
</code></pre>

<p>Processing:</p>

<pre><code>serialInArray[serialCount] = inByte;
    serialCount++;

if (serialCount &gt; 4 ) {
  firstSens = serialInArray[0];
  secondSens = serialInArray[1];
  thirdSens = serialInArray[2];
  fourthSens = serialInArray[3];
  fifthSens = serialInArray[4];

  println(firstSens + "\t" + secondSens + "\t" + thirdSens + "\t" + fourthSens + "\t" + fifthSens);

  myPort.write('A');
  serialCount = 0;
</code></pre>

<p>My problem is that sensors find their place in Processing's array randomly, so for example arduino's <code>firstSens</code> could be Processing's <code>secondSens</code> or <code>fifthSens</code></p>

<p>Why is this happening and how can I control it?</p>
]]></description>
   </item>
   </channel>
</rss>