FlickerShow wrote:
My current problem is that when I send out an impulse, it's verifies the wrong integer, and sends the same wrong integer to the servo. Here's my serial code
What do you mean by "wrong integer"? What do you send to the Arduino, and how? Your code just reads one byte/character, which means that your pulse can only be between 0 and 255 microseconds. Doesn't sound right to me. If you want to enter a number in the Arduino serial console and set the pulse width to this number, you need to read a string and then convert it to an int. Something like this:
#define SERVOPIN 8
void setup()
{
pinMode(SERVOPIN, OUTPUT);
Serial.begin(9600);
}
void loop()
{
int pos;
// Read the pulsewidth from the serial port
pos = read_pulsewidth();
Serial.println(pos); // For debugging purposes
// Pulse the servo
digitalWrite(SERVOPIN, HIGH);
delayMicroseconds(pos);
digitalWrite(SERVOPIN, LOW);
delay(20);
}
// Wait until four numeric characters has been received
// on the serial port. Return the integer value of the
// string.
int read_pulsewidth(void)
{
char buffer[] = "0000", *p = buffer;
while(*p != '\0')
{
char c = Serial.read();
if (c >= '0' and c <= '9')
*p++ = c;
}
return atoi(buffer);
}
This (untested! Don't have an Arduino available at work...) code waits until you've entered a four digit number (so 795 must be entered as 0795) on the Arduino serial console. Then it pulses the servo once, before waiting for a new command. This is what your code did, except it only read one byte.
I don't know if you can get away with just sending one pulse though, or if the servo requires a steady train of pulses. If it does, then loop() should look something like this instead:
void loop()
{
static int pos = 600;
// Read the pulsewidth from the serial port
if (Serial.available())
{
pos = read_pulsewidth();
Serial.println(pos); // For debugging purposes
}
// Pulse the servo
digitalWrite(SERVOPIN, HIGH);
delayMicroseconds(pos);
digitalWrite(SERVOPIN, LOW);
delay(20);
}
Still a bit fragile (if you enter anything else than four numeric characters before pressing Enter on the console, this code will loop in read_pulsewidth()) but good enough for testing I think.
Btw I think there's too much comments in your code, every line was commented. This is unnecessary if you use descriptive names for all variables/constants/functions. Ideally each function should do just one really focused task, and a brief comment that describes the purpose of the function is enough. The code should speak for itself.