Writing to a file when a button is pushed

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
cgsmith
Posts: 2
Joined: Wed Jan 10, 2018 7:03 pm

Writing to a file when a button is pushed

Post by cgsmith » Wed Jan 10, 2018 7:10 pm

When trying to write to a file called 'camera.txt' - it doesn't appear to be working. When connected to the REPL with screen /dev/ttyACM0 115600 I can see the count increment correctly.

Below is the main.py - I also have it posted as a Gist for easier reading: https://gist.github.com/anonymous/2b99e ... bd6106dc2d


from pyb import LED
from pyb import Pin
from pyb import Switch
import time

sw = Switch()

# 1 red, 2 green, 3 yellow, 4 blue
ledg = LED(2)
ledb = LED(4)

p_in = Pin('X2', Pin.IN, Pin.PULL_UP)

camera = 0

while True:
#if (p_in.value()):

if sw():
if camera < 5:
camera += 1
else:
camera = 0
ledg.on()
ledb.off()
f = open('camera.txt', 'w')
f.write(str(camera))
print(str(camera))
f.close()
else:
ledb.on()
ledg.off()

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

Re: Writing to a file when a button is pushed

Post by dhylands » Thu Jan 11, 2018 3:19 am

How are you trying to detect that the count is increasing? If you're using the USB Mass Storage (i.e. the hard drive that the host uses) then that will be your problem. USB Mass Storage doesn't work properly when the pyboard writes to the file system. And worst yet, it can corrupt your file.

cgsmith
Posts: 2
Joined: Wed Jan 10, 2018 7:03 pm

Re: Writing to a file when a button is pushed

Post by cgsmith » Thu Jan 11, 2018 5:19 pm

I logged into the REPL over serial to see the count increasing. It is via USB Mass Storage.

So my other approach/idea is to detect a button press and send a keyboard command (CTRL+ALT+T). Then on the linux box I want to map the keyboard event of CTRL+ALT+T to send a message off to a queuing system.

Is this a logical approach? It seems better than writing to a file since you mentioned corruption.

Post Reply