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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. GPIO.setmode(GPIO.BCM)
  26. # set up GPIO output channel - internal led
  27. GPIO.setup(47, GPIO.OUT)
  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. mixer.init()
  37. mixer.set_num_channels(32)
  38. done = False
  39. clock = pygame.time.Clock()
  40. TIMER = pygame.USEREVENT + 1
  41. playhead = 0
  42. timer = pygame.time.get_ticks
  43. start = now = timer()
  44. cs_pin = digitalio.DigitalInOut(board.CE0)
  45. dc_pin = digitalio.DigitalInOut(board.D25)
  46. reset_pin = None
  47. BAUDRATE = 64000000 # The pi can be very fast!
  48. #BAUDRATE = 24000000
  49. # display = st7789.ST7789(
  50. # board.SPI(),
  51. # cs=cs_pin,
  52. # dc=dc_pin,
  53. # rst=reset_pin,
  54. # baudrate=BAUDRATE,
  55. # width=135,
  56. # height=240,
  57. # x_offset=53,
  58. # y_offset=40,
  59. # )
  60. backlight = digitalio.DigitalInOut(board.D22)
  61. backlight.switch_to_output()
  62. backlight.value = True
  63. buttonA = digitalio.DigitalInOut(board.D23)
  64. buttonB = digitalio.DigitalInOut(board.D24)
  65. buttonA.switch_to_input()
  66. buttonB.switch_to_input()
  67. spi = board.SPI()
  68. # Create blank image for drawing.
  69. # Make sure to create image with mode 'RGB' for full color.
  70. # Get drawing object to draw on image.
  71. # Draw a black filled box to clear the image.
  72. #draw.rectangle((0, 0, width, height), outline=0, fill=(0, 0, 0))
  73. #disp.image(image, rotation)
  74. # Draw some shapes.
  75. # First define some constants to allow easy resizing of shapes.
  76. # Move left to right keeping track of the current x position for drawing shapes.
  77. x = 0
  78. # Turn on the backlight
  79. backlight = digitalio.DigitalInOut(board.D22)
  80. backlight.switch_to_output()
  81. backlight.value = True
  82. class Prog:
  83. def __init__(self):
  84. self.FSM = FSM.ProgFSM(self)
  85. self.font = ImageFont.truetype("/home/pi/examples/HLM.ttf", 64)
  86. #self.h1 = ImageFont.truetype("/home/pi/examples/HLM.ttf", 26)
  87. self.h1 = ImageFont.truetype("/home/pi/Pixellari.ttf", 30)
  88. self.h2 = ImageFont.truetype("/home/pi/Pixellari.ttf", 20)
  89. self.h3 = ImageFont.truetype("/home/pi/Pixellari.ttf", 54)
  90. self.disp = st7789.ST7789(
  91. spi,
  92. cs=cs_pin,
  93. dc=dc_pin,
  94. rst=reset_pin,
  95. baudrate=BAUDRATE,
  96. width=135,
  97. height=240,
  98. x_offset=53,
  99. y_offset=40,
  100. )
  101. self.height = self.disp.width # we swap height/width to rotate it to landscape!
  102. self.width = self.disp.height
  103. self.rotation = 270
  104. self.padding = -2
  105. self.top = self.padding
  106. self.bottom = self.height - self.padding
  107. self.image = Image.new("RGB", (self.width, self.height))
  108. self.draw = ImageDraw.Draw(self.image)
  109. self.playhead = 0
  110. self.playing = False
  111. #self.bpm = 90
  112. self.bpm_inc = 1
  113. self.note_bank = 0
  114. self.pat_bank = 0
  115. self.volume = 10
  116. self.note_vol = 16
  117. self.note_pitch = 0.0
  118. self.soundSlots = []
  119. #self.slots = []
  120. self.keys = []
  121. self.keyState = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
  122. #self.song = [2, 3, 0, 1, 0, 1, 0, 1, 0, 1]
  123. self.song = [0]
  124. self.songCycle = cycle(self.song)
  125. self.curPattern = next(self.songCycle)
  126. self.songStart = self.curPattern
  127. self.eSound = 0
  128. self.ePattern = 0
  129. self.patternClipboard = []
  130. self.soundClipboard = []
  131. self.black = "#000000"
  132. self.bg_color = "#336699"
  133. self.color_a = "#FFFFFF"
  134. self.color_b = "#929230"
  135. self.color_c = "#FFFF00"
  136. self.dark_grey = "#404040"
  137. self.grey = "#808080"
  138. self.light_grey = "#D3D3D3"
  139. self.blue = "#336699"
  140. self.dark_blue = "#2A2AD5"
  141. self.pink = "#D52A80"
  142. self.red = "#D52A2A"
  143. self.olive = "#80D52A"
  144. self.green = "#2AD52A"
  145. self.notes_on = []
  146. self.clear_notes_on()
  147. self.pub = observer.Publisher(['beat', 'the joint'])
  148. #self.song_file_name = "default.sng"
  149. self.mconf = ConfigObj("config.txt")
  150. self.sconf = ConfigObj("/home/pi/zpc_ct/user/songs/" + self.mconf['default_song'])
  151. self.theme = ConfigObj("/home/pi/zpc_ct/themes/" + self.mconf['theme'] + ".thm")
  152. self.load_song_dir = '/home/pi/zpc_ct/sounds/'
  153. self.light_grey = self.theme['light_grey']
  154. self.apply_theme()
  155. self.display_thread = threading.Thread(target=self.update_display, args=([0]))
  156. class SoundSlot:
  157. def __init__(self, file, obj_id, o):
  158. self.file = file
  159. self.id = obj_id
  160. self.o = o
  161. self.mixerSound = None
  162. self.soundArray = None
  163. self.og_sound = None
  164. if file != None:
  165. #self.mixerSound = pygame.mixer.Sound(self.file)
  166. #self.soundArray = pygame.sndarray.array(self.mixerSound)
  167. #self.og_sound = self.mixerSound
  168. self.create_sound()
  169. #self.pattern = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]
  170. #self.notes = self.init_notes()
  171. self.pitch = 0
  172. self.volume = 16
  173. self.start = 0
  174. self.end = 0
  175. def create_sound(self):
  176. self.mixerSound = pygame.mixer.Sound(self.file)
  177. self.soundArray = pygame.sndarray.array(self.mixerSound)
  178. self.og_sound = self.mixerSound
  179. def play(self, vol):
  180. # snd_array = pygame.sndarray.array(self.mixerSound)
  181. # snd_resample = resample(snd_array, 2.5, "sinc_fastest").astype(snd_array.dtype)
  182. # snd_out = pygame.sndarray.make_sound(snd_resample)
  183. # snd_out.play()
  184. #lst = ast.literal_eval(self.o.sconf.as_list('volumes')[self.id])
  185. #print('---------- ', 'this is a volume')
  186. #print(lst)
  187. #print('note vol ', self.volume)
  188. #o.sconf
  189. if self.file != None:
  190. if vol != 0:
  191. vol = (vol / 16) * (self.volume / 16) * (self.o.volume / 16)
  192. self.mixerSound.set_volume(vol)
  193. pygame.mixer.Sound.play(self.mixerSound)
  194. def set_pitch(self):
  195. if self.pitch == 0:
  196. self.mixerSound = self.og_sound
  197. else:
  198. snd_resample = resample(self.soundArray, ((self.pitch * - 1) / 10) + 1, "sinc_fastest").astype(self.soundArray.dtype)
  199. self.mixerSound = pygame.sndarray.make_sound(snd_resample)
  200. # snd_array = pygame.sndarray.array(self.mixerSound)
  201. print('setting pitch to ', self.pitch)
  202. def init_notes(self):
  203. #print('initing notes')
  204. outp = []
  205. _id = 0
  206. while _id < 64:
  207. outp2 = []
  208. _id2 = 0
  209. while _id2 < 16:
  210. outp2.append([0,16])
  211. _id2 += 1
  212. outp.append(outp2)
  213. _id += 1
  214. return outp
  215. def init_slots(self):
  216. # slot_id, file, volume, pitch, notes
  217. _iter = 0
  218. self.slots = []
  219. while _iter < 64:
  220. #def __init__(self, file, obj_id, o):
  221. p1 = self.SoundSlot(None, _iter, self)
  222. self.slots.append(p1)
  223. _iter += 1
  224. print('adding slot ', _iter)
  225. def Execute(self):
  226. self.keys = keypad.pressed_keys
  227. self.update_keys()
  228. self.FSM.Execute()
  229. def update_keys(self):
  230. _id = 0
  231. for k in self.keyState:
  232. if k == 0:
  233. if _id in self.keys:
  234. self.keyState[_id] = 1
  235. elif k == 1:
  236. if _id in self.keys:
  237. self.keyState[_id] = 2
  238. else:
  239. self.keyState[_id] = 3
  240. elif k == 2:
  241. if _id in self.keys:
  242. self.keyState[_id] = 2
  243. else:
  244. self.keyState[_id] = 3
  245. else:
  246. self.keyState[_id] = 0
  247. _id += 1
  248. if buttonA.value == 0:
  249. if self.keyState[16] == 0:
  250. self.keyState[16] = 1
  251. elif self.keyState[16] == 1:
  252. self.keyState[16] = 2
  253. else:
  254. self.keyState[16] = 2
  255. else:
  256. if self.keyState[16] == 3:
  257. self.keyState[16] = 4
  258. elif self.keyState[16] == 2:
  259. self.keyState[16] = 3
  260. elif self.keyState[16] == 4:
  261. self.keyState[16] = 0
  262. if buttonB.value == 0:
  263. if self.keyState[17] == 0:
  264. self.keyState[17] = 1
  265. elif self.keyState[17] == 1:
  266. self.keyState[17] = 2
  267. else:
  268. self.keyState[17] = 2
  269. else:
  270. if self.keyState[17] == 3:
  271. self.keyState[17] = 4
  272. elif self.keyState[17] == 2:
  273. self.keyState[17] = 3
  274. elif self.keyState[17] == 4:
  275. self.keyState[17] = 0
  276. def update_bpm(self):
  277. bpm = (60000 / self.sconf['bpm']) / 4
  278. pygame.time.set_timer(TIMER, int(bpm))
  279. def start_playback(self):
  280. self.playing = True
  281. self.playhead = -1
  282. self.playhead = 0
  283. self.songCycle = cycle(self.song)
  284. self.curPattern = next(self.songCycle)
  285. self.songStart = self.curPattern
  286. bpm = (60000 / self.sconf.as_int('bpm')) / 4
  287. pygame.time.set_timer(TIMER, int(bpm))
  288. def stop_playback(self):
  289. self.playing = False
  290. self.playhead = -1
  291. self.playhead = 0
  292. self.curPattern = self.song[0]
  293. pygame.time.set_timer(TIMER, 0)
  294. def center_text(self, text, font, width, y, color):
  295. w,h = font.getsize(text)
  296. self.draw.text(((width-w)/2,(y-h)/2), text, font=font, fill=color)
  297. def center_block(self, message, font, bounding_box, color):
  298. x1, y1, x2, y2 = bounding_box # For easy reading
  299. w, h = self.draw.textsize(message, font=font)
  300. x = (x2 - x1 - w)/2 + x1
  301. y = (y2 - y1 - h)/2 + y1
  302. self.draw.text((x, y), message, align='center', font=font, fill=color)
  303. def apply_theme(self):
  304. self.light_grey = self.theme["light_grey"]
  305. self.blue = self.theme["blue"]
  306. self.pink = self.theme["pink"]
  307. self.olive = self.theme["olive"]
  308. self.black = self.theme["black"]
  309. self.dark_blue = self.theme["dark_blue"]
  310. self.green = self.theme["green"]
  311. self.red = self.theme["red"]
  312. def save_song(self):
  313. base_dir = "/home/pi/zpc_ct/user/songs/"
  314. #self.sconf = ConfigObj(base_dir + self.sconf['title'] + '.sng')
  315. #self.sconf['title'] = "default"
  316. #self.sconf['volume'] = self.volume
  317. # sounds = []
  318. # notes = []
  319. # vols = []
  320. # pitches = []
  321. # outp = []
  322. # for x in self.soundSlots:
  323. # sounds.append(x.file)
  324. # notes.append(x.notes)
  325. # vols.append(x.volume)
  326. # pitches.append(x.pitch)
  327. # outp.append([x.id, x.file, x.volume, x.pitch, x.notes])
  328. # self.sconf['sounds'] = sounds
  329. # self.sconf['notes'] = notes
  330. # self.sconf['song'] = self.song
  331. # self.sconf['volumes'] = vols
  332. # self.sconf['pitches'] = pitches
  333. # self.sconf['Sound Slot'] = outp
  334. # self.sconf.write()
  335. self.sconf = ConfigObj(base_dir + self.sconf['title'] + '.sn2')
  336. self.sconf['volume'] = self.volume
  337. self.sconf['song'] = self.song
  338. self.sconf['bpm'] = self.sconf['bpm']
  339. notes = []
  340. for n in self.soundSlots:
  341. notes.append([n.id, n.file, n.volume, n.pitch, n.notes])
  342. self.sconf['sounds'] = notes
  343. #tmp
  344. #for s in self.soundSlots:
  345. # self.sconf['sounds'][s.id] = [s.id, s.file, s.volume, s.pitch, s.notes]
  346. self.sconf.write()
  347. def save_config(self):
  348. base_dir = "/home/pi/zpc_ct/"
  349. #self.mconf = ConfigObj(base_dir + 'config.txt')
  350. print('before writing')
  351. print(self.mconf['theme'])
  352. self.mconf.write()
  353. def load_config(self):
  354. base_dir = "/home/pi/zpc_ct/"
  355. self.sconf = ConfigObj(base_dir + 'config.txt')
  356. self.theme = ConfigObj("/home/pi/zpc_ct/themes/" + self.mconf['theme'] + ".thm")
  357. def load_song(self):
  358. base_dir = "/home/pi/zpc_ct/user/songs/"
  359. self.sconf = ConfigObj(base_dir + self.mconf['default_song'] + '.sn2')
  360. print(base_dir + self.mconf['default_song'] + '.sn2')
  361. #one = self.sconf['song']
  362. #one = self.sconf['title']
  363. #print('song ', one)
  364. song = []
  365. for i in self.sconf['song']:
  366. song.append(int(i))
  367. obj_id = 0
  368. self.soundSlots = []
  369. _iter = 0
  370. while _iter < 64:
  371. #for s in self.sconf.as_list('sounds'):
  372. snd = self.sconf.as_list('sounds')[_iter]
  373. #print('-----')
  374. snd_lst = ast.literal_eval(snd)
  375. obj_id = snd_lst[0]
  376. filename = snd_lst[1]
  377. volume = int(snd_lst[2])
  378. pitch = int(snd_lst[3])
  379. notes = snd_lst[4]
  380. _iter += 1
  381. p1 = self.SoundSlot(filename, obj_id, self)
  382. p1.volume = volume
  383. p1.pitch = pitch
  384. #p1.notes = ast.literal_eval(notes)
  385. self.soundSlots.append(p1)
  386. # if (len(self.sconf.as_list('volumes')) - 1) > obj_id:
  387. # p1.volume = int(self.sconf.as_list('volumes')[obj_id])
  388. # else:
  389. # p1.volume = 12
  390. # if (len(self.sconf.as_list('pitches')) - 1) > obj_id:
  391. # p1.pitch = int(self.sconf.as_list('pitches')[obj_id])
  392. # p1.set_pitch()
  393. # else:
  394. # p1.pitch = 0
  395. # print('adding ', s)
  396. # obj_id += 1
  397. p1.notes = notes
  398. # _iter2 = 0
  399. # while _iter2 < 64:
  400. # _iter2 += 1
  401. #print(self.soundSlots)
  402. _iter = 0
  403. #lst = ast.literal_eval(self.sconf['notes'][0])
  404. #print('length ', len(lst))
  405. # for n in self.soundSlots:
  406. # m = []
  407. # #if (len(notes) - 1) > _iter:
  408. # #lst = ast.literal_eval(notes)[_iter]
  409. # lst = notes
  410. # new_notes = []
  411. # for i in lst:
  412. # new_notes.append(i)
  413. # n.notes = new_notes
  414. # if _iter == 0:
  415. # print(new_notes)
  416. # _iter += 1
  417. self.song = song
  418. self.songCycle = cycle(self.song)
  419. self.curPattern = next(self.songCycle)
  420. self.songStart = self.curPattern
  421. # def load_song(self):
  422. # base_dir = "/home/pi/zpc_ct/user/songs/"
  423. # self.sconf = ConfigObj(base_dir + self.mconf['default_song'] + '.sng')
  424. # print(base_dir + self.mconf['default_song'] + '.sng')
  425. # #one = self.sconf['song']
  426. # one = self.sconf['title']
  427. # print('song ', one)
  428. # song = []
  429. # for i in self.sconf['song']:
  430. # song.append(int(i))
  431. # obj_id = 0
  432. # self.soundSlots = []
  433. # for s in self.sconf['sounds']:
  434. # p1 = self.SoundSlot(s, obj_id, self)
  435. # self.soundSlots.append(p1)
  436. # if (len(self.sconf.as_list('volumes')) - 1) > obj_id:
  437. # p1.volume = int(self.sconf.as_list('volumes')[obj_id])
  438. # else:
  439. # p1.volume = 12
  440. # if (len(self.sconf.as_list('pitches')) - 1) > obj_id:
  441. # p1.pitch = int(self.sconf.as_list('pitches')[obj_id])
  442. # p1.set_pitch()
  443. # else:
  444. # p1.pitch = 0
  445. # print('adding ', s)
  446. # obj_id += 1
  447. # print(self.soundSlots)
  448. # _iter = 0
  449. # lst = ast.literal_eval(self.sconf['notes'][0])
  450. # print('length ', len(lst))
  451. # for n in self.soundSlots:
  452. # m = []
  453. # if (len(self.sconf.as_list('notes')) - 1) > _iter:
  454. # lst = ast.literal_eval(self.sconf.as_list('notes')[_iter])
  455. # n.notes = lst
  456. # _iter += 1
  457. # self.song = song
  458. # self.songCycle = cycle(self.song)
  459. # self.curPattern = next(self.songCycle)
  460. # self.songStart = self.curPattern
  461. def update_display(self, x):
  462. # if self.display_thread.is_alive():
  463. # pass
  464. # #self.disp.image(self.image, self.rotation)
  465. # else:
  466. # self.display_thread = threading.Thread(target=self.ud, args=([0]))
  467. # self.display_thread.start()
  468. # time.sleep(.001)
  469. self.disp.image(self.image, self.rotation)
  470. def ud(self, x):
  471. self.disp.image(self.image, self.rotation)
  472. def clear_notes_on(self):
  473. _iter = 0
  474. self.notes_on = []
  475. while _iter < 64:
  476. self.notes_on.append(0)
  477. _iter += 1
  478. p = Prog()
  479. #while True:
  480. while not done:
  481. p.Execute()
  482. if pygame.event.get(pygame.USEREVENT + 1):
  483. #if p.playhead == 0:
  484. #print('pattern ', p.curPattern)
  485. p.playhead += 1
  486. if p.playhead == 16:
  487. p.playhead = 0
  488. p.curPattern = next(p.songCycle)
  489. #blink internal led
  490. if p.playhead % 8 == 0:
  491. GPIO.setup(47, GPIO.OUT)
  492. GPIO.output(47, GPIO.LOW)
  493. else:
  494. GPIO.setup(47, GPIO.OUT)
  495. GPIO.output(47, GPIO.HIGH)
  496. p.pub.dispatch('beat', [p.curPattern, p.playhead])
  497. clock.tick_busy_loop()
  498. #print(clock.get_fps())
  499. pygame.quit()