Receiving string via serial port and storing in a text file

This is the place for queries that don't fit in any of the other categories.

Receiving string via serial port and storing in a text file

Postby vishnuvarkala » Fri Jan 03, 2014 8:48 pm

I am using this code to send a string from arduino to PC serially via USB
Code: Select all
int i=0;
void setup(){
  Serial.begin(9600);    // Open serial connection at a baud rate of 9600
  pinMode(13, OUTPUT);   //set pin13 in o/p mode
}
void loop(){
while(1)
{
Serial.write("10.028371,76.328873");
Serial.write('\0');
delay(1000);
  }
}

I need a python code that receives this string and store it in a text file as such.The arduino is transmitting this string continuously but i need it only once in the text file. The serially transmitted data is "10.028371,76.328873". I have written the below code but am getting only unexpected values in the text file

Code: Select all
## import the serial library
import serial

## Boolean variable that will represent
## whether or not the arduino is connected
connected = False

## establish connection to the serial port that your arduino
## is connected to.

locations=['/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3']

for device in locations:
    try:
        print "Trying...",device
        ser = serial.Serial(device, 9600)
        break
    except:
        print "Failed to connect on",device

## loop until the arduino tells us it is ready
while not connected:
    serin = ser.read()
    connected = True

## open text file to store the current
##gps co-ordinates received from the rover   
text_file = open("position4.txt", 'w')
## read serial data from arduino and
## write it to the text file 'position.txt'
while ser.read():
    x=ser.read()
    print(x)
    if x=="\0":
      text_file.seek(0)
      text_file.truncate()   
    text_file.write(x)
    text_file.flush()
## close the serial connection and text file
text_file.close()
ser.close()
Last edited by stranac on Fri Jan 03, 2014 9:01 pm, edited 1 time in total.
Reason: Added code tags. Locked.
vishnuvarkala
 
Posts: 1
Joined: Fri Jan 03, 2014 8:33 pm

Re: Receiving string via serial port and storing in a text f

Postby stranac » Fri Jan 03, 2014 9:09 pm

Please read this to learn how to post code properly:
New Users, Read This

vishnuvarkala wrote:I (...) am getting only unexpected values in the text file

And what are those unexpected values?
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1144
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot], plas4844 and 4 guests