NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Reading from serial and sending info to a text file using python?

February 16, 2011
by lcruz007
lcruz007's Avatar

Can you check my python code?? It is not working for me, info is not recorded to the text file after reading data from the serial port.

import serial
serial = serial.Serial("/dev/ttyUSB0", 115200, timeout=1)
f = open("eog.txt", "w")
while True:
 data = serial.read()
 if data == "1": f.write("1")
 f.close()
February 17, 2011
by hevans
(NerdKits Staff)

hevans's Avatar

Hi lcruz,

On the if statement the f.write() should be on the next line and indented one more level from the if statement. I don't know if it just got messed up on the copy (or if it is actually legal syntax for some reason).

There might be several issues here. Fist, it might be that you are not getting a 1 over the serial port at all so your if statement is failing. my suggestion is to skip the test and just write everything you get to the file, then you can get a better idea of what you are looking at.

Second, you seem to be closing the file as part of your while loop. This is probably not what you want, as you are likely going to be writing more than one thing, Since you close the file the first time through the loop and not open it again, you really are only attempting to write to the file once. I suggest moving the f.close() outside the whole loop, and put an f.flush() inside the while loop to flush the file buffer. Then you will have a better idea of what is going on.

Humberto

February 18, 2011
by lcruz007
lcruz007's Avatar

Humberto, Thanks for your reply!

I've tried almost everything though, changing the code, trying different algorithms, switching it etc. But none of these methods have worked. The text won't be recorded on the text file (sometimes until I close the program, but not in the while loop).

This doesn't work either:

import serial 
serial = serial.Serial("/dev/ttyUSB0", 115200, timeout=1)

f = open("file.txt", "w")

while True:
#uses the serial port
 data = serial.read()

 if data == "0": 
  f.write(data)

Any ideas? thanks!

February 19, 2011
by hevans
(NerdKits Staff)

hevans's Avatar

Hi Lcruz,

Did you try what I suggested, to just not check the data before you write it to the file?

import serial 
serial = serial.Serial("/dev/ttyUSB0", 115200, timeout=1)

f = open("file.txt", "w")

while True:
#uses the serial port
  data = serial.read()
  print data
  f.write(data)
  f.flush()

f.close()

Note I added a print to print the data out to make sure you are getting anything at all out of the serial port.

Humberto

February 17, 2012
by RevMoses
RevMoses's Avatar

Your code may be busted but it was helpful to me. The meat python code was rough because i hadn't heard of python before I got the kit. Heres the code I got working from the above. ...i did put a limit on it (20) because i'm still customizing it for what i'm doing.

import serial

serial = serial.Serial("COM4", 115200, timeout=1) i=1 while (i<20): #uses the serial port data = serial.readline() print data
i=i+1

February 17, 2012
by RevMoses
RevMoses's Avatar

Hoot! got it goin to excel. I have a simple average routine built in. Its not fancy like the moving average. But by changing the Avr=5 to a bigger value and making the while loop inifinite, i could let the thing run all night without it crashing excel's row limit of 65000.

import serial,csv
#excel stuff
from time import gmtime, strftime
resultFile=open('MyData.csv','wb')
#end excel stuff

serial = serial.Serial("COM4", 115200, timeout=1)

i=1
a=1
numberSum=0
Avr=5

while (i<Avr*4+1):
    # uses the serial port
    data = serial.readline()
    # print data

    # leaves only the numbers and converts them to float
    numbers = float(data[:-12])
    # print numbers

    if (a<Avr+1):
        numberSum=numberSum+numbers
    if (a==Avr):
        numberAv=numberSum/Avr

        #excel stuf
        RESULT=[[numberAv,strftime("%Y-%m-%d %H:%M:%S", gmtime())]]
        wr = csv.writer(resultFile, dialect='excel')
        wr.writerows(RESULT)
        #end excel stuf

        print numberAv
        a=0
        numberSum=0

    i=i+1
    a=a+1
resultFile.close()
July 15, 2012
by raildoc
raildoc's Avatar

RevMoses Any new developments on this or your Posts on 2162 and 2165? Good work! You gave me some good ideas on unipolar pulse generation and monitoring. I'm also working on a quadrature decoding and data recording set-up and a GPS with python-to-Excel programs. Incidentally, were your 'scope pics from an actual circuit or circuit/BB simulator? NK and others have good ones that specifically simulate various 5051-and PIC-type chips. These are a little easier to use than NI's MultiSim. I also use NI SignalExpress for DAQ and analysis. With Excel, have you tried an xls.VBA interface with uart? I know NK Forum doesn't like VB. But, I think it's a matter of which end of the data stream is easier to program and manipulate: PC or mcu. Thanks much for your posts.

July 16, 2012
by Ralphxyz
Ralphxyz's Avatar

"I know NK Forum doesn't like VB."

Why would the NK Forum not like VB?

It has nothing to do with the microprocessor which Nerdkits promotes.

The PC interface is whatever works best for you.

In fact if you search the NK forum I bet you will find VB Serial XLS code examples.

It might be in VBA and not the newest version of VB. I think you will find VB is welcome here.

Yes the "Nerdkits Guys" use Python but the rest of us use whatever we are comfortable with.

Ralph

July 16, 2012
by raildoc
raildoc's Avatar

Ralph: You're right. However, Arduino Forum may also be a richer source for various serial communication code posts. There is even a cheap ($3) Kindle eBook on it. Also, compiled Arduino "sketch" hex files can be seamlessly uploaded into NK. Other "5051" and 8-bit PIC sites are equally informative and also compatible with 328 C-coding. I just thought I'd expand the horizon and revisit older germane NK posts that I considered (IMHO) very good. Thanks for the follow-up.

July 18, 2012
by Ralphxyz
Ralphxyz's Avatar

Other "5051" and 8-bit PIC sites are equally informative and also compatible with 328 C-coding.

Now that would make for some interesting discusions and of course a Nerdkit Community Library article.

I would really like to know how to use a Arduino.hex and how to move code from 5051 and PIC to AVR.

Ralph

July 18, 2012
by raildoc
raildoc's Avatar

Ralph: see http://www.nerdkits.com/forum/thread/715/ for my first stumbling effort. In that case, Arduino had the perfect sketch, and I finally got it right for NK. "If the hex fits, ya gotta affix." There is other good stuff on Arduino-related sites (ADA, Smiley's, Robot this and that, etc.), even "upgrading" to REAL C code. Also, there are some good Arduino system interface/shield tools. I see from your NK posts, that you have also dabbled in this. Next step?

July 19, 2012
by Ralphxyz
Ralphxyz's Avatar

you have also dabbled in this

Dabbled is most appropiate :-)

There really should be a consolidated write up in the Nerdkits Community Library.

Some people apparently take offense at Arduino or VB for that matter, but I have nver heard Humberto or Mike put it down, they do not support it, and encourage people to use C and python but I never heard "Oh my God that is horrible you cannot use Arduino code or only a ignoramous would ever use VB what is the mattter with you?"

I think those that might be offended can just suck it up and understand it is a big world out there and different strokes for different folks.

So if you are offended, move on, ignore the thread.

Ralph

Post a Reply

Please log in to post a reply.

Did you know that you can connect a computer keyboard to your microcontroller? Learn more...