Saturday, September 7, 2013

Python Serial Talkies, Interface Milestone 2

I tweaked the arduino dartboard interface sketch a little bit and wrote a test python script to talk to the dartboard.  I used PySerial to handle the USB port.  It was easy to implement and is working well so far.

I put a little handshake business in there, but otherwise really trust that everything will work just swell all the time.  It worked almost immediately, so I got to spend a long time fiddling with minutia.  

I let it sit for a couple days and then kept noticing the snipped wires from the dartboard's speaker dangling near the small breadboard that attaches to the dartboards ribbon connector.  So I found the Arduino tones example, wired the speaker to the breadboard, grounding one and sending the other to arduino digital pin 12, through a 100 Ohm resistor and added a generic playMelody procedure in the interface sketch.

// based on the arduino tones example, plays the given melody
void playMelody(int melody[], int noteDurations[], int notecount) {
  // don't even try to play nothin' if we don't got no speaker
  if (HAS_SPEAKER) {
    noTone(SPEAKER_PORT);
    
    // iterate over the notes of the melody:
    for (int thisNote = 0; thisNote < notecount; thisNote++) {
  
      // to calculate the note duration, take one second 
      // divided by the note type.
      //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
      int noteDuration = 1000/noteDurations[thisNote];
      tone(SPEAKER_PORT, melody[thisNote], noteDuration);
  
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);
      
      // stop the tone playing:
      noTone(SPEAKER_PORT);
    }
  }
}

Then a playCharge procedure which is called when the interface changes to the play state.

void playCharge() {
  int notes[] = {NOTE_G3, NOTE_C4, NOTE_E4, NOTE_G4, NOTE_E4, NOTE_G4};
  int durations[] = {8, 8, 8, 4, 8, 2};
  int noteCount = 6;
  
  playMelody(notes, durations, noteCount);
}


...
      case IFACE_PLAY:
        if (gameState == IFACE_STOP) {
          gameState = IFACE_PLAY;
          Serial.write(IFACE_PLAY);
          playCharge();
        }
        break;
...

It's totally awesome.

I ordered me a raspberry pi and will be working on the pygame dartboard game engine.

No comments:

Post a Comment