0

I need to input config parameters from serial input. After a period (1 min) with no input I would like the program to start with preconfigured parameters.

Currently in the loop() section I use Serial.available, which stops until it receives new data.

How can I implement that?

void loop() {
  // read serial input
  if (Serial.available() > 0) {
    inChar = (char)Serial.read();
    inputString += inChar;
1

The Serial.available function does NOT block execution. If you want to try, upload this

unsigned long lastTime;
#define LED1 5
#define LED2 13

void setup() {
  Serial.begin(9600);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
}

void loop() {
  if (Serial.available() > 0)
  {
    Serial.read();
    digitalWrite(LED1, !digitalRead(LED1));
  }
  if ((millis() - lastTime) > 500)
  {
    lastTime = millis();
    digitalWrite(LED2, !digitalRead(LED2));
  }
}

You will see led on pin 13 to turn on and off even if the serial port buffer is empty.

Maybe your problem is somewhere else. Anyway what you want can be solved this way:

void setup()
{
    Serial.begin(9600);

    // Wait for one minute - millis is started at 0, so there's no
    // need to store the initial value of the waiting time
    boolean receivedConfiguration = false;
    while ((!receivedConfiguration) && (millis() < 60000))
    {
        if (Serial.available() > 0)
        {
            // There's some data; parse it

            if (__receivedDataIsComplete)
            {
                __myConfiguration = __configurationFromSerial;

                receivedConfiguration = true;
            }
        }
    }
    if (!receivedConfiguration)
    {
        __myConfiguration = __defaultConfiguration;
    }
}

In this setup function, the microcontroller waits for one minute. If it receives the data it ends the waiting time and uses that configuration, otherwise restores the default one and goes on. In your loop you can then use the configuration.

Please note that the variables starting with a double underscore (__) are false variables, you will have to fill with the proper code and/or variables

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.