Hi, i am learning the serial communication by using the Arduino collect the data and use the processing to do a GUI to display the data. Here is my Arduino code and Processing code.
Arduino
#include <Servo.h>
Servo myservo;
const int trig = 11;
const int echo = 12;
float duration, distance;
void setup() {
myservo.attach(9);
pinMode(trig,OUTPUT);
pinMode(echo,INPUT);
Serial.begin(9600);
}
void loop() {
for (int i=0; i<=180;i++){
myservo.write(i);
digitalWrite(trig,LOW);
delay(2);
digitalWrite(trig,HIGH);
delay(20);
digitalWrite(trig,LOW);
duration = pulseIn(echo,HIGH);
distance = (duration*0.034)/2;
Serial.print(distance,2);
Serial.print(",");
Serial.print(myservo.read());
Serial.print("\n");
delay(30);
}
for (int i=180;i>=0;i--){
myservo.write(i);
digitalWrite(trig,LOW);
delay(2);
digitalWrite(trig,HIGH);
delay(20);
digitalWrite(trig,LOW);
duration = pulseIn(echo,HIGH);
distance = (duration*0.034)/2;
Serial.print(distance,2);
Serial.print(",");
Serial.print(myservo.read());
Serial.print("\n");
delay(30);
}
}
Processing
import processing.serial.*;
Serial myPort;
float distance,degree;
void setup(){
//fullScreen();
myPort = new Serial(this,"COM4",9600);
}
void draw(){
if (myPort.available() > 0){
String dis_and_deg = myPort.readStringUntil('\n');
//print(dis_and_deg);
String[] list = split(dis_and_deg,',')
distance = float(list[0]);
degree = float(list[1]);
print(distance + " cm " + degree + " degree \n");
}
}
I cant understand why i change my processing code like below and then the degree will became 0 can someone help me to explain how it happen?
import processing.serial.*;
Serial myPort;
float distance;
int degree;
void setup(){
//fullScreen();
myPort = new Serial(this,"COM4",9600);
}
void draw(){
if (myPort.available() > 0){
String dis_and_deg = myPort.readStringUntil('\n'); // cant use readString() because once used readString(), the parameter of split(value,delimiter) got 2 delimiter ("," and "\n") since there is two delimieter therefore error.
//print(dis_and_deg); // Check the string is correct or not.
String[] list = split(dis_and_deg,','); // also can try substring() to split the string.
distance = float(list[0]);
degree = int(list[1]);
print(distance + " cm " + degree + " degree \n"); // Check the variable distance and degree correct or not.
}
}