#include "msp.h"
#include "stdint.h"

void error(void);

int main(void)
{
	uint32_t currentPowerState;
	WDTCTL = WDTPW | WDTHOLD;               // Stop WDT


	/* NOTE: This example assumes the default power state is AM0_LDO.
	* Refer to  MSP4322001_pcm_0x code examples for more complete PCM operations
	* to exercise various power state transitions between active modes.
	*/

	/* Step 1: Transition to VCORE Level 1: AM0_LDO --> AM1_LDO */

	/* Get current power state, if it's not AM0_LDO, error out */
	currentPowerState = PCMCTL0 & CPM_M;
	if (currentPowerState != CPM_0)
		error();

	while ((PCMCTL1 & PMR_BUSY));
	PCMCTL0 = PCM_CTL_KEY_VAL | AMR_1;
	while ((PCMCTL1 & PMR_BUSY));
	if (PCMIFG & AM_INVALID_TR_IFG)
		error();                            // Error if transition was not successful
	if ((PCMCTL0 & CPM_M) != CPM_1)
		error();                            // Error if device is not in AM1_LDO mode

	/* Step 2: Configure Flash wait-state to 2 for both banks 0 & 1 */
	FLCTL_BANK0_RDCTL = FLCTL_BANK0_RDCTL & ~FLCTL_BANK0_RDCTL_WAIT_M | FLCTL_BANK0_RDCTL_WAIT_1;
	FLCTL_BANK1_RDCTL = FLCTL_BANK0_RDCTL & ~FLCTL_BANK1_RDCTL_WAIT_M | FLCTL_BANK1_RDCTL_WAIT_1;

	/* Step 3: Configure DCO to 48MHz, ensure MCLK uses DCO as source*/
	CSKEY = CSKEY_VAL;                        // Unlock CS module for register access
	CSCTL0 = 0;                            // Reset tuning parameters
	CSCTL0 = DCORSEL_5;                    // Set DCO to 48MHz
	/* Select MCLK = DCO, no divider */
	CSCTL1 = CSCTL1 & ~(SELM_M | DIVM_M) | SELM_3;
	CSKEY = 0;                             // Lock CS module from unintended accesses


	/* Step 4: Output MCLK to port pin to demonstrate 48MHz operation */
	P4DIR |= BIT3;
	P4SEL0 |=BIT3;                         // Output MCLK
	P4SEL1 &= ~(BIT3);
	P1DIR |= BIT0;

	/* Go to sleep */
	while(1)
	{
		P1OUT ^= BIT0;
		P1OUT ^= BIT0;
		//Delayms(1000);
	}
	__sleep();
	__no_operation();                      // For debugger


}

void error(void)
{
	volatile uint32_t i;
	P1DIR |= BIT0;
	while (1)
	{
		P1OUT ^= BIT0;
		for(i=0;i<20000;i++);       // Blink LED forever
	}
}