10
10
except OSError :
11
11
pass
12
12
13
- # Check that there is a qrcode.txt, if not preload
13
+ # Load all available QR Code Files
14
14
try :
15
- text = open ( "qrcodes/qrcode.txt" , "r" )
15
+ CODES = [ f for f in os . listdir ( "/qrcodes" ) if f . endswith ( ".txt" )]
16
16
except OSError :
17
- text = open ("qrcodes/qrcode.txt" , "w" )
18
- text .write ("""https://pimoroni.com/badger2040
17
+ CODES = []
18
+
19
+ # create demo QR code file if no QR code files exist
20
+ if len (CODES ) == 0 :
21
+ try :
22
+ new_qr_code_filename = "qrcode.txt"
23
+ with open (f"/qrcodes/{ new_qr_code_filename } " , "w" ) as text :
24
+ text .write ("""https://pimoroni.com/badger2040
19
25
Badger 2040
20
26
* 296x128 1-bit e-ink
21
27
* six user buttons
25
31
Scan this code to learn
26
32
more about Badger 2040.
27
33
""" )
28
- text .flush ()
29
- text .seek (0 )
34
+ text .flush ()
30
35
31
- # Load all available QR Code Files
32
- try :
33
- CODES = [f for f in os .listdir ("/qrcodes" ) if f .endswith (".txt" )]
34
- TOTAL_CODES = len (CODES )
35
- except OSError :
36
- pass
36
+ # Set the CODES list to contain the new_qr_code_filename (created above)
37
+ CODES = [new_qr_code_filename ]
37
38
39
+ except OSError :
40
+ CODES = []
38
41
39
- print (f'There are { TOTAL_CODES } QR Codes available:' )
40
- for codename in CODES :
41
- print (f'File: { codename } ' )
42
+ TOTAL_CODES = len (CODES )
42
43
43
44
display = badger2040 .Badger2040 ()
44
45
50
51
}
51
52
52
53
54
+ def set_state_current_index_in_range ():
55
+ badger_os .state_load ("qrcodes" , state )
56
+ if state ["current_qr" ] >= len (CODES ):
57
+ state ["current_qr" ] = len (CODES ) - 1 # set to last index (zero-based). Note: will set to -1 if currently 0
58
+ if state ["current_qr" ] < 0 : # check that the index is not negative, thus still out of range
59
+ state ["current_qr" ] = 0
60
+ badger_os .state_save ("qrcodes" , state )
61
+
62
+
53
63
def measure_qr_code (size , code ):
54
64
w , h = code .get_size ()
55
65
module_size = int (size / w )
@@ -70,9 +80,13 @@ def draw_qr_code(ox, oy, size, code):
70
80
def draw_qr_file (n ):
71
81
display .led (128 )
72
82
file = CODES [n ]
73
- codetext = open ("qrcodes/{}" .format (file ), "r" )
74
83
75
- lines = codetext .read ().strip ().split ("\n " )
84
+ try :
85
+ with open (f"/qrcodes/{ file } " , "r" ) as codetext :
86
+ lines = codetext .read ().strip ().split ("\n " )
87
+ except OSError :
88
+ lines = ["" , "" , "" , "" , "" , "" , "" , "" , "" , "" ]
89
+
76
90
code_text = lines .pop (0 )
77
91
title_text = lines .pop (0 )
78
92
detail_text = lines
@@ -110,7 +124,7 @@ def draw_qr_file(n):
110
124
display .update ()
111
125
112
126
113
- badger_os . state_load ( "qrcodes" , state )
127
+ set_state_current_index_in_range ( )
114
128
changed = not badger2040 .woken_by_button ()
115
129
116
130
while True :
0 commit comments