justStarting
Posts: 12
Joined: Fri Jul 12, 2013 12:55 am

Arduino Serial doesn't work until open Serial Monitor

Tue Jul 18, 2017 11:45 pm

Hi folks =)
So I wrote a simple serial testing script between the arduino and python. Arduino code:

Code: Select all

String inputString = "";
int led = 13;
boolean stringComplete;

void setup() {
  Serial.begin(9600);
  inputString.reserve(200);
  pinMode(led, OUTPUT);
  stringComplete = false;
}

void loop() {
  if (stringComplete) {
      Serial.println(inputString);
      stringComplete = false;
      if(inputString == "on") {
        digitalWrite(led, HIGH);
        Serial.println("woo light");
      }
      if(inputString == "off") {
        digitalWrite(led, LOW);
        Serial.println("no light");
      }
      inputString = "";
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n') {
      stringComplete = true;
      break;
    }
    inputString += inChar;
  }
}

Code: Select all

#!/usr/bin/python
import serial
import sys

if len(sys.argv) == 2:
    s = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    s.write(sys.argv[1] + "\n")
    print sys.argv[1]

had the Serial Monitor on the Arduino IDE open to test the output, everything looked great.
Rebooted.
Ran the python program and it didn't turn on the led, so I opened the arduino ide and reuploaded -> same problem.
Then I opened the serial monitor and tried to see what the output was and it started working again, and throughout several successive tests it never worked until I opened the serial monitor after a reboot. I could shutdown the monitor and it would keep working until the next reboot as well.
So my question is: how can I get it to just work correctly on a reboot without having to open the Serial Monitor? I remember something from years ago about a logic level converter working correctly for that instead of USB, but I don't know the pin configuration for rPi3 for one anyway and I'd prefer to use usb. Anyone know how to solve this?

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 1:42 am

-a- pls understand that at every power on, serial connection opened AND closed the arduino reboots.

-b- you write a oneshot python program?
you should do a s.write only inside a check if isOpen
and you need to close() the connection or the port hangs.

Code: Select all

if s.isOpen():
   s.flush()     # clear input
while s.isOpen(): # for continuous operation
#.....
if s.isOpen(): # for oneshot operation
  s.write("")
  s.close()

s.close() # forget not to close serial at end of program
-c- you can only have one program on RPI to open the port,
it needs to shut down with a clean s.close() b4 a other program can use the port.

usually my arduino python usb port program is a background operation ( could be started after boot )
and handles all usb in out from arduino
and read ( for commands ) and write for USB input.. files
i make at user ramdisk: /run/shm/
used by the operator program... what can be started and stopped independently
Last edited by KLL on Wed Jul 19, 2017 2:06 am, edited 1 time in total.

justStarting
Posts: 12
Joined: Fri Jul 12, 2013 12:55 am

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 1:49 am

Thank you for the response =) I'll go ahead and modify my python code, you're right and it being a test program is no reason for my code to be sloppy ^_^
Any idea about how to solve the problem I posted about though? Looking to have an Arduino hooked up to a headless rPi zeroW and having to buy or connect a monitor to it anytime it needs to reboot would be very inconvenient.

Edit: this problem exists until specifically the Arduino Serial Monitor opens, then all is well and it works as expected every time. The python script does not run whatsoever until that Serial Monitor is opened.
Last edited by justStarting on Wed Jul 19, 2017 2:10 am, edited 1 time in total.

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 2:08 am

justStarting wrote:Any idea about how to solve the problem
well i think that your code HANGS the USB port, so above s.close() should solve that

why you talk about monitor??
many work "headless" use putty and VNC ( from LAN ) only.

justStarting
Posts: 12
Joined: Fri Jul 12, 2013 12:55 am

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 2:17 am

Thank you for taking the time to help me ^_^ but no, even after changing the code to the following:

Code: Select all

#!/usr/bin/python
import serial
import sys

if len(sys.argv) == 2:
    s = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    if s.isOpen():
        s.flush()
        s.write(sys.argv[1] + "\n")
        s.close()
    print sys.argv[1]

the problem still persists, no serial communication with the Arduino until the Serial Monitor in the IDE is opened.

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 2:39 am

-a- again you not use the s.close() at end of program.

-b- i write that at every open AND close of the serial connection reboots the arduino.
i use only continuous open connections, so your problem is not too much known to me,
i never had the idea to do that arduino - write - from - command line like you use.
but what i do need to do is a wait 7sec ( for arduino ( leonardo / UNO different) ) bootup

Code: Select all

s = serial.Serial('/dev/ttyACM0', 9600, timeout=3)
sleep(7) 
if s.isOpen():
   s.flush()     # clear input
if s.isOpen(): # for oneshot operation
  s.write("")
  s.close()

s.close() 
-c-
justStarting wrote:no serial communication with the Arduino until the Serial Monitor in the IDE is opened.
that means what?
- - the python program never work?
- - or the python program only work after you used the monitor program??
so anyhow there is one point i not understand, you write your arduino ide monitor usage shows
serial connection, that means the port is free ( without rebooting RPI )
( you could use also any other serial program ( like minicom... ) to check )
then you must close the monitor and start the python program...

justStarting
Posts: 12
Joined: Fri Jul 12, 2013 12:55 am

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 2:57 am

ok, I fear that a translation issue may be a problem here, so I'll try to go through what's happened so far =)
Thank you KLL for all your help and your patience with me =) I was going through everything you had put so far to see if I misunderstood something or what was happening. The very first letter you put "-a-" I tested first and added this line:

Code: Select all

Serial.println("bootup complete!");
to the setup() function in the arduino and modified the python code like this:

Code: Select all

#!/usr/bin/python
import serial
import sys

if len(sys.argv) == 2:
    s = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    if s.isOpen():
        s.flush()
        s.write(sys.argv[1] + "\n")
        print sys.argv[1]
        try:
            while True:
                print s.readline()
        except KeyboardInterrupt:
            s.close()
            sys.exit()
this way I could easily read back anything the arduino was saying, and what would you know, everytime I ran the Python program it said "bootup complete!" so yep, it was resetting with every serial command, for some reason the Serial Monitor turns the arduino on for that and leaves it there.... weird. The command was being sent too fast because the arduino was rebooting. It's funny, one of the first tutorials I went through actually had the fix there and I used it on previous projects for this reason without a second thought, and now a few years later I'd forgotten it lol.
Ok, so the fix?
A 10uf capacitor between Reset and GND.
Test program just works right out the box now!
Thank you again KLL, it was your input that got the answer so I am very appreciative =)

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 3:04 am

if you need a nice desktop serial tool:

Code: Select all

sudo apt-get install -y cutecom
nano /home/pi/Desktop/cutecom.desktop

[Desktop Entry]
Type=Application
Comment=RPI serial terminal
Name=cutecom
Exec=/usr/bin/cutecom
Icon=openterm
Terminal=false
Categories=System;
StartupNotify=false
if you need something for the CLI ( like via putty ..)

Code: Select all

sudo apt-get install -y minicom
minicom -b 115200 -o -D /dev/ttyACM0
for exit use [ctrl][a][x]

User avatar
jojopi
Posts: 3274
Joined: Tue Oct 11, 2011 8:38 pm

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 6:01 am

KLL wrote:you should do a s.write only inside a check if isOpen
No way. It is far better just to write(). If you ever try to use a port that is not open, an exception will be raised. That is good, since then you will know your code has a bug.

What you propose is to have the buggy program carry on running, but not write anything. That is worse than useless.

In this case it is impossible for the port not to be open, anyway. We opened it when constructing the object, and if that had failed it would have raised an exception. Once it is open, the port cannot randomly close itself.
and you need to close() the connection or the port hangs.
All files and devices will be properly closed when the program exits.
s.flush() # clear input
flush() waits for written data to drain. To discard unread input see flushInput() or reset_input_buffer().

User avatar
KLL
Posts: 1453
Joined: Wed Jan 09, 2013 3:05 pm
Location: thailand
Contact: Website

Re: Arduino Serial doesn't work until open Serial Monitor

Wed Jul 19, 2017 6:20 am

jojopi wrote:All files and devices will be properly closed when the program exits.
where you got this info from?

so could you pls. give the OP a revised version of his program?

albertg
Posts: 2
Joined: Thu Dec 21, 2017 10:08 am

Re: Arduino Serial doesn't work until open Serial Monitor

Thu Dec 21, 2017 10:12 am

Same problem, is there a solution? I cant conclude this from previuous replies.
thks

albertg
Posts: 2
Joined: Thu Dec 21, 2017 10:08 am

Re: Arduino Serial doesn't work until open Serial Monitor

Thu Dec 21, 2017 10:39 am

A 10uf capacitor between Reset and GND. >>> Solved problem.

Return to “Beginners”