Serial interface causing interrupt

Hi!

I’m a fairly experienced programmer but new to the embedded world. At the moment I’m trying to get a basic Python<->Arduino serial communication program going.

As far as I can tell it seems to be sort of working but for some reason, the first time I initiate communication from the Python script the Arduino throws some sort of interrupt, runs the setup function again an then seems to go ahead and do all the serial communication correctly. If anyone could tell me what is going on and why that’d be brilliant.

Here’s my sketch:

const int BLUE_LED = 10;

void setup() {
  pinMode(BLUE_LED, OUTPUT);
  Serial.begin(9600); // set the baud rate
  while (!Serial) {
    ;
  }
  Serial.println("Ready"); // print "Ready" once
  digitalWrite(BLUE_LED, HIGH);
  delay(2000);
  digitalWrite(BLUE_LED, LOW);
}

void loop() {
  if(Serial.available() > 0){
    char inByte = Serial.read();
    Serial.println(inByte);
  }
  delay(100);
}

And here’s the Python script:

#!/usr/bin/env python

import serial
from time import sleep

ser = serial.Serial('/dev/ttyACM0', 9600) # Establish the connection on a specific port
counter = 48
print ser.readline()
while True:
     counter +=1
     ser.write(str(chr(counter))) # Convert the decimal number to ASCII then send it to the Arduino
     print ser.readline() # Read the newest output from the Arduino
     sleep(.1) # Delay for one tenth of a second
     if counter == 255:
        counter = 48

When I load the sketch onto the Arduino (Uno r3), the blue LED lights up for 2s like it should. Then, when I run the python script, it turns on again for 2s and then the two pieces of code go on to talk happily to eachother. What is actually going on here?

When you open the serial port, the arduino resets. You can see the same thing if you open the serial monitor in the IDE.

It's part of the Auto Reset feature that makes the Arduino easier to upload. To disable that feature you can connect a 1 to 10 uF capacitor between the Reset pin and a Ground pin. For a polarized capacitor, + to Reset and - Ground.

To upload a new sketch after this you will either have to remove/disconnect the capacitor or use the manual reset button to reset the board at the right time.

I see. Thanks!

This Python - Arduino demo may help.

Also Serial Input Basics

...R