controlling servo via processing program on computer

I am having trouble getting the servo to respond to the x co-ordinate of my mouse and am not sure what i am doing wrong.

any help would be greatly appreciated.

here is the code for arduino

#include <Servo.h>

Servo servo;

String inputString = “”;

boolean stringComplete = false;

void setup() {

servo.attach(9);

Serial.begin(9600);

inputString.reserve(200);

}

[/code]

void loop() {

if (stringComplete) {

int servoval = map(stringComplete, 0, 500, 600, 2400);

servo.writeMicroseconds(servoval);

stringComplete = false;

}

else {

servo.writeMicroseconds(1700);

}

}

void serialEvent() {

while (Serial.available()) {

char inChar = (char)Serial.read();

inputString += inChar;

if (inChar == ‘\n’) {

stringComplete = true;

}

}

}

[/code]

and here is the code for processing

import processing.serial.*;

Serial myPort;

int centre = 1390;

void setup() {

size(500,500);

String portName = Serial.list()[3];```

myPort = new Serial(this, portName, 9600);

}

void draw() {

background(255, 0, 0);

if (keyPressed) {

if (key == 'c') {

myPort.write(centre);

println("1390");

}

}

if (mousePressed) {

ellipse(mouseX, mouseY, 50, 50);

int servoval = mouseX;

myPort.write(servoval);

println(servoval);

}

}

First off use the code tags to make your code more readable on the forum.

(click on)

Then I see this …

  if (stringComplete) {
    int servoval = map(stringComplete, 0, 500, 600, 2400);
    servo.writeMicroseconds(servoval);
    stringComplete = false;

But the variable stringComplete is a boolean, a 0 or 1. Didn’t you want the string read in, properly converted to an integer, be the thing “mapped” ? Shouldn’t it be …

int servoval = map(inputString, 0, 500, 600, 2400);

Next I’m a bit worried that, from what I see, the code doesn’t turn the input string into a something the map() function can use. As a test to find out where the problem lies, try replacing that line w/code with a line that just sets servoval to to “good” value, something between 0 and 500. See it that works. If so you may need to explicitly recast the string to the proper type of variable.

If none of the above works, then your Processing code is the thing to look at.