Man, that timing loop is just not going to be accurate. It depends on a delay that's truncated to ms, and the time it takes to read bytes off the serial will also factor into it.
replace this code:
digitalWrite(pin, HIGH);
delayMicroseconds(pulseTime);
digitalWrite(pin, LOW);
delay(10-(pulseTime/1000));
with:
// OUTSIDE THE loop(), IN YOUR ***GLOBAL VARIABLE DECLARATIONS***
uint32_t pulseChangeUs;
// INSIDE THE loop(), REPLACING THE CODE ABOVE
if(digitalRead(pin) == LOW) {
if(micros() - pulseChangeUs >= pulseTime) {
digitalWrite(pin, LOW);
pulseChangeUs += pulseTime;
}
}
else {
if(micros() - pulseChangeUs >= 10000L - pulseTime) {
digitalWrite(pin, HIGH);
pulseChangeUs += (10000L - pulseTime);
}
}
You may be able to imprive it a smidge by precalculating 10000-pulseTime and having two variables.
Note that pulseChangeUs is advanced by the time that should have elapsed, rather than the time that did elapse. This means that the timing ignores delays caused by serialRead
Note that I put 'Us' on the end of my varibales to indicate microseconds. This saves confusion.
Consider using a higher baud rate on your serial. You can see in the dropdown on the ardiuino serial monitor what baud rates it can cope with.
If this fixes your problem, the hunnert bucks goes to my paypal pmurray@bigpond.com
.