Problems with serial port and Python

First of all I'm sorry for my bad english, hope you guys wont have problem understand me
so, the code:

/*  Serial Read.ino  */
int val = 255, bom;
void setup() {
  Serial.begin(9600);
  pinMode(9, OUTPUT);
}
void loop() {
  analogWrite(9 ,val);
  if(Serial.available()>0) {
     bom = Serial.read();
     Serial.println(bom);
     if(bom == 49){
         if(val == 0) { val = 255; } else { val = 0; }
     }
   }
}

/* Problems:

  1. When opening\closing serial monitor (COM18) window the led stops for a sec and then light up again.
  2. If sending '1' on serial monitor (in order to shut the led off) and then closing the serial monitor window the led light up again.
  3. Trying to connect to the Arduino via Python, best working code that i come up with is:
import serial, time
ser = serial.Serial('COM18', 9600)
for i in range(2):
  ser.write(1)
  time.sleep(2)

After the script stop running the led light up again, and yes, just ser.write(1) or ser.write('1') does not work by itself, don't ask me why XD */

I hope someone can help me :slight_smile:

The Arduino board automatically resets when the serial port is opened. Instructions for disabling auto-reset are here...
http://arduino.cc/playground/Main/DisablingAutoResetOnSerialConnection

There are other options than using the resistor.
In your python script, you could wait a sec after making your connection. Or a better option might be:

ser = serial.Serial('com5', 9600,timeout=1)
while 1:
  ser.write(1)
  a = ser.readline()
  if (a == 1):
    break
rest_of_your_code

I take it you can understand what that code is doing and write the appropriate code in your sketch to work with it. The jist of it is, it halts the python script until it is fully ready. Using a sleep command or some other option may not be long enough, or annoying long.
If you really don't care, you could do

ser = serial.Serial('com5', 9600,timeout=2)
ser.readline()
rest_of_your_code

Readline will block the serial port until it receives an eol or timeout. Basically the same thing as using sleep, but without having to include another library.

Coding Badly, thank you very much, now I can proceed with my project :slight_smile: