<?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 createwriter() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=createwriter%28%29</link>
      <pubDate>Sun, 08 Aug 2021 18:40:46 +0000</pubDate>
         <description>Tagged with createwriter() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggedcreatewriter%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>createWriter() ouput based on time of the day</title>
      <link>https://forum.processing.org/two/discussion/25401/createwriter-ouput-based-on-time-of-the-day</link>
      <pubDate>Tue, 05 Dec 2017 21:49:02 +0000</pubDate>
      <dc:creator>Layzfat</dc:creator>
      <guid isPermaLink="false">25401@/two/discussions</guid>
      <description><![CDATA[<p>Hi I'm using the carnivore library/code to get some data of my network. 
I want to analyse and read as much packets as possible.</p>

<p>For the moment I'm troubled with the ascii convertion and saving the output of the console log.</p>

<p>I've used the createWriter() to log the console to a file. This only stops after hitting a key.</p>

<p>How could I turn this into a daily or maybe hourly 'save to file' happening. So I have multiple files with shorter amounts of code in it?</p>
]]></description>
   </item>
   <item>
      <title>Launching ffmpeg from cmd in sketch?</title>
      <link>https://forum.processing.org/two/discussion/22076/launching-ffmpeg-from-cmd-in-sketch</link>
      <pubDate>Wed, 19 Apr 2017 06:43:07 +0000</pubDate>
      <dc:creator>SnailPropulsionLabs</dc:creator>
      <guid isPermaLink="false">22076@/two/discussions</guid>
      <description><![CDATA[<p>Hi all,
As the title says, i'm trying to launch ffmpeg, which is a command line utility, from within a sketch.
I've tried exec(), and open() and launch(), with no real success that I can see.
The code below prints "the process returned 1" to the processing console, but the command line is never launched.</p>

<p>What do I need to do to make this work?</p>

<p>Thanks in advance.</p>

<p>code:</p>

<pre><code>import processing.video.*;
Movie mov;
String fileName;

void setup() {
  size(800, 800);
}  

void draw() {
}

void keyPressed() {
  if (key == 'p') selectInput("Select movie:", "movieSelected");
}

void movieSelected(File selection) { 
  if (selection == null) {
    println("Window was closed or the user hit cancel.");
  } else {
    fileName = selection.getAbsolutePath();
    mov = new Movie(this, fileName);

    String[] processCommands = {
      "E:/Tertiary/COMP390/Movie Second/ffmpeg/bin/ffmpeg.exe", 
      "ffmpeg", "-i", "mov", "-codec:a", "libmp3lame", "-qscale:a 2", "fileName" + "output.mp3"
    };
    Process p = launch(processCommands);

    try {
      int result = p.waitFor();
      println("the process returned " + result);
    } 
    catch (InterruptedException e) {
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Getting an Access error with PrintWriter</title>
      <link>https://forum.processing.org/two/discussion/20442/getting-an-access-error-with-printwriter</link>
      <pubDate>Tue, 24 Jan 2017 04:43:52 +0000</pubDate>
      <dc:creator>CantSayIHave</dc:creator>
      <guid isPermaLink="false">20442@/two/discussions</guid>
      <description><![CDATA[<p>I have a PrintWriter object named <code>fileOut</code> which I initialize with <code>createWriter("testfile.txt")</code>. I then print to it, flush and close it.</p>

<p>It will not compile, repeatedly giving me two of these errors:</p>

<p><code>check = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Manifest.permission.READ_EXTERNAL_STORAGE cannot be resolved</code></p>

<p>I have both <code>READ_EXTERNAL_STORAGE</code> and <code>WRITE_EXTERNAL_STORAGE</code> enabled properly.</p>

<p>Anyone experience this before?</p>
]]></description>
   </item>
   <item>
      <title>Unable to save new data into new TXT file</title>
      <link>https://forum.processing.org/two/discussion/19848/unable-to-save-new-data-into-new-txt-file</link>
      <pubDate>Tue, 20 Dec 2016 14:52:39 +0000</pubDate>
      <dc:creator>IvanNYU</dc:creator>
      <guid isPermaLink="false">19848@/two/discussions</guid>
      <description><![CDATA[<p>Hi,
i am facing a problem in exporting the data in .txt file: all the files i created contains the same informations (same x and y coordinates)</p>

<p>My goal is to collect several trials with x and y coordinates and export them in separate data files 9one for each trial).  i am using PrintWirter</p>

<p>PrintWriter[] output = new PrintWriter[4];</p>

<p>in this case it created 5 output files where i can save my data, and then i would like to fill them with the x and y positions.</p>

<p>The files are correctly created, but they contain the same data, i.e. file number 1 contain the same x and y data of the file number 5.</p>

<p>here the code</p>

<pre><code>void setup(){
smooth();
fullScreen();
rectMode(CENTER);
//define the output file where you want to save it
for (int i =0; i &lt;output.length; i++){
output[i] = createWriter("/Users/Dropbox/ProcessingData/positions" + nfs(i,2) + ".txt");
}
//define the sampling frequency
frameRate(200);
}
</code></pre>

<p>here the part of the code with x and y coordinates</p>

<pre><code> if(mousePressed){
      for (int i =0; i &lt;output.length; i++){
 output[i].println(mouseY + "\t" +mouseX);
 }
</code></pre>

<p>and this is the part where i save the data</p>

<pre><code>for (int i =0; i &lt;output.length; i++){
output[i].flush();
output[i].close();
}
</code></pre>

<p>any help is appreciated.</p>

<p>Thanks</p>

<p>Ivan</p>
]]></description>
   </item>
   <item>
      <title>How to stop Processing from overwriting txt file?</title>
      <link>https://forum.processing.org/two/discussion/18707/how-to-stop-processing-from-overwriting-txt-file</link>
      <pubDate>Tue, 25 Oct 2016 17:08:17 +0000</pubDate>
      <dc:creator>Mitch_</dc:creator>
      <guid isPermaLink="false">18707@/two/discussions</guid>
      <description><![CDATA[<p>Im wrote the following code but i wanna make it so that it will not overwrite the existing strings in the .txt file. Every time i run the sketch the createWriter command overwrites the .txt file. How do i make it so that it keeps the strings in the .txt file even when i run the sketch again?</p>

<p>Also i only want to print the first 10 lines of the txt file in the console when i press the ENTER key. But if the file contains only 3 lines i get an ArrayIndexOutOfBoundsException. How do i stop this from happening?</p>

<pre><code>PrintWriter history;

void setup() {
  size(700, 350);
  history = createWriter("history.txt");
}

void draw() {
}

void keyPressed() {
  if ((key=='1')) { 
    history.println("User pressed 1");
  }

  if ((key=='2')) { 
    history.println("User pressed 2");
  }

  if ((key == ENTER)) {
    history.flush(); 
    history.close();
    String[] history = loadStrings("history.txt");
    for (int i = 0; i &lt;= 9; i++) { //only print first 10 lines
        printArray("[" + i + "] " + history[i]);
    }
  }
}
</code></pre>

<p>Any help will be appreciated :)</p>
]]></description>
   </item>
   <item>
      <title>Fill() and Transform</title>
      <link>https://forum.processing.org/two/discussion/18031/fill-and-transform</link>
      <pubDate>Thu, 01 Sep 2016 12:43:00 +0000</pubDate>
      <dc:creator>phaidon</dc:creator>
      <guid isPermaLink="false">18031@/two/discussions</guid>
      <description><![CDATA[<p>Hi,why the fill and transform and rotate goes to next shape,although i used popMatrix and pushMatrix?</p>

<pre><code>import peasy.*;
import saito.objloader.*;
import spout.*;

//PrintWriter output;
OBJModel model ;
OBJModel Smodel ;
OBJModel tmpmodel ;

Spout spout;


PeasyCam cam;

float z=0;
float easing = 0.005;
float r;
float k;
int VertCount;
PVector[] Verts;
PVector[] locas;
PVector Mouse;
PVector Mouse2;

int VECS = 600;


void setup()
{
  size(800, 800, P3D);
  frameRate(30);
  noStroke();

  model = new OBJModel(this, "Model2.obj", "absolute", TRIANGLES);
  model.enableDebug();
  model.scale(200);
  model.translateToCenter();


  Smodel = new OBJModel(this, "Model2.obj", "absolute", TRIANGLES);
  Smodel.enableDebug();
  Smodel.scale(200);
  Smodel.translateToCenter();


  tmpmodel = new OBJModel(this, "Model2.obj", "absolute", TRIANGLES);
  tmpmodel.enableDebug();
  tmpmodel.scale(200);
  tmpmodel.translateToCenter();

  //output = createWriter("positions.txt"); 

  cam = new PeasyCam(this, width/2, height/2, 0, 1600);

  spout = new Spout(this);

  spout.createSender("Self");
}



void draw()
{
  background(0);
  lights();



  int VertCount = model.getVertexCount ();
  Verts = new PVector[VertCount];
  locas = new PVector[VertCount];
  r =100;
  k = k + 0.01;


PVector psVerts[] = new PVector[VECS];
PVector psVerts2[]= new PVector[VECS];


  cam.setMouseControlled(false);


  Mouse = new PVector(mouseX-width/2, mouseY-height/2, z);
  Mouse2 = new PVector(width/2 -height/2, z);





  //println(frameCount);
  pushMatrix();




  translate(width/2, height/2, 0);
  rotateY(k);


  for (int i = 0; i &lt; VertCount; i++) {
    //PVector orgv = model.getVertex(i);

    locas[i]= model.getVertex(i);
    Verts[i]= Smodel.getVertex(i);


    //PVector tmpv = new PVector();


    if (frameCount&gt; 100) {



      float randX = noise(randomGaussian());
      float randY = noise(randomGaussian());
      float randZ = noise(randomGaussian());

      PVector Ran = new PVector(randX, randY, randZ);

      //float norX = abs(cos(k)) * randX;
      //float norY = abs(cos(k)) * randY;
      //float norZ = abs(cos(k)) * randZ;









      if ((Verts[i].y &gt; Mouse.y  - r/2 &amp;&amp; Verts[i].y &lt; Mouse.y  + r/2 &amp;&amp; Verts[i].x &gt; Mouse.x  - r/2 &amp;&amp; Verts[i].x &lt; Mouse.x  + r/2 &amp;&amp; Verts[i].z &gt; Mouse.z  - 1920/2 &amp;&amp; Verts[i].z &lt;  Mouse.z  + 1920/2)||(Verts[i].y &gt; Mouse2.y  - r/2 &amp;&amp; Verts[i].y &lt; Mouse2.y  + r/2 &amp;&amp; Verts[i].x &gt; Mouse2.x  - r/2 &amp;&amp; Verts[i].x &lt; Mouse2.x  + r/2 &amp;&amp; Verts[i].z &gt; Mouse2.z  - 1920/2 &amp;&amp; Verts[i].z &lt;  Mouse2.z  + 1920/2)) {
        tmpmodel.setVertex(i, locas[i].x, locas[i].y, locas[i].z);
      } else {   



        Verts[i].x+=Ran.x;
        Verts[i].y+=Ran.y;
        Verts[i].z+=Ran.z;

        if (Verts[i].x &gt; width/2 ) {
          Verts[i].x=-width/2;
        } else if (Verts[i].x &lt; -width/2) {
          Verts[i].x=width/2;
        }
        if (Verts[i].y &gt; height/2 ) {
          Verts[i].y=-height/2;
        } else if (Verts[i].y &lt; -height/2) {
          Verts[i].y=height/2;
        }

        if (Verts[i].z &lt; -800/2 ) {  
          Verts[i].z=800/2;
        } else if ( Verts[i].z &gt; 800/2) {
          Verts[i].z=-800/2;
        }
        tmpmodel.setVertex(i, Verts[i].x, Verts[i].y, Verts[i].z);
      }
    }
    // output.println("Verts " + Verts[i] + " locas " +locas[i]);
  }

  pushMatrix();
  rotateY(-k); //-----------------HERE
  //translate(0, 0, 0);
  //rotateY(k); //
  fill(26, 59, 45);
  noStroke();
  beginShape();

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

    psVerts[i] = new PVector (Mouse.x, Mouse.y,Mouse.z);
   psVerts2[i] = new PVector(Mouse2.x, Mouse2.y,Mouse2.z);



  vertex(psVerts[i].x, psVerts[i].y, psVerts[i].z);
  vertex(psVerts2[i].x, psVerts2[i].y, psVerts2[i].z);
  vertex(noise(-width/2,+width/2),noise(-height/2,+height/2),noise(-width/2,+width/2));
  }
  endShape();
  popMatrix();


  pushMatrix();
  rotateY(-k); //-----------------HERE

  translate(Mouse.x, Mouse.y, Mouse2.z+width/2);
  rotateY(k); //-------------AND HERE

  fill(255, 0, 0);

  ellipse(0, 0, 10, 10);
  popMatrix();




  pushMatrix();
  rotateY(-k); //-----------------HERE
  fill(255, 0, 0);
  translate(Mouse2.x, Mouse2.y, Mouse2.z+width/2);
  rotateY(k); //-------------AND HERE


  ellipse(0, 0, 10, 10);
  popMatrix();


  noStroke();

  tmpmodel.draw();

  popMatrix();



  pushMatrix();
  translate(width/2, height/2, 0);
  rotateY(k);
  noFill();

  stroke(255);
  strokeWeight(7);
  box(width, height, 800);
  popMatrix();
  //output.flush(); // Writes the remaining data to the file
  //output.close(); // Finishes the file
  //saveFrame();
  println(z);

  spout.sendTexture();
}

void keyPressed() {
  if (keyCode == UP) {
    z++;
  }
  if (keyCode == DOWN) {
    z--;
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Importing serial from two processing sketches simultaneously</title>
      <link>https://forum.processing.org/two/discussion/17539/importing-serial-from-two-processing-sketches-simultaneously</link>
      <pubDate>Fri, 15 Jul 2016 06:36:42 +0000</pubDate>
      <dc:creator>yapyap</dc:creator>
      <guid isPermaLink="false">17539@/two/discussions</guid>
      <description><![CDATA[<p>Hi all, 
I currently have two Arduinos (Uno and Nano) set up to do and record different functions but running at the same time. To import the serial data to csv files, I also have two separate processing sketches, one for each corresponding Arduino, that needs to run simultaneously. The sketches are pretty much the same since it is just importing serial data and they are working fine between the Arduino to Processing. The only hiccup is that when I open the csv files, one would have successfully imported the data but the other hasn't. Is there something I might be missing? Is it possible to read two Arduino serials into one Processing sketch instead?
Thanks.</p>

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

PrintWriter output;
Serial portGenerator;  // Arduino Uno, Controlling and recording generator
String valueGenerator;
String fileName;
String timestamp;
String timer;
StopWatchTimer sw;

void setup()
{
  println(Serial.list());
  println("Generator Control");
  print("Setting up Serial ports... ");
  portGenerator = new Serial(this, "COM3", 9600);  // intialising serial to Arduino Uno
  println("Done");

  fileName = year() + nf(month(),2) + nf(day(),2) + "-" + nf(hour(),2) + nf(minute(),2) + nf(second(),2) + "_test.csv";
  sw = new StopWatchTimer();
  output = createWriter(fileName); 
  sw.start();
}

void draw()
{
  while (portGenerator.available() &gt; 0) // only when there are bytes available
  {
    valueGenerator = portGenerator.readStringUntil('\n'); // read line until \n
    timer = nf(sw.elapsedTime(), 6);
    if (valueGenerator != null)
    {
      output.print(timer);
      output.print(", ");
      output.print(valueGenerator);

      print(timer);
      print(", ");
      print(valueGenerator);
    }
  }
}

class StopWatchTimer
{
  int startTime = 0;
  int stopTime = 0;
  boolean running = false;

  void start()
  {
    startTime = millis();
    running = true;
  }

  void stop()
  {
    stopTime = millis();
    running = false;
  }

  int elapsedTime()
  {
    int elapsed;
    int elapsedSecond;
    if (running)
    {
      elapsed = (millis() - startTime);
    } else {
      elapsed = (stopTime - startTime);
    }

    elapsedSecond = (elapsed/1000);
    return elapsedSecond;
  }
}

void keyPressed()
{
  sw.stop();
  output.flush(); // Writes the remaining data to the file
  output.close(); // Finishes the file
  exit();         // Stops the program
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>how to createwrite with selection.getAbsolutePath();</title>
      <link>https://forum.processing.org/two/discussion/16889/how-to-createwrite-with-selection-getabsolutepath</link>
      <pubDate>Mon, 30 May 2016 03:53:39 +0000</pubDate>
      <dc:creator>vincent2</dc:creator>
      <guid isPermaLink="false">16889@/two/discussions</guid>
      <description><![CDATA[<p>I used the createWrite() to save my out file. I want to add the function for change folder by selectFolder() to save the file in new folder. but with fail to change folder.  I got the new folder but failed to path to createWrite(), Is there any suggestion?</p>

<p>AbsolutePath = selection.getAbsolutePath();<br />
println("new Folder = " + AbsolutePath );
fileoutput = createWriter( AbsolutePath + ADC" +str(month())+"-"+str(day())+"-"+str(year())+"_"+str(hour())+"."+str(minute())+"."+str(second())+".txt");</p>
]]></description>
   </item>
   <item>
      <title>Random Spikes in Real Time Data Graphing</title>
      <link>https://forum.processing.org/two/discussion/16416/random-spikes-in-real-time-data-graphing</link>
      <pubDate>Wed, 04 May 2016 01:25:14 +0000</pubDate>
      <dc:creator>agustinpfrpa</dc:creator>
      <guid isPermaLink="false">16416@/two/discussions</guid>
      <description><![CDATA[<p>Hi! So I am using this program to plot data from serial coming from an accelerometer connected to an Arduino. As you can see there are random spikes appearing in the plot. I know that it is not because of the data because I am looking at the data that is being transmitted and none of the points match with those in the image. Any suggestion as to what I can do to get rid of the random spikes? Thank you!</p>

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

<p>Serial myPort;        // The serial port
int xPos = 0;         // horizontal position of the graph
float inByte = 0;
int lastxPos = 1;
int lastHeight = 0;</p>

<p>void setup () {
  // set the window size:
  size(800,600);</p>

<p>// List all the available serial ports
  // if using Processing 2.1 or later, use Serial.printArray()
  println(Serial.list());</p>

<p>// I know that the first port in the serial list on my mac
  // is always my  Arduino, so I open Serial.list()[0].
  // Open whatever port is the one you're using.
  myPort = new Serial(this, "COM3", 115200);</p>

<p>// don't generate a serialEvent() unless you get a newline character:
  myPort.bufferUntil('\n');</p>

<p>//writer = createWriter("new_data.txt");
  // set inital background:
  background(0);
}
void draw () {
  // draw the line:
  stroke(255,255,255);
    strokeWeight(1);
    //delay(5);
    line(lastxPos, lastHeight, xPos, height - inByte);
    lastxPos = xPos;
    lastHeight = int(height - inByte);
if (xPos &gt;= width) {
    xPos = 0;
    lastxPos = 0;
    background(0);
  } else {
    // increment the horizontal position:
    xPos++;
  }</p>

<p>}</p>

<p>void serialEvent (Serial myPort) {
  // get the ASCII string:
  if(myPort.available() &gt; 0){
  String inString = myPort.readStringUntil('\n');</p>

<p>if (inString != null) {
    // trim off any whitespace:</p>

<pre><code>inString = trim(inString);
// convert to an int and map to the screen height:
inByte = float(inString);
//println(inByte);    
inByte = constrain(inByte, 0, 32768);
println(inByte/16384.0);
inByte = map(inByte, 0, 32768, 0, height);
</code></pre>

<p>}</p>

<p>}
}`</p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/328/WHYD2YO367A4.png" alt="RandomLines" title="RandomLines" /></p>
]]></description>
   </item>
   <item>
      <title>How to open a .txt file that I created using createWriter() at any time??</title>
      <link>https://forum.processing.org/two/discussion/16182/how-to-open-a-txt-file-that-i-created-using-createwriter-at-any-time</link>
      <pubDate>Fri, 22 Apr 2016 03:24:03 +0000</pubDate>
      <dc:creator>magc</dc:creator>
      <guid isPermaLink="false">16182@/two/discussions</guid>
      <description><![CDATA[<p>I created a .txt file using createWriter(). And I have been trying to open the .txt file that this output generates using launch(). The problem with this is that using launch() I must close the output with output.close() so I wont be able to write in the .txt file again and in my program I have information that I need to save coming constantly. So How can I open my .txt file at any time??</p>
]]></description>
   </item>
   <item>
      <title>Problem with save data from serial port</title>
      <link>https://forum.processing.org/two/discussion/14931/problem-with-save-data-from-serial-port</link>
      <pubDate>Mon, 15 Feb 2016 18:23:54 +0000</pubDate>
      <dc:creator>Pedro_Henrique</dc:creator>
      <guid isPermaLink="false">14931@/two/discussions</guid>
      <description><![CDATA[<p>Hi guys I'm new with Processing development and I having some problems. here's the issue: I'm using an Arduino to measuere temperature and just wanna to send it to Processing by serial communication and store it in to a .txt file.
I have already searched a solution in Processing tutorials and in this forum, but didn't find yet.
Any help is welcome!!
Here is my code (the comments are in Portuguese):</p>

<pre>
//Ler os dados da porta serial e salvar num arquivo .txt

import processing.serial.*;
import cc.arduino.*;

Serial portaCOM5; //Cria um objeto da classe Serial
String dados, COM5; //Dados em ASCII recebidos do Arduino
int val ;// Dados recebidos pela porta serial

//Banco de dados
PrintWriter arquivo; 

void setup ()
{
  size (200, 200);
  frameRate(10);   
  
     
   println(Serial.list ()); //Lista no Prompt de Comando todas as portas seriais disponíveis
   
   COM5 = Serial.list()[0]; //Recebe a porta USB escolhida
   portaCOM5= new Serial(this, "COM5", 9600); //taxa de transfarencia 9600bps
   portaCOM5.bufferUntil('\n');
      
        //Banco de dados:
   arquivo = createWriter("temperaturas"+"_"+month()+"-"+day()+"-"+year()+"_"+hour()+"-"+minute()+"-"+
            second()+".txt"); //cria um arquivo para armazenar as temperaturas
    
    arquivo.print("Monitoramento de Temperatura DHT11");
    arquivo.println();    
  
}

void draw()
{
  background (255); //Ajusta cor de fundo como branca
  
  }
   
void serialEvent(Serial portaCOM5)
{
  
     COM5= Serial.list()[0]; //Recebe a porta USB escolhida
       
      
  while (portaCOM5.available()&gt;0)
  {
     val = portaCOM5.readString();
     arquivo.println();
  }
         
  arquivo.flush(); // Writes the remaining data to the file
  arquivo.close(); // Finishes the file
         
}

</pre>

<p>PS: When I check the monitor serial from Arduino, the data are there, so I believe anything here is wrong.</p>

<p>Thanks!!!!</p>
]]></description>
   </item>
   <item>
      <title>Handle a huge text file without error</title>
      <link>https://forum.processing.org/two/discussion/14816/handle-a-huge-text-file-without-error</link>
      <pubDate>Mon, 08 Feb 2016 13:00:45 +0000</pubDate>
      <dc:creator>TothProc</dc:creator>
      <guid isPermaLink="false">14816@/two/discussions</guid>
      <description><![CDATA[<p>``Hi,</p>

<p>I have a huge text file with millions of point. (x,y,z). I need to transfer the data between two different software.
But the format is not same as I need. (of course'' :-)   )
I have a short code to change the file line by line. It works with approx.: 1 million point well. But if I want to test the final version, stucks somewhere. How I need to change the code to handle the huge file? The machine time is not important, but I need to be sure the code is running. (A chance of proper interrupt option to  the code would be great. (ex.: close the file properly after the press a specific key)
Thank you in advance.</p>

<p>` 
output = createWriter("result.txt");
}</p>

<p>void draw(){
  String[] ln= loadStrings("liftgate test_tab.txt");<br />
  String[] content1 = new String[2];
    String content2;
    int progress;</p>

<p>//for (int i=0; i &lt; (ln.length-1) ;i++){
for (int i=1; i &lt; (100) ;i++){
content1 =split(ln[i],",");
content2=join(content1,"\t");
progress=(i);
output.print(content2);
output.print("\n");
println(progress);</p>

<p>}
output.flush();  // Writes the remaining data to the file
output.close();  // Finishes the file
 println("vege");
 noLoop();
}
`</p>

<p>Thanks!</p>
]]></description>
   </item>
   <item>
      <title>Control de humedad, temperatura y presión desde PC con Processing</title>
      <link>https://forum.processing.org/two/discussion/14282/control-de-humedad-temperatura-y-presion-desde-pc-con-processing</link>
      <pubDate>Tue, 05 Jan 2016 23:23:55 +0000</pubDate>
      <dc:creator>MrSpock</dc:creator>
      <guid isPermaLink="false">14282@/two/discussions</guid>
      <description><![CDATA[<p>Hola.  Necesito hacer un fichero txt con los datos que mide un circuito arduino.  Por ello he pensado en hacer una pequeña aplicación para ejecutarla desde un pc con processing.  El tema es que necesito medir la humedad relativa y la temperatura por un lado, y la presión por otro lado, y recoger los datos en un fichero de texto de un ordenador.  Es evidente que necesito que se esté midiendo de forma contínua cada cierto tiempo para recoger un número de datos significativo para el estudio que debo hacer en un trabajo académico.</p>

<p>Aunque he estudiado programación en PASCAL hace ya algún tiempo, mis conocimientos de programación están bastante obsoletos, por lo cual el contacto con el JAVA y PROCESSING me está costando mucho trabajo.</p>

<p>Estudiando un poco por aquí y por allí he logrado hacer un código para un programa, pero me da problemas.  Y quisiera preguntar si alguno puede ayudarme en este proyecto, que imagino para algunos será relativamente fácil.</p>

<p>El código que he logrado hacer es el siguiente:</p>

<p>import processing.serial.*; //Importamos la librería Serial</p>

<p>Serial port; //Nombre del puerto serie</p>

<p>PrintWriter output;  //Para crear el archivo de texto donde guardar los datos</p>

<p>float valorP;//Valor de la presión<br />
float valorH;//Valor de la humedad relativa
float valorT;//Valor de la Temperatura
int index=0;</p>

<p>{
  println(Serial.list()); //Visualiza los puertos serie disponibles en la consola de abajo
  port = new Serial(this, Serial.list()[1], 9600); //Abre el puerto serie COM3</p>

<p>output = createWriter("Parametros_datos.txt"); //Creamos el archivo de texto, que es guardado en la carpeta del programa</p>

<p>size(800, 400); //Creamos una ventana de 800 píxeles de anchura por 600 píxeles de altura 
}</p>

<p>void setup()
{
port.write("p"); //Envia una "p" para que el Arduino lea la presión
}</p>

<p>{
  //Recibir datos presión del Arduino 
  if(port.available() &gt; 0) // si hay algún dato disponible en el puerto
   {
     valorP=port.read();//Lee el dato y lo almacena en la variable "valorP"
   }</p>

<p>//Visualizamos la presión con un texto
   text("Presión =",390,200);
   text(valorP, 520, 200);
   text(" hPa",547,200);</p>

<p>//Escribimos los datos de la presión con el tiempo (h/m/s) en el archivo de texto
   output.print(valorP + " hPa     ");
   output.print(hour( )+":");
   output.print(minute( )+":");
   output.println(second( ));
   output.println("");</p>

<p>}</p>

<p>{
port.write("h"); //Envia una "h" para que el  Arduino lea la humedad y la temperatura</p>

<p>}</p>

<p>void draw()</p>

<p>{
  //Recibir datos de Temperatura y Humedad del Arduino 
  if(port.available() &gt; 0) // si hay algún dato disponible en el puerto</p>

<p>{</p>

<p>//Leemos hasta que se encuentre un espacio y guardamos lo leido en Data
  Data = port.readStringUntil(" ");
   //buscamos la posición del espacio que separa 
  //los dos valores y guardamos la posición en index
  index = Data.indexOf(" ");</p>

<p>//almacenamos la primera parte del texto en valorH
  valorH= Data.substring(0,index);
  //Almacenamos la segunda parte en valorT
  valorT= Data.substring(index+1,Data.length());
}
 }
   {
     valor=port.read();//Lee el dato y lo almacena en la variable "valorH" 
   }
   //Visualizamos la humedad y la temperatura con un texto
   text("Humedad = ", 390, 300);
  [color=green] text(valorH, 520, 300);
   text(" % ", 547, 300);
   text("Temperatura = ", 630, 300);
   text(valorT, 520, 547);
   text("  ºC  ", 547, 300);[/color]
 }
      {
   //Escribimos los datos de la temperatura y la humedad con el tiempo (h/m/s) en el archivo de texto
   output.print(valorHT + "   %     ºC     ");
   output.print(hour( )+":");
   output.print(minute( )+":");
   output.println(second( ));
   output.println("");</p>

<p>}</p>

<p>void keyPressed() //Cuando se pulsa una tecla
{</p>

<p>}
  {
  //Pulsar la tecla E para salir del programa
  if(key=='e' || key=='E')</p>

<p>{
    output.flush(); // Escribe los datos restantes en el archivo
    output.close(); // Final del archivo
    exit();//Salimos del programa
  }
}</p>

<p>Pero no se si está bien porque me da varios errores.  Si alguien pudiese echar un vistazo a ver qué está mal, me sería de gran ayuda.  Muchas gracias.</p>
]]></description>
   </item>
   <item>
      <title>Why does my scale not appear at the second screen?</title>
      <link>https://forum.processing.org/two/discussion/14484/why-does-my-scale-not-appear-at-the-second-screen</link>
      <pubDate>Fri, 15 Jan 2016 22:24:31 +0000</pubDate>
      <dc:creator>lupo99</dc:creator>
      <guid isPermaLink="false">14484@/two/discussions</guid>
      <description><![CDATA[<p>So I'm kinda new to Processing and java and had to programm a plotter, which gets data from an Arduino(connected to a Pirani Gauge), converts to pressure and displays it . When the Graph has ran once trough ( xPos &gt;= width) the programm clears the screen and should draw the scale new but it doesn't. I think I didn't get the Java Structure :D 
Thank you for your help and have a nice day :)</p>

<p>Here is the Code, you may need an Arduino sending println Strings to execute it</p>

<pre lang="java">
import processing.serial.*;
Serial myPort;       
int xPos = 1;         
float inByte = 0;
float printValue = 0;
PrintWriter output;
int d  =  day();    
int m  =  month();
int y  =  year();   
int h  =  hour();
int mi =  minute();
int value = 0;
int number = 55;
int axis = 0;
int incree = 1;
int increeax = 14;
String Tag     = str(d);
String Monat   = str(m);
String Jahr    = str(y);
String Stunde  = str(h);
String Minute  = str(mi);
String End     = (".txt");
String textValue = "";
void setup () {
fullScreen(); 
String[] Date = new String[6] ;
Date[0] = Tag   ;
Date[1] = Monat ;
Date[2] = Jahr  ; 
Date[3] = Stunde;
Date[4] = Minute;
Date[5] = End;
String DateData = join(Date, ",");
output = createWriter(DateData); 
printArray(Serial.list());
   
   myPort = new Serial(this, Serial.list()[0], 9600);
   myPort.bufferUntil('\n');
   
   background(0);
  
  }
void draw () {
  
  stroke(250, 0, 0);
  line(xPos, height, xPos, height - inByte);
  
  for (int i = 0; i &lt; 1370; i = i+14) {
       stroke(#FFFFFF);
       line(0, i, width, i); 
       textSize(15);
       text(number, 10, axis);
       number -= incree;
       axis += increeax;
      }
      
  output.println(printValue +" mBar" ); 
  printValue = map(inByte, 0, 1023, 0, 10);       //auf pressure ummappen, noch formel einsetzen
  fill(0);
  noStroke();
  rect(0, 0, width, 30);
  fill(#FFFFFF);
  text("Pressure:  " + printValue    + "     mBar", width -600, 25); 
  text("Pirani gauge pressure Analyzer Ver. 1.2  Copyright 2016 L.Ponzio", width - 1300, 25);
  text("Time: " + millis()+ " mSec", width -775, 25);
  text("mBar", width-1350, 25);
  
  if (xPos &gt;= width) {
    xPos = 30;
    background(0);
     } else {
       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 = float(inString);
   // println(inByte);
    inByte = map(inByte, 0, 1023, 0, height);
  }
}
void keyPressed() {
  output.flush();  
  output.close();  
  exit();  
}
</pre>

<p>`</p>
]]></description>
   </item>
   <item>
      <title>Android Savefile,Openfile,Writefile processing 3.0.1...THE EASY WAY!!!</title>
      <link>https://forum.processing.org/two/discussion/13877/android-savefile-openfile-writefile-processing-3-0-1-the-easy-way</link>
      <pubDate>Thu, 10 Dec 2015 14:30:36 +0000</pubDate>
      <dc:creator>mod345</dc:creator>
      <guid isPermaLink="false">13877@/two/discussions</guid>
      <description><![CDATA[<p>im writing a visualiser and need save and load settings here is a quick save file function.</p>

<p>still working on the string save function and open function.</p>

<p>got this from stackoverflow works to save file to Android internal storage SDCARD.</p>

<p>import android.os.Environment;  // need this for Environment Android stuff</p>

<p>public void SaveFile() {</p>

<p>try
  { String filename="visualiser.txt"; 
  String directory = new String(Environment.getExternalStorageDirectory().getAbsolutePath() ); 
  save(directory + "/" + filename);
  }
  catch (Exception e)
{</p>

<p>} 
}</p>

<p>just call SaveFile(); or what ever you want to call it...
you will need to set sketch permissions to WRITE_EXTERNAL_STORAGE for file io.</p>

<p>anyone know of a simple method to read write load file into a string.</p>

<p>seen a few methods but it seems overly complicated.
createbuffer writebuffer etc.</p>

<p>im no expert in android or java so dont ask me how this works.
but its sort of easy to follow. ( declare name/find path/savefile/catch error etc).</p>
]]></description>
   </item>
   <item>
      <title>BufferedReader doenst read</title>
      <link>https://forum.processing.org/two/discussion/14313/bufferedreader-doenst-read</link>
      <pubDate>Thu, 07 Jan 2016 11:27:43 +0000</pubDate>
      <dc:creator>Bool</dc:creator>
      <guid isPermaLink="false">14313@/two/discussions</guid>
      <description><![CDATA[<p>Hi guys,
 it looks like my BufferedReader doesnt read my txt file.</p>

<p>Basically i want to save my Highscore in a Snake game.</p>

<p>But if I start a new game my Highscore stays always at 10! even if i reset it or
in my txt file stands other staff like 39.</p>

<p>Here my Code
</p>

<pre>
 updateHighscore(){
&nbsp;&nbsp;if(highscore &lt; s.score){
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;highscore&nbsp;=&nbsp;s.score;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Create a new file in the sketch directory
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output&nbsp;=&nbsp;createWriter(highscoreDatei);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output.println(highscore);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output.close(); // Writes the remaining data to the file &amp; Finishes the file
&nbsp;&nbsp;}
}

 importHighscore(){
//&nbsp;Open&nbsp;the&nbsp;file&nbsp;from&nbsp;the&nbsp;createWriter()

reader&nbsp;=&nbsp;createReader(highscoreDatei);
&nbsp;&nbsp;&nbsp;&nbsp;if(reader==null){ 
&nbsp;&nbsp;&nbsp;&nbsp;highscore&nbsp;=&nbsp;0;
&nbsp;&nbsp;&nbsp;&nbsp;return;
&nbsp;&nbsp;}
String zeile;
try{
&nbsp;&nbsp;zeile&nbsp;=&nbsp;reader.&gt;readLine();
}catch (IOException e){
&nbsp;&nbsp;e.printStackTrace();
&nbsp;&nbsp;zeile&nbsp;=&nbsp;null;
}
if(zeile != null){
&nbsp;&nbsp;highscore&nbsp;=&nbsp;int(zeile);
&nbsp;&nbsp;//println(highscore)
}
&nbsp;&nbsp;try{
&nbsp;&nbsp;&nbsp;&nbsp;reader.close();
&nbsp;&nbsp;}catch (IOException e){
&nbsp;&nbsp;&nbsp;&nbsp;e.printStackTrace();
&nbsp;&nbsp;}
}
</pre>

<p></p>

<p>importHighscore() is in the setup function and updateHighscore() is in my gameOver() function.
Btw the updateHighscore() function works well, the txt gets always updated.</p>

<p>Hope anyone can help me. Thanks</p>
]]></description>
   </item>
   <item>
      <title>error in processing ide for code shown.</title>
      <link>https://forum.processing.org/two/discussion/12325/error-in-processing-ide-for-code-shown</link>
      <pubDate>Mon, 31 Aug 2015 23:06:31 +0000</pubDate>
      <dc:creator>arduidiot</dc:creator>
      <guid isPermaLink="false">12325@/two/discussions</guid>
      <description><![CDATA[<p>Hi any help for this one would be much appreciated. 
ive obv picked up some kind of bad programming habit in learning at home as i get alot of null pointers, i know now why most of the time, but for some reason i just dont get why for this</p>

<pre><code>BufferedReader RootDIRcontentExtractor;
PrintWriter DIR_Line_Extracted_Output;
int n=1;
String[] Ext=new String[2];
long[] NumberOfFilesofExt;
Boolean[] UserPressedButton;
long[] Number_of_inner_directories;
int k;
String line;
StringList[] LineIndexed;
String[] pieces=new String[100];
void setup(){
size(1200,1200);

Ext[0]="exe";
Ext[1]="txt";
RootDIRcontentExtractor=createReader("C:/Users/Adam/Desktop/MAIN/LEVEL1/ROOT_DIR_LEVEL1_NAMES.txt");  
DIR_Line_Extracted_Output=createWriter("C:/Users/Adam/Desktop/MAIN/output1.txt");

}

void draw(){

 try {




    line= RootDIRcontentExtractor.readLine();
    LineHasText(line);
  } catch (IOException e) {
    e.printStackTrace();
    line = null;
  }
  if (line == null) {
    exit(); 
  } else {
   for(int j=0;j&lt;=line.length();j++){ 

    pieces = split(line," ");
    n=pieces.length;   
   for(int i=0;i&lt;=n-1;i++){  
   LineIndexed[j].append(pieces[i]);


    DIR_Line_Extracted_Output.println(LineIndexed[j]);
   }
   }
  }

}
</code></pre>

<p>this output was:</p>

<p><img src="http://forum.processing.org/two/uploads/imageupload/059/VJ63RZD6OGB4.PNG" alt="forum" title="forum" /></p>

<p>i will have a go in cmd,exe in evevalted mode and try assigning a label to the C drive, there isnt any harm in me doing this, right? i mean i can only assume that its mentioned in the verbose because its related, learning how to do all this stuff is already mind rapey at 32, it would be pure evil if they just threw unrelated commentary into the output so yea its safe to assume it wants me to label the drive, although im still not entirely clear on what that means. right?</p>
]]></description>
   </item>
   <item>
      <title>How to have data in a file without having the buffer full</title>
      <link>https://forum.processing.org/two/discussion/12646/how-to-have-data-in-a-file-without-having-the-buffer-full</link>
      <pubDate>Tue, 22 Sep 2015 21:26:18 +0000</pubDate>
      <dc:creator>AndreaRojasM</dc:creator>
      <guid isPermaLink="false">12646@/two/discussions</guid>
      <description><![CDATA[<p>I have this code, it works almost fine, it read the data at the serial and saves it in a .txt file, i run the program during 16 seconds and all i got is a 8 seconds of data, i'm quite sure there's a delay of 8 seconds (kind of) later i let the program run for 24 seconds and i get 16 seconds of data (quite sure i got a delay of 8) now i'm letting the 8 seconds, and i start to trying to obtain the data from second 8 til 15 for example and i didn't get data cuz it seemed to me that the buffer isn't full, i would like to have data without having to wait for the buffer to be completely full.</p>

<p>Any idea?
Also, any idea if it's possible for me to no wait the fisrt 8 seconds.</p>

<p>Thanks</p>

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

                Serial myPort;  // The serial port

                void setup() {

                  output = createWriter("andyPiezoBuzzerADXL335.txt");
                  // Open whatever port is the one you're using.
                  myPort = new Serial(this, "COM4", 9600);
                }

                void draw()
                {
                  while (myPort.available () &gt; 0) {
                    String inBuffer = myPort.readString();   
                    if (inBuffer != null) {  // != not equal
                      output.println(inBuffer);
                      delay(3000);
                    }
                  }


                  output.flush(); // Write the remaining data

                  output.close(); // Finish the file

                    exit(); // Stop the program
                } 
</code></pre>
]]></description>
   </item>
   <item>
      <title>How can I modify the code of saving score so it can work on Android mode?</title>
      <link>https://forum.processing.org/two/discussion/12407/how-can-i-modify-the-code-of-saving-score-so-it-can-work-on-android-mode</link>
      <pubDate>Sat, 05 Sep 2015 08:05:16 +0000</pubDate>
      <dc:creator>infsys</dc:creator>
      <guid isPermaLink="false">12407@/two/discussions</guid>
      <description><![CDATA[<p>The code works on one of my games on Java mode. But on another game that I want to run only in Android mode does not work. The code I created is:</p>

<pre><code>class Score {
  PrintWriter writer;
  String[] reader = loadStrings("scores.txt");
  int data;
  int data2;
  int data3;

  Score() {
    data  = 0;
    data2 = 0;
    data3 = 0;
  }
  Score(int receiver, int receiver2, int receiver3) {
    data  = receiver;
    data2 = receiver2;
    data3 = receiver3;
  }

  void write() {
    int[] collection = {data, data2, data3};
    writer = createWriter("scores.txt");
    for (int i = 0; i &lt; collection.length; i++)
    writer.println(collection[i]);
    writer.flush();
    writer.close();
  }

    int read() {
    int piece = 0;
    piece  = int(reader[0]);
    return piece;
  }
    int read2() {
    int piece2 = 0;
    piece2 = int(reader[1]);
    return piece2;
  }
    int read3() {
    int piece3 = 0;
    piece3 = int(reader[2]);
    return piece3;
  }
}// End Class
</code></pre>
]]></description>
   </item>
   <item>
      <title>Why can't I read a JSON file with a different program while my sketch is still open?</title>
      <link>https://forum.processing.org/two/discussion/12218/why-can-t-i-read-a-json-file-with-a-different-program-while-my-sketch-is-still-open</link>
      <pubDate>Sun, 23 Aug 2015 11:45:10 +0000</pubDate>
      <dc:creator>crowhurst</dc:creator>
      <guid isPermaLink="false">12218@/two/discussions</guid>
      <description><![CDATA[<p>I'm writing data to a JSON file in Processing with the saveJSONObject command. I would like to access that JSON file with another program (MAX/MSP) while my sketch is still open. The problem is, MAX is unable to read from the file while my sketch is running. Only after I close the sketch is MAX able to import data from my file.</p>

<p>Is Processing keeping that file open somehow while the sketch is running? Is there any way I can get around this problem?</p>
]]></description>
   </item>
   <item>
      <title>Is there a way to know when a port is connected?</title>
      <link>https://forum.processing.org/two/discussion/12142/is-there-a-way-to-know-when-a-port-is-connected</link>
      <pubDate>Tue, 18 Aug 2015 22:48:00 +0000</pubDate>
      <dc:creator>Mino32</dc:creator>
      <guid isPermaLink="false">12142@/two/discussions</guid>
      <description><![CDATA[<p>Hi guys!! I have the code bellow:</p>

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

    PrintWriter output;
    Serial myPort;    // The serial port
    PFont myFont;     // The display font
    String inString;  // Input string from serial port
    int lf = 10;      // ASCII linefeed 
    char uno = ' '; //To compare data
    boolean hay_puerto = false; //True if there are ports on the list

    void setup() 
    { 
      size(400, 200); 
      output = createWriter("data.txt"); //Create txt file
      noLoop();
`//To know if there is a port `
      String[] s  = Serial.list();
      println(s.length);
      if (s.length!=0)
      {
        hay_puerto = true;
      } else
      {
        hay_puerto = false;
      }

`//If there is a port, start connection`
      if (hay_puerto)
      {
        myPort = new Serial(this, Serial.list()[0], 9600); 
        myPort.bufferUntil(lf);
      } else
      {
        println("No serial port connected");
      }
    } 

    void draw() 
    { 
      background(0); 
      text("received: " + inString, 10, 50);
    } 

    void serialEvent(Serial p) 
    {
      uno = myPort.readChar();
      if (uno == '$')
      {
        inString = myPort.readString();

        if (inString != null) 
        {
          println(inString);
          output.println(inString);
        }
      } else
      {
        myPort.clear();
      }
      //inString = p.readString();
      redraw();
    }

    void keyPressed()
    {
      if (key=='x')
      {
        output.flush();  //writes data in the file
        output.close();  //Closes document
        exit();
      }
    }
</code></pre>

<p>My question is: Is there another way to know if the port is available? I mean, in my code I check for the size of the port list, and if it is zero it means that there is no port. If I don't do this, the program gets an error because there is no port. The problem is happen when I connect the port (while running the program), my program does not detect it so it does not do anything when I send something.</p>

<p>I hope my question is clear, and thanks :).</p>
]]></description>
   </item>
   <item>
      <title>How to append a text to a file</title>
      <link>https://forum.processing.org/two/discussion/11883/how-to-append-a-text-to-a-file</link>
      <pubDate>Wed, 29 Jul 2015 07:49:14 +0000</pubDate>
      <dc:creator>arco</dc:creator>
      <guid isPermaLink="false">11883@/two/discussions</guid>
      <description><![CDATA[<p>Hi there,</p>

<p>As seen in SaveFile2 in the example, you can save a file with PrintWriter like:</p>

<p>PrintWriter output = createWriter("log.txt"); output.println("This is a log"); output.flush(); output.close();</p>

<p>However, log.txt will be overwritten when you run this code twice. Does anyone know how to "append" text to a file?</p>

<p>Best..Yui</p>
]]></description>
   </item>
   <item>
      <title>Question about PrintWriter</title>
      <link>https://forum.processing.org/two/discussion/11190/question-about-printwriter</link>
      <pubDate>Sat, 06 Jun 2015 21:30:49 +0000</pubDate>
      <dc:creator>lolnyancats</dc:creator>
      <guid isPermaLink="false">11190@/two/discussions</guid>
      <description><![CDATA[<pre><code>    out=createWriter("highscore.txt");
  }
  void output() {
    if (gamemode==2) {

      for (int i=0; i&lt;10; i++) {
        out.println(0);
      } 

      out.flush();
    }
</code></pre>

<p>doesn't work... i am not sure why... I am trying to get it to print 10 zeros and then flush puts all of the info into the file, what am i doing wrong</p>
]]></description>
   </item>
   <item>
      <title>New file for serial data on button toggle?</title>
      <link>https://forum.processing.org/two/discussion/10481/new-file-for-serial-data-on-button-toggle</link>
      <pubDate>Thu, 23 Apr 2015 22:12:24 +0000</pubDate>
      <dc:creator>frostygoat</dc:creator>
      <guid isPermaLink="false">10481@/two/discussions</guid>
      <description><![CDATA[<p>I had an earlier question on this but it wasn't very clear and I hadn't done enough homework.</p>

<p>I'm viewing serial data from Arduino (it will be plotted but isn't here to make the example simpler). I only want to record when something interesting is happening. Record is triggered with a mouse click on a button from Processing.  The following code works great. BUT, I can only record one snippet of the data stream.</p>

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

Serial myPort;    // The serial port
int mills; 
String dataOutput;
int val;
int value;
PrintWriter output;

int rectX = 50; //button coords
int rectY = 400;
int rectW = 100;
int rectH = 50;
String command = "";
boolean canStart = true;
String timestamp;

void setup() { 
  size(1500, 480);
  println(Serial.list()); 
  myPort = new Serial(this, Serial.list()[2], 9600); 
  //output = createWriter("test.txt");
  //myPort.bufferUntil(lf); 
  //output = createWriter(timestamp + ".txt");
  timestamp = year() + nf(month(),2) + nf(day(),2) + "-"  + nf(hour(),2) + nf(minute(),2)+ nf(second(),2);
  output = createWriter(timestamp + ".txt");
} 
int getValue() {
  int value = -1;
  while (myPort.available () &gt;= 3) {
    if (myPort.read() == 0xff) {
      value = (myPort.read() &lt;&lt; 8) | (myPort.read());
    }
  }
  return value;
}
void draw() {
  background(0);

  if (canStart) {
    command = "REC";
    fill(0, 255, 0);
  } else {
    saveData();
    command = "STOP";
    fill(255, 0, 0);
  }
  noStroke();
  rect(rectX, rectY, rectW, rectH);
  fill(255);
  text(command, rectX + 30, rectY + 30);  
 }

void mousePressed() {
    if(buttonOver()){
   if(canStart){
    } else {
    output.flush(); // Writes the remaining data to the file
    output.close(); // Finishes the file
    PrintWriter output;
    }
     canStart = !canStart;
  }
}

boolean buttonOver()  {
  if (mouseX &gt;= rectX &amp;&amp; mouseX &lt;= rectX+rectW &amp;&amp; 
      mouseY &gt;= rectY &amp;&amp; mouseY &lt;= rectY+rectH) {
    return true;
  } else {
    return false;
  }
}

void saveData(){
  val = getValue();
  mills= millis();
  String[] dataOutput = {val + "," + mills};
  println(dataOutput); 
  output.println(val + "," + mills); // Write the coordinate to the file 
}
</code></pre>

<p>I really need a new createWriter to make a new file each time the button is pressed. So I tried the following:</p>

<pre><code>void saveData(){
  timestamp = year() + nf(month(),2) + nf(day(),2) + "-"  + nf(hour(),2) + nf(minute(),2)+ nf(second(),2);
  output = createWriter(timestamp + ".txt");
  val = getValue();
  mills= millis();
  String[] dataOutput = {val + "," + mills};
  println(dataOutput); 
  output.println(val + "," + mills); // Write the coordinate to the file 
}
</code></pre>

<p>This continually creates empty files, and doesn't get me where I want to be.</p>
]]></description>
   </item>
   <item>
      <title>Only first value is read correctly</title>
      <link>https://forum.processing.org/two/discussion/10200/only-first-value-is-read-correctly</link>
      <pubDate>Sun, 05 Apr 2015 20:21:38 +0000</pubDate>
      <dc:creator>kevinks</dc:creator>
      <guid isPermaLink="false">10200@/two/discussions</guid>
      <description><![CDATA[<p>So, after the selfless help from you guys I finally managed to complete my first project which reads a couple of RFID tags and stores their key. I just wanted to see the keys in the console, but except for the first value, all others are scrambled, like in one or two lines etc. And I can't find what is wrong. Please do help me out..</p>

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

<p>PrintWriter output;</p>

<p>Serial myPort;</p>

<p>void setup()</p>

<p>{</p>

<p>output= createWriter("data.txt");</p>

<p>myPort=new Serial(this,"COM1",9600);</p>

<p>}</p>

<p>void draw()</p>

<p>{</p>

<p>if(myPort.available()&gt;0)</p>

<pre><code> {


   String rfid=myPort.readString();


     if(rfid!=null)


         {


           trim(rfid); 


           output.println(rfid); println(rfid);


           logger.println(rfid);


           logger.println(" ");


                     output.flush();


                     output.close();



         }


 }
</code></pre>

<p>}</p>

<p>void keyPressed()</p>

<p>{</p>

<p>logger.flush();</p>

<p>logger.close();</p>

<p>exit();</p>

<p>}</p>
]]></description>
   </item>
   <item>
      <title>How to save keyboard input as multiple .txt files using timestamp in naming convention</title>
      <link>https://forum.processing.org/two/discussion/9963/how-to-save-keyboard-input-as-multiple-txt-files-using-timestamp-in-naming-convention</link>
      <pubDate>Sat, 21 Mar 2015 14:50:32 +0000</pubDate>
      <dc:creator>Vaun</dc:creator>
      <guid isPermaLink="false">9963@/two/discussions</guid>
      <description><![CDATA[<p>I'm at the start of an ambitious (for me) project in Processing 2 for my MA in Creative Media. I want to create a sort of chain novel where users add to a long continuous narrative, but each user's input is saved as an individual text file and printed on separate index cards.</p>

<p>My issue (first of many presumably) is when saving the individual .txt files which are a record of each user's input, I want the filename to contain the timestamp.</p>

<p>I've used textFile = textFile = createWriter(timestamp()+".txt"); as a placeholder for the moment, but this obviously isn't a 'thing'...</p>

<p>This is what I have so far <strong><em>(Code adapted from examples by Amnon available here: <a href="https://amnonp5.wordpress.com/2012/01/28/25-life-saving-tips-for-processing/" target="_blank" rel="nofollow">https://amnonp5.wordpress.com/2012/01/28/25-life-saving-tips-for-processing/</a> and Daniel Shiffman available here: <a href="http://www.learningprocessing.com/examples/chapter-18/example-18-1/" target="_blank" rel="nofollow">http://www.learningprocessing.com/examples/chapter-18/example-18-1/</a>:)</em></strong>:</p>

<pre><code>    String myText = "Give me your story.";
    String yourText = ""; // Variable to store text currently being typed
    String savedText = ""; // Variable to store saved text when control is hit
    PrintWriter textFile;

    void setup() {
      size(500, 500);
      textAlign(CENTER, CENTER);
      textSize(30);
      fill(0);
      // Create a new file in the sketch directory
      textFile = createWriter(timestamp()+".txt");
    }

    void draw() {
      background(255);
      text(myText, 0, 0, width, height);
      text(yourText, 0, 0, width, height);
      text(savedText, 0, 0, width, height);
    {
      textFile.println(savedText);
      textFile.flush();
      textFile.close();
     } 
      }

    void keyPressed() {
      if (keyCode == ENTER) {
        myText="";}
      if (keyCode == BACKSPACE) {
        if (yourText.length() &gt; 0) {
          yourText = yourText.substring(0, yourText.length()-1);
      }
      } 
      else if (keyCode == DELETE) {
        yourText = "";
      } 
      else if (keyCode != SHIFT &amp;&amp; keyCode != CONTROL &amp;&amp; keyCode != ALT) {
        yourText = yourText + key;
      }
        // If the Control key is pressed, save the String and clear it
      if (key == CODED) 
      {
        if (keyCode == CONTROL) {
        savedText = yourText;
        // Text is cleared
        yourText = ""; 
      } else {
        // Otherwise, concatenate the String
        // Each character typed by the user is added to the end of the String variable.
        yourText = yourText + key; 
      }
    }
    }
</code></pre>

<p>As you can tell I am brand-new to code and what's above is not an elegant piece of code (and probably making your eyes bleed). If you have any suggestions for making it better, or a better alternative than timestamp for naming the multiple .txt files, please let me know. Thanks in advance.</p>
]]></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>create writer creates a file at the sketch directory, how can I change the directory?</title>
      <link>https://forum.processing.org/two/discussion/9744/create-writer-creates-a-file-at-the-sketch-directory-how-can-i-change-the-directory</link>
      <pubDate>Sat, 07 Mar 2015 20:07:30 +0000</pubDate>
      <dc:creator>devonrevenge</dc:creator>
      <guid isPermaLink="false">9744@/two/discussions</guid>
      <description><![CDATA[<p>I have this:</p>

<pre><code>  //records where data is being saved to
    print("saving " + save_name +" to ..//programming_year1//io");

    //I will create a printWriter object for writing text to a file, this
    //will save me from having to first a String array as I would with 'saveStrings()'
    PrintWriter out = createWriter(save_name+".txt");
</code></pre>

<p>But its annoying that it doesn't save into a file I have stored in the sketch dorectory called 'io'</p>
]]></description>
   </item>
   <item>
      <title>[help] method to efficiently append a new line to a text file</title>
      <link>https://forum.processing.org/two/discussion/9664/help-method-to-efficiently-append-a-new-line-to-a-text-file</link>
      <pubDate>Tue, 03 Mar 2015 06:36:42 +0000</pubDate>
      <dc:creator>oat</dc:creator>
      <guid isPermaLink="false">9664@/two/discussions</guid>
      <description><![CDATA[<p>I have the following function to append a new line to an existing text file. But it doesn't seem to be efficient as it re-reads and re-writes every line each time I add a new line, especially when I need to append a lot of new lines. Can you advise an efficient way to do this? Thank you!</p>

<pre><code>// general function of appending  a new line of text to an existing text file
void appendNewLine (String _fileName, String _newLine) {
  // <a href="http://forum.processing.org/two/discussion/comment/33698" target="_blank" rel="nofollow">http://forum.processing.org/two/discussion/comment/33698</a>

  // method B:
  // text file can be put in any folder relative to the sketch folder

  String[] lines = loadStrings(_fileName);

  // create a copy of the existing file
  PrintWriter output = createWriter(_fileName);

  // write the contents of the existing file to the new one
  for (int i = 0; i &lt; lines.length; i++) {
    output.println(lines[i]); 
  }

  // append new contents to the new file
  //output.println("\n"); 

  output.println(_newLine);
  //output.flush(); // might be redundant
  output.close();
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>how to append a new line of text to an existing text file</title>
      <link>https://forum.processing.org/two/discussion/8840/how-to-append-a-new-line-of-text-to-an-existing-text-file</link>
      <pubDate>Wed, 31 Dec 2014 12:14:03 +0000</pubDate>
      <dc:creator>oat</dc:creator>
      <guid isPermaLink="false">8840@/two/discussions</guid>
      <description><![CDATA[<p>May I ask how to append a new line of text to an existing text file in processing?</p>

<p>Thanks!</p>
]]></description>
   </item>
   </channel>
</rss>