Advertisement
Guest User

MSGEQ7 graphic visualizer on Espruino

a guest
May 19th, 2014
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // MSGEQ7 chip
  2. var msg7RESET = B9,
  3.     msg7Strobe = B8,
  4.     msg7DCout = A0;
  5.  
  6.  
  7. // Band values
  8. var levels = [];
  9. var poll = null;
  10. var band = 0,
  11.     bass = 0,
  12.     tmp = 0;
  13.  
  14.  
  15. SPI2.setup({baud:3200000, mosi:B15});
  16. var matrix = Graphics.createArrayBuffer(16,8,24,{zigzag:true});
  17. matrix.flip = function(){ SPI2.send4bit(matrix.buffer, 0b0001, 0b0011); };
  18.  
  19.  
  20. function onInit() {
  21.   setInterval(loop, 1000/120);
  22. }
  23.  
  24.  
  25.  
  26. function loop() {
  27.  
  28.   // Reset the MSGEQ7's counter
  29.   digitalWrite(msg7RESET, 1);
  30.   digitalWrite(msg7RESET, 0);
  31.  
  32.   band = 0;
  33.   poll = setInterval(function(){
  34.     if ((band&1)===0) {
  35.       digitalWrite(msg7Strobe, 0);
  36.     } else {
  37.       // Get outputted value and store it
  38.       tmp = analogRead(msg7DCout);
  39.       if(tmp < 0.06) {
  40.         levels[band>>1] = 0;
  41.       } else {
  42.         levels[band>>1] = tmp;
  43.       }
  44.      
  45.       digitalWrite(msg7Strobe, 1);
  46.     }
  47.     // Stop after 7 bands
  48.     band++;
  49.     if(band >= 14) { clearInterval(poll); }
  50.   }, 0.035); // 35 microseconds
  51.  
  52.  
  53.   matrix.clear();
  54.  
  55.   fullLevels = expandLevels(levels);
  56.  
  57.   // Draw bars
  58.   for(var i=0; i < fullLevels.length; i++) {
  59.     drawBar(i, fullLevels[i]);
  60.   }
  61.  
  62.   // BASS
  63.   bass = fullLevels[0] / 3;
  64.   matrix.setColor(fullLevels[0]/2,fullLevels[2]/2,fullLevels[10]/2);
  65.   matrix.fillRect(14, 0, 15, 1);
  66.   // MID
  67.   bass = fullLevels[2] / 2;
  68.   matrix.setColor(bass,0,bass);
  69.   matrix.fillRect(14, 3, 15, 4);
  70.   // MIX
  71.   bass = fullLevels[10] / 2;
  72.   matrix.setColor(bass,bass,0);
  73.   matrix.fillRect(14, 6, 15, 7);
  74.  
  75.   matrix.flip();
  76.  
  77. }
  78.  
  79. function drawBar(bar, level) {
  80.   level = Math.round(level * 8);
  81.  
  82.   matrix.setColor(0.05, 0, 0.05);
  83.   matrix.fillRect(bar,  8-level, bar,  8);
  84.  
  85. }
  86.  
  87.  
  88. function expandLevels(levels) {
  89.   var newLevels = [];
  90.  
  91.   for(var i=0; i < levels.length; i++) {
  92.     newLevels[i*2] = levels[i];
  93.     if((i+1) < levels.length) {
  94.       newLevels[i*2+1] = (levels[i] + levels[(i+1)]) / 2;
  95.     }
  96.   }
  97.  
  98.   return newLevels;
  99.  
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement