Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jlesech
Created July 30, 2012 17:25
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 jlesech/3208522 to your computer and use it in GitHub Desktop.
Save jlesech/3208522 to your computer and use it in GitHub Desktop.
Python script which allow to compute TWI configuration register values (TWBR and TWPS) for an ATmega328P.
#!/usr/bin/env python
# encoding: utf-8
"""
Copyright (C) 2012 Julien Le Sech - www.idreammicro.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import argparse
import sys
"""
TWI bus max frequency.
"""
TWI_MAX_FREQUENCY = 400000
"""
Prescaler bits in TWPS register.
"""
TWPS0 = 0
TWPS1 = 1
"""
Prescaler configuration.
"""
class PrescalerConfiguration:
def __init__(self, prescalerValue, prescalerBits):
self.value = prescalerValue
self.bits = prescalerBits
"""
Available prescaler configurations.
"""
prescalerConfigurations = [
PrescalerConfiguration(1, 0),
PrescalerConfiguration(4, (1 << TWPS0)),
PrescalerConfiguration(16, (1 << TWPS1)),
PrescalerConfiguration(64, ((1 << TWPS1) | (1 << TWPS0)))
]
"""
Compute bit rate.
"""
def ComputeBitRate(f_cpu, f_scl, prescalerValue):
bitRate = (f_cpu - 16 * f_scl) / (2 * f_scl * prescalerValue)
return bitRate
"""
Main function.
"""
def main():
# Parse arguments.
parser = argparse.ArgumentParser()
parser.add_argument(
"-f_cpu", dest = "f_cpu", type = int, default = 16000000,
help = "CPU frequency in Hz")
parser.add_argument(
"-f_scl", dest = "f_scl", type = int, default = 400000,
help = "SPI frequency in Hz")
args = parser.parse_args()
print "F_CPU = %d Hz" % (args.f_cpu)
print "F_SCL = %d Hz" % (args.f_scl)
# Check the preconditions.
assert(args.f_scl <= TWI_MAX_FREQUENCY)
bitRate = 65535
index = 0
for index in range(len(prescalerConfigurations)):
bitRate = ComputeBitRate(args.f_cpu, args.f_scl, prescalerConfigurations[index].value)
if bitRate <= 255:
break
# TODO: check bitrate value.
print "Bit rate (TWBR) = %d" % (bitRate)
print "Prescaler value = %d => prescaler bits (TWPS) = %d" % (prescalerConfigurations[index].value, prescalerConfigurations[index].bits)
"""
"""
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment