Arduino + Processing + Servo control

Hello there!

Im new to processing and i need some help. I have written some code that works but badly. SImply all its meant to do is take the my keyboard input ( with proccessing) and based off that turn a servo left or right.

How ever i encounter a weird problem. For the servo to turn i have to press each key on the keyboard twice.... and also when i hit 'w' there is a big delay of about 2 seconds for no reason...

The processing code:

import processing.serial.*;

Serial myPort;

void setup()
{
  myPort = new Serial(this, Serial.list()[4], 9600);
  println(Serial.list());
}


void draw()
{
}


void keyPressed() {

  switch (key) {

  case 'w':
    myPort.write('1');
    break;

  case 'p':
    myPort.write('2');
    break;

  default:
    myPort.write('0');
  }
}

The arduino code:

#include <Servo.h>

Servo myServo;
int ledPin = 13;
void setup(){

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  myServo.attach(9);
  myServo.write(0);

}


void loop(){
  int val;
 
  val = Serial.read() - '0';

  while (Serial.available() == 0);

  if (val == 1){

    for (int i ; i < 180; i ++){

      myServo.write(i);
     
    }
  }
  if (val == 2){

    for (int i ; i < 180; i--){

      myServo.write(i);
    }
  }


}
  val = Serial.read() - '0';

  while (Serial.available() == 0);

Even if there is nothing to read, read a byte.

Then, wait for there to be more data.

Why?

Your arduino code is wrong. You should first check available() and then if that breaks out, read. You instead read first, without knowing whether there is something to be read.

You also should add some delay after myServo.write(i);

Thanks for the help! But if i put the val under while avaible it doesnt work at all!

I think i wrote really bad code! Could you help me out?

All i wanna do is control a servo with my keyboard input.

Thanks!!

lele_gricc:
Thanks for the help! But if i put the val under while avaible it doesnt work at all!

I think i wrote really bad code! Could you help me out?

All i wanna do is control a servo with my keyboard input.

Thanks!!

Post the code that is not working after you placed val "under while". Post it so we can point out how to correct it.

#include <Servo.h>

Servo myServo;
int ledPin = 13;
void setup(){

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  myServo.attach(9);
  myServo.write(0);

}


void loop(){
  int val;
 


  while (Serial.available() == 0);

 val = Serial.read() - '0';

  if (val == 1){

    for (int i ; i < 180; i ++){

      myServo.write(i);
     
    }
  }
  if (val == 2){

    for (int i ; i < 180; i--){

      myServo.write(i);
    }
  }


}

But so is the processing code correct?

But so is the processing code correct?

Have you tested it? You can use Serial.print() and/or Serial.println() to send data back to Processing.

for (int i ; i < 180; i ++){

You didn't assign initial value for i.
Not working = not moving, or what else?