Hello,
I got a little project where i'm trying to control a servo with a key press from the keyboard, and i made it work (partially at least),
if i press the left arrow it goes to the left and if i press the right arrow it goes to the right ,very basic stuff, but now i want it to stop when i release the key and not go all the way and i cant seem to find the right method , i dont know if its something in the processing code or in the arduino one. I'm using and arduino Leonardo board and an 6001HB servo.
Here is the processing code:
import processing.serial.*;
color fillVal = color(0,0,0); // set variable 'fillVal'
Serial port;
void setup() {
size(100, 100);
println("Available serial ports:");
println(Serial.list());
port = new Serial(this, Serial.list()[1], 9600);
}
void draw() {
background(0,0,0);
if (keyPressed == true) { // if key is pressed
fill(fillVal);
ellipse(50, 50, 50, 50);
}
else {
keyReleased();
}
}
void keyPressed() {
if (key == CODED) {
if (keyCode == LEFT) {
fillVal = color(255,255,255);
}
else if (keyCode == RIGHT) {
fillVal = color(0,255,150);
}
} else {
fillVal = 0;
}
port.write(keyCode);
if (keyPressed == false) {
port.write('0');
}
}
void keyReleased() {
port.write('0');
}
And the Arduino one:
#include <Servo.h>
Servo servo1,
int pos = 0;
const unsigned int BAUD_RATE = 9600;
char key = 0;
void setup() {
servo1.attach(2);
Serial.begin(BAUD_RATE);
}
void loop() {
if (Serial.available()) {
key = Serial.read();
if (key == byte(37))
{ //left
for(pos = 0; pos < 180; pos += 1)
{
servo1.write(pos);
delay(15);
}
}
else if (key == byte(39))
{ // right
for(pos = 180; pos >=1; pos -= 1)
{
servo1.write(pos);
delay(15);
}
}
}
}