How to simulate a pwm semnal python script


I need to Simulate Saw-Tooth voltage (4.5 – 0.5V) a total of 30 times . And I don’t know how to do it only with python scripts without special library or something. I have this function, but how I do it to work?

def PWM(t, frequency, dutyCycle):

    #period = 1 / frequency
    #pt = tt / period
    pt = tt * frequency # "period" time, where 1 unit is 1 period on the "real" time stamp.
    tc = pt - trunc(pt) # cycle time within 1 period. 0..1.
    return 1 if tc < dutyCycle else 0 # where 1 means on and 0 means off
Asked By: Alex Alexe



Not sure if this is what you want, but here you can see a function that given a time t returns the amplitude of a saw-tooth signal with a certain frequency and dutyCycle.

The signal is normalized, you can shift the values if you need

import numpy as np
import matplotlib.pyplot as plt

def SawTooth(t, frequency, dutyCycle):
    period = 1 / frequency
    t_on = period * dutyCycle
    t_off = period - t_on
    # the modulo will return the remainder of time inside the current period
    remainder = t % period
    if remainder > t_on:
        return 0
        return remainder / t_on

frequency = 50
dutyCycle = 0.5
samplingFreq = 10000
timeDuration = 0.1
# Generate 100ms of data with a sampling freq of 10k
t_ms = np.linspace(0, time_duration*1000, samplingFreq*timeDuration)
y = []
for t in t_ms:
    y.append(SawTooth(t/1000, frequency, dutyCycle))


enter image description here

Answered By: Sembei Norimaki