<?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 serialevent() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/p3/feed.rss?Tag=serialevent%28%29</link>
      <pubDate>Sun, 08 Aug 2021 18:55:51 +0000</pubDate>
         <description>Tagged with serialevent() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggedserialevent%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>Get Selected Item value from ScrollableList</title>
      <link>https://forum.processing.org/two/discussion/20391/get-selected-item-value-from-scrollablelist</link>
      <pubDate>Sat, 21 Jan 2017 11:41:29 +0000</pubDate>
      <dc:creator>Rocks</dc:creator>
      <guid isPermaLink="false">20391@/two/discussions</guid>
      <description><![CDATA[<p>I am getting error in recovering the Item Value set using .setvalue(0). Also please guide how to use when users change the default value.</p>

<pre><code>`//Imports
import processing.serial.*;
import controlP5.*;
import java.util.*;

//Variable Declarations
ControlP5 lstPortList;
ControlP5 lstBaud;
String tport;
int tbaud;
Serial myPort;      // The serial port
int whichKey = -1;  // Variable to hold keystoke values
int inByte = -1;    // Incoming serial data
int Indexport =0;
int Indexbaud =1;

///Setup/////
void setup() {
  size(400, 400);
  // create a font with the third font available to the system:
  PFont myFont = createFont(PFont.list()[2], 14);
  textFont(myFont);

  // List all the available serial ports:
  // printArray(Serial.list());

  lstPortList = new ControlP5(this);
  String[] portNames =Serial.list();
  lstPortList.addScrollableList("Port")
    .setPosition(10, 10)
      .setSize(100, 100)
        .setBarHeight(20)
          .setItemHeight(20)
            .addItems(portNames)
              .setFont(createFont("Arial", 13))
                .setColorForeground(color(40, 128))
                  .setValue(Indexport);

  lstBaud = new ControlP5(this);
  List BaudList = Arrays.asList("4800", "9600", "19200", "38400", "57600", "115200");
  lstBaud.addScrollableList("Baud")
    .setPosition(200, 10)
      .setSize(100, 100)
        .setBarHeight(20)
          .setItemHeight(20)
            .addItems(BaudList)
              .setFont(createFont("Arial", 13))
                .setColorForeground(color(40, 128))
                  .setValue(Indexbaud);
  tport= port(Indexport);//lstPortList.get(ScrollableList.class, "port").getItem(Indexport).get("text");
  tbaud= baud(Indexbaud); //lstBaud.get(ScrollableList.class, "port").getItem(Indexbaud).get("text");
  myPort = new Serial(this, tport, tbaud );
}

void draw() { 

  background(0);
  text("Last Received: " + inByte, 10, 130);
  text("Last Sent: " + whichKey, 10, 100);
}

void serialEvent(Serial myPort) {
  inByte = myPort.read();
}

void keyPressed() {
  // Send the keystroke out:
  myPort.write(key);
  whichKey = key;
}

String port(int n) {
  return lstPortList.get(ScrollableList.class, "Port").getItem(n).get("text");  
}
int baud(int n) {
  return lstBaud.get(ScrollableList.class, "Baud").getItem(n).get("text");  
}`
</code></pre>

<p>Thanks</p>
]]></description>
   </item>
   <item>
      <title>How do you implement java.awt.robot into a sketch?</title>
      <link>https://forum.processing.org/two/discussion/20346/how-do-you-implement-java-awt-robot-into-a-sketch</link>
      <pubDate>Wed, 18 Jan 2017 23:40:09 +0000</pubDate>
      <dc:creator>fxmech</dc:creator>
      <guid isPermaLink="false">20346@/two/discussions</guid>
      <description><![CDATA[<p>I have been using this code below in my sketch, but it causes processing to stop when it is combined with serial communication to an arduino...
The serial part of my sketch works fine as long as I remove all of the code below...  if I leave it in, it will error out about 4 out of 5 times... then work fine until I run it again... Is there a chance that I am not setting up the robot class correctly or that the serial class is wrong but somehow works because robot isnt there???</p>

<pre><code>import java.awt.Robot;
import java.awt.AWTException;
Robot robby;
void setup()
{

//robot setup
   try
    {
      robby = new Robot();
    }
    catch (AWTException e)
    {
      println("Robot class not supported by your system!");
      exit();      
    }
  robby.mouseMove(screenResX/2, screenResY/2); //test line to move cursor
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>intermittent NULL error while communicating between arduino and processing</title>
      <link>https://forum.processing.org/two/discussion/20332/intermittent-null-error-while-communicating-between-arduino-and-processing</link>
      <pubDate>Wed, 18 Jan 2017 04:43:26 +0000</pubDate>
      <dc:creator>fxmech</dc:creator>
      <guid isPermaLink="false">20332@/two/discussions</guid>
      <description><![CDATA[<p>I am using modified code that came with a 9DOF sensor from adafruit...  It included a processing and Arduino sketch.  I used the communication part of the sketch but deleted the GUI portion...  The communication works but only 1 out of 4 or 5 times... the rest of the time I get this error in processing 3:</p>

<p><strong>Error, disabling serialEvent() for COM17
null</strong></p>

<p>I cant figure out how to resolve this intermittency... hope you can help</p>

<p>the relevant part of the processing sketch:</p>

<pre><code>void setup()
{
  size(displayWidth, displayHeight);
  smooth();
 setSerialPort("COM17");

  //robot setup
  try
  {
    robby = new Robot();
  }
  catch (AWTException e)
  {
    println("Robot class not supported by your system!");
    exit();
  }
  robby.mouseMove(screenResX/2, screenResY/2); //test line to move cursor
}

void serialEvent(Serial p) 
{
  String incoming = p.readString();
  if (printSerial) {
    //println(incoming);
  }

  if ((incoming.length() &gt; 8))
  {
    String[] list = split(incoming, " ");
    if ( (list.length &gt; 0) &amp;&amp; (list[0].equals("Orientation:")) ) 
    {
      leftClick = float(list[5]);
      rightClick = float(list[4]);
      roll  = float(list[3]); 
      pitch = float(list[2]); // Pitch = Y 
      yaw   = float(list[1]); // yawLeftRight
    }
  }
}

// Set serial port to desired value.
void setSerialPort(String portName) {
  // Close the port if it's currently open.
  if (port != null) {
    port.stop();
  }
  try {
    // Open port.
    port = new Serial(this, portName, 115200);
    port.bufferUntil('\n');
    // Persist port in configuration.
    saveStrings(serialConfigFile, new String[] { portName });
  }
  catch (RuntimeException ex) {
    // Swallow error if port can't be opened, keep port closed.
    port = null;
  }
}
</code></pre>

<p>HERE IS THE FULL ARDUINO CODE:</p>

<pre><code>#include &lt;Wire.h&gt;
#include &lt;Adafruit_Sensor.h&gt;
#include &lt;Adafruit_BNO055.h&gt;
#include &lt;utility/imumaths.h&gt;

/** 
   History
   =======
   2015/MAR/03  - First release (KTOWN)
*/

/** Set the delay between fresh samples */
#define BNO055_SAMPLERATE_DELAY_MS (100)

Adafruit_BNO055 bno = Adafruit_BNO055(55);


void displaySensorDetails(void)
{
  sensor_t sensor;
  bno.getSensor(&amp;sensor);
  Serial.println("------------------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" xxx");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" xxx");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" xxx");
  Serial.println("------------------------------------");
  Serial.println("");
  delay(500);
}

void setup(void)
{
  Serial.begin(115200);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);

  /** Initialise the sensor */
  if(!bno.begin())
  {
    /** There was a problem detecting the BNO055 ... check your connections */
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while(1);
  }

  delay(1000);

  /** Use external crystal for better accuracy */
  bno.setExtCrystalUse(true);
}


void loop(void)
{
  int rightClick = digitalRead(6);
  int leftClick = digitalRead(5);
  /** Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&amp;event);

  /** The processing sketch expects data as roll, pitch, heading */
  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.x);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.y);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.z);
  Serial.print(F(" "));

  Serial.print((float)rightClick);
  Serial.print(F(" "));
  Serial.print((float)leftClick);
  Serial.println(F(""));

  delay(BNO055_SAMPLERATE_DELAY_MS);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Code only working in Processing 2</title>
      <link>https://forum.processing.org/two/discussion/20212/code-only-working-in-processing-2</link>
      <pubDate>Thu, 12 Jan 2017 06:35:11 +0000</pubDate>
      <dc:creator>MaxM4X</dc:creator>
      <guid isPermaLink="false">20212@/two/discussions</guid>
      <description><![CDATA[<p>Hello!
Why is this code not working in processing 3?
I would just run it with processing 2, however I need to run it on a raspberry pi.</p>

<p>What part of the code is incompatible / what has to be changed to make it work?</p>

<p>Thanks!</p>

<pre><code>    /******************************************************************************
    Heart_Rate_Display.ino
    Demo Program for AD8232 Heart Rate sensor.
    Casey Kuhns @ SparkFun Electronics
    6/27/2014
    <a href="https://github.com/sparkfun/AD8232_Heart_Rate_Monitor" target="_blank" rel="nofollow">https://github.com/sparkfun/AD8232_Heart_Rate_Monitor</a>

    The AD8232 Heart Rate sensor is a low cost EKG/ECG sensor.  This example shows
    how to create an ECG with real time display.  The display is using Processing.
    This sketch is based heavily on the Graphing Tutorial provided in the Arduino
    IDE. <a href="http://www.arduino.cc/en/Tutorial/Graph" target="_blank" rel="nofollow">http://www.arduino.cc/en/Tutorial/Graph</a>

    Resources:
    This program requires a Processing sketch to view the data in real time.

    Development environment specifics:
        IDE: Arduino 1.0.5
        Hardware Platform: Arduino Pro 3.3V/8MHz
        AD8232 Heart Monitor Version: 1.0

    This code is beerware. If you see me (or any other SparkFun employee) at the
    local pub, and you've found our code helpful, please buy us a round!

    Distributed as-is; no warranty is given.
    ******************************************************************************/

    import processing.serial.*;

    Serial myPort;        // The serial port
    int xPos = 1;         // horizontal position of the graph
    float height_old = 0;
    float height_new = 0;
    float inByte = 0;


    void setup () {
      // set the window size:
      size(1000, 400);        

      // List all the available serial ports
      println(Serial.list());
      // Open whatever port is the one you're using.
      myPort = new Serial(this, Serial.list()[2], 9600);
      // don't generate a serialEvent() unless you get a newline character:
      myPort.bufferUntil('\n');
      // set inital background:
      background(0xff);
    }


    void draw () {
      // everything happens in the serialEvent()
    }


    void serialEvent (Serial myPort) {
      // get the ASCII string:
      String inString = myPort.readStringUntil('\n');

      if (inString != null) {
        // trim off any whitespace:
        inString = trim(inString);

        // If leads off detection is true notify with blue line
        if (inString.equals("!")) { 
          stroke(0, 0, 0xff); //Set stroke to blue ( R, G, B)
          inByte = 512;  // middle of the ADC range (Flat Line)
        }
        // If the data is good let it through
        else {
          stroke(0xff, 0, 0); //Set stroke to red ( R, G, B)
          inByte = float(inString); 
         }

         //Map and draw the line for new data point
         inByte = map(inByte, 0, 1023, 0, height);
         height_new = height - inByte; 
         line(xPos - 1, height_old, xPos, height_new);
         height_old = height_new;

          // at the edge of the screen, go back to the beginning:
          if (xPos &gt;= width) {
            xPos = 0;
            background(0xff);
          } 
          else {
            // increment the horizontal position:
            xPos++;
          }

      }
    }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Convert ascii into image?</title>
      <link>https://forum.processing.org/two/discussion/20136/convert-ascii-into-image</link>
      <pubDate>Sat, 07 Jan 2017 21:48:24 +0000</pubDate>
      <dc:creator>lucshi09</dc:creator>
      <guid isPermaLink="false">20136@/two/discussions</guid>
      <description><![CDATA[<p>Hi everyone! Quick question as I'm learning about processing:</p>

<p>Using a string of values coming in via serial, how can I tell processing to use these consider each number as the value for a pixel in order to create a black &amp; white image?</p>

<p>Here's the code that I have so far... any suggestions/examples would be great!</p>

<pre><code>PImage img;

import processing.serial.Serial;

static final int PORT_INDEX = 0, BAUDS = 9600;
String myString;

void setup() {
  noLoop();
  final String[] ports = Serial.list();
  printArray(ports);
  new Serial(this, ports[3], BAUDS).bufferUntil(ENTER);
}



void draw() {
  // show values coming in via Serial
  // e.g.: 0,0,0,0,0,0,0,0,0,0,255,255,255,255,255...
  //print("Received data: ");
  println(myString);


  // Use the values from serial to build a BLACK &amp; WHITE image
  // image has a size of 20x20 pixels
  // pixel values --&gt; 0 represents black; 255 represents white
  PImage img = createImage(20, 20, ALPHA);      // create a "placeholder" with the correct size
  img.loadPixels();

  // fill the placeholder with white pixels
  for (int i = 0; i &lt; img.pixels.length; i++) {
    img.pixels[i] = color(255);
  }
  img.updatePixels();
  image(img, 17, 17);


  // use values from myString to populate the image pixels
  //  ????

}



void serialEvent(final Serial s) {
  myString = s.readString().trim();
  redraw = true;
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to count rectangular signals and calculate signal/minute?</title>
      <link>https://forum.processing.org/two/discussion/19674/how-to-count-rectangular-signals-and-calculate-signal-minute</link>
      <pubDate>Sun, 11 Dec 2016 22:27:41 +0000</pubDate>
      <dc:creator>Oppogo</dc:creator>
      <guid isPermaLink="false">19674@/two/discussions</guid>
      <description><![CDATA[<p>Hello!
I have little expierence with programming and I had followed some instructions to make a light sensitive counter that would peak every time there's a sufficient change in ambient or artificial lighting. I took an example build of a heartrate sensor and adapted it for this purpose.</p>

<p>I was wondering If there's a way for processing to count signal position and display a calculated minute average of signals. For example 25 signals in 10 seconds multiplied by 6 to get signals per minute.</p>

<p>Example signal would be</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/760/X00IZKKDYYEA.png" alt="LightSensor" /></p>

<p>The processing code i'm using is taken from an example about a heartrate sensor.</p>

<p>How would I go about making the code detect a signal like this and count it once it goes over a certain treshold?</p>

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

Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph
float oldHeartrateHeight = 0; // for storing the previous reading

void setup () {
  // set the window size:
  size(600, 400);
  frameRate(25);

  // List available serial ports.
  println(Serial.list());

  // Setup which serial port to use.
  // This line might change for different computers.
  myPort = new Serial(this, Serial.list()[1], 9600);

  // set inital background:
  background(0);
}

void draw () {
}

void serialEvent (Serial myPort) {
  // read the string from the serial port.
  String inString = myPort.readStringUntil('\n');

  if (inString != null) {
    // trim off any whitespace:
    inString = trim(inString);
    // convert to an int
    println(inString);
    int currentHeartrate = int(inString);

    // draw the Heartrate BPM Graph.
    float heartrateHeight = map(currentHeartrate, 0, 1023, 0, height);
    stroke(0,255,0);
    line(xPos - 1, height - oldHeartrateHeight, xPos, height - heartrateHeight);
    oldHeartrateHeight = heartrateHeight;
    // at the edge of the screen, go back to the beginning:
    if (xPos &gt;= width) {
      xPos = 0;
      background(0);
    } else {
      // increment the horizontal position:
      xPos++;
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Arduino to Processing with push button and LEDs</title>
      <link>https://forum.processing.org/two/discussion/19528/arduino-to-processing-with-push-button-and-leds</link>
      <pubDate>Mon, 05 Dec 2016 05:12:11 +0000</pubDate>
      <dc:creator>emburke</dc:creator>
      <guid isPermaLink="false">19528@/two/discussions</guid>
      <description><![CDATA[<p>I have created a program that allows you to use processing to communicate to LEDs connected to a nano. The processing code allows the user to select an LED colour and how many times the LED will flash. Now, I have to connect a push button to the circuit. This is what I'm struggling with. When I push the button, it is supposed to bring the processing screen back to its original state and turn off all the LEDs. I have put the code in Arduino for the button push, but I have no idea what kind of code I need to communicate this back to Processing. I haven't put any code into Processing yet for the push button. Any help would be greatly appreciated.</p>

<p>Processing code...</p>

<pre><code>PFont jpFont, ebFont; 
int iLED=0, iCount=0, iData=0; 
import processing.serial.*; 
Serial rrSerial;

void setup()
{
  size(1000,500); 
  jpFont=loadFont("Tahoma-48.vlw"); 
  ebFont=loadFont("Tahoma-Bold-48.vlw"); 
  println(Serial.list()[2]);
  rrSerial=new Serial(this, Serial.list()[2],9600);
  rrSerial.write(0x83);
}

void draw()
{
   background(100);

   fill(255,0,0); 
   stroke(0); 
   strokeWeight(10); 
   ellipse(width/2-350,height/2+100,200,200); 

   fill(0,255,0); 
   stroke(0); 
   strokeWeight(10); 
   ellipse(width/2-125,height/2+100,200,200); 

   fill(0,0,255); 
   stroke(0); 
   strokeWeight(10); 
   ellipse(width/2+100,height/2+100,200,200); 

   fill(247,142,12); 
   stroke(0); 
   strokeWeight(10); 
   ellipse(width/2+325,height/2+100,200,200);  

   if(iLED==1) 
   {
     textFont(ebFont); 
     textSize(75); 
     fill(#F7F70C); 
     text(""+iCount,125,375); 
   }

   if(iLED==2) 
   {
     textFont(ebFont); 
     textSize(75);
     fill(#F7F70C); 
     text(""+iCount,350,375);  
   }

  if(iLED==3) 
  {
     textFont(ebFont); 
     textSize(75); 
     fill(#F7F70C); 
     text(""+iCount,575,375); 
  } 

   if(iLED==4) 
   {
     textFont(ebFont); 
     textSize(75); 
     fill(#F7F70C); 
     text(""+iCount,800,375); 
   }

   iData=iLED&lt;&lt;4|iCount&amp;0x0F; 
}

void keyPressed()
{
   if(keyCode==RIGHT&amp;&amp;iLED&lt;5) 
   {
     iLED++; 
     iCount=0; 
     if(iLED==5)iLED=0; 
   }

   if(keyCode==LEFT&amp;&amp;iLED&gt;0) 
   {
     iLED--; 
     iCount=0; 
     if(iLED==0)iLED=5; 
   }

   if(keyCode==UP&amp;&amp;iCount&lt;10) 
   {
     iCount++; 
     if(iCount==10)iCount=0;      
   }

   if(keyCode==DOWN&amp;&amp;iCount&gt;-1) 
   {
     iCount--; 
     if(iCount==-1)iCount=9; 
   }

   if(key==ENTER)rrSerial.write(iData); 

   if(key=='q')exit(); 
}
</code></pre>

<p>Now Arduino...</p>

<pre><code>boolean bToggle=0;
int iButton;

void setup() 
{
  Serial.begin(9600); 
  pinMode(3,OUTPUT); 
  pinMode(5,OUTPUT); 
  pinMode(9,OUTPUT); 
  pinMode(11,INPUT); 
  digitalWrite(3,LOW); 
  digitalWrite(5,LOW); 
  digitalWrite(9,LOW); 
  digitalWrite(11,HIGH); 
}

void loop() 
{
  if(Serial.available()&gt;0)
  {
    int iInput=Serial.read(); 
    int iWhich_Led=iInput&gt;&gt;4;
    int iFlash_Count=iInput&amp;0x0f;

    if(iWhich_Led==1)LED_burst(3,iFlash_Count); 

    if(iWhich_Led==2)LED_burst(5,iFlash_Count); 

    if(iWhich_Led==3)LED_burst(9,iFlash_Count); 

    if(iWhich_Led==4)LED_sequence(iFlash_Count); 
  }

  iButton=digitalRead(11); 

  if(iButton==0) 
  {
    while(digitalRead(11)==0); 
    bToggle=!bToggle; 
  }

  if(bToggle==1) 
  {
    digitalWrite(3,LOW); 
    digitalWrite(5,LOW); 
    digitalWrite(9,LOW); 
  }
}

void LED_burst(int iLED,int iCount) 
{
  for(int iX=0;iX&lt;iCount;iX++) 
  {
    digitalWrite(iLED,HIGH); 
    delay(100); 
    digitalWrite(iLED,LOW); 
    delay(100);
  }
}

void LED_sequence(int iCountx) 
{
  for(int iY=0;iY&lt;iCountx;iY++)
  {
    digitalWrite(3,HIGH); 
    delay(50); 
    digitalWrite(3,LOW); 
    delay(50); 
    digitalWrite(5,HIGH); 
    delay(50); 
    digitalWrite(5,LOW); 
    delay(50); 
    digitalWrite(9,HIGH); 
    delay(50); 
    digitalWrite(9,LOW); 
    delay(50); 
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Horizontal scrolling</title>
      <link>https://forum.processing.org/two/discussion/19168/horizontal-scrolling</link>
      <pubDate>Sun, 20 Nov 2016 00:44:03 +0000</pubDate>
      <dc:creator>aster94</dc:creator>
      <guid isPermaLink="false">19168@/two/discussions</guid>
      <description><![CDATA[<p>hello, i would like to add a horizontal scolling bar to this sketch since i "lost" some data at the end of the windows</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/683/2XVEWGDYBNHW.jpg" alt="partialSave" title="partialSave" /></p>

<p>i can't use the example in the reference since it uses an immage. Really i tried to use it but without good results. any idea? maybe i miss a library that could help me?</p>
]]></description>
   </item>
   <item>
      <title>Looping recorded sounds with minim...</title>
      <link>https://forum.processing.org/two/discussion/19238/looping-recorded-sounds-with-minim</link>
      <pubDate>Wed, 23 Nov 2016 11:23:33 +0000</pubDate>
      <dc:creator>Nilan974</dc:creator>
      <guid isPermaLink="false">19238@/two/discussions</guid>
      <description><![CDATA[<p>Hi
I want to record sounds (multiple sounds which should be stored in a folder) with a microphone and loop it with the other sounds I have added - song, song 2 and song 3. The problem is I want the software to initialize and loop the recorded sound by itself, so even if I shut down the program and start it up again, it should continue from where I left. 
Thanks in advance.</p>

<p>`import processing.serial.*; //Importing serial library
import ddf.minim.*; //Importing minim library. Minim is the library we are using for sound-related activities, such as record and playback.</p>

<p>Serial myPort;</p>

<p>Minim minim;</p>

<p>AudioPlayer song; 
AudioPlayer song2;
AudioPlayer song3;</p>

<p>AudioInput in;
AudioRecorder recorder;</p>

<p>int countname; //change the name
int name = 000000;
int startGain = 0;</p>

<p>void newFile()
{<br />
 countname = (name + 1);
 recorder = minim.createRecorder(in, "Rec" + countname + ".wav", true);
}</p>

<p>void setup()
{
  size(120, 120);</p>

<p>//println(Serial.list());
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n');</p>

<p>minim = new Minim(this);</p>

<p>in = minim.getLineIn(Minim.STEREO, 2048);
  newFile();//go to change file name</p>

<p>song = minim.loadFile("beyonce.mp3");
  song2 = minim.loadFile("dajam.wav");
  song3 = minim.loadFile("Rec1.wav");
}</p>

<p>void draw()
{
   background(0); 
   stroke(255);</p>

<p>if ( recorder.isRecording() )
   {
     text("Currently recording...", 5, 15);
     ellipse(60,60,55,55);
     fill(255,0,0);
   }
   else
   {
     text("    Not recording.", 5, 15);
     ellipse(60,60,55,55);
     fill(0,255,0);
   }
}</p>

<p>void serialEvent (Serial myPort) {
  String inString = myPort.readStringUntil('\n');</p>

<p>if (inString != null) {
    inString = trim (inString);</p>

<pre><code>float inByte = float(inString); 
println(inByte);

if (inByte == 1){
  song.loop();
  song2.loop();
  song3.loop();
  song.rewind();
  song2.rewind();
  song3.rewind();
}

if (inByte == 0){
  song.pause();
  song2.pause();
  song3.pause();
  song.rewind();
  song2.rewind();
  song3.rewind();
}
</code></pre>

<p>if (inByte == 2){
      if ( recorder.isRecording() ) 
      {<br />
      recorder.endRecord();</p>

<pre><code>  name++; 
  recorder.save();
  println("Done saving.");
  println(name);
  }
  else 
  {
  newFile();
  recorder.beginRecord();
  }
}
</code></pre>

<p>if (inByte == 3){
     song.setGain(startGain++ * 2);
     song2.setGain(startGain++ * 2);
     song3.setGain(startGain++ * 2);
    }</p>

<pre><code>if (inByte == 4){
 song.setGain(startGain-- * 2);
 song2.setGain(startGain-- * 2);
 song3.setGain(startGain-- * 2);
}
</code></pre>

<p>}
}</p>

<p>void stop()
{
 // always close Minim audio classes when you are done with them
 in.close();
 minim.stop();</p>

<p>super.stop();
}`</p>
]]></description>
   </item>
   <item>
      <title>Spin Arrow when inByte == "X" read.</title>
      <link>https://forum.processing.org/two/discussion/19050/spin-arrow-when-inbyte-x-read</link>
      <pubDate>Tue, 15 Nov 2016 11:17:11 +0000</pubDate>
      <dc:creator>valiaugalukas</dc:creator>
      <guid isPermaLink="false">19050@/two/discussions</guid>
      <description><![CDATA[<p>Hi, Im pretty new to processing, I have a sketch which I figured out before.
It reads for incoming bytes coming from arduino.</p>

<p>I've used it before to trigger sounds.
Which was fine triggering them within method where the bytes are read.</p>

<p>I am trying to make it now spin an arrow.</p>

<p>I have setup a function for 'spinning an arrow' which I then can use in 'draw', however, I don't know how to make a statement saying inByte read in 'void serialEvent(Serial myPort)' should trigger 'spin();' in 'void draw()'. 
Hope it makes sense and please please help me.</p>
]]></description>
   </item>
   <item>
      <title>inByte == "A" play video</title>
      <link>https://forum.processing.org/two/discussion/19054/inbyte-a-play-video</link>
      <pubDate>Tue, 15 Nov 2016 15:19:40 +0000</pubDate>
      <dc:creator>valiaugalukas</dc:creator>
      <guid isPermaLink="false">19054@/two/discussions</guid>
      <description><![CDATA[<p>Hi, 
I have a sketch which listens to arduino and when it reads incoming bytes then plays sounds.
I am having hard time changing that to play video instead.
Could you please advice me.</p>

<pre><code>import processing.serial.*;
import ddf.minim.*;
Minim minim;
AudioPlayer player;
int loopcount;

int bgcolor;                 // Background color
int fgcolor;                 // Fill color
Serial myPort;                       // The serial port
int[] serialInArray = new int[3];    // Where we'll put what we receive
int serialCount = 0;                 // A count of how many bytes we receive
int xpos, ypos;                  // Starting position of the ball
boolean firstContact = false;        // Whether we've heard from the microcontroller

void setup() {
  size(256, 256);  // Stage size
  noStroke();      // No border on the next thing drawn
  minim = new Minim(this);



  printArray(Serial.list());


  String portName = Serial.list()[0];
  //myPort = new Serial(this, "/dev/cu.usbmodem1510721", 9600);
  myPort = new Serial(this, "/dev/cu.HC-05-DevB", 9600);
}

void draw() {
  background(bgcolor);
  fill(fgcolor);
  // Draw the shape
}

void serialEvent(Serial myPort) {

  int inByte = myPort.read();

  if (firstContact == false) {
    if (inByte == 'A') { 
      player = minim.loadFile("drumgroove_3.wav");
       player.loop();
      // ask for more
    }

    if (inByte == 'F'){
      player = minim.loadFile("sound_7.mp3");
 player.play();
  }

     if(inByte == 'B'){
player = minim.loadFile("sound_2.mp3");
player.play();
}
    if (inByte == 'C'){
      player = minim.loadFile("sound_6_converted.wav");
      player.loop(2);
      loopcount = 3;
    }

    if (inByte == 'D'){
      player = minim.loadFile("sound_4.mp3");
      player.play();
    }

    if (inByte == 'E'){
      player = minim.loadFile("sound_5.mp3");
      player.play();
    }


}
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Working on binary data</title>
      <link>https://forum.processing.org/two/discussion/18984/working-on-binary-data</link>
      <pubDate>Fri, 11 Nov 2016 14:54:15 +0000</pubDate>
      <dc:creator>aster94</dc:creator>
      <guid isPermaLink="false">18984@/two/discussions</guid>
      <description><![CDATA[<p>I am facing some problems sending and using a byte from arduino to processing. My goal would be to make an array of boolean from this byte. If you can, tell me if i am doing something wrong:</p>

<p>In arduino i send a single byte using Serial.write();
In processing I receive using Serial.read();</p>

<p>Problems:</p>

<p>1) looks like that i have a problem of comunication because i reveice much more bytes than i wait. Baudrate is the same and the port is correct.</p>

<p>2) There must be something that i miss because i am forced to use an int to store the value of Serial.read(), why can't i use a byte?</p>

<p>3) i have also problems in working on this byte using the normal | &amp; and ^ operations, same problem as point 2, why am i fprced to use an int to use them? Them are  bitwise operations and i would like to use bytes not int!</p>

<p>4) how can i use directly binary data? For example in arduino i use 'B101010' but here seems that i can use only hex</p>
]]></description>
   </item>
   <item>
      <title>URGENT in need of help with processing code SRF10 ultrasonic sensor</title>
      <link>https://forum.processing.org/two/discussion/18922/urgent-in-need-of-help-with-processing-code-srf10-ultrasonic-sensor</link>
      <pubDate>Mon, 07 Nov 2016 15:16:41 +0000</pubDate>
      <dc:creator>karipuff</dc:creator>
      <guid isPermaLink="false">18922@/two/discussions</guid>
      <description><![CDATA[<p>``Hello, im in need of help with my project using SRF10 ultrasonic sensor. Im and using arduino + processing for our project but our coding is not strong. I have 2 ultrasonic which use to track moving object. I need help in showing the object location and showing it change when the object changes location. I currently able to show a printed value but only for one sensor displayed on processing. Any kind soul able to help :)</p>

<p>Here is our processing code:</p>

<pre><code>import processing.serial.*;
//import cc.arduino.*;
//println(Arduino.list());
 String val;
Serial myPort;

float Distance1 = 0, Distance2 = 0;
float LocationX=0; // Assumed location of an object (X,Y)
float LocationY=0;
float SRF1_x=300;  // location of SRF1 (x,y)
float SRF1_y=100;
float SRF2_x=500;  // location of SRF2 (x,y)
float SRF2_y=100;
float AngularRes=PI/180*10; //   Angle change step size
int xPos = 1;      // horizontal position of the graph

void setup()
{
  size(1000, 700);
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
myPort = new Serial(this, portName, 9600); 
  background(200);
  smooth();
  myPort.bufferUntil('\n');
  DrawGrid();
}

void draw()
{
      if( myPort.available() &gt; 0) 
      {  // If data is available,
        val = myPort.readStringUntil('\n');  
      }
  println(val);
     FindLocation();
//     background(300, 300, 300);
     fill(300);
     ellipse(SRF1_x,SRF1_y,25,25); // location of SRF1
     fill(100);
     ellipse(SRF2_x,SRF2_y,25,25); // location of SRF2
     fill(400);
     ellipse(LocationX,LocationY,10,10); // actual location of an object


}

void serialEvent(Serial myPort)
{
  String str = myPort.readStringUntil('\n');
  if (str != null )
  {
      str = trim(str); //remove whitespace around our values
      float  DistanceArr[]=float (split(str, ','));
      Distance1= map( DistanceArr[0], 0, 540, 0, 3000); // map distance of SRF1 to another range
      Distance2= map( DistanceArr[1], 0, 540, 0, 3000); // map distance of SRF2 to another range
  }
}

void FindLocation(){
     float MinimumDist = 50000;
     float x_CL_SRF1, y_CL_SRF1, x_CL_SRF2, y_CL_SRF2,Cal_MinimumDist; // x-y coordinates along two circles
     for (float theta1 = 0; theta1 &lt; PI; theta1 = theta1+AngularRes) {
         x_CL_SRF1=SRF1_x +Distance1*cos(theta1);   // get x-y coordinates along circle for SRF1
         y_CL_SRF1=SRF1_y +Distance1*sin(theta1);
         ellipse(x_CL_SRF1,y_CL_SRF1,10,10);
         for (float theta2 = 0; theta2 &lt; PI; theta2 = theta2+AngularRes) {
              x_CL_SRF2=SRF2_x +Distance2*cos(theta2);  // get x-y coordinates along circle for SRF2
              y_CL_SRF2=SRF2_y +Distance2*sin(theta2);
              ellipse(x_CL_SRF2,y_CL_SRF2,10,10);
              Cal_MinimumDist=sqrt(sq(x_CL_SRF1- x_CL_SRF2)+sq(y_CL_SRF1- y_CL_SRF2));
              if (Cal_MinimumDist&lt;MinimumDist){
                  MinimumDist=Cal_MinimumDist;
                  LocationX=x_CL_SRF1;
                  LocationY=y_CL_SRF1;
               }

         }
    }     
}

void DrawGrid() {
    for (int i = 0; i &lt; 700; i = i+100) {
        line(0, i, 990, i);
        }

        for (int i = 0; i &lt; 1000; i = i+100) {
             line(i, 0, i, 690 );
        }
}
</code></pre>

<p>Here is the arduino code:
    /*
     *
     * rosserial srf02 Ultrasonic Ranger Example
     *
     * This example is calibrated for the srf02 Ultrasonic Ranger.
     *
     * By Poh Hou Shun 24 September 2015
    */</p>

<pre><code>//#include &lt;Sonar_srf02.h&gt; //srf02 specific library
#include &lt;Wire.h&gt;
//#include &lt;ros.h&gt;
//#include &lt;std_msgs/Float32.h&gt;


//Set up the ros node and publisher
//std_msgs::Float32 sonar_msg;
//ros::Publisher pub_sonar("sonar", &amp;sonar_msg);
//ros::NodeHandle nh;

//Sonar_srf02 MySonar; //create MySonar object

#define COMMANDREGISTER 0x00
#define RESULTREGISTER  0x02

#define CENTIMETERS 0x51
// use 0x50 for inches
// use 0x51 for centimeters
// use 0x52 for ping microseconds

#define NO_OF_SENSORS 2

int SEQUENCE[] = {115, 116};

int reading = 0;
String stringData;

void setup()
{

  Wire.begin();                // join i2c bus (address optional for master)
  Serial.begin(9600);          // start serial communication at 9600bps

  //nh.initNode();
  //nh.advertise(pub_sonar);

}


long publisher_timer;

void loop()
{

  if (millis() &gt; publisher_timer || 1) {

    for (int i = 0; i &lt; NO_OF_SENSORS; i++) {
      takeData(SEQUENCE[i]);
    }

    // step 2: wait for readings to happen
    delay(70);                   // datasheet suggests at least 65 milliseconds

    readData(SEQUENCE[0]);

    stringData = String(reading);
    Serial.print(reading);

    for (int i = 1; i &lt; NO_OF_SENSORS; i++) {
      readData(SEQUENCE[i]);
      stringData = ' ' + String(reading);
      Serial.print(' ');
      Serial.print(reading);    
    }

    //stringData = stringData + '\0';

    //sonar_msg.data = stringData;
    //pub_sonar.publish(&amp;sonar_msg);

    publisher_timer = millis() + 4000; //publish once a second
    //Serial.println(sensorReading);
    Serial.println('\0');

  }

  //Serial.println(stringData);   // print the reading
  //nh.spinOnce();

}

void takeData(int address) {

  // step 1: instruct sensor to read echoes
  Wire.beginTransmission(address); // transmit to device #112 (0x70)

  // the address specified in the datasheet is 224 (0xE0)
  // but i2c adressing uses the high 7 bits so it's 112
  Wire.write(byte(COMMANDREGISTER));      // sets register pointer to the command register (0x00)
  Wire.write(byte(CENTIMETERS));      // command sensor to measure in "centimeters" (0x51)

  Wire.endTransmission();      // stop transmitting

}

void readData(int address) {

  // step 3: instruct sensor to return a particular echo reading
  Wire.beginTransmission(address); // transmit to device #112
  Wire.write(byte(RESULTREGISTER));      // sets register pointer to echo #1 register (0x02)
  Wire.endTransmission();      // stop transmitting

  // step 4: request reading from sensor
  Wire.requestFrom(address, 2);    // request 2 bytes from slave device #112

  // step 5: receive reading from sensor
  if (2 &lt;= Wire.available()) { // if two bytes were received
    reading = Wire.read();  // receive high byte (overwrites previous reading)
    reading = reading &lt;&lt; 8;    // shift high byte to be high 8 bits
    reading |= Wire.read(); // receive low byte as lower 8 bits
  }

  delay(250);
  //Serial.println(reading);

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to work around "Error, disabling serialEvent()"?</title>
      <link>https://forum.processing.org/two/discussion/18754/how-to-work-around-error-disabling-serialevent</link>
      <pubDate>Thu, 27 Oct 2016 19:00:01 +0000</pubDate>
      <dc:creator>Oppogo</dc:creator>
      <guid isPermaLink="false">18754@/two/discussions</guid>
      <description><![CDATA[<p>Hello! I recently got my own Arduino and decided to use it to make a pulse sensor from a tutorial.
The tutorial also suggested using Processing to display peaks of pulse. I used their code but after returning few values and a peak of the graph the process stops, encountering a null value and giving the "disabling serialEvent() for COM3" error.
Does anyone know how to deal with this error? I would love to learn more about it!</p>

<p>The code looks like this:</p>

<p>// Based on examples from Arduino's Graphing Tutorial and OscP5 documentation
    import processing.serial.*;
    Serial myPort; // The serial port
    int xPos = 1; // horizontal position of the graph
    float oldHeartrateHeight = 0; // for storing the previous reading</p>

<pre><code>void setup () {
// set the window size:
size(600, 400);
frameRate(25);

// List available serial ports.
println(Serial.list());

// Setup which serial port to use.
// This line might change for different computers.
myPort = new Serial(this, Serial.list()[1], 9600);

// set inital background:
background(0);
}

void draw () {
}

void serialEvent (Serial myPort) {
// read the string from the serial port.
String inString = myPort.readStringUntil('\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to an int
println(inString);
int currentHeartrate = int(inString);

// draw the Heartrate BPM Graph.
float heartrateHeight = map(currentHeartrate, 0, 1023, 0, height);
stroke(0,255,0);
line(xPos - 1, height - oldHeartrateHeight, xPos, height - heartrateHeight);
oldHeartrateHeight = heartrateHeight;
// at the edge of the screen, go back to the beginning:
if (xPos &gt;= width) {
xPos = 0;
background(0);
} else {
// increment the horizontal position:
xPos++;

}
}
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>EGLDisplayUtil error – Processing on Raspberry</title>
      <link>https://forum.processing.org/two/discussion/18530/egldisplayutil-error-processing-on-raspberry</link>
      <pubDate>Thu, 13 Oct 2016 14:03:45 +0000</pubDate>
      <dc:creator>lxnr_p</dc:creator>
      <guid isPermaLink="false">18530@/two/discussions</guid>
      <description><![CDATA[<p>Hello everyone,</p>

<p>I'm working on a raspberry and when I run it, I everytime have this error in the console: (but the sketch run even though)</p>

<pre><code>EGLDisplayUtil.EGLDisplays: Shutdown (open: 1)
EGLDisplayUtil: Open EGL Display Connections: 1
EGLDisplayUtil: Open[0]: 0x1: EGLDisplayRef[0x1: refCnt 2]
</code></pre>

<p>Do you know what does it mean and how I can solve it?
The sketch read the values of the arduino (plugged on the raspberry)  where a proximity sensor is plugged and when we put an object above the sensor the first video change and another one is launched.
I also have another problem: When the sketch is running, the videos are slow down. And I remove everything that relate to the arduino and the sensor in processing, the videos are fine.</p>

<p>So is somebody can help me for this, it drives me crazy, and I didn't found a thing on our friend Google...
Thanks so much :)</p>

<p>Here my code:</p>

<pre><code>    ////////////////////////////////////////////
    ////////////////////////////////// LIBRARIES
    ////////////////////////////////////////////

    import processing.serial.*;
    import processing.video.*;





    /////////////////////////////////////////////////
    ////////////////////////////////// INITIALIZATION
    /////////////////////////////////////////////////

    Movie mymovie;
    Movie mymovie2;





    ////////////////////////////////////////////
    ////////////////////////////////// VARIABLES
    ////////////////////////////////////////////

    int lf = 10;    // Linefeed in ASCII
    String myString = null;
    Serial myPort;  // The serial port
    int sensorValue = 0; //value of the sensore
    int x = 100; //the sensor will be triggered when this value is reached. Modify it to change when the videos will switch




    /////////////////////////////////////////////
    ////////////////////////////////// VOID SETUP
    /////////////////////////////////////////////

    void setup() {
      //frameRate(50);
      fullScreen();
      //size(1280, 1024, P3D);
      // List all the available serial ports
      printArray(Serial.list());
      // Open the port you are using at the rate you want:
      myPort = new Serial(this, Serial.list()[1], 9600);
      myPort.clear();
      // Throw out the first reading, in case we started reading 
      // in the middle of a string from the sender.
      myString = myPort.readStringUntil(lf);
      myString = null;
      //load the video
      mymovie = new Movie(this, "VIDEO_1_v06bis.mov"); //Modify the line in quotation marks to change the videos. (put it inside the "data" folder
      mymovie2 = new Movie(this, "VIDEO_2_v02.mov");
      //set the videos for a continuous loop
      mymovie.loop();
      mymovie2.loop();
    }




    ////////////////////////////////////////////
    ////////////////////////////////// VOID DRAW
    ////////////////////////////////////////////

    void draw() {
      //image(mymovie, 0, 0); //display the video in a continuous loop
      // to trigger the sensor
      // check if there is something new on the serial port
      while (myPort.available() &gt; 0) {
        // store the data in myString 
        myString = myPort.readStringUntil(lf);
        // check if we really have something
        if (myString != null) {
          myString = myString.trim(); // let's remove whitespace characters
          // if we have at least one character...
          if (myString.length() &gt; 0) {
            println(myString); // print out the data we just received
            // if we received a number (e.g. 123) store it in sensorValue, we sill use this to change the background color. 
            try {
              sensorValue = Integer.parseInt(myString);
            } 
            catch(Exception e) {
            }
          }
        }
      }


      ///////////SENSOR TRIGGERED
      ///////////////////////////

      if (x &lt; sensorValue) {
        mymovie.jump(0);
        //background(mymovie2);
        image(mymovie2, mouseX, mouseY);
        //mymovie2.pause();
      } else {
        //mymovie2.play();
        //mymovie.jump(0);
      }


      ///////////SENSOR NOT TRIGGERED
      ///////////////////////////////

      if (x &gt; sensorValue) {
        mymovie2.jump(0);
        //background(mymovie);
        image(mymovie, mouseX, mouseY);
        //mymovie.pause();
      } else {
        //mymovie.play();
      }
    }



    //////////////////////////////////////////////
    ////////////////////////////////// VOID CUSTOM
    //////////////////////////////////////////////

    void movieEvent(Movie mymovie) {
      mymovie.read(); //read the video
      mymovie2.read();
    }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Logic analyzer</title>
      <link>https://forum.processing.org/two/discussion/18513/logic-analyzer</link>
      <pubDate>Wed, 12 Oct 2016 07:49:47 +0000</pubDate>
      <dc:creator>aster94</dc:creator>
      <guid isPermaLink="false">18513@/two/discussions</guid>
      <description><![CDATA[<p>Hello, i am working on a very simple logyc analyzer.</p>

<p>The hardware is made of an arduino which semd through serial this kind of data:</p>

<p>100:20:20</p>

<p>Where the first number is the time in microseconds when the pulse is high, the second low, and the last is the duty cycle.</p>

<p>Processing read everything correct from arduino</p>

<p>My problem is in drawing it. I tried with lines and points but i m not able to draw it correct</p>
]]></description>
   </item>
   <item>
      <title>Pulse Input Displayed to Processing Window</title>
      <link>https://forum.processing.org/two/discussion/18253/pulse-input-displayed-to-processing-window</link>
      <pubDate>Thu, 22 Sep 2016 22:26:58 +0000</pubDate>
      <dc:creator>jameshayek</dc:creator>
      <guid isPermaLink="false">18253@/two/discussions</guid>
      <description><![CDATA[<p>Hello! First time poster, new to Processing.</p>

<p>I was following the following tutorial on making a Pulse Sensor:
<a rel="nofollow" href="https://www.youtube.com/watch?v=psTa5ZrqAyo">https://www.youtube.com/watch?v=psTa5ZrqAyo
</a></p>

<p>I was able to see output from a scope. I can therefore conclude output is being sent to the Arduino.</p>

<p>The code provided does not draw any pulse in Processing 3. I added a few lines, they are:</p>

<pre><code>noFill();
stroke(0,255,0);
strokeWeight(4);
</code></pre>

<p>On lines 40-42. The rest is original code from the tutorial.</p>

<p>It is as follows:</p>

<pre><code>    // Based on examples from Arduino's Graphing Tutorial and OscP5 documentation
    import processing.serial.*;
    Serial myPort; // The serial port
    int xPos = 1; // horizontal position of the graph
    float oldHeartrateHeight = 0; // for storing the previous reading


    void setup () {
    // set the window size:
    size(600, 400);
    frameRate(25);

    // List available serial ports.
    println(Serial.list());

    // Setup which serial port to use.
    // This line might change for different computers.
    myPort = new Serial(this, Serial.list()[0], 9600);

    // set inital background:
    background(0);
    }

    void draw () {
    }

    void serialEvent (Serial myPort) {
    // read the string from the serial port.
    String inString = myPort.readStringUntil('\n');

    if (inString != null) {
    // trim off any whitespace:
    inString = trim(inString);
    // convert to an int
    println();
    int currentHeartrate = int(inString);

    // draw the Heartrate BPM Graph.
    float heartrateHeight = map(currentHeartrate, 0, 1023, 0, height);
    noFill();
    stroke(0,255,0);
    strokeWeight(4);
    line(xPos - 1, height - oldHeartrateHeight, xPos, height - heartrateHeight);
    oldHeartrateHeight = heartrateHeight;
    // at the edge of the screen, go back to the beginning:
    if (xPos &gt;= width) {
    xPos = 0;
    background(0);
    } else {
    // increment the horizontal position:
    xPos++;

    }
    }
    }
</code></pre>

<p>Any ideas what lines I need to append to get the output to display?</p>

<p>Any help is much appreciated, thanks in advance.</p>
]]></description>
   </item>
   <item>
      <title>Values through Serial not matching from Arduino to Processing</title>
      <link>https://forum.processing.org/two/discussion/17919/values-through-serial-not-matching-from-arduino-to-processing</link>
      <pubDate>Sat, 20 Aug 2016 15:55:04 +0000</pubDate>
      <dc:creator>LCEnquire</dc:creator>
      <guid isPermaLink="false">17919@/two/discussions</guid>
      <description><![CDATA[<p>I'm trying to adapt some code that will speak tweets through Processing (using the twitter4j and guru.ttslib libraries) but ONLY when processing has detected the correct value from Arduino.</p>

<p>I've managed to get the tweets read out through Processing and I've also got Arduino sending values to Serial. The values I'm sending are simple integers of '1' and '2', but Processing picks these Serial values up as longer numbers. For example, when a '1' is sent from Arduino, Processing reads (and prints) this as '491310'.</p>

<p>Because the value of the int cannot exceed 255, any if statement I write in Processing to recognise '491310' doesn't work. Ideally, I'd like '1' to be sent from Arduino and for it to be read as '1' by Processing</p>

<p>Any help would be greatly appreciated. Absolute novice here. Thanks.</p>

<p>PROCESSING CODE:</p>

<pre><code>import twitter4j.util.*;
import twitter4j.*;
import twitter4j.management.*;
import twitter4j.api.*;
import twitter4j.conf.*;
import twitter4j.json.*;
import twitter4j.auth.*;

import guru.ttslib.*;
import processing.serial.*;

java.util.List statuses = null;


TTS tts;
Serial myPort;

int sensor = 0;

void setup() {
  tts = new TTS();

  myPort = new Serial(this, Serial.list()[0], 9600);

  ConfigurationBuilder cb = new ConfigurationBuilder();

  cb.setOAuthConsumerKey("XXXX");
  cb.setOAuthConsumerSecret("XXXX");
  cb.setOAuthAccessToken("XXXX");
  cb.setOAuthAccessTokenSecret("XXXX");

  Twitter twitter = new TwitterFactory(cb.build()).getInstance();

  String userName ="@BBC";
  int numTweets = 19;
  String[] twArray = new String[numTweets];

  try {
    statuses = twitter.getUserTimeline(userName);
  }
  catch(TwitterException e) {
     e.printStackTrace();
  }
}

void serialEvent (Serial myPort) {
  int inByte = myPort.read();
  sensor = inByte;
  print(sensor);
}

void draw() {
  if (statuses != null) {
    for (int i=0; i&lt;statuses.size(); i++) {
      Status status = (Status)statuses.get(i);

      if (sensor == 491310) {
        println(status.getUser().getName() + ": " + status.getText());
        tts.speak(status.getUser().getName() + ": " + status.getText());
      }
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Data received from Arduino to Processing, but is not saved in file</title>
      <link>https://forum.processing.org/two/discussion/18129/data-received-from-arduino-to-processing-but-is-not-saved-in-file</link>
      <pubDate>Sat, 10 Sep 2016 11:17:29 +0000</pubDate>
      <dc:creator>JRob</dc:creator>
      <guid isPermaLink="false">18129@/two/discussions</guid>
      <description><![CDATA[<p>Hello everybody</p>

<p>I'm currently trying to send some data from Arduino to Processing, so I can save it in a file.
To be more specific, there are two variables (frequency of a blinking LED and respective LED number) which should be saved in tabular form.</p>

<p>Hereby the following Processing code is used:</p>

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


Serial myPort;
Table dataTable; //table to store my values.

int lf = 10;
String Arduinostring = null;
float values;

String fileName;
void setup()
{
  String portName = Serial.list()[0]; 
  myPort = new Serial(this, portName, 9600); //the port I'm using to listen to the serial port

  dataTable = new Table();
  dataTable.addColumn("id"); 


  //columns for values
  dataTable.addColumn("Data");
}

  void draw() {
    while (myPort.available() &gt; 0) {
      Arduinostring = myPort.readStringUntil(lf);
      if (Arduinostring != null) {
          print(Arduinostring);  // Prints String
          values=float(Arduinostring);  // Converts and prints float
          println(values);
      }
    TableRow newRow = dataTable.addRow(); //add a row for this new reading
    newRow.setInt("id", dataTable.lastRowIndex());//record a unique identifier (the row's index)

    //record information. 
    newRow.setFloat("Data", values);   
    }

    saveTable(dataTable, "data/new.csv"); // save it to computer.

}
</code></pre>

<p>My intention here is to get my data into the table (and into my file).
I managed to receive the required data (frequency, LED number), but this data isn't saved in my file.
The mentioned file is created by the way and at least has the right ID for each Row.</p>

<p>What I simply do not understand is that he can't save it though the received data should be converted to float with the command num=float(myString), shouldn't it?</p>

<p>Many thanks in advance for any help!</p>
]]></description>
   </item>
   <item>
      <title>Out of Control y Axis- ROLLING GRAPH</title>
      <link>https://forum.processing.org/two/discussion/17900/out-of-control-y-axis-rolling-graph</link>
      <pubDate>Fri, 19 Aug 2016 03:53:51 +0000</pubDate>
      <dc:creator>Chil_Polins</dc:creator>
      <guid isPermaLink="false">17900@/two/discussions</guid>
      <description><![CDATA[<p>Noobie here, I'm trying to take an input from an arduino over a usb and plot onto a graph. Everything is fine except I cant seem to map where the y begins and ends on my graph. I tried so many things but its stuck between 0 and about 400px. You'll see the box where the graph is suppose to occupy. I can't move/control the y axis. I drew out the issue in red on the attached image, please help!!</p>

<p>You'll see reference to multiple sensors, I am only trying to plot the sensor "moisture" for now.</p>

<pre><code>/This sketch is frankensteined from the SerialCall Response example with arduino and 
//this guy's sketch(code in description of video) - <a href="http://pastebin.com/kSrU3nVH" target="_blank" rel="nofollow">http://pastebin.com/kSrU3nVH</a>

import processing.serial.*;

int moisture;  //the only sensor I'm currently trying to plot 
float inByte;
int second; //sensors that ar![]()e not yet plotted but printed in the Console
int third;  // " "
int fourth; // " "

Serial myPort;                       // The serial port
int[] serialInArray = new int[4];    // Where we'll put what we receive
int serialCount = 0;                 // A count of how many bytes we receive
PFont  g_font;
boolean firstContact = false;        // Whether we've heard from the microcontroller

int[] yValues;
int w;

//SETUP
void setup() {
  size(1280, 720);  // Stage size

  g_font = loadFont("ArialMT-20.vlw");
  textFont(g_font, 20);

  w = 640; //width of our plot
  strokeWeight(1);
  smooth(); // or noSmooth();
  yValues = new int[w];

  println(Serial.list());
  String portName = Serial.list()[1];
  myPort = new Serial(this, portName, 9600);
}

void draw() { 
  String inString = myPort.readStringUntil('\n');

  if (inString != null) {
    inString = trim(inString);
    inByte = float(inString);

    moisture = int(map(inByte, 0, 255, 360, 25));
    //setting the boundry for the graph line, inside box EXCEPT IT DOESNT WORK
  }

  //This should be down here, but works inside the if statement.
  //moisture = int(map(inByte, 0, 255, 360, 25));

  //Background and box for graph
  background(55);
  rect(25, 25, 615, 335);
  fill(255);
  //LEGEND
  strokeWeight(1.5);
  stroke(255, 0, 0);     
  line(20, 420, 35, 420);
  stroke(0, 255, 0);     
  line(20, 440, 35, 440);
  stroke(0, 0, 255);     
  line(20, 460, 35, 460);
  stroke(255, 255, 0);   
  line(20, 480, 35, 480);

  fill(0, 0, 0);
  text("Moisture", 40, 430);
  text("Analog A1", 40, 450);
  text("Analog A2", 40, 470);
  text("Analog A3", 40, 490);

  //ACTUAL PLOTTED LINE
  for (int i = 1; i &lt; w; i++) {
    yValues[i-1] = yValues[i];
  }
  yValues[w-1] = moisture; 
  //}

  stroke(120, 200, 0);
  line(w, moisture, 0, moisture);
  strokeWeight(3);


  //This controls the horizontal "TICKER LINE"
  for (int i=1; i&lt;w; i++) {
    //stroke (rgb)
    stroke(220, 75, yValues[i]);
    //point folar x, float y
    point(i, yValues[i]);
    rect(0, 25, 50, 335);
    fill(255);
  }
}

void serialEvent(Serial myPort) {
  // read a byte from the serial port:
  int inByte = myPort.read();

  if (firstContact == false) {
    if (inByte == 'A') {
      myPort.clear();          // clear the serial port buffer
      firstContact = true;     // you've had first contact from the microcontroller
      myPort.write('A');       // ask for more
    }
  } else {
    // Add the latest byte from the serial port to array:
    serialInArray[serialCount] = inByte;
    serialCount++;

    // If we have 3 bytes:
    if (serialCount &gt; 3) {
      moisture = serialInArray[0];
      second = serialInArray[1];
      third = serialInArray[2];
      fourth = serialInArray[3];

      // print the values (for debugging purposes only):
      println(moisture + "\t" + second + "\t" + third + "\t" + fourth);

      // Send a capital A to request new sensor readings:
      myPort.write('A');
      // Reset serialCount:
      serialCount = 0;
    }
  }
}

/*ARDUINO UNO CODE
 int firstSensor = 0;    // first analog sensor
 int secondSensor = 0;   // second analog sensor
 int thirdSensor = 0;    // digital sensor
 int fourthSensor = 0; //turning this into a fluxuating value
 int inByte = 0;         // incoming serial byte

 void setup()
 {
 // start serial port at 9600 bps:
 Serial.begin(9600);


 pinMode(2, INPUT);   // digital sensor is on digital pin 2
 establishContact();  // send a byte to establish contact until receiver responds
 }

 void loop()

 {

 // if we get a valid byte, read analog ins:
 if (Serial.available() &gt; 0) {
 // get incoming byte:
 inByte = Serial.read();
 // read first analog input, divide by 4 to make the range 0-255:
 firstSensor = analogRead(A0);
 // delay 10ms to let the ADC recover:
 delay(10);
 // read second analog input, divide by 4 to make the range 0-255:
 secondSensor = analogRead(A1) / 4;
 // read  switch, map it to 0 or 255L
 thirdSensor = map(digitalRead(A2), 0, 1, 0, 255);
 // send sensor values:
 fourthSensor = analogRead(A3) / 4; //new sensor I added
 Serial.write(firstSensor);
 Serial.write(secondSensor);
 Serial.write(thirdSensor);
 Serial.write(fourthSensor);

 }
 }

 void establishContact() {
 while (Serial.available() &lt;= 0) {
 Serial.print('A');   // send a capital A
 delay(300);

 }
 }
 */![Screen Shot 2016-08-18 at 11.45.51 PM](<a href="https://forum.processing.org/two/uploads/imageupload/608/2KIEZIROU05C.jpg" target="_blank" rel="nofollow">https://forum.processing.org/two/uploads/imageupload/608/2KIEZIROU05C.jpg</a> "Screen Shot 2016-08-18 at 11.45.51 PM")
</code></pre>
]]></description>
   </item>
   <item>
      <title>processing arduino 2 sensors ultrasonic</title>
      <link>https://forum.processing.org/two/discussion/17846/processing-arduino-2-sensors-ultrasonic</link>
      <pubDate>Mon, 15 Aug 2016 03:06:23 +0000</pubDate>
      <dc:creator>felipera</dc:creator>
      <guid isPermaLink="false">17846@/two/discussions</guid>
      <description><![CDATA[<p>Hello
Get accurate processing via 2 Separated Values ​​2 ultrasonic distance sensors via Arduino .
In arduino I'm OS Values ​​tendon however no processing I'm picking up .
Can anyone help , follow OS 2 codes
thanks in advance</p>

<p>ARDUINO</p>

<h1>include &lt;Ultrasonic.h&gt;</h1>

<h1>define echoPin 13 //Pino 13 recebe o pulso do echo</h1>

<h1>define trigPin 12 //Pino 12 envia o pulso para gerar o echo</h1>

<h1>define echoPin2 4 //Pino 4 recebe o pulso do echo</h1>

<h1>define trigPin2 5 //Pino 5 envia o pulso para gerar o echo</h1>

<p>//iniciando a função e passando os pinos
Ultrasonic ultrasonic(12,13);
Ultrasonic ultrasonic2(4,5);</p>

<p>void setup()
{
   Serial.begin(9600); //inicia a porta serial
   pinMode(echoPin, INPUT); // define o pino 13 como entrada (recebe)
   pinMode(trigPin, OUTPUT); // define o pino 12 como saida (envia)
   pinMode(echoPin2, INPUT); // define o pino 4 como entrada (recebe)
   pinMode(trigPin2, OUTPUT); // define o pino 5 como saida (envia)
}</p>

<p>void loop()
{
  //seta o pino 12 com um pulso baixo "LOW" ou desligado ou ainda 0
    digitalWrite(trigPin, LOW);
  // delay de 2 microssegundos
    delayMicroseconds(2);
  //seta o pino 12 com pulso alto "HIGH" ou ligado ou ainda 1
    digitalWrite(trigPin, HIGH);
  //delay de 10 microssegundos
    delayMicroseconds(10);
  //seta o pino 12 com pulso baixo novamente
    digitalWrite(trigPin, LOW);
  // função Ranging, faz a conversão do tempo de
  //resposta do echo em centimetros, e armazena
  //na variavel distancia
    float duration = pulseIn(echoPin,HIGH);<br />
  //Esse calculo é baseado em s = v . t, lembrando que o tempo vem dobrado<br />
  //porque é o tempo de ida e volta do ultrassom<br />
    float distancia = duration /29 / 2 ; 
     //seta o pino 12 com um pulso baixo "LOW" ou desligado ou ainda 0
    digitalWrite(trigPin2, LOW);
  // delay de 2 microssegundos
    delayMicroseconds(2);
  //seta o pino 5 com pulso alto "HIGH" ou ligado ou ainda 1
    digitalWrite(trigPin2, HIGH);
  //delay de 10 microssegundos
    delayMicroseconds(10);
  //seta o pino 5 com pulso baixo novamente
    digitalWrite(trigPin2, LOW);
  // função Ranging, faz a conversão do tempo de
  //resposta do echo em centimetros, e armazena
  //na variavel distancia
    float duration2 = pulseIn(echoPin2,HIGH);<br />
  //Esse calculo é baseado em s = v . t, lembrando que o tempo vem dobrado<br />
  //porque é o tempo de ida e volta do ultrassom<br />
    float distancia2 = duration2 /29 / 2 ;</p>

<p>Serial.println("pé da frente");
Serial.println(distancia);
Serial.println("pé de tras");
Serial.println(distancia2);
delay(1000); //espera 1 segundo para fazer a leitura novamente
}</p>

<p>PROCESSING</p>

<p>// Example by Tom Igoe</p>

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

<p>Serial myPort;    // The serial port
PFont myFont;     // The display font
String distancia;
String distancia2;// Input string from serial port
int lf = 10;
;      // ASCII linefeed</p>

<p>void setup() { 
  size(500,500); 
  // You'll need to make this font with the Create Font Tool 
  //myFont = loadFont("ArialMS-18.vlw"); 
  //textFont(myFont, 18); 
  // List all the available serial ports: 
  printArray(Serial.list());</p>

<p>myPort = new Serial(this, Serial.list()[0], 9600); 
  myPort.bufferUntil(lf); 
}</p>

<p>void draw() { 
  background(0); 
  text("Pé de trás: " + distancia, 10,50); 
  text("Pé de trás: " + distancia2, 10,150);</p>

<p>}</p>

<p>void serialEvent(Serial p) { 
distancia = p.readString(); 
}</p>
]]></description>
   </item>
   <item>
      <title>Ultrasound sensor, Arduino, playing movie, using build-in Camera</title>
      <link>https://forum.processing.org/two/discussion/17760/ultrasound-sensor-arduino-playing-movie-using-build-in-camera</link>
      <pubDate>Fri, 05 Aug 2016 16:03:32 +0000</pubDate>
      <dc:creator>Anita</dc:creator>
      <guid isPermaLink="false">17760@/two/discussions</guid>
      <description><![CDATA[<p>Hello everyone,</p>

<p>I am trying to get an ultrasound sensor to read the distance of a person. 
—When the person is far it should trigger a movie to play. 
—When the person is at mid distance camera should activate and should film him. 
When the person is near to the sensor, there should be again a movie being played. 
At the point the code was reading the distances properly but when the camera was added the distance sensor didn't work anymore or it didn't give me the values anymore, only the camera appears to be activated, but it doesn't show any picture.
At use there are a MacBookPro, Build-in Camera, Arduino Uno, Ultrasound sensor and Processing...
I am including the code maybe a soul can shed a light!</p>

<p>Thanks so much in advance,
Ana</p>

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

<p>Movie movie_1;
Movie movie_2;
Capture cam;</p>

<p>int distance;
Serial myPort;  // The serial port
String comPortString;
int output = 0;</p>

<p>void setup() {
  // Serial stuff 
  // List all the available serial ports
  printArray(Serial.list());
  // Open the port you are using at the rate you want:
  myPort = new Serial(this, Serial.list()[2], 9600);</p>

<p>// Movie stuff
  frameRate(30);
  size(200, 200);
  movie_1 = new Movie(this, "01_CloseUp.mov");
  movie_2 = new Movie(this, "01_CloseUp.mov");</p>

<p>// Camera stuff
  String[] cameras = Capture.list();</p>

<p>if (cameras.length == 0)
  {
    println("There are no cameras available for capture.");
    exit();
  } else {
    println("Available cameras:");
    for (int i = 0; i &lt; cameras.length; i++) {
      println(cameras[i]);
    }</p>

<pre><code>// The camera can be initialized directly using an 
// element from the array returned by list():
cam = new Capture(this, cameras[0]);
cam.start();     
</code></pre>

<p>}<br />
}
  // With this void starts the camera to be detected
void draw() {</p>

<p>if (output == 0)
  {
    image(movie_1, mouseX, mouseY);
  }
  else if (output == 1)
  {
    if (cam.available() == true)
    {
      cam.read();
    }
    image(cam, 0, 0);
  }
  else if (output == 2)
  {
    image(movie_2, mouseX, mouseY);
  }
}</p>

<p>void serialEvent(Serial cPort)
{
  comPortString = cPort.readStringUntil('\n');
  if(comPortString != null)
  {
   comPortString=trim(comPortString);</p>

<p>// Use the distance received by the Arduino to modify the lines
   distance = int(map(Integer.parseInt(comPortString),1,200,1,height));
   println(distance);</p>

<p>// Values from 100 to 5000
   if (distance &lt; 1000)
   {
     // Play video 2 (dancing)
     output = 2;
   }
   else if (distance &lt; 2500)
   {
     // Play video feed from camera (person)
     output = 1;
   }
   else
   {
     // Play video 1 (dancer sitting)
     output = 0;
   }
 }</p>

<p>}</p>
]]></description>
   </item>
   <item>
      <title>Need some form of debounce for my code and have no idea how to implement one</title>
      <link>https://forum.processing.org/two/discussion/17694/need-some-form-of-debounce-for-my-code-and-have-no-idea-how-to-implement-one</link>
      <pubDate>Fri, 29 Jul 2016 11:13:55 +0000</pubDate>
      <dc:creator>silageman</dc:creator>
      <guid isPermaLink="false">17694@/two/discussions</guid>
      <description><![CDATA[<p>As above i'm currently working on an arduino project (physical edrum trigger/piezo) i currently have an uno talking to processing 3 through a serial connection and then displaying a simple graph, when the inByte is greater than 1 (pull down resistor is at 0 untriggered) it sends midi notes to ezdrummer 2, i have all this working my problem is when i hit the drum it triggers multiple times within a short period of the strike, anyone know what would be the best solution for a debounce?</p>

<p>my current code below.</p>

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

import themidibus.*; 

MidiBus myBus; 

Serial myPort;        
int xPos = 1;         
float inByte = 0;

void setup () {
  MidiBus.list();
  // set the window size:
  size(900, 400);

  println(Serial.list());
  myBus = new MidiBus(this, 1, 3); 

  myPort = new Serial(this, Serial.list()[1], 115200);

  myPort.bufferUntil('\n');

  background(0);
}

void draw () {
  // draw the line:
  stroke(127, 34, 255);
  line(xPos, height, xPos, height - inByte);

  // at the edge of the screen, go back to the beginning:
  if (xPos &gt;= width) {
    xPos = 0;
    background(255,255,255);
  } else {
    // increment the horizontal position:
    xPos++;
  }
}

void serialEvent (Serial myPort) {
  // get the ASCII string:
  String inString = myPort.readStringUntil('\n');

  if (inString != null) {
    // trim off any whitespace:
    inString = trim(inString);
    // convert to an int and map to the screen height:
    inByte = int(inString);

    println(inByte);
    int a = 56;
    inByte = map(inByte, 0, 1023, 0, 127);
    int test = int(inByte);
    if(inByte &gt; 2){
      myBus.sendNoteOn(1, 38, test); // Send a Midi noteOn
      delay(1);
      inByte--;
      myBus.sendNoteOff(1, 38, test); // Send a Midi nodeOff
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Integrating Arduino and Processing - button counter</title>
      <link>https://forum.processing.org/two/discussion/17602/integrating-arduino-and-processing-button-counter</link>
      <pubDate>Wed, 20 Jul 2016 22:39:13 +0000</pubDate>
      <dc:creator>ksenia_n</dc:creator>
      <guid isPermaLink="false">17602@/two/discussions</guid>
      <description><![CDATA[<p>I am looking to integrate Arduino controls and Processing Interface. In my Arduino code, there are three buttons attached to pin a1, a0 and d0 (all digitalRead).</p>

<pre><code>int x;// assigned to A0 input
int y;// assigned to A1 input
int z; //assigned to D0 input
int votes[3]={0,0,0};

void setup() {
  // initialize the serial communication
  Serial.begin(9600);

  while(!Serial);
}

void loop() {
  // first we need to read the values from the BUTTONS

  x = digitalRead(A0);

  y = digitalRead(A1);

  z = digitalRead(0);

  if(digitalRead(A0) == HIGH) 
    {
    Serial.print("cat1 ");                  
    Serial.print(votes[0]=votes[0]+1);
    Serial.print("\n");
    }
   else if(digitalRead(A1) == HIGH)
    {
    Serial.print("cat2 ");
    Serial.print(votes[1]=votes[1]+1);
      Serial.print("\n");
    }
   else if(digitalRead(0) == HIGH) 
    {
    Serial.print("cat3 ");
    Serial.print(votes[2]=votes[2]+1);
    Serial.print("\n");
    }
    delay(200);
}
</code></pre>

<p>I would like the counter to increment every time the button is pressed and display in processing as a bar graph. Whenever the button is pressed, the bar graph goes up by some amount. In this case I want one of the three lines (associated to three buttons) to draw, if pressed.</p>

<p>The processing code is below:</p>

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

// Serial Port variables
Serial myPort;
String buff = "";
String buff1 = "";
String buff2 = "";
int index = 0;
int NEWLINE = 10;
// Store the last 256 values from the sensors so we can draw them.
int[] valuesx = new int[256];
int[] valuesy = new int[256];
int[] valuesz = new int[256];

void setup()
{ 
  // set size of the window 
  size(512, 512);
  // turn on anti-aliasing, this makes things look smoother 
  smooth();

  println(Serial.list()); // use this to determine which serial port is your Arduino
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n');
}

// draw() happens every frame of the sketch. This is where all the calculations are made.
// When draw() is finished executing, it executes again, over and over.
void draw() {
  // set the background to purple
  background(87, 36, 124);
  // set stroke weight(thickness of the line) to 5 pixels
  strokeWeight(5);

  for (int i = 0; i &lt; 255; i++) {

    stroke(247, i);
    // draw the line (x1, y1, x2, y2)
    line(1, valuesx[i], 1, valuesx[i + 1]);
    line(5, valuesy[i], 5, valuesy[i + 1]);
    line(10, valuesz[i], 10, valuesz[i + 1]);
  }

  // Check the Serial port for incoming data
  while (myPort.available () &gt; 0) {
    // if there is data waiting...
    // execute serialEvent() function. Look below to see how SerialEvent works.
    serialEvent(myPort.read());
  }
}

// serialEvent controls how incoming serial data from the Arduino module is handled
void serialEvent(int serial)
{
  if (serial != NEWLINE) {
    // Store all the characters on the line.
    buff += char(serial);
  } 
  else {
    // The end of each line is marked by two characters, a carriage
    // return and a newline.  We're here because we've gotten a newline,
    // but we still need to strip off the carriage return.
    buff = buff.substring(0, buff.length()-1);
    index = buff.indexOf(",");
    buff1 = buff.substring(0, index);
    buff2 = buff.substring(index+1, buff.length());

    // Parse the String into an integer.  We divide by 4 because
    // analog inputs go from 0 to 1023 while colors in Processing
    // only go from 0 to 255.
    int x = Integer.parseInt(buff1)/2;
    int y = Integer.parseInt(buff2)/2;

    // Clear the value of "buff"
    buff = "";

    // Shift over the existing values to make room for the new one.
    for (int i = 0; i &lt; 255; i++)
    {
      valuesx[i] = valuesx[i + 1];
      valuesy[i] = valuesy[i + 1];
    }

    // Add the received value to the array.
    valuesx[255] = x;
    valuesy[255] = y;
  }
}
</code></pre>

<p>Unfortunately, here's the error that I get when I press a button.
<img src="http://i.stack.imgur.com/U4WyU.jpg" alt="" /></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>LUBUNTU error opening serial port /dev/ttyS0: Incorrect serial port</title>
      <link>https://forum.processing.org/two/discussion/17512/lubuntu-error-opening-serial-port-dev-ttys0-incorrect-serial-port</link>
      <pubDate>Wed, 13 Jul 2016 12:49:14 +0000</pubDate>
      <dc:creator>ilioSS</dc:creator>
      <guid isPermaLink="false">17512@/two/discussions</guid>
      <description><![CDATA[<p>Hi all,</p>

<p>I just installed LUBUNTU 16-04 with a running arduino IDE. No problem.</p>

<p>Now I would like to install processing3. I have it running.</p>

<p>But my adxl345 read out in pitch-roll give the above mentioned error.</p>

<p>Already looked on the internet for possible solutions s.a. i must be mention of the group etc.</p>

<p>Al I treid nothing works.</p>

<p>Situation arduino for linux and processing3</p>

<p>linux prog is LUBUNTU 16-04 and linux32 4.4.0.22</p>

<p>Who has the solution. Help is very much apriciated.</p>

<p>Kind regards,</p>

<p>ilioSS</p>

<p>btw arduino uses ttyUSB0  serial port</p>
]]></description>
   </item>
   <item>
      <title>How ti invert grayscale (0-255) in this code ?</title>
      <link>https://forum.processing.org/two/discussion/17497/how-ti-invert-grayscale-0-255-in-this-code</link>
      <pubDate>Tue, 12 Jul 2016 11:50:03 +0000</pubDate>
      <dc:creator>Josip</dc:creator>
      <guid isPermaLink="false">17497@/two/discussions</guid>
      <description><![CDATA[<p>Hello everyone ! I have a LIDAR lite v2 and i used it to measure distances , i mount him on 2 servo motors wich rotates in Y and X and lidar scanning distance in that time. Now i have this program which communicate with arduino and creating point cloud from degrees of X servo degrees of Y servo and distances in cm .</p>

<p>Now the question is why a get small picture whatever i put in size() i get the same small picture and with this program DARKER the pixel is closer the object is. AND NOW the main question is how to invert grayscale , cause i want darker pixel farther.</p>

<p>Sorry for so many words and thank u.</p>

<p>This is the code in processing.</p>

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

float pcolor = 0; // point color value
float xVal = 0;  // x value
float yVal = 0;  // y value

Serial myPort;

void setup() {

  size(400,200);

  printArray(Serial.list()); 

  myPort = new Serial(this, Serial.list()[0], 57600);

  myPort.bufferUntil('\n');   
  background(0);
}

void draw() {
  stroke(pcolor);    
  point(xVal,yVal);
}

void serialEvent(Serial myPort) {

  String inString = myPort.readStringUntil('\n');  

  if (inString !=null) {
    inString = trim(inString);    

    float[] colors = float(split(inString, ","));    

    if (colors.length &gt;=3) {       
      xVal = colors[0];          
      yVal = colors[1];
      pcolor = map(colors[2], 0, 400, 0,255);
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>wrong format</title>
      <link>https://forum.processing.org/two/discussion/17352/wrong-format</link>
      <pubDate>Wed, 29 Jun 2016 04:11:26 +0000</pubDate>
      <dc:creator>joeblogs</dc:creator>
      <guid isPermaLink="false">17352@/two/discussions</guid>
      <description><![CDATA[<p>hey guys, 
new to java.  only started C++ a couple of weeks ago.
im having trouble trying to get a class to work, but keep getting null pointer errors.  cant quite figure out what im not setting up wrong.  can anyone see from the code what im doing wrong.
Cheers
excuse all the commented out stuff i was just trying to narrow down the problem</p>

<p>(Code in comments)</p>
]]></description>
   </item>
   <item>
      <title>How use millis() in static methods?</title>
      <link>https://forum.processing.org/two/discussion/17130/how-use-millis-in-static-methods</link>
      <pubDate>Mon, 13 Jun 2016 18:44:35 +0000</pubDate>
      <dc:creator>kucky</dc:creator>
      <guid isPermaLink="false">17130@/two/discussions</guid>
      <description><![CDATA[<p>Hello,
I want to calculate the time within the Serialevent Methode.</p>

<pre><code>static class SerialPortReader implements SerialPortEventListener {

    public void serialEvent(SerialPortEvent event) {
        startLoop = millis(); 
        ...
        ...
        long endLoop = millis();                    
        println("Looptime = "+(endLoop - startLoop));

    }// End of serialEvent  
}// End of SerialPortReader 
</code></pre>

<p>I'm not static friendly  :))   ;)</p>
]]></description>
   </item>
   <item>
      <title>How to save ellipse color if mouse pressed via serial Port</title>
      <link>https://forum.processing.org/two/discussion/17039/how-to-save-ellipse-color-if-mouse-pressed-via-serial-port</link>
      <pubDate>Wed, 08 Jun 2016 11:39:34 +0000</pubDate>
      <dc:creator>Tipikosh</dc:creator>
      <guid isPermaLink="false">17039@/two/discussions</guid>
      <description><![CDATA[<p>Hey, i want the ellipse that is being drawn to save its color on every position it was. i want to have the pen Function in Paint.
here is my code and thanks for your help!!</p>

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

<p>float x,y;</p>

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

<p>size(800,800);</p>

<p>Serial arduino = new Serial(this, "COM3", 250000);</p>

<p>arduino.bufferUntil('\n');</p>

<p>}</p>

<p>void draw()</p>

<p>{</p>

<p>}</p>

<p>void serialEvent(Serial p) {</p>

<p>String rawString = p.readStringUntil('\n');</p>

<p>if (rawString != null) {</p>

<p>rawString = rawString.trim();</p>

<p>try{</p>

<pre><code>String[] values = split(rawString,",");

int serialX = int(values[0]);

int serialY = int(values[1]);    

x = map(serialY,0,640,0,width);

y = map(serialX,0,480,0,height);
</code></pre>

<p>/* maybe something like</p>

<p>if (values[0]!=0)</p>

<p>{</p>

<p>fill
ellipse(x,y,10,10);
}</p>

<p>*/</p>

<p>}catch(Exception e){</p>

<pre><code>println("Error parsing string from Serial:");

e.printStackTrace();
</code></pre>

<p>}</p>

<p>}</p>

<p>}</p>

<p>`</p>
]]></description>
   </item>
   </channel>
</rss>