Page 1 of 1

Writing to a local file is giving an error

Posted: Fri Oct 12, 2018 4:42 pm
by analogdiode
Hello,

I am trying to write to a local file every 100ms, and after the program has run I expect to see a txt file with numbers 0 through 99 in it. However, the text in the file stops at 5, and I cannot debug this. (The program given below is the minimum program that illustrates the issue, and my overall objective is to store data from 6 ADC inputs every millisecond for about a week on an SDCard. I am deliberately opening and closing the file at over iteration of the loop).

Hardware: Pyboard 1.1, using with OSX.

Thanks for the help!

MAIN.PY
# main.py -- put your code here!
import pyb
c = 0
while c< 100:
pyb.delay(100)
f = open('data.txt', 'a')
f.write(str(c)+'\n')
f.flush()
f.close()
c = c+1

Re: Writing to a local file is giving an error

Posted: Fri Oct 12, 2018 9:46 pm
by jickster
You should add exception handling to make sure that you’re open and your writes actually work.

This way you’ll be able to distinguish a software error from a hardware error


Sent from my iPhone using Tapatalk Pro

Re: Writing to a local file is giving an error

Posted: Fri Oct 12, 2018 11:25 pm
by analogdiode
I assume we want to add a try exception like so:
<code>
try:
with open('dat.txt', 'a') as f:
while c< 100:
pyb.delay(100)

f.write(str(c)+'\n')
f.flush()

c = c+1

f.close ()
except OSError as exc:
print("Error is:" + exc)
</code>

I tried this two ways:
(a) Name this file as main.py, and try to observe error statement on REPL: In this case the REPL hangs, but a dat.txt file is created with numbers 0 thru 5.
(b) Name this file as main1.py, and run this as "import main1" on REPL: In this case the program produces no error statement, but no dat.txt file is created.

I wonder if this is linked to the USB also being used to mount the flash. So it tried "pyb.usb_mode('VCP') in boot.py, and then later when I booted in safe mode, I find that while dat.txt is created, it's contents seem to be garbage.

Any suggestion on what I might try next? Thanks!


[quote=jickster post_id=30995 time=1539380785 user_id=3167]
You should add exception handling to make sure that you’re open and your writes actually work.

This way you’ll be able to distinguish a software error from a hardware error


Sent from my iPhone using Tapatalk Pro
[/quote]

Re: Writing to a local file is giving an error

Posted: Sat Oct 13, 2018 2:51 am
by analogdiode
Figured it out.... use of "pyb.usb_mode('VCP')" is required in boot.py, and after that to see the data collected you have to boot in safe mode. I was probably making some mistake trying to boot in safe mode.