Code: Select all
import pyb
class IC_Channel:
def __init__(self, pin_name, timer, channel):
self.channel = channel
self.rising = 0
self.falling = 0
self.high_time = 0
self.low_time = 0
self.period = 0
self.icpin = pyb.Pin(pin_name)
self.timer_channel = timer.channel(channel, pyb.Timer.IC, pin=self.icpin, polarity=pyb.Timer.BOTH,
callback=self.callback)
self.tick = (timer.prescaler() + 1) / timer.source_freq()
if timer in (2,5):
self.overflow = 0x0fffffff
else:
self.overflow = 0x0fff
def callback(self, tim):
'''
Callback function for the input capture channel
:param tim: timer of the callback source
:return:
'''
# Read the GPIO pin to figure out if this was a rising or falling edge
if self.icpin.value():
# Rising edge - start of the pulse
self.rising = self.timer_channel.capture()
self.low_time = (self.rising - self.falling) & self.overflow
else:
# Falling edge - end of the pulse
self.falling = self.timer_channel.capture()
self.high_time = (self.falling - self.rising) & self.overflow
self.period = self.high_time + self.low_time
def get_freq(self):
'''
Get frequency of the input capture channel
:return:
'''
if(self.period > 0):
freq = 1 / (self.period * self.tick)
else:
freq = 0
return (freq)
def get_period(self):
'''
Get period of the input capture channel
:return:
'''
return (self.period * self.tick)
def get_high_time(self):
'''
Get time (high state) of the input capture channel
:return:
'''
return (self.high_time * self.tick)
def get_low_time(self):
'''
Get time (low state) of the input capture channel
:return:
'''
return (self.low_time * self.tick)