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);
}
}
}
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);
#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);
}
}
}