I am trying to control a servo using a mouse, I uploaded a sketch to arduino to read from serial and write to the servo and I am using a processing program to write the position of the mouse to the serial.
the thing is it doesn't work unless i used a delay function in the processing code after the serial write command for atleast 900 ms otherwise it doesn't work.
both code were tested on uno on youtube and worked very well; mine is mega 2560 but i don't think this is the issue.
my laptob is 64-bit and i am using a 32-bit version of processing because 64-bit doesn't support serial
here is the sketch on arduino
#include <Servo.h>
Servo xservo;
void setup(){
xservo.attach(9);
Serial.begin(19200);
Serial.println("Rolling");
}
void loop()
{
static int v = 0;
if ( Serial.available() > 0)
{
char ch = Serial.read();
switch(ch)
{
case '0'...'9':
v = v * 10 + ch - '0';
break;
case 'x':
xservo.write(v);
v = 0;
break;
}
}
}
and here is the processing code with delay
//Processing code:
import processing.serial.*;
int xpos=90; // set x servo's value to mid point (0-180);
int ypos=90; // and the same here
Serial port; // The serial port we will be using
void setup()
{
size(360, 360);
frameRate(100);
println(Serial.list()); // List COM-ports
//select second com-port from the list (COM3 for my device)
// You will want to change the [1] to select the correct device
// Remember the list starts at [0] for the first option.
port = new Serial(this, Serial.list()[0], 19200);
}
void draw()
{
fill(175);
rect(0,0,360,360);
fill(255,0,0); //rgb value so RED
rect(180, 175, mouseX-180, 10); //xpos, ypos, width, height
update(mouseX);
}
void update(int x)
{
//Calculate servo postion from mouseX
xpos= x/2;
//Output the servo position ( from 0 to 180)
port.write(xpos+"x");
mydelay(900);
}
void mydelay (int ms)
{
try
{
Thread.sleep(ms);
}
catch(Exception e){}
}