Using Arduino for timer and using 2 readstringuntill

please format code with </> button * homework policy * asking questions

Hi, in my code I am trying to implement a sampling rate to sample the incoming data from my Arduino.
Right now, my Arduino code has a timer of 1.5 s to print the sampled data to the serial port to Processing, but also printing ALL the data (at the beginning of the void loop) to Processing as well.

In my Processing code the section with the **** ***** is the most relevant to look at. I am trying to implement two readstringuntil(), one for each new line and one after DELAY_TIME, but it isnt working. ESSENTIALLY, what I am wanting to do is read all the data from the port so the Processing code can plot it, AND use the second printed value (the sampled value) from the Arduino code, read it and then store it as sampleVal. Any help would be appreciated!

Arduino code:

#include <SoftwareSerial.h> 
int x;                                  //Initialsing x
int analog_output;                         //Serial Read output
int sample_output;
int r_pin = A0;                              //Initialising output pin
unsigned long delayStart = 0;   // the time the delay started
unsigned long DELAY_TIME = 1500;
bool delayRunning = false;      // true if still waiting for delay to finish
int value;

void setup() {              
  Serial.begin(9600);           // Starting serial communication at 9600 Baud Rate
  delayStart = millis();      //start delay
  delayRunning = true;
}

void loop() {
  analog_output = analogRead (r_pin);    // Reading from the resistor
  Serial.println (analog_output);        // Sending the output to Processing IDE
//  delay(100);

  if (delayRunning && ((millis() - delayStart) >= DELAY_TIME)) {
    sample_output = analogRead (r_pin);
    value = Serial.println (sample_output);   
    delayStart += DELAY_TIME;              // this prevents drift in the delays
  }
}

Processing code:

//This program takes ASCII-encoded strings
//from the serial port at 9600 baud and graphs them. It expects values in the
//range 0 to 1023, followed by a newline, or newline and carriage return
import processing.serial.*;

Serial myPort;                           // The serial port - object from serial class
String[] list = new String[3];           // For serial port
boolean newData = false;                 // Sets incoming data to false at the beginning
float inByte;                            // For incoming serial data
int xPos = 0;                            // Horizontal position of the graph (from bottom of screen) 
String inString;                         // Data recieved from serial port
int lastxPos=0;                          // X position from (0,0) of graph 
int lastheight=700;                      // Y position from (0,0) of graph 
                                         // - (Also Y length of graph)
                                         // Note: This number should be the Y value of the size() function in void setup()
int X = 1000;                            // X length of graph                     
                                         // Note: This number should be the X value of the size() function in void setup()
int halflength = X/2;       
String Title = "Signal";                 // Sets Title of Graph 
                                         // Note: Please change this to suit experiment
String Timer = "Time Elapsed: ";
int boxLength = 700;
int rectSize = 30;
Button save;
Button cont;

int min;
int sec;
int millisec;
int msec = millis()/1000;
float Sfreq = 1;
//float TSfreq = 1/Sfreq;

Table table;

Grid grid;
float Q = 45.0;
int qSave = 0;
boolean outputOpen = false;
PrintWriter output;

float zoom;

String txt;
int value;
int DELAY_TIME = 1500;

//****************************************************************************************
void setup () {
  size(1000, 700);                               // Set the window size:   
  smooth();
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);    // A serialEvent() is generated when a newline character is received
  myPort.bufferUntil('\n');                     // Sets a specific byte to buffer until before calling serialEvent()
  myPort.bufferUntil(DELAY_TIME);
  background(0);                              // Set inital background colour
    
  zoom = 1.0f;
  
  grid=new Grid(0, 0, 1000,705);
  save=new Button(width-width/12,boxLength/10,"Save data \n in data.csv");
  
  table = new Table();
  
  table.addColumn("Time Elapsed: ");
  table.addColumn("Signal Value: ");
  
  frameRate(60);
}

void serialEvent (Serial myPort) {
  // get the ASCII string:
  value = myPort.read();
  inString = myPort.readStringUntil('\n');
  println(inString);
  if (inString != null) {
    inString = trim(inString);                // trim off whitespaces.
    inByte = float(inString);                 // convert to a number.
    inByte = map(inByte, 0, 1023, 0, height); // map to the screen height.
    //data.append(int(inString));
    newData = true; 
  }
  
  String sampleVal = myPort.readStringUntil(DELAY_TIME);
  
  TableRow newRow = table.addRow();
  newRow.setString("Time Elapsed: ", txt);
  newRow.setString("Signal Value: ", sampleVal);
 
  //delay(100); //100 gives only 1 time stamp
  
}
//******************************************************************************
void draw () {
  //grid.display();
  stroke(0);
  line(width - width/10,0,width - width/10,boxLength);
  fill(255);
  rect(width-width/10,0,width/10,boxLength);
  
  fill(255);                                         // These few lines draws on screen text
  //textSize(20); 
  //textAlign(CENTER);                                 //Centre's Title
  //text(Title, halflength, 30);
  stroke(100);
  fill(0);                                  
  textSize(13);                              
  text(Timer,width-width/20,boxLength/3);
  fill(0);  
  
  int m = millis(), sec = floor(millis()/1000) % 60, min = floor(floor(millis()/1000)/60) % 60, hr = floor(floor(floor(millis()/1000)/60)/60) % 24, d = floor(floor(floor(floor(millis()/1000)/60)/60/24)),y = floor(floor(floor(floor(millis()/1000)/60)/60/24)/365);
  //println("Days:",nf(d,2),("(Y:"+y+",D:"+d%365+")"),"Hr:Min:Sec",nf(hr,2)+":"+nf(min,2)+":"+nf(sec,2));
  millisec = m/(10*10) - (m/(10*10)/ 10)*10;
  textSize(13);            
  txt = nf(hr,2)+":"+nf(min,2)+":"+nf(sec,2)+":"+millisec;
  text(txt,width-width/20,boxLength/2.5);
 
  save.display();
  
  if (newData) {                                        // If there is new input data:
    stroke(204,102,0);                                        // Stroke color
    strokeWeight(2);                                    // Stroke wider
    line(lastxPos, lastheight, xPos, height-inByte);    // Draw line
    lastxPos = xPos;                                    // Allows for continuous signals
    lastheight= int(height-inByte);

    if (xPos >= width-width/10) {                       // At the edge of the window, go back to the beginning
      xPos = 0;
      lastxPos= 0;
      background(0);                                  // Clear the screen.
    } 
    else {
      xPos++;                                           // Increment the horizontal position
    }    
    newData = false;                                     // Again sets new data to false
  }
}

void mouseClicked(){{
        if (save.click){
          if (outputOpen==false){ // if is not recording then start recording
            String fileName ="dataf"+"_"+nf(year(),4)+"_"+nf(month(),2)+"_"+nf(day(),2)+"_"+nf(hour(),2)+"_"+nf(minute(),2)+"_"+nf(second(),2)+".csv";
            output=createWriter(fileName);
            outputOpen=true;
            save.title="saving";
     
            saveTable(table,fileName);
       
            qSave=0;
            // when entering each data in the stream write to output.print ()
            // write to the entry routine
          } else { // save is already recording, so stop recording
            output.close();
            outputOpen=false;
            qSave=1;
            //if (qSave>10) {qSave=1;}
            save.title="Save data \n in data.txt" + "-"+qSave;
            save.click=false;
          }
        } else {
          String fileName ="data"+"_"+nf(year(),4)+"_"+nf(month(),2)+"_"+nf(day(),2)+"_"+nf(hour(),2)+"_"+nf(minute(),2)+"_"+nf(second(),2)+".csv";
          output=createWriter(fileName);
          
          saveTable(table,fileName);

          output.close();
          qSave+=1;
          //if (qSave>10) {qSave=1;}
          save.title="Save data \n in data.txt" + "-"+qSave;
          save.click=false;
        }
  }
}

I don’t get it… why do you print at “machine gun speed” (every loop - thousands times per second) the outcome of analogRead (r_pin) and then only every 1.5s the same reading?

Also communicating at 9600 bauds between two computers used to be the norm 40 years ago… nowadays you could do 1,000,000 bauds between your Arduino and Processing… that would probably help.

The second thing is that Serial is an asynchronous protocol. I would discourage the use of readBytesUntil() or readStringUntil() or at least you should handle the fact those function can return null.

My advice would be to read data when it arrives, byte by byte and build up your buffer and once you’ve got your ‘\n’ parse the data.