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

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