1

Is there a way to save the variable value in python In case of power failure so when i run the program again it does not start from initial value but the value which was saved last.In the below code i am counting the number of times a button is pressed so can i save the value of age and start counting from the saved value insted of starting from 15.

 import RPi.GPIO as GPIO
 import time
 age=15                   //initialize for debugging
 GPIO.setmode(GPIO.BCM)
 GPIO.setup(25, GPIO.IN,GPIO.PUD_DOWN)

 def led(channel):                     //funtion for increnment age
     global age
     age=(age+1)
     print(age)

PIN 7 AND 3.3V

normally 0 when connected 1

 GPIO.add_event_detect(25, GPIO.RISING, callback=led, bouncetime=1000 )
 print(age)
 try:
     while(True):
            time.sleep(1)
 except KeyboardInterrupt:
           GPIO.cleanup()
           print (age)
           print ("Exiting")
M. Suarez
  • 23
  • 6

2 Answers2

0

The typical way to do this is via writing and writing to a file. You can read from the file the program state when starting the program, and modify the file as the variable state changes.

For saving more complex data structures, the Pickle module exists. This allows objects to be serialized.

Brett Holman
  • 743
  • 6
  • 18
  • JSON is a highly useful and standardized way to store data beyond a simple integer or string as well, and it's also cross-platform and cross-language. – stevieb Feb 07 '18 at 15:12
0

Try this:

open a terminal and type the following to create an file named as 'led.txt' :

>>>import pickle    
>>>s={'age':None}    
>>>with open('led.txt','w') as f:
...        f.write(pickle.dumps(s))

Then proceed with you code

 import RPi.GPIO as GPIO
 import time
 import pickle

 led_age={'age':None}  # initialise as dictionary

 with open('led.txt') as f: # open file in read mode  
   led_age = pickle.loads(f.read())  #initialize for debugging

 GPIO.setmode(GPIO.BCM)
 GPIO.setup(25, GPIO.IN,GPIO.PUD_DOWN)


 def led(channel): 
     global led_age       

     led_age['age'] += 1     # increment value
     with open('led.txt','w') as f:    # again open the file in write mode
       f.write(pickle.dumps(led_age))  #pickle the dictionary and write back to the file

     print(led_age)

instead of an int variable I have used a dictionary.

the function led does the following:

  1. open the file 'led.txt' in readonly mode(default mode) and load the dictionary
  2. Increment the 'age'
  3. Again open the file 'led.txt' but in write mode and write back the updated dictionary

pickle.dumps serializes the dictionary to strings, and pickle.loads does the deserialization

Each time the function led is called this updation will be carried out automatically and the led.txt file will be updated.

Note : An alternative to pickle can be JSON which is compatible with other languages

Pratik Kumar
  • 2,211
  • 1
  • 17
  • 41