I did some troubleshooting and I think I have a figured out the problem. Basically the logic behind my program is to move two stepper motor is the X and Y direction depending on the Xpos and Ypos of a ball sent from processing. I included an extra value for the string which returns a value when a key is released. The reason for that is to stop the stepper motors from moving when the key is released.
So to troubleshoot I displayed the values received to Arduino on an LCD.
Xpos =
Ypos =
CH =
After sometime the values get mixed up so for instance CH value might be in the Xpos so on. How could that be fixed?
Also another issue is how to carry out two function at once in Arduino like moving the two motor at the same time.
Here is my processing code, its not finished. Just checking with the Xpos only yet.
int Xpos = 0;
int Ypos = 0;
int sizeX = 800;
int sizeY = 800;
int ch = 0;
import processing.serial.*;
Serial myPort;
void setup() {
size(sizeX, sizeY);
noStroke();
String portName = Serial.list()[2];
println(Serial.list());
myPort = new Serial(this, portName, 9600);
}
void draw() {
background(123);
ellipse(Xpos, Ypos, 20, 20);
//println(Xpos);
int value1 = Xpos;
int value2 = Ypos;
int value3 = ch;
byte out[] = new byte[3];
out[0] = byte(value1);
out[1] = byte(value2);
out[2] = byte(value3);
myPort.write(out);
}
void keyPressed() {
ch = 1;
if (key == CODED) {
if (keyCode == RIGHT) {
if (Xpos < sizeX) {
Xpos = Xpos + 2;
delay(10);
}
}
if (keyCode == LEFT) {
if (Xpos >0) {
Xpos = Xpos - 2;
delay(10);
}
}
if (keyCode == UP) {
if (Ypos > 0) {
Ypos = Ypos - 1;
}
}
if (keyCode == DOWN) {
if (Ypos < sizeY) {
Ypos = Ypos +1;
}
}
}
}
void keyReleased() {
ch = 0;
}
Here is my Arduino code,it also its not finished.
#include <Stepper.h>
#define steps 660
Stepper stepperX(steps, 8, 10, 9, 11);
int currentValue = 0;
int values[] = {0, 0, 0};
//const int steps = 64;
int prev, val;
void setup() {
Serial.begin(9600);
stepperX.setSpeed(30);
lcd.begin (20, 4);
lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
lcd.setBacklight(HIGH);
lcd.home (); // go home
}
void loop() {
if (Serial.available()) {
int incomingValue = Serial.read();
values[currentValue] = incomingValue;
currentValue++;
if (currentValue > 2) {
currentValue = 0;
}
}
int Xpos = values[0];
int Ypos = values[1];
int ch = values[2];
val = Xpos; //tried multiplying with a number too so that the motor moves faster, more steps. did work sometimes
if(ch == 1){
stepperX.step(val - prev);
prev = val;
}else{
stepperX.step(0);
}
lcd.setCursor(0,1);
lcd.print(Xpos);
lcd.setCursor(0,2);
lcd.print(Ypos);
lcd.setCursor(0,3);
lcd.print(ch);
}
Any help is greatly appreciated.