evenjc

[Python] Charging a Capacitor

Aug 21st, 2019
988
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. # Importing the math module, so we can use eulers e (e^x), written as exp(x) here.
  4. import math
  5.  
  6. # Importing the pyplot module from matplotlib, so we can plot our findings
  7. import matplotlib.pyplot as plt
  8.  
  9. # Defining Mega and Micro for easy use on component values
  10. Mega = 10**6
  11. Micro = 10**-6
  12.  
  13. # Variables for our circuit.
  14. V = 5
  15. C = 1*Micro
  16. R = 100*Mega
  17.  
  18. # This gives us a time constant of 100 seconds.
  19. # A time constant less than, or equal to 3s will result in a low resolution plot,
  20. # because we only sample one value each second.
  21. T_rc = R*C
  22.  
  23. # We will use the following formula to calculate the voltage:
  24. # V(t) = V_0 (1-e^(-t/T)), which can be written as
  25. # V(t) = V*(1-e^(-t/R*C)), in our case. T = RC.
  26. # This is stored in V_t.
  27. V_t = []
  28.  
  29. # A capacitor is 99.9% charged at 5 time constants.
  30. # We want to se it stabilize, so this for loop will find
  31. # values for V_t from 0 to 10 time constants. -> range(1, T_rc.__int__()*10)
  32. for t in range(1, T_rc.__int__()*10):
  33.     # Formula for voltage over a capacitor at a given time, t.
  34.     V_t.append(V*(1-math.exp(-t/(T_rc))))
  35.  
  36.  
  37. # Simple plotting of our findings.
  38. plt.plot(V_t)
  39. plt.grid()
  40. plt.xlabel("Time [s]")
  41. plt.ylabel("Current [A]")
  42. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment