<?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 trim() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=trim%28%29</link>
      <pubDate>Sun, 08 Aug 2021 18:39:22 +0000</pubDate>
         <description>Tagged with trim() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggedtrim%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>Processing (image display) via Arduino ultrasonic sensor</title>
      <link>https://forum.processing.org/two/discussion/28055/processing-image-display-via-arduino-ultrasonic-sensor</link>
      <pubDate>Thu, 14 Jun 2018 12:33:26 +0000</pubDate>
      <dc:creator>komats</dc:creator>
      <guid isPermaLink="false">28055@/two/discussions</guid>
      <description><![CDATA[<p>Hi,
I am just starting to explore posibilities to make something work in processing via arduino (sensors). On school exhibition I want to make a <strong>picture display that shows one image at the time on the wall (with a projector), depending how close or far person is located from distance sensor.</strong>
This is a sketch of what I am thinking about:<img src="https://forum.processing.org/two/uploads/imageupload/088/QJY2PU3L5TTS.jpg" alt="example" title="example" />
To see if it really works, I explored some tutorials that explains how to connect Arduino input with Processing. Currently, I have these codes in both programs:
<strong>for Arduino:</strong></p>

<pre><code>const int anPin1 = 0;
long distance1;

void setup() {
  Serial.begin(9600);  // sets the serial port to 9600
}

void read_sensors(){
  /*
  Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
  Arduino analog pin goes from 0 to 1024, so the value has to be divided by 2 to get the actual inches
  */
  distance1 = analogRead(anPin1)/2;
}

void print_all(){
  /*
  Serial.print("S1");
  Serial.print("inches");
  */
  Serial.print(" ");
  Serial.print(distance1);
  Serial.println();
}

void loop() {
  read_sensors();
  print_all();
  delay(50); 
}
</code></pre>

<p><strong>And for Processing:</strong></p>

<pre><code>import processing.serial.*;  
Serial myPort;  
String data="" ;
PFont  myFont;  
int distance;

void setup(){
  size(1366,900); // size of processing window
  //background(0);// setting background color to black

  myPort = new Serial(this, "/dev/cu.usbmodemfd111", 9600);
  myPort.bufferUntil('\n');
}

void draw(){

  background(0);
  textAlign(CENTER);
  fill(255);
  text(data,820,400);
  textSize(100);
  fill(#4B5DCE);
  text("              Distance :        cm",450,400);
  noFill();
  stroke(#4B5DCE);

}

void serialEvent(Serial myPort){

  data=myPort.readStringUntil('\n');

}
</code></pre>

<p>And this distance reading works perfect!</p>

<p>Unfortunately didn’t found any specific example for what i am looking for.
So the question is, <strong>how can I get, for example, 3 pictures working this way:</strong></p>

<pre><code>if(distance&gt;60){
image(photo1, 0, 0); //display first photograpgy
}
else if (40&lt;distance&lt;60) {
image(photo2, 0, 0);
}
else if (distance&lt;40) {
image(photo3, 0, 0);
}
</code></pre>

<p>Do I have to write something like that in draw ()?
And how can I get income distance value as number from which depends displayed image?
And should I upload any specific library for this?
Do i have to write something also again in Arduino code?</p>

<p>Would be great if someone could suggest any examples or codes for this.</p>

<p>Hoping for advise,
komats!!</p>
]]></description>
   </item>
   <item>
      <title>Online quantum random number generator</title>
      <link>https://forum.processing.org/two/discussion/23432/online-quantum-random-number-generator</link>
      <pubDate>Thu, 13 Jul 2017 14:14:58 +0000</pubDate>
      <dc:creator>SeanS6</dc:creator>
      <guid isPermaLink="false">23432@/two/discussions</guid>
      <description><![CDATA[<p>I'm sure someone who knows more about json can write this code better:
(Also I haven't checked this code too well!!!)</p>

<pre><code>// qrng.anu.edu.au

QRND qrnd=new QRND();

void setup() {
  noLoop();
  for (int i=0; i&lt;1024; i++){
    int r=qrnd.nextInt();
    println(r);
    println(hex(r));
    println(binary(r));
  }
}

class QRND {
  int pos;
  int[] rData=new int[512];

  int nextInt() {
    if (pos==0) {
      JSONObject json=loadJSONObject("https://" + "qrng.anu.edu.au/API/jsonI.php?length=1024&amp;type=uint16");
      String[] tok=splitTokens(json.toString(), "[,");
      for (int i=0; i&lt;512; i++) {
        rData[i]=(int(trim(tok[i*2+1]))&lt;&lt;16) | int(trim(tok[i*2+2]));
      }
    }
    int r=rData[pos];
    pos=(pos+1) &amp; 511;
    return r;
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Serial Communication.</title>
      <link>https://forum.processing.org/two/discussion/22971/serial-communication</link>
      <pubDate>Wed, 07 Jun 2017 08:13:56 +0000</pubDate>
      <dc:creator>Noerrenebels</dc:creator>
      <guid isPermaLink="false">22971@/two/discussions</guid>
      <description><![CDATA[<p>Hello,
the following Code:</p>

<p><code>void serialEvent(Serial p) {
  message = myPort.readStringUntil(124);
  if (message != null) {
    int messageLength = message.length();
    message = message.substring(0, messageLength - 1);
    println(message);
    try {
      elements = split(message, ":");
      println(elements[0]+"????");
      println(elements[0].equals("Panel"));
      if (elements[0].equals("Panel") == true) {
        panel = int (elements[1]);
        println("Panel = " + str(panel));
      }
    }
    catch (Exception e) {
    }
  }
}</code></p>

<p>Print out to Console:</p>

<hr />

<p>`Panel:1
Panel????
true
Panel = 1</p>

<p>Panel:2</p>

<p>Panel????
false</p>

<h2>`</h2>

<p>Why the second time 'elements[0].equals("Panel")' is false?</p>

<p>Sincerly
Jörg</p>
]]></description>
   </item>
   <item>
      <title>Convert string with leading spaces to integer.</title>
      <link>https://forum.processing.org/two/discussion/20456/convert-string-with-leading-spaces-to-integer</link>
      <pubDate>Tue, 24 Jan 2017 20:55:52 +0000</pubDate>
      <dc:creator>RichardDL</dc:creator>
      <guid isPermaLink="false">20456@/two/discussions</guid>
      <description><![CDATA[<p>I have incoming strings containing 1 or more leading spaces and then digits.  What's the easiest way to convert these to integer?  I've just found that int(" 4") is zero.  I'm surprised at this as I think several other languages that I've used, e.g. C ignore leading whitespace on the conversion.   Alright, is there anything for trimming whitespace?  I can write my own using String.charAt and .substring, but I'm thinking I there's probably a well-trodden easier way.</p>
]]></description>
   </item>
   <item>
      <title>Read data from serial(from another arduino through xbee) to usable string</title>
      <link>https://forum.processing.org/two/discussion/18905/read-data-from-serial-from-another-arduino-through-xbee-to-usable-string</link>
      <pubDate>Sun, 06 Nov 2016 09:53:01 +0000</pubDate>
      <dc:creator>amiz</dc:creator>
      <guid isPermaLink="false">18905@/two/discussions</guid>
      <description><![CDATA[<p>this is sender node :</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/913/R7A6TTJLKB3V.PNG" alt="sender" title="sender" /></p>

<p>My problem is when it receive "node1" from sender through xbee, the condition is aborted..
BUT, when i  manually write in serial, the condition is worked..
i think the data sent by sender is not actually "node1"..even when i Serial.print(), it shows ""node1" physically.</p>

<p>this is receiver node:</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/720/BCFSJ1PKRIN5.PNG" alt="receiver" title="receiver" /></p>
]]></description>
   </item>
   <item>
      <title>mapping error - arduino, very basic</title>
      <link>https://forum.processing.org/two/discussion/12274/mapping-error-arduino-very-basic</link>
      <pubDate>Thu, 27 Aug 2015 19:40:12 +0000</pubDate>
      <dc:creator>frawgpaw</dc:creator>
      <guid isPermaLink="false">12274@/two/discussions</guid>
      <description><![CDATA[<p>Hey yall - firstly thanks for any help.</p>

<p>I am trying to run the very basic "graph" tutorial off of an arduino. (<a href="https://www.arduino.cc/en/Tutorial/Graph" target="_blank" rel="nofollow">https://www.arduino.cc/en/Tutorial/Graph</a>). I have a simple circuit with a potentiometer.</p>

<p>When I run this processing code, I get the following error:</p>

<p>map(NaN, 0, 1023, 0, 300) called, which returns NaN (not a number)</p>

<p>Weird. But if I type "println(inByte)" after my map line, the console shows me changing potentiometer values just fine. No error. Also, I should say the pop-out window which is supposed to graph my moving values is black, and never shows any sort of graph. Thanks again for all your help -</p>
]]></description>
   </item>
   <item>
      <title>myPort.available always 0</title>
      <link>https://forum.processing.org/two/discussion/14534/myport-available-always-0</link>
      <pubDate>Tue, 19 Jan 2016 15:35:27 +0000</pubDate>
      <dc:creator>langrenne</dc:creator>
      <guid isPermaLink="false">14534@/two/discussions</guid>
      <description><![CDATA[<p>Hy,</p>

<p>I'm on Linux kubuntu.
I would like receive data from an arduino nano (3 axis motion for head tracking).
The arduino code works because I can read data with Pure Data (Pd).
The arduino is on port [32] (/dev/ttyUSB0)</p>

<p>I use the common code:</p>

<pre><code>// Example by Tom Igoe

import processing.serial.*;

int lf = 10;    // Linefeed in ASCII
String myString = null;
Serial myPort;  // The serial port

void setup() {
  // 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()[32], 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;
}

void draw() {
  println(myPort.available());

  while (myPort.available() &gt; 0) {
    myString = myPort.readStringUntil(lf);
    if (myString != null) {
      println(myString);
    }
  }
}
</code></pre>

<p>But myPort.available is always 0. I can't read anything.</p>

<p>Can someone help me ?</p>

<p>thanks</p>
]]></description>
   </item>
   <item>
      <title>Using Arduino buttons to do something in processing.  Best method?</title>
      <link>https://forum.processing.org/two/discussion/7293/using-arduino-buttons-to-do-something-in-processing-best-method</link>
      <pubDate>Mon, 22 Sep 2014 21:29:21 +0000</pubDate>
      <dc:creator>alexs</dc:creator>
      <guid isPermaLink="false">7293@/two/discussions</guid>
      <description><![CDATA[<p>I'm working on a project that is quite simple, but very confusing for a beginner like myself...</p>

<p>In summary, this is the goal:
- I push a button (BTN01) on Arduino, my computer plays Sound01A
- I flick a swicth (BTN02) on Arduino, it plays Sound02A or Sound02B (depending on it's state)
- There will be many, many buttons...</p>

<p><strong>I have a few questions:</strong></p>

<p><strong>1)</strong> Is the best method of wiring each button (with two pins) GND and corresponding Digital Input Pin?  Do I need a pullup resistor? (I'm testing on Uno but finalising on Mega)
**
2)** Should use "serial.print" or "serial write" in the Arduino code?</p>

<p><strong>3)</strong> How should I best label each button state in Arduino that is sent via serial?  I was thinking 01a, 01b, 02a, 02b, etc (number is the button/pin, letter is the state eg pushed or not)</p>

<p><strong>4)</strong> Should I use some kind of array to m
ake the code easier to create and work with? Or should I just have lots of separate if statements (one for each button)?</p>

<p><strong>5)</strong> What would be the recommended/ simplest method of receiving the serial inputs in processing?</p>
]]></description>
   </item>
   <item>
      <title>Arduino and Processing</title>
      <link>https://forum.processing.org/two/discussion/15102/arduino-and-processing</link>
      <pubDate>Wed, 24 Feb 2016 23:14:15 +0000</pubDate>
      <dc:creator>iLegendX</dc:creator>
      <guid isPermaLink="false">15102@/two/discussions</guid>
      <description><![CDATA[<p>I have the arduino and ultrasonic HC-SR04. I want to help please us.
The arduino want to measure the distance and what gives the serial. Communicates with the processing and when the distance is greater than 150cm displays an image, if less playing video.
My problem is that I run the processing but the video plays either away or close.
Please help me. I beginner!!</p>

<p>Arduino is from a library NewPing
    // ---------------------------------------------------------------------------
    // Example NewPing library sketch that does a ping about 20 times per second.
    // ---------------------------------------------------------------------------</p>

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

#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
  delay(50);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo)
  Serial.println("cm");
}
</code></pre>

<p>Processing</p>

<pre><code>// Video
import processing.video.*;
Movie movie;

// Image
PImage img;  // Declare variable "a" of type PImage

// Serial
import processing.serial.*;
Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port


void setup() {
  size(640, 360);
  background(0);

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

  // Load and play the video in a loop
  movie = new Movie(this, "transit.mov");
  movie.loop();
  img = loadImage("moonwalk.jpg");  // Load the image into the program
}

void movieEvent(Movie m) {
  m.read();
}

void draw() {
  if (movie.available() == true) {
    movie.read(); 
  }
  image(movie, 0, 0, width, height);

  if ( myPort.available() &gt; 0) {  // If data is available,
    val = myPort.read();         // read it and store it in val
  }  


  if (val&gt;130) {
    image(img, 0, 0);
  } else {
    image(movie, 0, 0, width, height);
  }
  println(val);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Processing + Arduino + Flexiforce</title>
      <link>https://forum.processing.org/two/discussion/15278/processing-arduino-flexiforce</link>
      <pubDate>Fri, 04 Mar 2016 13:13:10 +0000</pubDate>
      <dc:creator>CharlesDesign</dc:creator>
      <guid isPermaLink="false">15278@/two/discussions</guid>
      <description><![CDATA[<p>Hi there,</p>

<p>I'm trying to import readings from a Flexiforce sensor however, the values in processing are different than the ones displayed in the Arduino serial monitor but they somehow respond to any force applied on the sensor.</p>

<p>Could anyone clarify what's going on?</p>

<p>Thanks in advance :)</p>

<p>Arduino Code:</p>

<pre><code>void setup()
{
  // Start serial at 9600 baud
  Serial.begin(9600);
}

void loop()
{
  // Read the input on analog pin 0:
  int sensorValue = analogRead(A0);

  //Serial.println(sensorValue);
  Serial.write(sensorValue);

  // Wait 100 milliseconds
  delay(100);
}
</code></pre>

<p>Serial Monitor Value (150gr):</p>

<pre><code>    330
    330
    330
    330
    330
    330
    331
    330
    330
    330
    330
    329
    330
    330
    330
    330
    330
    330
    330
    331
</code></pre>

<p>Processing Code:</p>

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

Serial port;                             // Create object from Serial class 
int val = 0;

void setup() { 
  size(200, 200); 
  frameRate(10); 
  // Open the port that the board is connected to and use the same speed (9600 bps) 
  printArray(Serial.list());
  port = new Serial(this, Serial.list()[3], 9600);
} 

void draw() { 

  if (0 &lt; port.available()) {         // If data is available,
    val = port.read();     // read it and store it in val
  }

  background(255);                       // Set background to white
  println(val);
  float dia = map(val, 0, 300, height*0.1, height*0.9);
  fill(0);
  ellipse(width*0.5, height*0.5, dia, dia);
} 
</code></pre>

<p>Processing Println Values (150gr):</p>

<pre><code>    88
    88
    87
    88
    88
    88
    88
    89
    88
    88
    88
    88
    88
    88
    87
</code></pre>
]]></description>
   </item>
   <item>
      <title>Does serial.bufferUntil work with any character?</title>
      <link>https://forum.processing.org/two/discussion/15177/does-serial-bufferuntil-work-with-any-character</link>
      <pubDate>Sun, 28 Feb 2016 18:42:44 +0000</pubDate>
      <dc:creator>RetiredProgrammer</dc:creator>
      <guid isPermaLink="false">15177@/two/discussions</guid>
      <description><![CDATA[<p>Every example I have seen uses either a newline or linefeed. Hoes it work with say *,#,% or ??</p>
]]></description>
   </item>
   <item>
      <title>Unpacking UDP Packet - byte to float</title>
      <link>https://forum.processing.org/two/discussion/13598/unpacking-udp-packet-byte-to-float</link>
      <pubDate>Sun, 22 Nov 2015 13:26:25 +0000</pubDate>
      <dc:creator>potter3366</dc:creator>
      <guid isPermaLink="false">13598@/two/discussions</guid>
      <description><![CDATA[<p>I am receiving this message from another app via a udp socket (hypermedia.net). I'd like to convert message after blank to a floating point value.</p>

<p><em>receive: "56871833174353 -0.095239157733537" from 192.168.178.52 on port 50396</em></p>

<pre><code>void receive( byte[] data, String ip, int port ) {
  data = subset(data, 0, data.length-2);
  String message = new String( data );
  println( "receive: \""+message+"\" from "+ip+" on port "+port );
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Cannot parse a string from serial</title>
      <link>https://forum.processing.org/two/discussion/13603/cannot-parse-a-string-from-serial</link>
      <pubDate>Sun, 22 Nov 2015 16:34:38 +0000</pubDate>
      <dc:creator>Dirruk</dc:creator>
      <guid isPermaLink="false">13603@/two/discussions</guid>
      <description><![CDATA[<p>A week ago I wrote a little sketch that reveals a bitmap pixel by pixel based on mouse coordinates. <img src="" alt="" />Thanks to the good people here it works like a charm. If you're interested, here it is:</p>

<pre><code>import processing.serial.*; //import the Serial library

Serial myPort;  //the Serial port object

PImage img;

void setup()
{

  size(182,262);  //This is the size of the canvas and the range of the printer
  // Make a new instance of a PImage by loading an image file
  img = loadImage("parel.bmp");
  tint(255,100);
  image (img,0,0);

}


void draw()
{ 
  color pix = img.get(mouseX, mouseY);
  stroke(pix);
  point(mouseX, mouseY);
}
</code></pre>

<p>So I am trying to expand this sketch by receiving pixel data from my arduino. I wrote a little arduino sketch that systematically sends all the pixel coordinates in the bitmap mentioned above over serial. And that seems to work too.
But Processing is giving me some trouble here when I try to receive the coordinates over serial. Here's the sketch:</p>

<pre><code>import processing.serial.*; //import the Serial library

Serial myPort;  //the Serial port object
String strIn = "";  //Declare a string with name str_in, this will store the coordinates received from the arduino
String portName = "";  //apparently this is necessary
int coordinates;
int locX= 0;
int locY= 0;

PImage img;

void setup()
{

  size(182,262);  //This is the size of the canvas and the range of the printer
  // Make a new instance of a PImage by loading an image file
  img = loadImage("parel.bmp");
  tint(255,100);
  image (img,0,0);
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName,9600);
}


void draw()
{ 
  while (myPort.available() &gt; 0) {                 // If data is available,
  strIn = myPort.readStringUntil('\n');         // read it and store it in a string called strIn
  } 
  int[] coordinates = int(split(strIn, ","));   
  //This should cut the strIn string in two integers, separated by a space 
  //and called coordinates. We expect a message coming in something like "XXX YYY"
  int locX = coordinates[0];        //This says that the first integer is an integer called LocX
  int locY = coordinates[1];       //This says that the first integer is an integer called LocX
  color pix = img.get(locX, locY);
  stroke(pix);
  point(locX, locY);
}
</code></pre>

<p>The debugger tells me it stores the incoming serial message in the strIn string, but locX and locY remain at 0. If I run the sketch without the debugger I get an arrayindexoutofboundsexception in line 34, which I think means it doesn't store anything in LocY. From what I read on this forum, I get that serial communication is troubling a lot more people than just me, but I can't find what the problem is. So if anybody has any ideas, you'd be a great help. My bitmap image is attached here as well.</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/121/ZXVHWVUJ0DXV.jpg" alt="parel" title="parel" /></p>
]]></description>
   </item>
   <item>
      <title>Arduino+Processing Problem: ArrayIndexOutOfBounds</title>
      <link>https://forum.processing.org/two/discussion/13110/arduino-processing-problem-arrayindexoutofbounds</link>
      <pubDate>Mon, 19 Oct 2015 08:51:17 +0000</pubDate>
      <dc:creator>Moonbrain</dc:creator>
      <guid isPermaLink="false">13110@/two/discussions</guid>
      <description><![CDATA[<p>Hi Everyone, i've been working on a little program combining arduino and processing aiming at generating visuals from movement ( gyroscope + vibration sensor).</p>

<p>So far I tested both the gyroscope and the vibration sensor separately and it worked just fine. 
Since I've tried to combine them i've been getting this error message:  <strong>ArrayIndexOutOfBoundsException: 1</strong> and the line 53: <strong>float  roty = (sensors[1]*10);</strong> is highlighted at the same time</p>

<p>I assume there is a problem with myString content, or I guess with the string access and my sensors declaration but I can't figure out what to do.
I've been learning code for a very short time, please have mercy on my inaccuracies ^^<br />
(i'm french so comments are mostly in french,let me know if you need me to explain myself)
Thank you so much for your help !!!</p>

<pre><code>    import glitchP5.*; //import Glitch P5
    String portName = "/dev/cu.usbmodem1421"; 
    import processing.serial.*;
    String serial; 
    Serial myPort;
    int linefeed = 10; 
    int numSensors = 3; 
    float[] sensors;
    float[] pSensors;
    float bornexinf=0; 
    float bornexsup=0;
    float borneyinf=0; 
    float borneysup=0; 
    float rotxold=0; 
    float rotyold=0; 
    // vibration
    int end = 10;    //Le nombre 10 en ASCII pour linefeed marquant la fin du serial.println
    GlitchP5 glitchP5; // declare an instance of GlitchP5. only one is needed
    int j=0; //variable d'incrémentation carré dans carré
    int max=1; //nombre d'itération, soit le nb de carrés dans le carré
    int longueur=10; // longueur du carré 
    int largeur=10; //largeur du carré
    float value=0; //variable pour la rotation
    float mouseXold=displayWidth/2;
    float mouseYold=displayHeight/2;

    void setup() {

     size(displayWidth, displayHeight);
     background (255);
     smooth();

      myPort = new Serial(this, portName, 9600);
      myPort.bufferUntil(linefeed);
      serial = myPort.readStringUntil(end); // fonction qui lit la chaine de caractères depuis le port série jusqu'à println et ensuite assigne string à notre variable qui appelle serial
      serial = null; // initialisation de serial
     glitchP5 = new GlitchP5(this);
    }


    void draw() {

      while (myPort.available() &gt; 0) { //tant qu'il n'y a pas de données provenant du port on lit l'entrée série
        serial = myPort.readStringUntil(end);
      }
        if (serial != null) {  
          String[] a = split(serial, ','); //on créé un tableau qui définit une chaine séparée par des virgules. 
          println(a[0]); //on affiche la première valeur du tableau
        }

      if((pSensors != null)&amp;&amp;(sensors != null)) { 
        float  rotx = (sensors[0]*10);
        float  roty = (sensors[1]*10);
        float  rotz = (sensors[2]*PI)/180;

    strokeWeight(1);
    noFill(); 
    stroke(random(255),random(255),random(255));
    translate(500,150);
    rectMode(CENTER);


    for(j=0;j&lt;max;j++){
        longueur=longueur+1; 
        largeur=largeur+1; 
        translate(width/2, height/2);
        rotate(value);
        translate(-width/2, -height/2);
        rect(rotx,roty,longueur,largeur); 
        redraw();
        bornexinf=rotxold-10; 
        bornexsup=rotxold+10;
        borneyinf=rotyold-10; 
        borneysup=rotyold+10; 
        if(bornexinf&gt;rotx || rotx&gt;bornexsup || borneyinf&gt;roty || roty&gt;borneysup){
        longueur=5;
        largeur=5;
        }
        rotxold=rotx;
        rotyold=roty;
    }
      }
     glitchP5.run();
    }


    void serialEvent(Serial myPort) {


      String myString = myPort.readStringUntil(linefeed);
      if (myString != null) {
              myString = trim(myString);
              pSensors = sensors;
              sensors = float(split(myString, ','));

                     for (int sensorNum = 0; sensorNum &lt; sensors.length; sensorNum++) {
                     print("Sensor" + sensorNum + ": " + sensors[sensorNum] + "\t");
        }
        println();
      }
    }

    void mousePressed() //===&gt; Will be triggered by the vibration sensor : if =0 do nothing; if =1 glitch; //
    {
     glitchP5.glitch(mouseX, mouseY, 200, 400, 200, 60, 120, 10.0f, 20, 1);
    }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Problem reading a RFID reader</title>
      <link>https://forum.processing.org/two/discussion/12920/problem-reading-a-rfid-reader</link>
      <pubDate>Fri, 09 Oct 2015 23:43:31 +0000</pubDate>
      <dc:creator>elunicotomas</dc:creator>
      <guid isPermaLink="false">12920@/two/discussions</guid>
      <description><![CDATA[<p>Hi there,</p>

<p>I have this <strong>SparkFun RFID Starter Kit</strong> (<a rel="nofollow" href="https://www.sparkfun.com/products/13198?_ga=1.242738306.1686357739.1444361942">https://www.sparkfun.com/products/13198?_ga=1.242738306.1686357739.1444361942</a>), I followed the steps in the <strong>HookUp guide</strong> (<a rel="nofollow" href="https://learn.sparkfun.com/tutorials/sparkfun-rfid-starter-kit-hookup-guide?_ga=1.177165093.1278763627.1444260091">https://learn.sparkfun.com/tutorials/sparkfun-rfid-starter-kit-hookup-guide?_ga=1.177165093.1278763627.1444260091</a>), and It seems that is working fine, although I'm not getting the same reads as the guide.</p>

<p>Example: 
The guide shows this screenshot of the Arduino serial port while reading the card:</p>

<p><img src="https://cdn.sparkfun.com/assets/learn_tutorials/2/2/8/scanned_card.png" alt="" /></p>

<p>And I get this value:</p>

<p><img src="http://i.imgur.com/gOXIgET.png" alt="" /></p>

<p>If I swipe the card another time, I get this reading:</p>

<p><img src="http://i.imgur.com/ceUHcxq.png" alt="" /></p>

<p>What are those little squares? I guess is some kind of character but I don't know which, or why is there.</p>

<p>Any ideas?</p>

<p>I am also trying this RFID reader in Processing. To change a message in the screen if someone swipes the card.</p>

<p>Initial screen:</p>

<p><img src="http://i.imgur.com/z7jKar7.png" alt="" /></p>

<p>After one read:</p>

<p><img src="http://i.imgur.com/7sM4HTt.png" alt="" /></p>

<p>The text "saldo en 0" should have changed to "deposito $50"", but it shouldn't.</p>

<p>Any ideas?</p>

<p>Thanks!!</p>

<p>The code:</p>

<pre><code>import processing.serial.*;
Serial myPort;
String inString = "texto inicial";
String mensaje;

void setup () {
  size(400, 300);        
  println(Serial.list());
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n');
  background(0);
}
void draw () {
  background(0);
  String s = inString;
  String comparador = "4500B8C02A17";
  textSize(24);
  fill(100);
  text(s, height/3, width/3); 

  if (comparador.equals(s) == true) {
    mensaje = "deposito $50";
  } else {
    mensaje = "saldo en 0";
  }
  text(mensaje, height/3, width/3+30);
}

void serialEvent (Serial myPort) {
  inString = myPort.readStringUntil('\n');
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Movement traces</title>
      <link>https://forum.processing.org/two/discussion/12831/movement-traces</link>
      <pubDate>Mon, 05 Oct 2015 15:04:23 +0000</pubDate>
      <dc:creator>hoefhearted</dc:creator>
      <guid isPermaLink="false">12831@/two/discussions</guid>
      <description><![CDATA[<p>Hello everybody,</p>

<p>any suggestions how I could merge my code below (movement tracing through for now a simple box) with e.g. this (<a href="http://studio.processingtogether.com/sp/pad/export/ro.9ldYvJUyiXGzi/latest" target="_blank" rel="nofollow">http://studio.processingtogether.com/sp/pad/export/ro.9ldYvJUyiXGzi/latest</a>)  sketchpad code in which the trace fades slowly. I getting actual sensor data and am not using the mouse. I am trying to make the movement interpretation 'feel' more natural.</p>

<p>All suggestions or hints are super welcome
Thank you already!!</p>

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

<p>Serial myPort;<br />
int linefeed = 10;   // Linefeed in ASCII
int numSensors = 3;  // we will be expecting for reading data from 3 sensors
float sensors[];       // array to read the 3 values
float pSensors[];</p>

<p>void setup() {
  size(1350, 800, P3D);<br />
  // List all the available serial ports in the output pane. 
  // You will need to choose the port that the Wiring board is 
  // connected to from this list. The first port in the list is 
  // port #0 and the third port in the list is port #2. 
  println(Serial.list());</p>

<p>myPort = new Serial(this, Serial.list()[2], 115200);
  // read bytes into a buffer until you get a linefeed (ASCII 10):
  myPort.bufferUntil(linefeed);</p>

<p>}</p>

<p>void draw() {
  if((pSensors != null)&amp;&amp;(sensors != null)) {</p>

<pre><code>// now do something with the values read sensors[0] .. sensors[2]
 //First I find all my rotation angles in radians so that center screen is (0,0)

float rotx = (sensors[0]*PI)/180;
float roty = (sensors[1]*PI)/180;
float rotz = (sensors[2]*PI)/180;
//float roty = 0;

background(0);
stroke(0, 0, 200);
//line (0,20,420,20); // monitor bar
fill(255);
textSize(1);
text (" rotateX(" + rotx +" pi)"+" , rotateY("+roty+" pi)"+" , rotateZ("+rotz+" pi)", 0,10);
fill(0, 0, 200);

translate(610, 380, 0); // center drawing start point in screen  180 TO 380

strokeWeight(1);
stroke(50);

line(-60, 0, 60, 0);       //
line(0, 60, 0, -60);       // draw stationary axis lines
line(0, 0, -60, 0, 0, 60); //
strokeWeight(0); // PPP: STROKEWEIGHT VON 1 NACH 0
stroke(0, 150, 0);
noFill();
box(40);                  // draw stationary box


rotateX(rotx);  //
rotateY(roty);  // rotate drawing coordinates according to user input variables
rotateZ(rotz);  //
strokeWeight(0);
stroke(255);
line(10, 0, 10, 0);       //PPPP ALL PLACES WITH 50 USED TO BE 150
line(0, 10, 0, -10);       // draw the rotating axis lines
line(0, 0, -10, 0, 0, 10); //
strokeWeight(4);
stroke(57, 255, 20);
noFill();
box(100,60,350); // draw rotating red box PPPPP: CHANGED FROM 140!!!
</code></pre>

<p>}
}</p>

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

<p>// read the serial buffer:2
  String myString = myPort.readStringUntil(linefeed);</p>

<p>// if you got any bytes other than the linefeed:
  if (myString != null) {</p>

<pre><code>myString = trim(myString);

// split the string at the commas
// and convert the sections into integers:

pSensors = sensors;
sensors = float(split(myString, ','));

// print out the values you got:

for (int sensorNum = 0; sensorNum &lt; sensors.length; sensorNum++) {
  print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t");
}

// add a linefeed after all the sensor values are printed:
println();
</code></pre>

<p>}
}</p>
]]></description>
   </item>
   <item>
      <title>Arduino Serialread makes my processing animation stop</title>
      <link>https://forum.processing.org/two/discussion/12348/arduino-serialread-makes-my-processing-animation-stop</link>
      <pubDate>Tue, 01 Sep 2015 18:28:12 +0000</pubDate>
      <dc:creator>torekndsen</dc:creator>
      <guid isPermaLink="false">12348@/two/discussions</guid>
      <description><![CDATA[<p>Hey guys, I want to control a ball's acceleration in a proccesing animation, accordingly to a analogue input on my Arduino. 
The balls acceleration and behaviour is written with PVectors (see code below) but when I activate my arduino sketch, the ball just disappears from the window. 
I have made several simple tests were I for an example changed the size of an ellipse by mapping the serialRead with success, so the communication between Arduino and Processing is not the problem.</p>

<p>//the code:</p>

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

Mover mover;

float inByte;

void setup(){
  size(800,600);
  background(240);
  smooth();
  mover = new Mover();

  myPort = new Serial(this,Serial.list()[2], 9600);
  myPort.bufferUntil('\n');
}


void draw(){
  background(240);
  mover.update();
  mover.checkEdges();
  mover.display();

  fill(10);

}

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

  if(inString != null){
    inString = trim(inString);
    inByte = float(inString);
    inByte = map(inByte,0,1023,0,5);
  }
}


//newtab 
class Mover{
  PVector location;
  PVector velocity;
  PVector acceleration;
  float topspeed;

  Mover(){
    location = new PVector(width/2,height/2);
    velocity = new PVector(0,0);
    topspeed = 10;
  }

  void update(){
    acceleration = PVector.random2D();
    acceleration.mult(inByte);

    velocity.add(acceleration);
    velocity.limit(topspeed);
    location.add(velocity);
  }

  void display(){
    noStroke();
    fill(10);
    ellipse(location.x, location.y, 50, 50);

  }


void checkEdges(){
  if(location.x &gt; width){
    location.x = 0;
  }
  else if (location.x &lt; 0 ){
    location.x = width;
  }

  if(location.y &gt; height){
    location.y = 0;
  }
  else if(location.x &lt; 0){
    location.y = height;
  }
}
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Arduino to Processing importing variables.</title>
      <link>https://forum.processing.org/two/discussion/12386/arduino-to-processing-importing-variables</link>
      <pubDate>Thu, 03 Sep 2015 18:47:08 +0000</pubDate>
      <dc:creator>jfanals</dc:creator>
      <guid isPermaLink="false">12386@/two/discussions</guid>
      <description><![CDATA[<p>Hey all, I am quite new at that world, but I would like to know why does it happen to me. The thing is that I created a variable on Arduino which receives a random number between 0 and 100; however, I wanted to print in on Processing but it is not recognized because instead of that it writes COM3, the port where Arduino is connected. 
By the way, here is the Arduino code:</p>

<p>void setup() 
{
//initialize serial communications at a 9600 baud rate</p>

<p>Serial.begin(9600);
}</p>

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

<p>int num = random(0, 100);</p>

<p>Serial.println(num);</p>

<p>delay(100);</p>

<p>}</p>

<p>And here the Processing one:</p>

<p>import vsync.*;</p>

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

<p>Serial myPort;</p>

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

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

<p>}</p>

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

<p>println(Serial.list());</p>

<p>delay(1000);
}</p>

<p>I don't know if I am missing some libraries but I am kinda stocked for hours.</p>

<p>Thank you.</p>
]]></description>
   </item>
   <item>
      <title>Parse string to long</title>
      <link>https://forum.processing.org/two/discussion/12180/parse-string-to-long</link>
      <pubDate>Thu, 20 Aug 2015 16:44:00 +0000</pubDate>
      <dc:creator>marizol</dc:creator>
      <guid isPermaLink="false">12180@/two/discussions</guid>
      <description><![CDATA[<p>Hi there</p>

<p>I am reading a string from serial port (from Arduino) and need to convert it to long. My code throws an exception every time - and catches it. Isn't the Long.parseLong(String) the way to parse string to long? :</p>

<pre><code>String val; //global variable

[..]
and in draw():

 if ( myPort.available() &gt; 0) 
  {  // If data is available,
  val = myPort.readStringUntil('\n');         // read it and store it in val
  println("Val=" + val);
  myPort.clear();
  } 

  // While Java's parseLong() throws an Exception:
  try {
   println("long l=" + Long.parseLong(val));
  } catch (NumberFormatException e) {
   println(val);
   println("can't be converted to a number!");
   }

  exit();
</code></pre>

<p>Many thanks in advance</p>
]]></description>
   </item>
   <item>
      <title>Error handling during serial read</title>
      <link>https://forum.processing.org/two/discussion/12129/error-handling-during-serial-read</link>
      <pubDate>Mon, 17 Aug 2015 18:21:00 +0000</pubDate>
      <dc:creator>mathews616</dc:creator>
      <guid isPermaLink="false">12129@/two/discussions</guid>
      <description><![CDATA[<p>I am working with an Arduino and making a small GUI to communicate with it on Processing. I am just printing out float values onto the serial port and reading it back using Processing. In most cases everything goes well and I am able to read the values. However, sometimes the serial read spits out fairly arbitrary values and I am not sure why. For example,</p>

<p>My Arduino code:</p>

<pre><code> void setup() {
   // put your setup code here, to run once:
 Serial.begin(9600);
 }

 void loop() {
   for (int i =1;i&lt;5;i++)
 {  Serial.println(float(i)+2.0);
 delay(1);
   // put your main code here, to run repeatedly:
 }
 }
</code></pre>

<p>The output according to the Serial monitor is 3.0,4.0,5.0,6.0 as expected.</p>

<p>Here's the processing code (Python Mode) that I use to read the data in</p>

<pre><code> def connect2Arduino(): 
     global arduinoPort
     arduinoPort= Serial(this, 'COM32',9600)

 def setup():
    background(0)
    connect2Arduino()

 def draw():
    global arduinoPort
    if arduinoPort.available()&gt;0:
        dataIn = arduinoPort.readStringUntil(int(10))
        if (dataIn != None or int(dataIn) != 13):
            print dataIn  
</code></pre>

<p>The output from processing looks like this</p>

<blockquote class="Quote">
  <p>4.00</p>
  
  <p>5.00</p>
  
  <p>6.00</p>
  
  <p>3.00</p>
  
  <p>4.00</p>
  
  <p>5.‚j</p>
  
  <p>6.°3.00</p>
  
  <p>4.00</p>
  
  <p>5.00</p>
  
  <p>6.00</p>
</blockquote>

<p>When I try to change the type of dataIn, an error pops up when output is 5.‚j which is as expected.</p>

<p>First of, I have no idea why these errors exist. I would like to know why it's showing up in the first place. Secondly, what's a fix? I could go print instead of println on my arduino code and maybe fix it, but I am looking for something better.</p>

<p>Thank you</p>
]]></description>
   </item>
   <item>
      <title>Help with serials and strings</title>
      <link>https://forum.processing.org/two/discussion/11803/help-with-serials-and-strings</link>
      <pubDate>Thu, 23 Jul 2015 01:10:21 +0000</pubDate>
      <dc:creator>LizzyB</dc:creator>
      <guid isPermaLink="false">11803@/two/discussions</guid>
      <description><![CDATA[<p>Hi Processing Forum,</p>

<p>I am in the process of hacking a rotary phone, using Arduino and Processing to convert the phone into a recording and playback device. It is a really interesting project and I have made some progress, but I got stuck on a string from the serial port. My code is long, so I will share my public gist here: <a href="https://gist.github.com/lizzybrooks/b88531b906860d4fc4af" target="_blank" rel="nofollow">https://gist.github.com/lizzybrooks/b88531b906860d4fc4af</a>.</p>

<p>Here is the function that seems to be giving me trouble:</p>

<pre><code>void readNumbers(){
if ( myPort.available() &gt; 0) 
  {  
    // get the value from the serial port
    do{
    val = myPort.readStringUntil('\n');         // read it and store it in val 
    } while (val == null);

    // print every value received to the console so we know what we got
   // println(val);
   // println(val.length()); 

if (val.equals("6\r\n")){
      println("hooray. you work. let's play a different audio file");

      // anything else and its input from the phone
      // so do whatever you want if you receive input from the phone here...
    }

  }
</code></pre>

<p>If you have any ideas or can help me with syntax, I would so much appreciate it. I am a beginner coder working on a complicated project, but I am eager to learn.</p>

<p>Thanks so much!</p>

<p>Lizzy</p>
]]></description>
   </item>
   <item>
      <title>displaying string from Arduino</title>
      <link>https://forum.processing.org/two/discussion/11518/displaying-string-from-arduino</link>
      <pubDate>Tue, 30 Jun 2015 19:32:52 +0000</pubDate>
      <dc:creator>Fiansyah</dc:creator>
      <guid isPermaLink="false">11518@/two/discussions</guid>
      <description><![CDATA[<p>I control manages speed dc motor , I want to show the speed that is read by arduino , but the speed sent by arduino can only appear on the monitor serial processing , all I want is a display in the window " run" .
this is processing code :</p>

<pre><code>          `import controlP5.*;
            import processing.serial.*;
            ControlP5 cP5a;
            ControlP5 cP5b;
            ControlP5 cP5c;
            ControlP5 cP5d;
            ControlP5 cP5e;
            ControlP5 cP5f;
            ControlP5 cP5g;
            ControlP5 cP5h;

            Serial arduino;
            String val;

            void setup() 
            {
              size(785, 520);
              println(Serial.list());
              arduino = new Serial(this, Serial.list()[0], 9600);

              cP5a = new ControlP5(this);
              cP5a.addSlider("ATUR_KECEPATAN_MOTOR_DC", 0, 255, 0, 30, 155, 350, 50);
              cP5b = new ControlP5(this);
              cP5b.addButton("FORWARD",1,30,220,100,40);
              cP5c = new ControlP5(this);
              cP5c.addButton("REVERSE",0,280,220,100,40);
              cP5d = new ControlP5(this);
              cP5d.addButton("BUKA_GERBANG",1,30,300,100,40);
              cP5e = new ControlP5(this);
              cP5e.addButton("TUTUP_GERBANG",1,30,355,100,40);
              cP5f = new ControlP5(this);
              cP5f.addSlider("SUDUT_SERVO", 0, 180, 0, 30, 435, 350, 50);
              cP5g = new ControlP5(this);
              cP5g.addButton("MASTER_ON",1,30,80,100,35);
              cP5h = new ControlP5(this);
              cP5h.addButton("MASTER_OFF",0,160,80,100,35);
            }

            void draw() 
            {
              background(#614DED);
              textSize(20);
              fill(#F5ED00);
              text("PENGENDALI MOTOR DC MOTOR STEPPER DAN MOTOR SERVO", 100, 30);
              textSize(18);
              text("KECEPATAN MOTOR DC :", 500, 140);
              textSize(18);
              text("FIANSYAH AFANDI RAKHMAN, TEKNIK ELEKTRO, UNIVERSITAS SILIWANGI TASIKMALAYA", 10,60);
              textSize(15);
              text("A. MOTOR DC", 15,140);
              textSize(15);
              text("B. MOTOR STEPPER", 15,285);
              textSize(15);
              text("C. MOTOR SERVO", 15,420);
              textSize(13);
              fill(#020108);
              text("created by: Fiansyah Afandi Rakhman", 545, 500);
              text("107002025/elektro2010", 617, 515);

              if (arduino.available() &gt;0){
              val=arduino.readStringUntil('\n');}

              println(val);

            }

            void controlEvent(ControlEvent theEvent) {
              if(theEvent.isController()) {

              print("control event from : "+theEvent.controller().name());
              println(", value : "+theEvent.controller().value());

             if(theEvent.controller().name()=="ATUR_KECEPATAN_MOTOR_DC") {
               int val1 = int(theEvent.getController().getValue());
               arduino.write("a" + val1);
             }
             if(theEvent.controller().name()=="FORWARD") {
               int val2 = int(theEvent.getController().getValue());
              arduino.write("b" + val2 );
             }
             if(theEvent.controller().name()=="REVERSE") {
               int val3 = int(theEvent.getController().getValue());
               arduino.write("c" + val3);
                }
             if(theEvent.controller().name()=="BUKA_GERBANG") { 
                int val4 = int(theEvent.getController().getValue());
               arduino.write("d" + val4 );
             }
             if(theEvent.controller().name()=="TUTUP_GERBANG") { 
                int val5 = int(theEvent.getController().getValue());
              arduino.write("e" + val5 );
             }
             if(theEvent.controller().name()=="SUDUT_SERVO") {
               int val6 = int(theEvent.getController().getValue());
              arduino.write("f" + val6);  
             }
             if(theEvent.controller().name()=="MASTER_ON") {
               int val7 = int(theEvent.getController().getValue());
              arduino.write("g" + val7);
             }
             if(theEvent.controller().name()=="MASTER_OFF") {
               int val8 = int(theEvent.getController().getValue());
             arduino.write("h" + val8);
               }
              }
            }`
</code></pre>

<p>in this section :</p>

<pre><code>    if (arduino.available() &gt;0){
    val=arduino.readStringUntil('\n');}
    println(val);
</code></pre>

<p>when i added into :</p>

<pre><code>        if (arduino.available() &gt;0){
                                  val=arduino.readStringUntil('\n');}

                                  println(val);
                                textSize(18);
                                text(val, 500, 180);
</code></pre>

<p>there is an error, and there is written "could'nt run the sketch"
and the problem is this section :</p>

<pre><code>            text(val, 500, 180)
</code></pre>

<p>help me to solve this problem , how to correct sketch writing if you want to display a string on the run window . Thank you , any help would be greatly appreciated</p>
]]></description>
   </item>
   <item>
      <title>Read Text Sent From Arduino</title>
      <link>https://forum.processing.org/two/discussion/11354/read-text-sent-from-arduino</link>
      <pubDate>Wed, 17 Jun 2015 13:01:30 +0000</pubDate>
      <dc:creator>TheIntern</dc:creator>
      <guid isPermaLink="false">11354@/two/discussions</guid>
      <description><![CDATA[<p>Not sure where this question would fit in the forum but I'm having an issue reading strings being sent from an Arduino.</p>

<p>The Arduino code sends text as a string when a function is called.</p>

<p>Processing reads these strings and acts accordingly.</p>

<p>I am trying to parse the strings based on the first three letters of each string element, then perform an action based on what the rest of the element says.</p>

<p>Example:</p>

<p>LOGstim off.</p>

<p>Processing reads this element, sees "LOG", saves everything after "LOG" as a new string named "log".</p>

<p>This part works fine.  What I can't figure out is how to get processing to act after it creates this new string "log".  I've managed to use match() to do what I want but its very bulky and involves creating about 30 separate strings, one for each instance of match().</p>

<p>I don't understand why log.equals("<em>what I need matched</em>") does not work.  Here is an example of the processing code:</p>

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

Serial myPort;
String dataReading = "";
String[] dataOutput = {
};
String log;

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

  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n');
}

void draw() {

}

void serialEvent(Serial myPort) {
  dataReading = myPort.readStringUntil('\n');
  println(dataReading);
  if (dataReading != null) {
    dataOutput = append(dataOutput, dataReading);
    if (dataReading.substring(0, 3).equals("LOG")) {
      log = dataReading.substring(3);
      println(log);
      if(dataReading.substring(3).equals("visual stim")) {
      //  String logVisStim = dataReading.substring(3); //here I tried to create a separate string for the substrings after LOG.
      //  println(logVisStim);//This is to test the line of code above.
        background(255);
      }else if(dataReading.substring(3).equals("vis left error")){
        background(0);
      }else{
        background(100);
      }
    }
  }
}

  void saveData() {
    println("saving to txt file...");
    saveStrings("data/data.txt", dataOutput);
  }


  void mousePressed() {
    saveData();
  }
</code></pre>

<p>Here is a copy of what is printed in the serial monitor.</p>

<p>CMDTVinitiation</p>

<p>LOGTVinitiation</p>

<p>TVinitiation</p>

<p>TIM279931</p>

<p>CMDtrialstart</p>

<p>LOGautostart</p>

<p>autostart //this is from println(log);</p>

<p>TIM280008</p>

<p>LOGstim right on</p>

<p>stim right on //this is from println(log);</p>

<p>TIM280039</p>

<p>LOGvisual stim</p>

<p>visual stim //this is from println(log);</p>

<p>TIM280040</p>

<p>TIM280140</p>

<p>LOGmissed your shot!</p>

<p>missed your shot! //this is from println(log);</p>

<p>TIM300008</p>

<p>LOGstim off</p>

<p>stim off //this is from println(log);</p>

<p>TIM300008</p>

<p>CMDsession stop R</p>

<p>CMDsession stop L</p>
]]></description>
   </item>
   <item>
      <title>How to correctly save serial data to a text file</title>
      <link>https://forum.processing.org/two/discussion/11073/how-to-correctly-save-serial-data-to-a-text-file</link>
      <pubDate>Sat, 30 May 2015 17:03:50 +0000</pubDate>
      <dc:creator>mgiara</dc:creator>
      <guid isPermaLink="false">11073@/two/discussions</guid>
      <description><![CDATA[<p>Hello!</p>

<p>The formatting of the saved text is a bit garbled.</p>

<p>Processing code:</p>

<pre><code>void draw() {
  background(50);
  textFont(t, 20);
  fill(255);

  readSerial();
  drawBenchA();
}


void drawBenchA() {

}

void readSerial() {
  if (mySerial.available ()&gt;0 ) {
    String myString = mySerial.readStringUntil('\n');
    if (myString!=null) {
      for (int i = 0; i&lt;myString.length (); i++) {
        Str1 [i] = myString.charAt(i);
      }
    }
    mySerial.clear();
  }

  for (int i = 0; i &lt; 15; i++)
  {
    output.print(Str1[i]);
  }

  textFont(t, 16);
  fill(255);
}


void keyPressed() {
  output.flush();  // Writes the remaining data to the file
  output.close();  // Finishes the file
  exit();  // Stops the program
}
</code></pre>

<p>Text file:
<code>
Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Start
                        Bench A
            velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-velope: 127546-Seconds
                27546-Seconds
                27546------</code></p>

<pre><code>        27546------

        27546------

        27546------

        27546------

        27546------

        27546------

        27546------

        27546------

        27546------

        27546------

        27546------
</code></pre>

<p></p>

<p>How it should appear:</p>

<pre><code>Start
Bench A
Envelope 127546-2
5 Seconds
----------------------------
</code></pre>

<p>I think this can be fixed with serialEvent, but not sure how.</p>
]]></description>
   </item>
   <item>
      <title>[Serial Problem] Conditions not working even thought the values match!</title>
      <link>https://forum.processing.org/two/discussion/10812/serial-problem-conditions-not-working-even-thought-the-values-match</link>
      <pubDate>Thu, 14 May 2015 22:37:32 +0000</pubDate>
      <dc:creator>tnowroz</dc:creator>
      <guid isPermaLink="false">10812@/two/discussions</guid>
      <description><![CDATA[<p>What I am trying to do is read some IR signals.</p>

<p>The code in Arduino is:</p>

<pre><code> /*
 * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Version 0.1 July, 2009
 * Copyright 2009 Ken Shirriff
 * <a href="http://arcfn.com" target="_blank" rel="nofollow">http://arcfn.com</a>
 */


 #include &lt;IRremote.h&gt;


 int RECV_PIN = 7;

 IRrecv irrecv(RECV_PIN);

 decode_results results;


 void setup() {

    Serial.begin(9600);

    irrecv.enableIRIn(); // Start the receiver  
}


void loop() {

  if (irrecv.decode(&amp;results)) {

    Serial.println(results.value);

    irrecv.resume(); // Receive the next value

  }

  delay(100);

}
</code></pre>

<p>It reads the IR signals, and suppose, Now I want to get this at Processing and want to open a webpage for that.</p>

<pre><code> // Example by Tom Igoe

 import processing.serial.*;

 Serial myPort;    // The serial port

 String inString;  // Input string from serial port

 int lf = 10;      // ASCII linefeed


 void setup() {

    size(400,200);

    // List all the available serial ports:

    println(Serial.list());

    // Open the port you are using at the rate you want:hat 

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

    myPort.bufferUntil(lf);

 }

 void draw() {

   background(0);

   text("received: " + inString, 10,50);


 }

 void serialEvent(Serial p) {

   inString = p.readString();


   if(inString.equals("544993039")){

    String[] params = { "start www.google.com" };

    open(params);


   }
 }
</code></pre>

<p>`</p>

<p>But however even though the signal of that value is caught in the receiver, but the codes do not get executed! :/</p>

<p>I am 100% sure that the signal reaches the receiver as Arduino seems to do what I want it to do when I send signals, for example when I use this code:
<code>if(results.value == 544993039) { digitalWrite(8, HIGH);  }</code></p>

<p>Anything connected to pin 8 seems to work just fine.</p>

<p>but in Processing:</p>

<pre><code>if(inString.equals("544993039")){

        String[] params = { "start www.google.com" };

        open(params);


       }
</code></pre>

<p>Nothing seems to happen. Can anybody help me please?</p>
]]></description>
   </item>
   <item>
      <title>Remove a Line Break</title>
      <link>https://forum.processing.org/two/discussion/10226/remove-a-line-break</link>
      <pubDate>Tue, 07 Apr 2015 14:57:18 +0000</pubDate>
      <dc:creator>fahadkalis</dc:creator>
      <guid isPermaLink="false">10226@/two/discussions</guid>
      <description><![CDATA[<p>I am writing a program, to get serial input string and then add three COMMAs with it.
but I am facing a problem of a line gap (carriage return+linefeed)  b/w string and COMMAs.
Can you plz guide me on how do I resolve this problem and remove the line gap.
below in my code.</p>

<pre><code>import processing.serial.*;
Serial serialPort;
String input;

void setup() {
  serialPort = new Serial(this,"COM4",9600);
  serialPort.bufferUntil('\n'); }

void draw() {
  background(1);
}

void serialEvent(Serial serialPort) {
  input = serialPort.readString();
  for (int i=0 ; i&lt;3; i++) {
  input = input + ",";
  }
println(input);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Serial out to .txt</title>
      <link>https://forum.processing.org/two/discussion/10031/serial-out-to-txt</link>
      <pubDate>Wed, 25 Mar 2015 16:49:18 +0000</pubDate>
      <dc:creator>kevinks</dc:creator>
      <guid isPermaLink="false">10031@/two/discussions</guid>
      <description><![CDATA[<p>Hi, I have got this code which reads serial out from an arduino and save it to a text file. Unfortunately, the file data.txt happens to have some garbage values in addition to the serial output data. I can't find what's wrong with the code. If i remove the processing and take the output on arduino ide's serial monitor i get the correct data. I would really like a helping hand here. And oh., the output is from an rfid reader connected to arduino. 
Here's the code</p>

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

<p>Serial myPort;
void setup()
{
output= createWriter("data.txt");
myPort=new Serial(this,"COM1",9600);
}
void draw()
{
 while(myPort.available()&gt;0)
     {
       String rfid=myPort.readString();
         if(rfid!=null)
             {
               output.println(rfid);
             }
     }
}
void keyPressed()
{
output.flush();
output.close();
exit();
}</p>
]]></description>
   </item>
   <item>
      <title>read incoming serial data as a string?</title>
      <link>https://forum.processing.org/two/discussion/7511/read-incoming-serial-data-as-a-string</link>
      <pubDate>Wed, 08 Oct 2014 16:13:32 +0000</pubDate>
      <dc:creator>prismspecs</dc:creator>
      <guid isPermaLink="false">7511@/two/discussions</guid>
      <description><![CDATA[<p>I have an Arduino program that is sending data to Processing via serial. It is meant to send a heads up message based on what kind of data is to follow. For example, when I want the Arduino to pipe some image data via serial, the message begins with "&gt;IMG:". So I'd like to test for that string, then do something with the array of numbers that follow.</p>

<pre><code>  if ( port.available() &gt; 0) {  // If data is available,
    //val = port.read();         // read it and store it in val

    String test[] = {
      "","","","",""
    };

    for (int i = 0; i &lt; test.length; i++) {
      test[i] = str(char(port.read()));
    }
    println(test);
    if(test == "&gt; I M G :") {
      println("yup");
    }
</code></pre>

<p>I can never figure out how to make Processing play nice with strings. I just want to take in the first 4 chars and see if combined they form "&gt;IMG:"</p>

<p>Also, if the Arduino is sending serial data as HEX, is there anything special I need to do when reading via Processing to make sure it safely converts to a usable int of the same value?</p>
]]></description>
   </item>
   </channel>
</rss>