I'm working on a project where mouse coordinates are read in processing, and then sent via a serial port to arduino. I'm pretty sure that the issue is how I'm sending the data, and not how its received by the arduino. The data is sent like this: x,y '/n' with the newline signaling to the arduino to start using the data. Is my Processing code wrong?
Processing code:
Serial serialPort;
void setup(){
size(100, 100);
serialPort = new Serial(this, Serial.list()[0], 9600);
}
void draw(){
int x = mouseX / 10;
int y = (100 - mouseY) / 10;
serialPort.write(x);
serialPort.write(' ');
serialPort.write(y);
serialPort.write('\n');
}
Arduino code:
#include <Servo.h>
Servo baseServo; //servo at base
Servo middleServo; //servo between links
int x;
int y;
int a = 5; //length between shoulder and elbow
int b = 5; //length between elbow and end
void setup(){
baseServo.attach(9);
middleServo.attach(11);
baseServo.write(0);
middleServo.write(0);
Serial.begin(9600);
}
void loop(){
if (Serial.available() > 0 ){
x = Serial.parseInt();
y = Serial.parseInt();
if (Serial.read() == '\n'){
float c = sqrt(sq(x) + sq(y)); //pythagorean theorem to find imaginary line c
float middleRad = acos((sq(c)-sq(a)-sq(b))/((-2)*a*b)); //law of cosines, returns angle of middle servo in radians
//law of cosines for base angle
float baseRad = acos((sq(b)-sq(a)-sq(c))/((-2)*a*c)) + atan(y/x);
//converting Radians to Degrees:
float baseDeg = baseRad*(180/PI);
float middleDeg = middleRad*(180/PI);
//writing to servos:
baseServo.write(baseDeg);
middleServo.write(middleDeg);
}
}
}