TTT4260/D2/Grafer/Graftegning.py

94 lines
2.3 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 18 22:30:00 2019
@author: oyvind
"""
import math
import matplotlib.pyplot as plt
# Name for the saved graph
filename = "4b"
# RPM
RPM = 40000
Hz = RPM / 60
# Tau in microseconds
tau = 1/(2 * Hz) * 10**6
# Square wave freq in kHz
sqWFreq = 5
# How many taus you want
periods = 3
# The resolution of each tau
resolution = 1000
# Forwardvoltage of diode
diodeVoltage = 0.7
# Calculates the length of each squarewave in taus
sqTime = (1/sqWFreq) * 10**3
sqTau = sqTime / tau
# Creats the square wave
# Default values are in the argument list
def CreateSquareWave(amp=2.5, offset=2.5, symetry=0.5):
squareWave = []
# Only generates as many datapoints we need
while len(squareWave) < periods * resolution:
# First generate the first half
for r in range(int(resolution*sqTau * symetry)):
squareWave.append(amp + offset)
# Then the second
for r in range(int(resolution*sqTau * (1 - symetry))):
squareWave.append(offset - amp)
squareWave = squareWave[:(resolution*periods)]
return squareWave
# Generate all the time-ticks
def GenerateTime():
times = []
for t in range(periods * resolution):
times.append(t/resolution)
print(len(times))
return(times)
def CapVoltage(wave, times):
cP = wave[0] # Start voltage-supply
v0 = 0 # Start voltage
cT = 0 #Start time
volt = []
for p in range(len(wave)):
# If the voltage-supply changes, recalculate startvalues
if wave[p] != cP:
v0 = volt[-1] # New start voltage, uses the last voltage calculated
if wave[p] == 0:
v0 = diodeVoltage
cP = wave[p] # Variable so the array is not accessed.
cT = times[p] # Offset time for each period
# Calculate the voltage over the CAPACITOR with the start values
volt.append(cP + (v0 - cP) * math.exp(-(times[p] - cT)))
return(volt)
SquareWave = CreateSquareWave()
time = GenerateTime()
CapWave = CapVoltage(SquareWave, time)
plt.figure(figsize=(15,5))
plt.plot(time, SquareWave, time, CapWave)
plt.xlabel("Time [τ]")
plt.ylabel("Voltage [V]")
plt.legend(["Supply voltage", "Capacitor voltage"], loc="lower right")
plt.savefig(filename + ".png", dpi = 300)
plt.show()