0

I want to send characters to Arduino serial port which makes the Arduino turn on/off an LED. Here is the code:

int led_main=8;


void setup() 
{
    pinMode(led_main, OUTPUT);

    Serial.begin(9600);
}


void loop()
{
    char chr;

    if (Serial.available())
    {
        chr = Serial.read();

        if (chr == '0')
        {
            digitalWrite(led_main, LOW);
        }
        else if (chr == '1')
        {
            digitalWrite(led_main, HIGH);
        }
    }
}

The Arduino is recognized as either /dev/ttyACM0 or /dev/ttyACM1 in my system. When I run the command echo "1" > /dev/ttyACM0, it doesn't work. But, when I open a second terminal, run tail -f /dev/ttyACM0, and then in the first terminal, run echo "1" > /dev/ttyACM0, it turns on the LED as expected. So why do I have to open a second terminal and keep monitoring the output with tail -f in order for this to work? Is there a way to do this with a single command?

1

Arduinos have auto-reset circuit to reset the board if new connection is initiated on USB. It is good for convenient upload or to reset for debugging at Serial Monitor open. But it causes troubles if you want to communicate with MCU from computer over USB from command line tools, scripts, python, C++, C#, Java. Always on new connection the board resets.

One solution is to disable the auto-reset circuit. Other option is to wait a second after the connection while the board resets.

  • Using stty -F /dev/ttyACM0 -hupcl worked (found in the link). Thanks! – CluelessNoob Dec 30 '18 at 16:20

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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