Page 1 of 1

General questions on data logging

Posted: Thu Mar 22, 2018 6:00 pm
by drsoptics
I am working on setting up a simple datalogger. The following code works in the REPL:

##################################################################################
adc = pyb.ADC('X1')

f = open('/sd/log_1.csv', 'w')

t_start = pyb.millis()

for i in range(10):
pyb.delay(1000)
dt = pyb.millis() - t_start
str = '%i, %i\n' %(dt, adc.read())
f.write(str)

f.close()
####################################################################################

If I type this in line-by-line in the REPL, it does exactly what I want, and saves to a file on the SD card the value of an ADC read.

However if I save this to main.py on the SD card, I get blinking red and green lights, indicating an error. The source can be traced back to the pyb.delay statement at the beginning of the for loop. Why would REPL and a runtime program be giving different results?

Re: General questions on data logging

Posted: Thu Mar 22, 2018 6:27 pm
by dhylands
The way that I usually debug this is to put your program into a .py file (lets say program.py) and then from the REPL do:

Code: Select all

import program
. If you do that you should see the following error:

Code: Select all

>>> import program
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "program.py", line 1, in <module>
NameError: name 'pyb' is not defined
which tells me that you're missing an import pyb statement.
The reason it works on the REPL is because any modules imported from boot.py stay in effect when you get to the command line, and boot.py has these 2 lines:

Code: Select all

import machine
import pyb
Then once importing your program does everything you want, then I go ahead and add

Code: Select all

import program
to main.py or rename program.py to main.py.

Re: General questions on data logging

Posted: Fri Mar 23, 2018 12:04 pm
by drsoptics
Thanks. I now see I also had an auto-indent error that I was not aware of inside the loop. Finally some debugging capabilities, this will help a lot!