send string to serial
Question: Buongiorno, I'm trying to send a simple string to a serial port to command an
instrument for noise measures.  
The strings are very easy:  
"M 1" = instrument on  
"M 2" = instrument off  
"M 3" = begin the measure  
"M 4" = stop the measure  

I've found this program:

    
    
    import serial
    
    ser = serial.Serial(0)  #Seleziona la porta seriale COM4
    ser.baudrate = 9600 #Imposta il baudrate a 9600bps
    
    ser.open() #apre la porta com
    ser.close() 
    #verifica se la porta e' aperta
    if ser.isOpen():
       com_num = ser.portstr
       print ("Porta " + com_num + " aperta")
       #invia il comando alla seriale
       buffer = "M 3"
       ser.write(buffer)     
       #Loop d'attesa caratteri
       num = 0
       while num == 0:
           num = ser.inWaiting()
       #scarica il buffer della seriale
       buffer = ser.read(num)
       print ("Dati ricevuti dalla seriale:")
       print buffer
       ser.close()             #chiude la porta
    else:
       print ("Porta seriale gia' in uso o inesistente") 
    s = raw_input("digita INVIA per uscire")
    

USING LINUX  
The program is ok and I have only some problems with the type of string. In
fact I had to insert a carriage return but I can't to do it.  
I said that the program is okay because the instrument turn from off to on
when I made my first connection, and on video I read "Porta /dev/ttyS= aperta"
thet means "open". But this appens for any kind of string I send. In fact this
is like an "iniatilization" of the port, not a really communication.  
Then I don't manage to send string in the correct way, may be for the problem
of carriage return.

USING WINDOWS  
I can't open the port, I have an error of Denied Access to the port, this is
the error:  
` Traceback (most recent call last):  
File "C:/d.py", line 9, in  
ser.open() #apre la porta com  
File "C:\Programmi\Python26\lib\site-packages\serial\serialwin32.py", line 53,
in open raise SerialException("could not open port %s: %s" % (self.portstr,
ctypes.WinError())) serial.serialutil.SerialException: could not open port
COM1: [Error 5] Accesso negato.`

Can you help me to:  
1\. Manage to run the program under windows  
2\. Manage to give in the exactly way the string with carriage return???  

Thak you very much.  
Stefano


Answer: To add the carriage return just append `\r` to your string, or perhaps, it may
need a carriage return/linefeed `\r\n`, which some systems use to mark the end
of line. Of course, it may only need a linefeed. In that case, you would
simply use `\n`.

    
    
    buffer = "M 3\r"
    

or

    
    
    buffer = "M 3\r\n"
    

or

    
    
    buffer = "M 3\n"
    

You might find the [pySerial](http://pyserial.sourceforge.net/) documentation
of help in resolving your Windows issues.

