Sunday, December 7, 2008

Morse code on the EZ-430/MSP430

//******************************************************************************
// Morse code blinker program
// derived from a basic blinker app
//******************************************************************************

#include "msp430.h"

const char* morse_table[] = { 
  ".-" , // A
  "-...", // B
  "-.-.", // C
  "-..", // D
  ".", // E
  "..-.", // F
  "--." , // G
  "....", // H
  ".."  , // I
  ".---", // J
  ".-.-", // K
  ".-..", // L
  "--", // M
  "-.", // N
  "---", // O
  ".--.", // P
  "--.-", // Q
  ".-.", // R
  "...", // S
  "-", // T
  "..-", // U
  "...-", // V
  ".--", // W
  "-..-", // X
  "-.--", // Y
  "--.." // Z
  
};

/**
 * Low power mode sleep
 *
 */ 

void sleep(int howlong)
{
  int i;
    for(i=2*howlong;i>0;i--) { LPM0; }
}

/**
 * Turn on pin 1
 *
 */

inline void led_on()
{
      P1OUT |= 0x01;
}

/**
 * Turn off pin 1
 *
 */

inline void led_off()
{
      P1OUT &= ~0x01;
}

/**
 * Blink a string in morse code
 *
 * Takes a string and blinks it
 */

void blink_morse(const char *s)
{
  int i,j, letter_index;
  const char *dots;
  for(i=0;s[i] != (char) 0; i++){
    letter_index = -1;
    if (s[i] >= 'A' && s[i] <= 'Z')
      letter_index = (int) s[i] - (int) 'A';
    
    if (s[i] >= 'a' && s[i] <= 'z')
      letter_index = (int) s[i] - (int) 'a';
    
    if (letter_index != -1) {
      dots = morse_table[letter_index];
     for(j=0;dots[j] != (char) 0; j++) {
       switch(dots[j]) {
        case '.':
        led_on();
        sleep(1);
        led_off();
        break;
        
       case '-':
         led_on();
         sleep(3);
         led_off();
         break;
       }
      sleep(1);
     }
    } else {
      // not a regular character
      sleep(4); // medium gap when combined with short gap below
    }
    led_off();
    sleep(3); // short gap
  }
}

int main(void)
{
  
  WDTCTL = WDTPW + WDTHOLD;
 
 // Set pin 1 for output
  P1DIR |= 0x01;
  
 
  CCTL0 = CCIE;
  // set CCR0 delay to 60,000 
  CCR0 = 60000;
  TACTL = TASSEL_2 + MC_1;
 
  _BIS_SR(LPM0_bits + GIE);
  // start with the LED off
  led_off(); 

  for(;;)
  {

 blink_morse("This message is blinking in morse code");
 blink_morse("You can fit a paragraph or two into even the smallest MSP430");

 
    sleep(10);
  }
}

#pragma vector=TIMERA0_VECTOR
__interrupt void Timer_A (void)
{
 LPM0_EXIT; 
 
}

1 comment:

kb1kdw said...

Hi -- fun posting. Thanks for putting it out there. It has saved me some time. K should be -.-, not .-.- . I have used your code and extended it by adding numbers. Thanks, Matt KB1KDW