# Sampling Incoming data from serial port

**URL:** <https://discourse.processing.org/t/sampling-incoming-data-from-serial-port/26600>\
**Category:** Electronics (Arduino, etc.)\
**Created:** [December 29, 2020, 10:20pm UTC](https://discourse.processing.org/t/sampling-incoming-data-from-serial-port/26600 "2020-12-29T22:20:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![saaqib.m](https://avatars.discourse-cdn.com/v4/letter/s/ee7513/32.png) [@saaqib.m](https://discourse.processing.org/u/saaqib.m)\
**Post date:** [December 29, 2020, 10:20pm UTC](https://discourse.processing.org/t/sampling-incoming-data-from-serial-port/26600/1 "2020-12-29T22:20:16Z")

</div>

> please format code with \</\> button \* [homework policy](https://discourse.processing.org/faq/#homework) \* [asking questions](https://discourse.processing.org/t/2147)

My code takes incoming data and stores it in a table but currently it takes in all the values that come in to the serial port. I would like to make it such that for an input sampling variable, it will sample the data at regular intervals of that variable. Does anyone have any idea on how I could implement this sampling variable? So this variable would indicate when to store/save the data and print on the command window. For example a value of 1Hz would sample the incoming data a certain amount of times etc. Many thanks, this is my code:

```auto
//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(s): ";
int boxLength = 700;
int rectSize = 30;
Button save;
Button cont;
int m;

Table table;

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

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()
  background(100); // Set inital background colour
  
  grid=new Grid(0, 0, 10*Q, 12*Q);
  save=new Button(width-width/12,boxLength/10,"Save data \n in data.txt");
  
  table = new Table();
  
  table.addColumn("Signal Value: ");
  table.addColumn("Time Elapsed(s): ");
  
  //TableRow newRow = table.addRow();
  //newRow.setInt("Time Elapsed(s): ", m);
  //newRow.setString("Signal Value: ", inString);
}

void draw () {
  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);  
  m = millis()/1000;
  textSize(13);                              
  text(m,width-width/20,boxLength/2.5);
 
  save.display();
  
  if (newData) { // If there is new input data:
    stroke(255); // 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(100); // Clear the screen.
    } 
    else {
      xPos++; // Increment the horizontal position
    }
   newData = false; // Again sets new data to false
  }
}

void serialEvent (Serial myPort) {
  // get the ASCII string:
  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.
    newData = true; 
  }
  
  TableRow newRow = table.addRow();
  newRow.setInt("Time Elapsed(s): ", m);
  newRow.setString("Signal Value: ", inString);
}

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";
            //output.print("Signal Value: "); output.print("Time Elapsed(s): ");
            //output.print("\n");
            //output.print(inString); output.print(m);
            //output.println();
            
            //TableRow newRow = table.addRow();
            //newRow.setInt("Time Elapsed(s): ", m);
            //newRow.setString("Signal Value: ", inString);
            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);
          //output.print("Signal Value: "); output.print("Time Elapsed(s): ");
          //output.print("\n");
          //output.println();
          //output.print(inString); output.print(m);
          //output.println(); 
          
          //TableRow newRow = table.addRow();
          //newRow.setInt("Time Elapsed(s): ", m);
          //newRow.setString("Signal Value: ", inString);
          saveTable(table, fileName);
          
          output.close();
          qSave+=1;
          //if (qSave>10) {qSave=1;}
          save.title="Save data \n in data.txt" + "-"+qSave;
          save.click=false;
        }
  }
}

```

Button class:

```auto
class Button{
   color cor_ativo=color(0,255,0);
   color cor_fio=color(0);
   
   float x,y;
   String title;
   boolean mouseClick = false;
   boolean click = false;
   
   Button(float x, float y, String title){
     this.x = x;
     this.y = y;
     this.title = title;
   } 
   
   void display(){
     if (mouseClick){
        fill(0,100,0);
     } else if (click){
         fill(cor_ativo); //fill(0,255,0); 
      } else{
        fill(200);
      }
      stroke(cor_fio); 
      strokeWeight(1);
      fill(100);
      rect(width-width/12, boxLength/10, width/15, rectSize);
      textAlign(CENTER);
      textSize(10);
      fill(255);
      text(title,width-width/20,boxLength/8.5);
   }
   
   void mouseClick(){
     if (mouseButton==LEFT) {
       if (mouseX>(width - width/12) && mouseX<(width - width/12 + width/15) && mouseY>(boxLength/10) && mouseY<(boxLength/10+rectSize)){
          mouseClick=true;
       }
     }
   }
  
   boolean mouseClickd(){ // returns if it is clicked or not
     boolean ret=false;
     if (mouseButton==LEFT){
       if (mouseX>(width - width/12) && mouseX<(width - width/12 + width/15) && mouseY>(boxLength/10) && mouseY<(boxLength/10+rectSize)){
          click=!click;
          ret=true;
          mouseClick=false;
       }
     }
     return ret;
   }
}

```

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [December 29, 2020, 11:59pm UTC](https://discourse.processing.org/t/sampling-incoming-data-from-serial-port/26600/2 "2020-12-29T23:59:15Z")

</div>

Hello,

I posted a response here:

> [@Storing all incoming data and button not working](https://discourse.processing.org/t/storing-all-incoming-data-and-button-not-working/26398/4):
>
> Hello, Here is the simplest example of collecting data into an ArrayList of Integers. 
> 
> > **Example 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 IntList data; import processing.serial.\*; Serial myPort; // The serial port - object from serial class //String[] list = new String[3]; // For serial port int inData…

`:)`

---

<div class="post-metadata">

**Author:** ![saaqib.m](https://avatars.discourse-cdn.com/v4/letter/s/ee7513/32.png) [@saaqib.m](https://discourse.processing.org/u/saaqib.m)\
**Post date:** [December 31, 2020, 6:08pm UTC](https://discourse.processing.org/t/sampling-incoming-data-from-serial-port/26600/3 "2020-12-31T18:08:01Z")

</div>

Hi! Thank you for your response. D you know how I could implement a variable such that it becomes the sampling rate here? Many thanks
