not logged in | [Login]

(Construction) Examples on how to use the SD card.

Reading files from the SD card

Conflict about SD card access when connected to host machine. It is mounted as a Drive, but if it is mounted as a drive then it's not available for the embedded CPU to use.

Note: Once you've opened a file, you can readlines() as usual but there is an issue with lists. .readlines() can be written as the equivalent list(f) if you really need the list of lines.

E.g. Compare these approaches:

fileobj =
for line in fileobj:
    print line
fileobj =
for line in fileobj.readlines():
    print line
fileobj =
lines = list(fileobj.readlines())
for line in lines:
    print line

Appending lines to a log file

Open a file with "a" to append data:

def writeLog(rtc, values):
    """Append a line with the current timestamp to the log file"""
    timestamp = ("%04d-%02d-%02d %02d:%02d:%02d" % (datetime[0], datetime[1], datetime[2], datetime[4], datetime[5], datetime[6]))
    logline = ("%s %s" % (timestamp, values))

        with open("/sd/logdata.txt", "a") as f:
            f.write("%s\n" % logline)

    except OSError as error:
        print("Error: can not write to SD card. %s" % error)

# usage example
rtc = RTC()
writeLog(rtc, "line 1")
writeLog(rtc, "line 2")
writeLog(rtc, "line n")

pyb.freq and SD cards

Writing data to the SD card does not work if the frequency is below 64 MHz. The "Appending lines to a log file" example fails with errno 5 if the frequency is too low.

# 64 MHz or more is required when writing to the SD card
pyb.freq(64 * 1000000)