bell.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/python
  2. # Bicycle Bell/Horn firmware
  3. # Copyright (C) 2015 Stuart Longland
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  18. import math
  19. import wave
  20. import struct
  21. import textwrap
  22. # Generate a bell sound
  23. F_sample = 6400 # 6.4kHz sample rate
  24. F_bell = 2063 # Fundamental frequency
  25. F_bell_mod = 15.625 # Modulated amplitude
  26. F_reverb = 3.77 # Reverberation frequency
  27. A_reverb = 0.07 # Reverberation amplitude
  28. duration = 1.0 # Duration
  29. decay = 1.0 # Decay
  30. samples = []
  31. bell = lambda t : ((1.0+math.cos(math.pi*t/duration))/2) * \
  32. (decay ** t) * \
  33. (1.0 - (A_reverb * math.cos(2*math.pi*F_reverb*t)) - (A_reverb/2)) * \
  34. (math.cos(2*math.pi*F_bell*t) * \
  35. math.sin(2*math.pi*F_bell_mod*t))
  36. for n in range(0, int(duration*F_sample)):
  37. t = float(n)/float(F_sample)
  38. samples.append(int(127*bell(t)) + 127)
  39. assert samples[-1] >= 0, '%s <= 0' % samples[-1]
  40. assert samples[-1] <= 255, '%s > 255' % samples[-1]
  41. num_samples = len(samples)
  42. # C output
  43. with file('bellsnd.c','w') as f:
  44. f.write('#include "bellsnd.h"\n')
  45. f.write('const uint8_t bell[%s] PROGMEM = {\n' % num_samples)
  46. f.write('\n'.join(textwrap.wrap(', '.join([str(s) for s in samples]),
  47. initial_indent='\t', subsequent_indent='\t',
  48. expand_tabs=False)))
  49. f.write('\n};\n')
  50. with file('bellsnd.h','w') as f:
  51. f.write('#include <stdint.h>\n')
  52. f.write('#include <avr/pgmspace.h>\n')
  53. f.write('#define BELL_RATE (%s)\n' % F_sample)
  54. f.write('#define BELL_SZ (%s)\n' % num_samples)
  55. f.write('const uint8_t bell[%s] PROGMEM;\n' % num_samples)
  56. # For the sake of analysis, we'll dump wav audio too
  57. f = wave.open('bellsnd.wav','w')
  58. f.setnchannels(1)
  59. f.setsampwidth(1)
  60. f.setframerate(F_sample)
  61. f.setnframes(num_samples)
  62. f.setcomptype('NONE','not compressed')
  63. f.writeframes(''.join([
  64. struct.pack('B', s) for s in samples
  65. ]))
  66. f.close()