Wednesday 30 October 2013

Some code samples...

I thought I might as well share some of the code I have been putting together to give an idea of complexity and structure. So here is the code for the part that displays the tuner. It needs refactoring, but isn't too embarassing.

You may also notice some code to dim the screen when nothing is happening. It doesn't work. A debug session is in order.

//////////////////////////////////////////////////////////////////////
// this code will aim to detect the nearest note and then show which
// direction to tune to get to the exact note
//////////////////////////////////////////////////////////////////////

void displayTuner() {
 
  String note = lastNote;
 
  // check to see if the sample buffer is ready
  if (isSampleReady() && isAmplitudeOK()) {
    frequency = getPitch();
    resetSampler();
    note = getNearestNote();
  }

  // if no amplitude detected, start to fade display
  if (!isAmplitudeOK()) {
    brightness--;
    if (brightness <= MIN_BRIGHTNESS) {
      brightness = MIN_BRIGHTNESS;
    }
  } else {
     brightness = MAX_BRIGHTNESS;
  }

  if (noteError == 0) {
    textColour = getGradientColour(brightness, SHADE_GREEN);
  }
  

  // redraw the background graphics if we've swapped sides of the error display
  if ((noteError == 0 && lastNoteError != 0) || (noteError < 0 && lastNoteError > 0) || (noteError > 0 && lastNoteError < 0)) {
    displayTunerGraphics();
  }

  if ((note != lastNote) || (textColour != lastTextColour)) {
    // display the note
    Display.txt_Height(5);
    Display.txt_Width(3);
    Display.txt_Attributes(0);
    Display.txt_Opacity(OPAQUE); 
    Display.gfx_OutlineColour(BLACK);
    Display.gfx_RectangleFilled(60, 0, 100, 50, BLACK);
    int xpos = note.length() * 22;
    xpos = 81 - (xpos / 2);
    displayTextAtPoint(note,textColour, xpos, 8);  
  } 
   
  Display.gfx_OutlineColour(colour); 
 
  int offset = TUNER_OFFSET;
  int increment = TUNER_INCREMENT;
  if (noteError > 0) {
    offset = 92 + offset;
    for (int i = 0; i < 10; i+=2) {
      if (noteError > i) {
        int shade = getGradientColour(brightness-(i*3), SHADE_GREEN);
        Display.gfx_RectangleFilled(offset, 5+i, offset+5, 45-i, shade);
      } else {
        Display.gfx_RectangleFilled(offset, 5+i, offset+5, 45-i, BLACK);
      }
      offset += increment;
    }
  } else if (noteError < 0) {
    offset = 67-offset;
    int invertError = -noteError;
    for (int i = 0; i < 10; i+=2) {
      if (abs(invertError) > i) {
        int shade = getGradientColour(brightness-(i*3), SHADE_GREEN);
        Display.gfx_RectangleFilled(offset, 5+i, offset-5, 45-i, shade);
      } else {
        Display.gfx_RectangleFilled(offset, 5+i, offset-5, 45-i, BLACK);
      }
      offset -= increment;
    }
  }
  
  lastTextColour =  textColour;
  lastNote = note;
  lastNoteError = noteError;
}

No comments:

Post a Comment