Arduino-SuperCollider reading button state problem

Hello all,

I was wondering if any user with SuperCollider+Arduino experience could shed a light to the problem I'm having with the code below? Basically, all I'm trying to do is to send data to SC from Arduino when a button is pushed. For some reason it keeps sending the same data, which, in this case, is the one that's set to be sent when the button is NOT pushed.

Here is the Arduino code:

const int buttonPin = 2;
const int ledPin =  13;

int buttonState = 0;

void setup() {

  pinMode(ledPin, OUTPUT);

  pinMode(buttonPin, INPUT);
  Serial.begin(115200);
}

void loop() {

  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH) {

    digitalWrite(ledPin, HIGH);
    Serial.print(10);
  }
  else {

    digitalWrite(ledPin, LOW);
    Serial.print(5);
  }
}

and here's the SC code:

p = SerialPort( "/dev/tty.usbserial-A800eI4B", 115200, crtscts:true);

r = Routine {
loop {
p.next.postln;
1.wait;
}
}.play;

r.stop; p.close;

The Arduino code is working, i.e. it turns on/off the LED connected to pin 13. However, no matter what the state of the button is, all it sends to SC is "5". Any idea as to what I might be doing wrong?

Thanks so much!

Taylan

tcihan,

Your Arduino sketch looks correct. However, you have to realize that it's going to be sending out about 11,500 characters per second. If you let it run for one second before you press the button, it will already have sent the numeral '5' 11,500 times. Are you waiting for all of those characters to be processed on your server before looking for a '10'?

As a quick test, you could hold the button down while you restart the Arduino. Then, it will send '10' more than 5,000 times per second until you release the button.

You could use 'delay()' to slow down your loop, or better yet, see the Blink Without Delay example sketch to see how to do it without delays.

Regards,

-Mike

Got it! By using delay I was able to get the data I want with a little bit of delay, which is totally acceptable. I will check the Blink example, though, but at least I've got something working for now!

Thanks a million, Mike!

Taylan