Skip to content

Instantly share code, notes, and snippets.

@ekiwi
Created January 8, 2016 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekiwi/51573729365405fef89c to your computer and use it in GitHub Desktop.
Save ekiwi/51573729365405fef89c to your computer and use it in GitHub Desktop.
CAN bit time calculation
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Kevin Laeufer <kevin.laeufer@rwth-aachen.de>
# bite_time.py
class UserSettings(object):
def __init__(self, clk, bitrate, sampling_point, max_tolerance=0.02):
self.clk = clk
self.bitrate = bitrate
self.sampling_point = sampling_point
self.max_tolerance = max_tolerance
def __str__(self):
lines = [
"CLK: {}MHz".format(float(self.clk) / 1000 / 1000),
"Bitrate: {}kHz".format(float(self.bitrate) / 1000),
"Desired Sampling Point: {:.5%}".format(self.sampling_point),
"Max Tolerance: {:.5%}".format(self.max_tolerance)]
return "\n".join(lines)
class ParameterSet(object):
def __init__(self, bs1, bs2):
self.bs1 = bs1
self.bs2 = bs2
@property
def bitlength(self):
return 1 + self.bs1 + self.bs2
@property
def sampling_point(self):
return (1 + self.bs1) / (1 + self.bs1 + self.bs2)
def prescaler(self, settings):
return float(settings.clk) / float(settings.bitrate) / float(self.bitlength)
def is_integer_prescaler(self, settings):
return self.prescaler(settings).is_integer()
def get_sampling_point_tolerance(self, settings):
return abs(self.sampling_point - settings.sampling_point)
def __str__(self):
lines = [
"BS1: {}".format(self.bs1),
"BS2: {}".format(self.bs2),
"Sampling Point: {:.5%}".format(self.sampling_point)]
return "\n".join(lines)
if __name__ == "__main__":
# generate all possible parametersets
parameters = []
for bs1 in reversed(range(1,17)):
for bs2 in reversed(range(1,9)):
parameters.append(ParameterSet(bs1, bs2))
# create user settings
settings = UserSettings(
clk = 8 * 1000 * 1000,
bitrate = 125 * 1000,
sampling_point = 0.7333)
print(settings)
# find best parameter set
best = min(
(ps for ps in parameters if ps.is_integer_prescaler(settings)),
key=lambda ps: ps.get_sampling_point_tolerance(settings))
print(best)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment