General questions on data logging

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
drsoptics
Posts: 2
Joined: Thu Mar 22, 2018 5:55 pm

General questions on data logging

Post by drsoptics » Thu Mar 22, 2018 6:00 pm

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?

User avatar
dhylands
Posts: 2708
Joined: Mon Jan 06, 2014 6:08 pm
Location: Shuswap, BC, Canada
Contact:

Re: General questions on data logging

Post by dhylands » Thu Mar 22, 2018 6:27 pm

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.

drsoptics
Posts: 2
Joined: Thu Mar 22, 2018 5:55 pm

Re: General questions on data logging

Post by drsoptics » Fri Mar 23, 2018 12:04 pm

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!

Post Reply