In this video lesson we show how mission critical data can be saved in Flash Memory on the Raspberry Pi Pico W. There is just 2 MB of flash memory available, and the flash memory is only specified for 100,000 write cycles. This means we must be careful and deliberate in when to use flash memory, and it should not be used as a general purpose data logger. For example, if you wrote a memory location once a second, you could reach cycle limit in a few days. However, storing things like calibration data, user preferences and so forth are excellent uses of the memory.
In order to demonstrate this capability, we will show a program where the position of the servo is saved in a .json file in flash memory. If power is lost, the program goes and reloads the last position of the servo from the .json file, and then proceeds from there. We use the following circuit:
We also include the code developed in this lesson below for your convenience:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
from machine import Pin, PWM import ujson import time decPin=16 incPin=17 servoPin=0 decBut=Pin(decPin,Pin.IN,Pin.PULL_UP) incBut=Pin(incPin,Pin.IN,Pin.PULL_UP) incButState=1 incButStateOld=1 decButState=1 decButStateOld=1 myServo=PWM(Pin(servoPin)) myServo.freq(50) servoAngle=90 try: f = open("/angle.json", "r") servoAngle = ujson.load(f) f.close() print(servoAngle) except: pass def moveServo(angle): writeVal=6553/180*angle+1638 myServo.duty_u16(int(writeVal)) print(angle) f=open("/angle.json",'w') ujson.dump(angle,f) f.close() moveServo(servoAngle) while True: incButState=incBut.value() decButState=decBut.value() if incButState==0 and incButStateOld==1: servoAngle=servoAngle+10 if servoAngle>180: servoAngle=180 moveServo(servoAngle) time.sleep(.1) if decButState==0 and decButStateOld==1: servoAngle=servoAngle-10 if servoAngle<0: servoAngle=0 moveServo(servoAngle) time.sleep(.1) incButStateOld=incButState decButStateOld=decButState |