The data received on Processing is different with the data sent from Arduino

edited September 2017 in Arduino

So here is code in Arduino

int sensorPin =A0;

void setup() {                   
  Serial.begin(9600);            
}

void loop() { 
  int data=analogRead(sensorPin);
  Serial.println(data);    
  Serial.write(10);        
  delay(1);                            
}

Processing Code

import processing.serial.*;
Serial myPort;  

float data;


void setup(){
  size(800, 800);
  smooth();
  String portName=Serial.list()[4];
  myPort = new Serial(this, portName, 9600);
}

void draw() {
  if (myPort.available() > 0) {
    data = myPort.read();
    rect(width / 2, height / 2, data, data);        
    println(data);
  }
}

Answers

  • edited September 2017

    Thank you so much, It works very well. Just may I ask why my code doesn't work? When I run my code,the data in Arduino varies based on the sensor. But in Processing the data I got is complete different,I can not see any clue how it changes.

    And more over can I use the data to make some graphs in this way.

    import processing.serial.*;
    
    static final int PORT_INDEX = 4, BAUDS = 9600;
    String myString;
    float f;
    
    
    
    void setup(){
    size(800,800);
    noLoop();
    String[]ports=Serial.list();
     //printArray(ports);
     new Serial(this, ports[PORT_INDEX], BAUDS).bufferUntil(ENTER);
    
    }
    void draw() 
    { 
    background(100);
    println(myString);
    
    }
    
    void serialEvent(final Serial s) {
    myString = s.readString();
    redraw = true;
    f=float(myString);
    rect(width/2,height/2,f,f);
    
    }
    

    Sorry for keeping bothering you,thank you so much.

  • ... why my code doesn't work?

    • B/c you're reading character by character instead of grabbing the whole number. #-o
    • Serial::bufferUntil() method specifies an end-of-transmission character.
    • It means that serialEvent() is only called back when that end-of-transmission character arrives.
    • Therefore when readString() is invoked inside serialEvent(), it gets the complete buffered transmission. \m/
  • edited September 2017

    Important: Never mutate the sketch's canvas outside the "Animation Thread"! [-X
    You're invoking rect() inside serialEvent() which is run outside the "Animation Thread"! :-SS

  • Aha,,yes,, the rect should be invoked inside draw. It's all solved now!!!!so cool, Thank you so much. Learned a lot. Have a good day.

Sign In or Register to comment.