Using a keyPressed function in Processing to control a servo position in arduino

basically I want (ex. keyPressed 'k' , servo goes from '0' to '180' and back to '0' and if keyPressed 'p' servo goes from '0' to 90' and back. Is this possible? I've been trying for a few days to get processing and arduino to communicate with each other but so far no luck.
here are my codes:
ARDUINO:

#include <OscSerial.h>
#include <Servo.h>

#include <EthernetUdp.h>
#include <SPI.h>

int baudRate = 9600;
OscSerial oscSerial;

Servo myservo;
int pos = 0;

long timer;

void setup() {
Serial.begin(baudRate);
oscSerial.begin(Serial);
myservo.attach(9);
}

void loop() {
if (millis() - 100 > timer) {

oscSerial.listen();
timer = millis();
}
}

void oscEvent(OscMessage & msg) {
msg.plug("/servoContol", myFunction);
}

void myFunction(OscMessage & msg) {

int data = msg.getInt(0);
if (data == 0) {
if (pos > 180) {
for (pos = 0; pos > 180; pos += 2) {
myservo.write(pos);
delay(100);
}
delay(500);
} else {
for (pos = 180; pos < 0; pos -= 2) {
myservo.write(pos);
delay(100);
}
}
} else if (data == 1) {
if (pos > 90) {
for (pos = 0; pos > 90; pos += 2) {
myservo.write(pos);
delay(100);
}
delay(500);
} else {
for (pos = 90; pos < 0; pos -= 2) {
myservo.write(pos);
delay(100);
}
}
}
}

void sendOscSerial() {
OscMessage msg("/outgoingSerial");
msg.add(0);
oscSerial.send(msg);
}

and PROCESSING CODE: (keep in mind my serial port will be different than yours most likely)

import processing.serial.;
import oscP5.
;

int serialTimerEnd;
int serialTimerInterval = 250;
Serial proSerial;
String serialName = "COM8";
int baudRate = 9600;
OscSerial oscSerial;

void setup() {
println(Serial.list());
proSerial = new Serial(this, serialName, baudRate);
oscSerial = new OscSerial(this, proSerial);
}

void draw() {
}

void keyPressed() {
if (key == 't') {
sendOscSerial(1);
}
if (key == 's') {
sendOscSerial(0);
}
}

void oscEvent(OscMessage incoming) {
println(incoming);
}

// send OSC serial messages
void sendOscSerial(int sam) {
OscMessage msg = new OscMessage("/servoControl");
msg.add(sam);
oscSerial.send(msg);
}

Thanks a ton :slight_smile:

Why are you using OscSerial ? Would not a simple serial connection suffice ?

void loop() {
  if (millis() - 100 > timer) {

    oscSerial.listen();
    timer = millis();
  }
}

Why are you doing this? Where do you stop listening? Why?

As UKHeliBob says, ditch the useless OscSerial class on both ends. Just use Serial to send and receive characters.