I saw this article on Hack a Day today for a library that supports some Arduino-like functions. I thought I’d share a couple of code snippets I have for analogRead(), millis(), and delayMillis(). The delay function on the HaD article used a software delay loop. My millis() and delayMillis() use the WDT.

Here’s my take on the time functions:


#include "msp430g2231.h"

#define MCLK_FREQUENCY      1000000
#define WDT_DIVIDER        512

const unsigned long WDT_FREQUENCY = MCLK_FREQUENCY / WDT_DIVIDER;
volatile unsigned long wdtCounter = 0;

unsigned long millis(){
  return wdtCounter / ((float)WDT_FREQUENCY / 1000);
}

void delayMillis(unsigned long milliseconds){
  unsigned long wakeTime = wdtCounter + (milliseconds * WDT_FREQUENCY / 1000);
  while(wdtCounter < wakeTime);
}

void main(void){
  DCOCTL = CALDCO_1MHZ;
  BCSCTL1 = CALBC1_1MHZ;
  WDTCTL = WDTPW + WDTTMSEL + WDTIS1;
  IE1 |= WDTIE;
  _BIS_SR(GIE);
  
  // toggle pin every second
  P1DIR |= BIT0;
  while(1){
    P1OUT ^= BIT0;
    delayMillis(1000);
  }
}
    
#pragma vector=WDT_VECTOR
__interrupt void watchdog_timer(void){
  wdtCounter++;
}

And here’s the analog functions:


#include "msp430g2231.h"

#define ANALOG_PIN      4

unsigned int analogRead(){
  ADC10CTL0 |= ADC10SC;
  while(ADC10CTL1 & ADC10BUSY);
  return ADC10MEM;
}

void analogPinSelect(unsigned int pin){
  if(pin < 8){
    ADC10CTL0 &= ~ENC;
    ADC10CTL1 = pin << 12;
    ADC10CTL0 = ADC10ON + ENC + ADC10SHT_0;
  }
}

void main(void){
  unsigned int analogValue;
  
  DCOCTL = CALDCO_1MHZ;
  BCSCTL1 = CALBC1_1MHZ;
  WDTCTL = WDTPW + WDTHOLD;
  
  // read adc repeatedly
  analogPinSelect(ANALOG_PIN);
  while(1){
    analogValue = analogRead();
  }
}

They’re not pure Arduino, but close.