Shahariar
Published © GPL3+

Easy Programming (MBED supported) on Kinetis FRDM-K82F Board

1000 of K82 Freedom Boards are collecting dust because of the hobbyist unfriendly IDE; pump up the duds with easy Arduino-like functions.

IntermediateProtip1 hour2,665
Easy Programming (MBED supported) on Kinetis FRDM-K82F Board

Things used in this project

Story

Read more

Schematics

K82 Freedom Board

KDS driver files and code

Download and Unzip this, then import in Kinetis Design Studio as "Projects for Projects"

Code

Adruino Function in K82 Freedom Board

C/C++
Supported Functions :
pinMode()
digitalRead()
digitalWrite()
analogRead()
analogWrite()
analogWriteDAC()
delay()
millis()
Serial_println() [ Serial.println() version ]
// Copyleft by PissedOff

//============== PLEASE SCROLL DOWN TO THE PART WITH void setup() =============//
//============== void loop() TO WRITE DOWN ARDUINO STYLE CODE     =============//

#include "fsl_device_registers.h"
#include "board.h"
#include "fsl_debug_console.h"
#include "fsl_gpio.h"
#include "fsl_lptmr.h"
#include "clock_config.h"
#include "pin_mux.h"
#include "fsl_common.h"
#include "fsl_port.h"
#include "fsl_adc16.h"
#include "fsl_pit.h"
#include "fsl_dac.h"
#include "stdbool.h"
#include "fsl_lpuart.h"
#include "fsl_lptmr.h"

#define HIGH 1
#define LOW 0
#define OUTPUT 1
#define INPUT 0

// Arduino R3 Layout ADC (Single Ended 12 Bit) Location on K82, // 0-3 volt gives 0 - 4095
// R3 Eq --- ADC Channel ---- Actual Pin on K82 Board with alias to Arduino R3 layout
#define A0 		8    			// 		B0
#define A1 		9				// 		B1
#define A2 		15				// 		C1
#define A3 		4				// 		C2
#define A4 		13				// 		B3
#define A5 		12				// 		B2

// Alternative defines for ADC with Reference to the K82 Board also work
#define B0 		8
#define B1 		9
#define B2 		12
#define B3 		13
#define C1 		15
#define C2 		4

// Analog Write real PWM supported pins, don't use digital Read/Write on these pins
#define C8 		8
#define C9 		9
#define C10 	10

volatile uint32_t msruntime=0;

///!!!!!!!!!! WARNING !!!!!!!!!!!///
///!!!!!!!!!! WARNING !!!!!!!!!!!///
///!!!!!!!!!! WARNING !!!!!!!!!!!///
//
// millis generating timer, interrupt driven

void LPTMR0_LPTMR1_IRQHandler(void)
{
    LPTMR_ClearStatusFlags(LPTMR0, kLPTMR_TimerCompareFlag);
    msruntime++;

}

/*
DO NOT USE PortC 14, 15 pins as GPIO -> Connected to UART for debugging
DO NOT USE PortC 13 and  PortA 1, 2  pins as GPIO -> Connected to I2C for on Board Sensors

PortC 8, 9, 10 pins are connected to RGB LED ( good choice for PWM Output)
PortC 6 and PortA 4  pins are connected to tactile Switchs SW2, SW3 ( good choice for Input)
*/

void ArduinoK82Init (void);

// SUPPORTED ARDUINO FUNCTIONS //
// SUPPORTED ARDUINO FUNCTIONS //
// SUPPORTED ARDUINO FUNCTIONS //

//*** Porvided that board speed is 120 MHz
void delay(int); // Example:  delay (500) gives 500 ms

// * provide 3 parameters port,pin state
// * The char is port 'A' or 'B' or 'C' or 'D' since this board's pin
// * are like C7 instead of 7 or A13 instead of 13,
// * port letter must be inside '' mark

void pinMode(char,int,int);        // Example: pinMode ('C',7,OUTPUT);
void digitalWrite(char,int,int);   // Example: digitalWrite('C',7,LOW);
int digitalRead(char,int);         // Example: digitalRead('A',4)

// * reads single ended 12 bit Analog value on specific 6 pins ( Arduino R3 location of ADC pins)
int analogRead(int);               // Example: analogRead(A0) or analogRead(B0) are same Port B pin 0 (ADC channel

// * Makes Real Analog Voltage fixed DAC_Out pin, no PWM
// * for 3.3 V, analogWriteDAC(4095)
void analogWriteDAC(uint32_t);

// * FTM based PWM, supports upto 3 fixed Channels now
// * C7, C8, C9 if used as PWM, should never call Digital Read/Write/Pin mode
// * or Hard Fault will occer freezing CPU
void analogWrite(int,int);

// * Primary Serial Always Enabled @ Baud rate of 115200 NO NEED Serial.begin
// * works on Arduino IDE built in serial monitor or putty
void Serial_println (char[500]);
// for serial FPRINT ("text %d", number ) also works

uint32_t millis(void);
// * Second Low Power UART usable with BT HC 05/06 module or with USB-Serial Device



int main()
{
// *performs necessary initialization on K82 H/W for GPIO/ADC/PWM
	ArduinoK82Init();

/// void setup() starts here ///////////////////

    pinMode('B',20,OUTPUT); // buzzer
    pinMode('A',4,INPUT); // SW 2
    pinMode('A',5,OUTPUT); // Led 1 Blue
    pinMode('B',16,OUTPUT); // Led 1 Yel
    pinMode('A',12,OUTPUT); // Led 1 Blue


/// void setup() Stops Here ///////////////////

    while (1)
    {
/////////////// Arduino void loop() Below Here ///////////////////
    	// digital read/write
// millis test fn LED toggle at every 1000 ms
    	while(1)
    	{
    		int ms = millis();
    		if (ms%1000 == 0)
    		{

    			digitalWrite('A',5,HIGH);
    			int x= analogRead(C1);

    			delay(20);
    			PRINTF(" millis val: %d \r\n",ms);
    			PRINTF(" adc val: %d \r\n",x);

    		}
    		else
    			digitalWrite('A',5,LOW);

    	}


    	// poll check switch press
     if  (digitalRead('A',4)==1)
        		 {

				for(int i=0;i<20;i++)
				{	digitalWrite('A',5,HIGH);
					delay(50);
					digitalWrite('A',5,LOW);
					delay(50);

				}
		// Real DAC
				for(int i=0;i<100;i++)
				{
				analogWriteDAC(i*40);
			 	delay(50);
	    		}

				for(int i=0;i<100;i++)
				{
				analogWrite(8,i);
				delay(50);
				analogWrite(9,i/2);
				delay(50);
				analogWrite(10,2*i/4);
				delay(50);
        		 }
        		 }
					else // sw on board is active low, following executes on press
				{


						digitalWrite('B',16,HIGH);
         	     	digitalWrite('B',20,HIGH);

                	 delay(125);
                	 digitalWrite('B',16,LOW);
                	 digitalWrite('B',20,LOW);

                	 for(int i=0;i<500;i++)
                	 {
                	 analogWrite(8,i/5);
                	 delay(5);
                	 analogWrite(9,i/20);
                	 delay(5);
                	 analogWrite(10,i/10);
                	 delay(5);
                	 }

     	 	 	 }


    } // while(1) or void loop() ends here

} // main() ends here


//////////// Arduino Function Body - DONT MODIFY ///////////////////////////

/*
// old blocking delay
void delay(int ms)
{
    volatile uint32_t i = 0;
    for (i = 0; i < 12000*ms; ++i)
    {
        __asm("NOP");
    }
}

void delaymicroSeconds(int us)
{
    volatile uint32_t i = 0;
    for (i = 0; i < 12*us; ++i)
    {
        __asm("NOP");
    }
}

 */

// new delay
void delay( int ms)
{
	  SysTick->CTRL |= SysTick_CTRL_CLKSOURCE_Msk;
		    SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;
		    SysTick->LOAD = ms * ((CLOCK_GetFreq(kCLOCK_CoreSysClk)) / 1000U);
		    SysTick->VAL = 0U;

		    SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk;

		    /* wait for timeout */
		    while (0U == (SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk))
		    {}
}

void pinMode(char port,int pin,int state)

{
	BOARD_InitPins();

	gpio_pin_config_t output = {
        kGPIO_DigitalOutput, 0,
    };

	gpio_pin_config_t input = {
	        kGPIO_DigitalInput, 0,
	    };

	if (port =='A' && state==1)
	{
		PORT_SetPinMux(PORTA, pin, kPORT_MuxAsGpio);
		GPIO_PinInit(GPIOA, pin, &output);

	}
	if (port =='A' && state==0)
	{
	PORT_SetPinMux(PORTA, pin, kPORT_MuxAsGpio);
    GPIO_PinInit(GPIOA, pin, &input);
	}
	    if (port =='B' && state==1)
		{
	    PORT_SetPinMux(PORTB, pin, kPORT_MuxAsGpio);
	    GPIO_PinInit(GPIOB, pin, &output);
		}
		if (port =='B' && state==0)
		{
		PORT_SetPinMux(PORTB, pin, kPORT_MuxAsGpio);
	    GPIO_PinInit(GPIOB, pin, &input);
		}
		    if (port =='C' && state==1)
			{
		    PORT_SetPinMux(PORTC, pin, kPORT_MuxAsGpio);
		    GPIO_PinInit(GPIOC, pin, &output);
			}
			if (port =='C' && state==0)
			{
			PORT_SetPinMux(PORTC, pin, kPORT_MuxAsGpio);
			GPIO_PinInit(GPIOC, pin, &input);
			}
				if (port =='D' && state==1)
				{
				PORT_SetPinMux(PORTD, pin, kPORT_MuxAsGpio);
				GPIO_PinInit(GPIOD, pin, &output);
				}
				if (port =='D' && state==0)
				{
				PORT_SetPinMux(PORTD, pin, kPORT_MuxAsGpio);
				GPIO_PinInit(GPIOD, pin, &input);
				}


}

void digitalWrite (char port,int pin,int state)
{
if(port=='A')
	{GPIO_WritePinOutput (GPIOA, pin, state);}
if(port=='B')
	{GPIO_WritePinOutput (GPIOB, pin, state);}
if(port=='C')
	{GPIO_WritePinOutput (GPIOC, pin, state);}
if(port=='D')
	{GPIO_WritePinOutput (GPIOD, pin, state);}

}

int digitalRead (char port,int pin)
{

if(port=='A')
	{return GPIO_ReadPinInput (GPIOA, pin);}
if(port=='B')
	{return GPIO_ReadPinInput (GPIOB, pin);}
if(port=='C')
	{return GPIO_ReadPinInput (GPIOC, pin);}
if(port=='D')
	{return GPIO_ReadPinInput (GPIOD, pin);}
}

void Serial_println(char str[500])
{

PRINTF("\r\n");
PRINTF(str);
PRINTF("\r\n");
}

int analogRead(int adc_Ch)

{
	uint32_t temp=0;
	for (int j=0;j<50;j++)
	{
    adc16_config_t adc16ConfigStruct;
    adc16_channel_config_t adc16ChannelConfigStruct;
    ADC16_GetDefaultConfig(&adc16ConfigStruct);
#ifdef BOARD_ADC_USE_ALT_VREF
    adc16ConfigStruct.referenceVoltageSource = kADC16_ReferenceVoltageSourceValt;
#endif
    ADC16_Init(ADC0, &adc16ConfigStruct);
    ADC16_EnableHardwareTrigger(ADC0, false); /* Make sure the software trigger is used. */
#if defined(FSL_FEATURE_ADC16_HAS_CALIBRATION) && FSL_FEATURE_ADC16_HAS_CALIBRATION
    if (kStatus_Success == ADC16_DoAutoCalibration(ADC0))
    {
    }
    else
    {
    }
#endif

    adc16ChannelConfigStruct.channelNumber = adc_Ch;
    adc16ChannelConfigStruct.enableInterruptOnConversionCompleted = false;
#if defined(FSL_FEATURE_ADC16_HAS_DIFF_MODE) && FSL_FEATURE_ADC16_HAS_DIFF_MODE
    adc16ChannelConfigStruct.enableDifferentialConversion = false;
#endif



        ADC16_SetChannelConfig(ADC0, 0, &adc16ChannelConfigStruct);
        while (0U == (kADC16_ChannelConversionDoneFlag &
                      ADC16_GetChannelStatusFlags(ADC0, 0)))
        {
        }
        temp=temp+ ADC16_GetChannelConversionValue(ADC0, 0);
}
return temp/50;

    }

void ArduinoK82Init (void)
{
	// These Functions must be included for clocking and debugging K82 Freedom //
	BOARD_InitPins();
    BOARD_BootClockRUN();
    BOARD_InitDebugConsole();
    ftm_config_t ftmInfo;
// sets parameters for pwm signal such as Channel No, Duty etc... 3 for 3 channels
    ftm_chnl_pwm_signal_param_t ftmParam[3];

    PORT_SetPinMux(PORTC, 8U, kPORT_MuxAlt3);
    ftmParam[0].chnlNumber = (ftm_chnl_t)4U;
    ftmParam[0].level = kFTM_LowTrue;
    ftmParam[0].dutyCyclePercent = 0U;
    ftmParam[0].firstEdgeDelayPercent = 0U;

    	PORT_SetPinMux(PORTC, 9U, kPORT_MuxAlt3);
   	    ftmParam[1].chnlNumber = (ftm_chnl_t)5U;
   	    ftmParam[1].level = kFTM_LowTrue;
   	    ftmParam[1].dutyCyclePercent = 0U;
   	    ftmParam[1].firstEdgeDelayPercent = 0U;

   	    	PORT_SetPinMux(PORTC, 10U, kPORT_MuxAlt3);
   	 		ftmParam[2].chnlNumber = (ftm_chnl_t)6U;
   	 	    ftmParam[2].level = kFTM_LowTrue;
   	 	    ftmParam[2].dutyCyclePercent = 0U;
   	 	    ftmParam[2].firstEdgeDelayPercent = 0U;

    FTM_GetDefaultConfig(&ftmInfo);
    FTM_Init(FTM3, &ftmInfo);
    FTM_SetupPwm(FTM3, ftmParam, 3U, kFTM_EdgeAlignedPwm, 24000U, CLOCK_GetFreq(kCLOCK_BusClk));

    FTM_StartTimer(FTM3, kFTM_SystemClock);



    lptmr_config_t lptmrConfig;
    LPTMR_GetDefaultConfig(&lptmrConfig);
    LPTMR_Init(LPTMR0, &lptmrConfig);
    LPTMR_SetTimerPeriod(LPTMR0, USEC_TO_COUNT(1000U, CLOCK_GetFreq(kCLOCK_LpoClk)));
    LPTMR_EnableInterrupts(LPTMR0, kLPTMR_TimerInterruptEnable);
    EnableIRQ(LPTMR0_LPTMR1_IRQn);
    LPTMR_StartTimer(LPTMR0);


}

uint32_t millis(void)
{
	return msruntime;
}

void analogWriteDAC(uint32_t dacValue)

{
    dac_config_t dacConfigStruct;
   DAC_GetDefaultConfig(&dacConfigStruct);
   DAC_Init(DAC0, &dacConfigStruct);
  DAC_SetBufferReadPointer(DAC0, 0U);
 if (dacValue>4095)
 {dacValue=4095;}

  DAC_SetBufferValue(DAC0, 0U, dacValue); // dacValue range 0-4095
}

void analogWrite (int pin ,int duty)
{

	if (duty>100)
	{duty=100;} // bound)

	    /* Configure ftm params with frequency 24kHZ */
if (pin==8)
{
        FTM_UpdatePwmDutycycle(FTM3, (ftm_chnl_t)4U, kFTM_EdgeAlignedPwm,duty);
        FTM_SetSoftwareTrigger(FTM3, true);

}

if (pin==9)
{
		FTM_UpdatePwmDutycycle(FTM3, (ftm_chnl_t)5U, kFTM_EdgeAlignedPwm,duty);
        FTM_SetSoftwareTrigger(FTM3, true);


}


if (pin==10)
{

	        FTM_UpdatePwmDutycycle(FTM3, (ftm_chnl_t)6U, kFTM_EdgeAlignedPwm,duty);

	        FTM_SetSoftwareTrigger(FTM3, true);
	    }




}

Credits

Shahariar

Shahariar

74 projects • 265 followers
"What Kills a 'Great life' is a 'Good Life', which is Living a Life Inside While Loop"

Comments