hey everyone,
as i am working on a project, I encountered a problem with servo+processing.
i want to make a quick processing sketch that allows me click my mouse to send the XY position of the mouse to the arduino, so that the servo on the arduino can rotate correspondingly.
I can run the arduino code and type the coordinates from the serial monitor. but it doesnt work when I run the processing sketch to send the coordinates. the code of the processing seems have some problem at write() function. could you please have a look of it?
thank you !
====================here is my arduino code====================
#include <Servo.h>
const int NUMBER_OF_FIELDS = 2; // how many comma separated fields we expect
int fieldIndex = 0; // the current field being received
int values[NUMBER_OF_FIELDS]; // array holding values for all the fields
int pos[NUMBER_OF_FIELDS];
int posX = 90;
int posY = 90;
Servo myservoP;
Servo myservoT;
void setup()
{
Serial.begin(9600);
myservoP.attach(9);
myservoP.write(90);
myservoT.attach(10);
myservoT.write(90);
}
void loop()
{
if (Serial.available()){
char ch = Serial.read();
if(ch >= '0' && ch <= '9')
{
values[fieldIndex] = (values[fieldIndex] * 10) + (ch - '0');
}
else if (ch == ',')
{
if(fieldIndex < NUMBER_OF_FIELDS-1)
fieldIndex++;
}
else
{
Serial.print( fieldIndex +1);
Serial.println(" fields received:");
for(int i=0; i <= fieldIndex; i++)
{
pos[i] = values[i];
values[i] = 0; // set the values to zero, ready for the next message
Serial.println(pos[i]);
}
myservoP.write(pos[0]);
myservoT.write(pos[1]);
fieldIndex = 0;
}
}
}
====================here is my processing code====================
import processing.serial.*;
Serial port;
int valX, valY;
float val1, val2;
void setup() {
size(800, 600);
background(255);
println(Serial.list());
port = new Serial(this, "COM3", 9600);
}
void draw() {
}
void mouseClicked(){
val1 = map(mouseX,0,800,0,179);
val2 = map(mouseY,0,600,179,80);
valX = int(val1);
valY = int(val2);
port.write(valX+','+valY);
}