raspberry pi zero based drum machine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import sys
  2. sys.path.insert(0, './lib')
  3. from pygame import mixer
  4. import time
  5. import digitalio
  6. import board
  7. import adafruit_matrixkeypad
  8. import pygame
  9. from PIL import Image, ImageDraw, ImageFont
  10. #import adafruit_rgb_display.st7789 as st7789
  11. #import digitalio
  12. #import board
  13. from adafruit_rgb_display.rgb import color565
  14. import adafruit_rgb_display.st7789 as st7789
  15. import FSM
  16. from itertools import cycle
  17. import observer
  18. from scikits.samplerate import resample
  19. from configobj import ConfigObj
  20. import json
  21. import ast
  22. import RPi.GPIO as GPIO
  23. #from time import sleep
  24. import threading
  25. import os
  26. GPIO.setmode(GPIO.BCM)
  27. GPIO.setup(29, GPIO.OUT) #internal led GPIO output channel
  28. cols = [digitalio.DigitalInOut(x) for x in (board.D21, board.D20, board.D16, board.D12)]
  29. rows = [digitalio.DigitalInOut(x) for x in (board.D26, board.D13, board.D6, board.D5)]
  30. keys = ((15, 14, 13, 12),
  31. (11, 10, 9, 8),
  32. (7, 6, 5, 4),
  33. (3, 2, 1, 0))
  34. keypad = adafruit_matrixkeypad.Matrix_Keypad(rows, cols, keys)
  35. pygame.init()
  36. done = False
  37. clock = pygame.time.Clock()
  38. TIMER = pygame.USEREVENT + 1
  39. playhead = 0
  40. timer = pygame.time.get_ticks
  41. start = now = timer()
  42. cs_pin = digitalio.DigitalInOut(board.CE0)
  43. dc_pin = digitalio.DigitalInOut(board.D25)
  44. reset_pin = None
  45. BAUDRATE = 64000000
  46. backlight = digitalio.DigitalInOut(board.D22)
  47. backlight.switch_to_output()
  48. backlight.value = True
  49. buttonA = digitalio.DigitalInOut(board.D23)
  50. buttonB = digitalio.DigitalInOut(board.D24)
  51. buttonA.switch_to_input()
  52. buttonB.switch_to_input()
  53. spi = board.SPI()
  54. x = 0
  55. # Turn on the backlight
  56. backlight = digitalio.DigitalInOut(board.D22)
  57. backlight.switch_to_output()
  58. backlight.value = True
  59. class Prog:
  60. def __init__(self):
  61. self.FSM = FSM.ProgFSM(self)
  62. #self.start_mixer()
  63. #self.font = ImageFont.truetype("/home/pi/examples/HLM.ttf", 64)
  64. #self.h1 = ImageFont.truetype("/home/pi/examples/HLM.ttf", 26)
  65. self.h1 = ImageFont.truetype("/home/pi/zpc_ct/fonts/Pixellari.ttf", 30)
  66. self.h2 = ImageFont.truetype("/home/pi/zpc_ct/fonts/Pixellari.ttf", 20)
  67. self.h3 = ImageFont.truetype("/home/pi/zpc_ct/fonts/Pixellari.ttf", 54)
  68. self.h4 = ImageFont.truetype("/home/pi/zpc_ct/fonts/Pixellari.ttf", 72)
  69. self.disp = st7789.ST7789(
  70. spi,
  71. cs=cs_pin,
  72. dc=dc_pin,
  73. rst=reset_pin,
  74. baudrate=BAUDRATE,
  75. width=135,
  76. height=240,
  77. x_offset=53,
  78. y_offset=40,
  79. )
  80. self.height = self.disp.width # we swap height/width to rotate it to landscape!
  81. self.width = self.disp.height
  82. self.rotation = 270
  83. self.padding = -2
  84. self.top = self.padding
  85. self.bottom = self.height - self.padding
  86. self.image = Image.new("RGB", (self.width, self.height))
  87. self.draw = ImageDraw.Draw(self.image)
  88. self.playhead = 0
  89. self.playing = False
  90. self.bpm = 90
  91. self.bpm_inc = 1
  92. self.half_bpm = 0.0
  93. self.note_bank = 0
  94. self.pat_bank = 0
  95. self.volume = 10
  96. self.note_vol = 16
  97. self.note_pitch = 0.0
  98. self.soundSlots = []
  99. self.keys = []
  100. self.keyState = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  101. self.song = [0]
  102. self.songCycle = cycle(self.song)
  103. self.curPattern = next(self.songCycle)
  104. self.songStart = self.curPattern
  105. self.eSound = 0
  106. self.ePattern = 0
  107. self.patternFollow = False
  108. self.patternClipboard = []
  109. self.soundClipboard = []
  110. self.last_load_sound_id = None
  111. self.odub = False
  112. self.undo_buf = []
  113. self.erase_buf = []
  114. self.erase = False
  115. self.mute_buf = []
  116. self.mute = False
  117. self.black = "#000000"
  118. self.bg_color = "#336699"
  119. self.color_b = "#929230"
  120. self.dark_grey = "#404040"
  121. self.grey = "#808080"
  122. self.light_grey = "#D3D3D3"
  123. self.blue = "#336699"
  124. self.dark_blue = "#2A2AD5"
  125. self.pink = "#D52A80"
  126. self.olive = "#80D52A"
  127. self.notes_on = []
  128. self.clear_notes_on()
  129. self.prev = True
  130. self.pat_odub = False
  131. self.pat_perf = False
  132. self.pat_buf = None
  133. self.song_in = []
  134. self.press_ticks_up = None
  135. self.press_ticks_down = None
  136. self.pub = observer.Publisher(['beat', 'the joint'])
  137. self.repeater_states = []
  138. _iter = 0
  139. while _iter < 18:
  140. self.repeater_states.append(None)
  141. _iter += 1
  142. self.mconf = ConfigObj("config.txt")
  143. self.sconf = ConfigObj("/home/pi/zpc_ct/user/songs/" + self.mconf['default_song'])
  144. self.theme = ConfigObj("/home/pi/zpc_ct/user/themes/" + self.mconf['theme'] + ".thm")
  145. self.load_sound_dir = '/home/pi/zpc_ct/user/sounds/'
  146. self.song_dir = self.mconf['song_dir']
  147. self.base_song_dir = '/home/pi/zpc_ct/user/songs/'
  148. self.light_grey = self.theme['light_grey']
  149. self.apply_theme()
  150. self.display_thread = threading.Thread(target=self.update_display, args=([0]))
  151. self.defender_sounds = []
  152. self.load_defender()
  153. class SoundSlot:
  154. def __init__(self, file, obj_id, o):
  155. self.file = file
  156. self.id = obj_id
  157. self.o = o
  158. self.mixerSound = None
  159. self.soundArray = None
  160. self.og_sound = None
  161. if file != None:
  162. self.create_sound()
  163. self.pitch = 0
  164. self.volume = 16
  165. self.start = 0
  166. self.end = 0
  167. def create_sound(self):
  168. self.mixerSound = pygame.mixer.Sound(self.file)
  169. self.soundArray = pygame.sndarray.array(self.mixerSound)
  170. self.og_sound = self.mixerSound
  171. def play(self, vol):
  172. if self.file != None:
  173. if vol != 0:
  174. vol = (vol / 16) * (self.volume / 16) * (self.o.volume / 16)
  175. self.mixerSound.set_volume(vol)
  176. pygame.mixer.Sound.play(self.mixerSound)
  177. def set_pitch(self):
  178. if self.pitch == 0:
  179. self.mixerSound = self.og_sound
  180. else:
  181. snd_resample = resample(self.soundArray, ((self.pitch * - 1) / 10) + 1, "sinc_fastest").astype(self.soundArray.dtype)
  182. self.mixerSound = pygame.sndarray.make_sound(snd_resample)
  183. def init_notes(self):
  184. outp = []
  185. _id = 0
  186. while _id < 64:
  187. outp2 = []
  188. _id2 = 0
  189. while _id2 < 16:
  190. outp2.append([0,16])
  191. _id2 += 1
  192. outp.append(outp2)
  193. _id += 1
  194. return outp
  195. def init_slots(self):
  196. _iter = 0
  197. self.slots = []
  198. while _iter < 64:
  199. p1 = self.SoundSlot(None, _iter, self)
  200. self.slots.append(p1)
  201. _iter += 1
  202. def Execute(self):
  203. self.keys = keypad.pressed_keys
  204. self.update_keys()
  205. self.FSM.Execute()
  206. def update_keys(self):
  207. _id = 0
  208. for k in self.keyState:
  209. if k == 0:
  210. if _id in self.keys:
  211. self.keyState[_id] = 1
  212. elif k == 1:
  213. if _id in self.keys:
  214. self.keyState[_id] = 2
  215. else:
  216. self.keyState[_id] = 3
  217. elif k == 2:
  218. if _id in self.keys:
  219. self.keyState[_id] = 2
  220. else:
  221. self.keyState[_id] = 3
  222. else:
  223. self.keyState[_id] = 0
  224. _id += 1
  225. if buttonA.value == 0:
  226. if self.keyState[16] == 0:
  227. self.keyState[16] = 1
  228. elif self.keyState[16] == 1:
  229. self.keyState[16] = 2
  230. else:
  231. self.keyState[16] = 2
  232. else:
  233. if self.keyState[16] == 3:
  234. self.keyState[16] = 4
  235. elif self.keyState[16] == 2:
  236. self.keyState[16] = 3
  237. elif self.keyState[16] == 4:
  238. self.keyState[16] = 0
  239. if buttonB.value == 0:
  240. if self.keyState[17] == 0:
  241. self.keyState[17] = 1
  242. elif self.keyState[17] == 1:
  243. self.keyState[17] = 2
  244. else:
  245. self.keyState[17] = 2
  246. else:
  247. if self.keyState[17] == 3:
  248. self.keyState[17] = 4
  249. elif self.keyState[17] == 2:
  250. self.keyState[17] = 3
  251. elif self.keyState[17] == 4:
  252. self.keyState[17] = 0
  253. def button_repeater(self, state, enables):
  254. if state == 0:
  255. pass
  256. elif state == 1:
  257. for i in self.repeater_states:
  258. i = None
  259. def update_bpm(self):
  260. bpm = (60000 / self.bpm) / 4
  261. self.half_bpm = bpm / 2
  262. if self.playing:
  263. pygame.time.set_timer(TIMER, int(bpm))
  264. def start_playback(self):
  265. if len(self.song) > 0:
  266. self.playing = True
  267. self.playhead = -1
  268. self.playhead = 0
  269. self.songCycle = cycle(self.song)
  270. self.curPattern = next(self.songCycle)
  271. self.songStart = self.curPattern
  272. bpm = (60000 / self.bpm) / 4
  273. pygame.time.set_timer(TIMER, int(bpm))
  274. GPIO.setup(29, GPIO.OUT)
  275. GPIO.output(29, GPIO.LOW)
  276. def stop_playback(self):
  277. self.playing = False
  278. self.playhead = -1
  279. self.playhead = 0
  280. if len(self.song) > 0:
  281. self.curPattern = self.song[0]
  282. else:
  283. self.curPattern = 0
  284. pygame.time.set_timer(TIMER, 0)
  285. GPIO.setup(29, GPIO.OUT)
  286. GPIO.output(29, GPIO.HIGH)
  287. if self.pat_odub:
  288. print('stopping with odub')
  289. self.pat_perf = False
  290. self.pat_odub = False
  291. self.song = self.song_in
  292. self.pat_buf = self.song_in
  293. self.song_in = []
  294. self.songCycle = cycle(self.song)
  295. self.songStart = self.song[0]
  296. def center_text(self, text, font, width, y, color):
  297. w,h = font.getsize(text)
  298. self.draw.text(((width-w)/2,(y-h)/2), text, font=font, fill=color)
  299. def center_block(self, message, font, bounding_box, color):
  300. x1, y1, x2, y2 = bounding_box
  301. w, h = self.draw.textsize(message, font=font)
  302. x = (x2 - x1 - w)/2 + x1
  303. y = (y2 - y1 - h)/2 + y1
  304. self.draw.text((x, y), message, align='center', font=font, fill=color)
  305. def apply_theme(self):
  306. self.grey = self.theme["grey"]
  307. self.light_grey = self.theme["light_grey"]
  308. self.dark_grey = self.theme["dark_grey"]
  309. self.blue = self.theme["blue"]
  310. self.pink = self.theme["pink"]
  311. self.olive = self.theme["olive"]
  312. def save_song(self):
  313. base_dir = self.song_dir
  314. title = self.sconf['title']
  315. fname = base_dir + self.sconf['title'] + '.sng'
  316. if os.path.exists(fname):
  317. os.utime(fname, None)
  318. else:
  319. open(fname, 'a').close()
  320. self.sconf = ConfigObj(fname)
  321. self.sconf['volume'] = self.volume
  322. self.sconf['song'] = self.song
  323. self.sconf['bpm'] = self.bpm
  324. self.sconf['title'] = title
  325. notes = []
  326. for n in self.soundSlots:
  327. notes.append([n.id, n.file, n.volume, n.pitch, n.notes])
  328. self.sconf['sounds'] = notes
  329. self.sconf.write()
  330. def save_config(self):
  331. base_dir = "/home/pi/zpc_ct/"
  332. self.mconf['song_dir'] = self.song_dir
  333. self.mconf.write()
  334. def load_config(self):
  335. base_dir = "/home/pi/zpc_ct/"
  336. self.sconf = ConfigObj(base_dir + 'config.txt')
  337. self.theme = ConfigObj("/home/pi/zpc_ct/user/themes/" + self.mconf['theme'] + ".thm")
  338. self.song_dir = self.mconf['song_dir']
  339. def load_song(self):
  340. self.quit_mixer()
  341. self.start_mixer()
  342. base_dir = self.song_dir
  343. self.sconf = ConfigObj(base_dir + self.mconf['default_song'] + '.sng')
  344. print(base_dir + self.mconf['default_song'] + '.sng')
  345. self.last_load_sound_id = None
  346. print('song bpm is ', self.sconf['bpm'])
  347. self.bpm = self.sconf.as_int('bpm')
  348. song = []
  349. for i in self.sconf['song']:
  350. song.append(int(i))
  351. obj_id = 0
  352. self.soundSlots = []
  353. _iter = 0
  354. while _iter < 64:
  355. snd = self.sconf.as_list('sounds')[_iter]
  356. snd_lst = ast.literal_eval(snd)
  357. obj_id = snd_lst[0]
  358. filename = snd_lst[1]
  359. volume = int(snd_lst[2])
  360. pitch = int(snd_lst[3])
  361. notes = snd_lst[4]
  362. p1 = self.SoundSlot(filename, obj_id, self)
  363. p1.volume = volume
  364. p1.pitch = pitch
  365. if pitch != 0:
  366. p1.set_pitch()
  367. self.soundSlots.append(p1)
  368. p1.notes = notes
  369. _iter += 1
  370. self.song = song
  371. self.songCycle = cycle(self.song)
  372. self.curPattern = next(self.songCycle)
  373. self.songStart = self.curPattern
  374. self.update_bpm()
  375. def update_display(self, x):
  376. try:
  377. self.disp.image(self.image, self.rotation)
  378. except:
  379. print('display failed')
  380. def ud(self, x):
  381. self.disp.image(self.image, self.rotation)
  382. def clear_notes_on(self):
  383. _iter = 0
  384. self.notes_on = []
  385. while _iter < 64:
  386. self.notes_on.append(0)
  387. _iter += 1
  388. def start_mixer(self):
  389. print('starting mixer')
  390. mixer.init()
  391. mixer.set_num_channels(32)
  392. def quit_mixer(self):
  393. if mixer.get_init() != None:
  394. print('quitting mixer')
  395. mixer.quit()
  396. def load_defender(self):
  397. s1 = pygame.mixer.Sound('/home/pi/zpc_ct/user/sounds/po-arc/05.wav')
  398. self.defender_sounds.append(s1)
  399. s2 = pygame.mixer.Sound('/home/pi/zpc_ct/user/sounds/po-arc/08.wav')
  400. self.defender_sounds.append(s2)
  401. s3 = pygame.mixer.Sound('/home/pi/zpc_ct/user/sounds/po-arc/11.wav')
  402. self.defender_sounds.append(s3)
  403. p = Prog()
  404. while not done:
  405. p.Execute()
  406. if pygame.event.get(pygame.USEREVENT + 1):
  407. p.playhead += 1
  408. if p.playhead == 16:
  409. p.playhead = 0
  410. p.curPattern = next(p.songCycle)
  411. #blink internal led
  412. if p.playhead % 4 == 0:
  413. GPIO.setup(29, GPIO.OUT)
  414. GPIO.output(29, GPIO.LOW)
  415. else:
  416. GPIO.setup(29, GPIO.OUT)
  417. GPIO.output(29, GPIO.HIGH)
  418. p.pub.dispatch('beat', [p.curPattern, p.playhead])
  419. clock.tick_busy_loop()
  420. #print(clock.get_fps())
  421. pygame.quit()