controlling two motors using mouse direction

hi

I’m trying to control two motors - x and y directions using a adafruit motor shield and mouse input in Processing [adapted from the dimmer example by David A. Mellis.

I’m having trouble getting the mouseX and mouseY values to the Arduino.

I’m trying to send them as bytes, reading them as an array.

Could someone have a quick look at my code, first time I’ve done this and I’m sure i’ve made a silly mistake somewhere.

Cheers

Tom


Arduino code

/*
xy motor control
*/

#include <AFMotor.h>

AF_DCMotor motor1(1, MOTOR12_64KHZ); // create motor #1, 64KHz pwm
AF_DCMotor motor2(2, MOTOR12_64KHZ); // create motor #2, 64KHz pwm

void setup() {
Serial.begin(9600); // set up Serial library at 9600 bps
Serial.println(“Motor test!”);

}

void loop() {

int xydata[2];
int index;

// check if data has been sent from the computer:
if (Serial.available()) {
xydata[index] = Serial.read();
index++;
Serial.print(xydata[0]);
motor1.setSpeed(xydata[0]); // set the speed to 200/255
motor1.run(FORWARD); // turn it on going forward

motor2.setSpeed(xydata[1]); // set the speed to 200/255
motor2.run(FORWARD); // turn it on going forward

Serial.print(“tick”);
}
else{
index = 0;
if((index >=1)){
index =0;
}

}
}

Processing code

// Dimmer - sends bytes over a serial port
// by David A. Mellis

import processing.serial.*;
Serial port;

void setup() {
size(256, 256);

println(“Available serial ports:”);
println(Serial.list());

// Uses the first port in this list (number 0). Change this to
// select the port corresponding to your Arduino board. The last
// parameter (e.g. 9600) is the speed of the communication. It
// has to correspond to the value passed to Serial.begin() in your
// Arduino sketch.
port = new Serial(this, Serial.list()[0], 9600);

// If you know the name of the port used by the Arduino board, you
// can specify it directly like this.
//port = new Serial(this, “COM1”, 9600);
}

void draw() {
// draw a gradient from black to white
for (int i = 0; i < 256; i++) {
stroke(i);
line(i, 0, i, 256);
}

port.write(mouseX);
port.write(mouseY);

}

I'm not sure but I think the way you manage index is the bad way. You can execute the loop a few times between two occurence of a digit receive so your index is always 0 when a new data arrive. I think you should send an end of transmission code at the very end of your transmission and use this to reset your index.

thanks, will give this a go - have found some code showing how to do it.