baudcheck.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * baudcheck.c
  3. * Mar, 2013 by Bill Westfield (WestfW@yahoo.com)
  4. * Exercises in executing arithmetic code on a system that we can't count
  5. * on having the usual languages or tools installed.
  6. *
  7. * This little "C program" is run through the C preprocessor using the same
  8. * arguments as our "real" target (which should assure that it gets the
  9. * same values for clock speed and desired baud rate), and produces as
  10. * output a shell script that can be run through bash, and THAT in turn
  11. * writes the desired output...
  12. *
  13. * Note that the C-style comments are stripped by the C preprocessor.
  14. *
  15. * Copyright 2013-2015 by Bill Westfield.
  16. * This software is licensed under version 2 of the Gnu Public Licence.
  17. * See optiboot.c for details.
  18. */
  19. /*
  20. * First strip any trailing "L" from the defined constants. To do this
  21. * we need to make the constants into shell variables first.
  22. */
  23. bpsx=BAUD_RATE
  24. bps=${bpsx/L/}
  25. bps=${bps/U/}
  26. fcpux=F_CPU
  27. fcpu=${fcpux/L/}
  28. fcpu=${fcpu/U/}
  29. // echo f_cpu = $fcpu, baud = $bps
  30. /*
  31. * Compute the divisor
  32. */
  33. BAUD_SETTING=$(( ( ($fcpu + $bps * 4) / (($bps * 8))) - 1 ))
  34. // echo baud setting = $BAUD_SETTING
  35. /*
  36. * Based on the computer divisor, calculate the actual bitrate,
  37. * And the error. Since we're all integers, we have to calculate
  38. * the tenths part of the error separately.
  39. */
  40. BAUD_ACTUAL=$(( ($fcpu/(8 * (($BAUD_SETTING)+1))) ))
  41. BAUD_ERROR=$(( (( 100*($BAUD_ACTUAL - $bps) ) / $bps) ))
  42. ERR_TS=$(( ((( 1000*($BAUD_ACTUAL - $bps) ) / $bps) - $BAUD_ERROR * 10) ))
  43. ERR_TENTHS=$(( ERR_TS > 0 ? ERR_TS: -ERR_TS ))
  44. /*
  45. * Print a nice message containing the info we've calculated
  46. */
  47. echo BAUD RATE CHECK: Desired: $bps, Real: $BAUD_ACTUAL, UBRRL = $BAUD_SETTING, Error=$BAUD_ERROR.$ERR_TENTHS\%