baudcheck.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #ifdef SINGLESPEED
  34. BAUD_SETTING=$(( ( ($fcpu + $bps * 8) / (($bps * 16))) - 1 ))
  35. #else
  36. BAUD_SETTING=$(( ( ($fcpu + $bps * 4) / (($bps * 8))) - 1 ))
  37. #endif
  38. // echo baud setting = $BAUD_SETTING
  39. /*
  40. * Based on the computer divisor, calculate the actual bitrate,
  41. * And the error. Since we're all integers, we have to calculate
  42. * the tenths part of the error separately.
  43. */
  44. #ifdef SINGLESPEED
  45. BAUD_ACTUAL=$(( ($fcpu/(16 * (($BAUD_SETTING)+1))) ))
  46. #else
  47. BAUD_ACTUAL=$(( ($fcpu/(8 * (($BAUD_SETTING)+1))) ))
  48. #endif
  49. BAUD_ERROR=$(( (( 100*($BAUD_ACTUAL - $bps) ) / $bps) ))
  50. ERR_TS=$(( ((( 1000*($BAUD_ACTUAL - $bps) ) / $bps) - $BAUD_ERROR * 10) ))
  51. ERR_TENTHS=$(( ERR_TS > 0 ? ERR_TS: -ERR_TS ))
  52. /*
  53. * Print a nice message containing the info we've calculated
  54. */
  55. echo BAUD RATE CHECK: Desired: $bps, Real: $BAUD_ACTUAL, UBRRL = $BAUD_SETTING, Difference=$BAUD_ERROR.$ERR_TENTHS\%