Go Down

Topic: Processing to Arduino serial communication problem (Read 187 times) previous topic - next topic

tinkerkid

Dec 30, 2015, 08:47 pm Last Edit: Dec 30, 2015, 09:03 pm by tinkerkid
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:
Code: [Select]
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:
Code: [Select]
#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);
    }
    }
  }

Robin2

You may like to try the examples in Serial Input Basics - probably the second one. Simple reliable, non-blocking ways to receive data. There is also a parse example

...R
Two or three hours spent thinking and reading documentation solves most programming problems.

PaulS

Use Serial.print() to print data to the serial port. Use a serialEvent() method in Processing to read what you print from the Arduino.

Make sure that you are reading what you think you are sending.

The trig functions on the Arduino take values in radians. Are the values you are passing in radians, rather than degrees?

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy