I've been experimenting with mapping a joystick to a servo (through a java application), and have been able to do it. Though, when I try to map a button to an LED, the light works, but the servo doesn't. here's my code so far:
You read the serial character and compare it to 200. But you never store the character. The next serial read tries to get the next character off the incoming serial stream.
if(Serial.available() > 0){
char c = Serial.read();
if(c == 200){
led = !led;
}else {
servo.write(c);
}
Thanks for the input, but its not working.
I've figured between the two posts that it was because the serial port in the java code and the arduino were out of sync, but I thought that MorganS's code would have sorted that out.
Another thing I've found is that the servo might have trouble getting the input from a character instead of an int.
If you want to see my java code for any problems, it's under the testing folder and releases here.
I don't see why it wouldn't work. The Java code is fine, I've checked that.
Well, you have made a bad assumption somewhere. Get your arduino code working with the serial monitor first, then compare that to the output of the java code.
On the serial monitor, there were QUITE a few problems (on the arduino side). When I opened it up, it started spamming ÿ. I looked up a fix, and replaced the if (Serial.available()) {...
with while(!Serial.available()); and that cleared that up.
Though, when I manually entered numbers (I was printing what was being read by the uno) they came out different. Here's what was printed vs. what I was submitting.
What really confused me was when I entered 10, it submitted 2 numbers.
I'm guessing this is the code for a character, based on the fact that 10 has 2 digits, and it has 2 separate numbers.
What really confused me was when I entered 10, it submitted 2 numbers.
Are you aware that the arduino only reads one byte at a time from the serial input buffer. Below is very basic servo code that captures the bytes in to a String, then converts the captured numeric String into a number.
//zoomkat 7-30-10 serial servo test
//type servo position 0 to 180 in serial monitor
// Powering a servo from the arduino usually *DOES NOT WORK*.
String readString;
#include <Servo.h>
Servo myservo; // create servo object to control a servo
void setup() {
Serial.begin(9600);
myservo.attach(9);
Serial.println("servo-test"); // so I can keep track of what is loaded
}
void loop() {
while (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the String readString
delay(2); //slow looping to allow buffer to fill with next character
}
if (readString.length() >0) {
Serial.println(readString); //so you can see the captured String
int n = readString.toInt(); //convert readString into a number
Serial.println(n); //so you can see the integer
myservo.write(n);
readString="";
}
}