/*
 * hal.c
 *
 *  Created on: Apr 7, 2020
 *  Modified on: Jan.9, 2021   / a0235549
 *      Author: a0223954
 */
#include "msp430.h"

void hal_init(void)
{
    // Disable the GPIO power-on default high-impedance mode
    // to activate previously configured port settings
    PM5CTL0 &= ~LOCKLPM5;

    // Configure two FRAM waitstate as required by the device datasheet for MCLK
    // operation at 24MHz(beyond 8MHz) _before_ configuring the clock system.
    FRCTL0 = FRCTLPW | NWAITS_2;

    __bis_SR_register(SCG0);                           // disable FLL
    CSCTL3 |= SELREF__REFOCLK;                         // Set REFO as FLL reference source
    CSCTL0 = 0;                                        // clear DCO and MOD registers
    CSCTL1 |= DCORSEL_7;                               // Set DCO = 24MHz
    CSCTL2 = FLLD_0 + 731;                             // DCOCLKDIV = 24MHz
    __delay_cycles(3);
    __bic_SR_register(SCG0);                           // enable FLL
    while(CSCTL7 & (FLLUNLOCK0 | FLLUNLOCK1));         // FLL locked

    CSCTL4 = SELMS__DCOCLKDIV | SELA__REFOCLK;         // set default REFO(~32768Hz) as ACLK source, ACLK = 32768Hz
                                                       // default DCOCLKDIV as MCLK and SMCLK source
    CSCTL5 |= DIVM_0 | DIVS_2;                         // MCLK = DCOCLK = 24MHZ, SMCLK = DCOCLK/4 = 6MHz

    // LCD configuration
    P2OUT = 0x00;
    P2DIR |= BIT2+BIT3+BIT5+BIT7;


    // SPI, P2.4-LCD_SCL,P2.6-LCD_SDA
    P2SEL0 |= BIT4 | BIT6;                    // set 3-SPI pin as second function
    UCA1CTLW0 |= UCSWRST;                     // **Put state machine in reset**
    UCA1CTLW0 |= UCMST|UCSYNC|UCCKPH|UCMSB;   // 3-pin, 8-bit SPI master
                                              // Clock polarity high, MSB
    UCA1CTLW0 |= UCSSEL__SMCLK;               // Select SMCLK
    UCA1BR0 = 0x01;                           // BRCLK = SMCLK/6
    UCA1BR1 = 0;                              //
    UCA1MCTLW = 0;                            // No modulation
    UCA1CTLW0 &= ~UCSWRST;                    // **Initialize USCI state machine**
    UCA1IE |= UCRXIE;

    // Data Log Configuration
    P1SEL0 |= BIT4;             // RXD
    P1SEL0 |= BIT5;             // TXD
    // Configure UART
    UCA0CTLW0 |= UCSWRST;
    UCA0CTLW0 |= UCSSEL__SMCLK;

    // Baud Rate calculation
    // 6000000/(16*115200) = 3.255
    // Fractional portion = 0.255
    // User's Guide Table 17-4: UCBRSx = 0x44
    // UCBRFx = int ( (3.255-3)*16) = 4
    UCA0BR0 = 3;                              // 6000000/16/115200
    UCA0BR1 = 0x00;
    UCA0MCTLW = 0x4400 | UCOS16 | UCBRF_4;
    UCA0CTLW0 &= ~UCSWRST;                    // Initialize eUSCI

//    UCA0IE |= UCRXIE;                         // Enable USCI_A0 RX interrupt

}
