// Low frequency 50% duty cycle signal
// Using the Blink Without Delay
// https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay
//
// For a motor driver, a short pulse should be enough.
// However, the minimal pulse width is not known.
float frequency = 1.0; // start with 1 Hz blinking led
unsigned long previousMillis;
unsigned long interval = 500;
void setup()
{
Serial.begin(115200);
Serial.setTimeout(50);
Serial.println( "Enter a frequency, for example: 0.25");
pinMode( 13, OUTPUT);
}
void loop()
{
unsigned long currentMillis = millis();
// ---------------------------------------------------
// Read Serial input for the frequency
// ---------------------------------------------------
if( Serial.available() > 0)
{
delay( 50); // wait for whole line to be received, delays are bad
frequency = Serial.parseFloat(); // this function can wait, delays are bad
// remove any remaining characters
while( Serial.available() > 0)
Serial.read();
Serial.print( "New frequency : ");
Serial.println( frequency);
float T = (1 / frequency) * 1000.0 * 0.5; // half T in milliseconds
interval = (unsigned long) T;
}
// ---------------------------------------------------
// millis-timer
// ---------------------------------------------------
if( currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis; // previousMillis += interval is better here
// Invert the digital output
int state = digitalRead(13);
if( state == HIGH)
state = LOW;
else
state = HIGH;
digitalWrite( 13, state);
}
}