terça-feira, 18 de outubro de 2016

PIC32 FreeRTOS The First Task: Blink LED



It's my first project with FreeRTOS and PIC32MX Port.
This program has three tasks that blink three LEDs with different frequencies.
The period of each task is 250 ms, 500 ms and 1000 ms.
The tasks have different priorities.
Real Time Operating System.
FreeRTOS v6.0.4 Kernel.
PIC32MX795F512L MIPS32 M4K Core @80 MHz 32-bit.
Debug the FreeRTOS with RTOS Viewer.
My First Project step-to-step.
The First Task: Blink LED.

Exemplo de como implementar o FreeRTOS v6.0.4, um Sistema Operacional em Tempo Real, com o PIC32.
São criadas 3 tarefas, com 3 prioridades diferentes, que piscam 3 LEDs em frequências distintas.
O projeto foi criado no MPLAB IDE v8.83 e compilado com o MPLAB C32 v2.02.
Utiliza o plugin RTOS Viewer no MPLAB para visualizar o estado das tarefas (tasks) e do escalonador (scheduler) do freeRTOS.
Cada task tem a tarefa de inverter o estado de um LED do PIC32 USB Starter Kit II e enviar para a saída padrão (SIM UART no MPLAB) uma string com o período de execução.




Hardware:
PIC32 USB Starter Kit II.

Software:
MPLAB IDE v8.83
MPLAB C32 Compiler v2.02
RTOS Viewer plugin.

Firmware:
FreeRTOS v6.0.4 kernel.




 
 Figure 1 - MPLAB IDE Project Structure.


Figure 2 - MPLAB IDE Build Options - Include Search Path for FreeRTOS port.

Figure 3 - MPLAB IDE Build Options - C Compiler Preprocessor Macro.





 
 Figure 4 - RTOS Viewer- MPLAB IDE plugin - FreeRTOS Scheduler Status.


 
Figure 5 - RTOS Viewer - Tasks Status.



Blink LEDs Project Video

Video 1 - The First Task: blink three LEDs with different frequencies.




Advanced Projects

 Video 2 - PIC32 Bluetooth DotStack HID Keyboard + RN42 Module.

 
Video 3 - PIC32 Bluetooth "App Blue Control" DotStack SDK SPP Android FreeRTOS - RN42 Module.
 

Video 4 -  PIC32 FreeRTOS Combo GOL + TCPIP MultiTask Application.
6 Tasks + 4 Semaphores + 1 Queue

Combo MultiTasks:
- Task TCP/IP;
- Task Graphics;
- Task TouchScreen;
- Task Refresh;
- Task Blink;
- Task I/O.

 Video 5 - PIC32 FreeRTOS My RTOS picoSYSTEM DOOR 32 MultiTask GOL + TCPIP + USB.
7 Tasks + 4 Semaphores + 1 Queue

TCP/IP + GOL + USB  MultiTasks

- TCP/IP Stack
- Graphic Display Library
- MDD I/O File System
- USB Stack
- Image Decoder
 7 Tasks running in Real-Time:
- task TCP/IP;
- task Graphic Display;
- task TouchScreen;
- task USB;
- task I/O;
- task Refresh Display;
- task Blink Heart Beat.


PIC32MX795F512 microcontroller:
- MIPS M4K core 32-bit;
- 80 MHz;
- 512 kB Flash;
- 128 kB RAM;
- 16 channels DMA;
- 16 channels ADC;
- USB 2.0;
- Ethernet 10/100 Mbps with internal MAC.



References:


WENN, Darren. Integrating Microchip Libraries with a Real-Time Operating System. Microchip Application Note AN1264. 2009.

WENN, Darren. Microchip RTOS and Stacks Demo Application. "AN1264 MCHP and FreeRTOS Demo". 2009.

BARRY, Richard. Using the FreeRTOS Real Time Kernel. A Pratical Guide, PIC32 Edition. Real Time Engineers.

FREERTOS. Microchip PIC32 MX RTOS port. Available in: http://www.freertos.org/port_PIC32_MIPS_MK4.html

FREERTOS. API. Available in: http://www.freertos.org/a00106.html

FREERTOS. FreeRTOS Demo Applications. Available in: http://www.freertos.org/a00102.html

uCONTROL.FreeRTOS, ejemplos en C32. Forum.2011. Available in: http://www.ucontrol.com.ar/forosmf/programacion-en-c/freertos-ejemplos-en-c32/

MICROCHIP web site: www.microchip.com/

FreeRTOS website: www.freertos.org/

 
Blink LEDs Example Project Code

main.c code:

// ***************************************************************************
// *             Meu Primeiro Projeto FreeRTOS com PIC32 MX
// *
// *        Cria 3 tasks  para piscar 3 LEDs com diferentes frequencias
// *************************************************************************

// PIC32 USB Starter Kit II
// Junho/2014   

#include <p32xxxx.h>

/*********************** CONFIGURATION BITS FUSES **************************/

#pragma config FPLLODIV=DIV_1, FPLLIDIV=DIV_2, FPLLMUL=MUL_20, FPBDIV=DIV_2
#pragma config FWDTEN=OFF, FCKSM=CSDCMD, POSCMOD=XT, FNOSC=PRIPLL
#pragma config CP=OFF, BWP=OFF
#pragma config FMIIEN = OFF, FETHIO = OFF    // external PHY in RMII

/********************* INCLUDE HEADER **************************************/

#include <plib.h>
#include "FreeRTOS.h"
#include "task.h"


int i=0,j=0,k=0;

/************************ PROTOTYPES ***************************************/

static void vTASK1( void *pvParameters );
static void vTASK2( void *pvParameters );
static void vTASK3( void *pvParameters );


/*************************** MAIN ******************************************/

int main( void ){
    
    SYSTEMConfigPerformance( configCPU_CLOCK_HZ - 1 );
    mOSCSetPBDIV( OSC_PB_DIV_2 );

    INTEnableSystemMultiVectoredInt();
    portDISABLE_INTERRUPTS();
    
    TRISDbits.TRISD0=0;
    TRISDbits.TRISD1=0;
    TRISDbits.TRISD2=0;        

    vPortInitialiseBlocks();

    xTaskCreate( vTASK1, "Task1", 200, NULL, tskIDLE_PRIORITY + 1, NULL );
    xTaskCreate( vTASK2, "Task2", 200, NULL, tskIDLE_PRIORITY + 2, NULL );
    xTaskCreate( vTASK3, "Task3", 200, NULL, tskIDLE_PRIORITY + 3, NULL );

    vTaskStartScheduler();
}
/************************** TASK 1 *****************************************/
static void vTASK1( void *pvParameters ){
    while(1)
    {
        LATDbits.LATD0=!PORTDbits.RD0;
        vTaskDelay(250/portTICK_RATE_MS);
        i++;
    }
}
/************************** TASK 2 *****************************************/
static void vTASK2( void *pvParameters ){
    while(1){
        LATDbits.LATD1=!PORTDbits.RD1;
        vTaskDelay(500/portTICK_RATE_MS);
        j++;
    }
}
/************************** TASK 3 *****************************************/
static void vTASK3( void *pvParameters ){
    while(1){
        LATDbits.LATD2=!PORTDbits.RD2;
        vTaskDelay(1000/portTICK_RATE_MS);
        k++;
    }
}
/************************* OVERFLOW ****************************************/
void vApplicationStackOverflowHook( void )
{
     for( ;; );
}
/*********************** EXCEPTION HANDLER *********************************/
void _general_exception_handler( unsigned portLONG ulCause, unsigned portLONG ulStatus )
{
    for( ;; );
}
/**************************** END ******************************************/



FreeRTOSConfig.h code:

/*
    FreeRTOS V6.0.4 - Copyright (C) 2010 Real Time Engineers Ltd.

    ***************************************************************************
    *                                                                         *
    * If you are:                                                             *
    *                                                                         *
    *    + New to FreeRTOS,                                                   *
    *    + Wanting to learn FreeRTOS or multitasking in general quickly       *
    *    + Looking for basic training,                                        *
    *    + Wanting to improve your FreeRTOS skills and productivity           *
    *                                                                         *
    * then take a look at the FreeRTOS eBook                                  *
    *                                                                         *
    *        "Using the FreeRTOS Real Time Kernel - a Practical Guide"        *
    *                  http://www.FreeRTOS.org/Documentation                  *
    *                                                                         *
    * A pdf reference manual is also available.  Both are usually delivered   *
    * to your inbox within 20 minutes to two hours when purchased between 8am *
    * and 8pm GMT (although please allow up to 24 hours in case of            *
    * exceptional circumstances).  Thank you for your support!                *
    *                                                                         *
    ***************************************************************************

    This file is part of the FreeRTOS distribution.

    FreeRTOS is free software; you can redistribute it and/or modify it under
    the terms of the GNU General Public License (version 2) as published by the
    Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes FreeRTOS without being obliged to provide the
    source code for proprietary components outside of the FreeRTOS kernel.
    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
    more details. You should have received a copy of the GNU General Public 
    License and the FreeRTOS license exception along with FreeRTOS; if not it 
    can be viewed here: http://www.freertos.org/a00114.html and also obtained 
    by writing to Richard Barry, contact details for whom are available on the
    FreeRTOS WEB site.

    1 tab == 4 spaces!

    http://www.FreeRTOS.org - Documentation, latest information, license and
    contact details.

    http://www.SafeRTOS.com - A version that is certified for use in safety
    critical systems.

    http://www.OpenRTOS.com - Commercial support, development, porting,
    licensing and training services.
*/

#ifndef FREERTOS_CONFIG_H
#define FREERTOS_CONFIG_H

#include <p32xxxx.h>

/*-----------------------------------------------------------
 * Application specific definitions.
 *
 * These definitions should be adjusted for your particular hardware and
 * application requirements.
 *
 * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
 * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. 
 *
 * See http://www.freertos.org/a00110.html.
 *----------------------------------------------------------*/

#define configUSE_PREEMPTION                   1
#define configUSE_IDLE_HOOK                    0
#define configUSE_TICK_HOOK                    0
#define configTICK_RATE_HZ                     ( ( portTickType ) 1000 )
#define configCPU_CLOCK_HZ                     ( ( unsigned long ) 80000000UL )  
#define configPERIPHERAL_CLOCK_HZ              ( ( unsigned long ) 40000000UL )
#define configMAX_PRIORITIES                   ( ( unsigned portBASE_TYPE ) 5 )
#define configMINIMAL_STACK_SIZE               ( 190 )
#define configISR_STACK_SIZE                   ( 400 )
#define configTOTAL_HEAP_SIZE                  ( ( size_t ) 28000 )
#define configMAX_TASK_NAME_LEN                ( 8 )
#define configUSE_TRACE_FACILITY               0
#define configUSE_16_BIT_TICKS                 0
#define configIDLE_SHOULD_YIELD                1
#define configUSE_MUTEXES                      1
#define configCHECK_FOR_STACK_OVERFLOW         2
#define configQUEUE_REGISTRY_SIZE              0

/* Co-routine definitions. */
#define configUSE_CO_ROUTINES                  0
#define configMAX_CO_ROUTINE_PRIORITIES      ( 2 )

/* Set the following definitions to 1 to include the API function, or zero
to exclude the API function. */

#define INCLUDE_vTaskPrioritySet                 1
#define INCLUDE_uxTaskPriorityGet                1
#define INCLUDE_vTaskDelete                      0
#define INCLUDE_vTaskCleanUpResources            0
#define INCLUDE_vTaskSuspend                     1
#define INCLUDE_vTaskDelayUntil                  1
#define INCLUDE_vTaskDelay                       1
#define INCLUDE_uxTaskGetStackHighWaterMark      1

/* The priority at which the tick interrupt runs.  This should probably be
kept at 1. */
#define configKERNEL_INTERRUPT_PRIORITY          0x01

/* The maximum interrupt priority from which FreeRTOS.org API functions can
be called.  Only API functions that end in ...FromISR() can be used within
interrupts. */
#define configMAX_SYSCALL_INTERRUPT_PRIORITY     0x03


#endif /* FREERTOS_CONFIG_H */




Minimum code to create one task:

// *********   Meu Primeiro Projeto FreeRTOS com PIC32 MX  *****************
#include <p32xxxx.h>

/*-------------- Configuração dos Bits Fuses do PIC32 ---------------------*/
#pragma config FPLLODIV=DIV_1, FPLLIDIV=DIV_2, FPLLMUL=MUL_20, FPBDIV=DIV_2
#pragma config FWDTEN=OFF, FCKSM=CSDCMD, POSCMOD=XT, FNOSC=PRIPLL
#pragma config CP=OFF, BWP=OFF
#pragma config FMIIEN = OFF, FETHIO = OFF    // external PHY in RMII

#include <plib.h>
#include "FreeRTOS.h"
#include "task.h"

int main( void ){

    SYSTEMConfigPerformance( configCPU_CLOCK_HZ - 1 );   //configuração do PIC32
    mOSCSetPBDIV( OSC_PB_DIV_2 );
        INTEnableSystemMultiVectoredInt();
    portDISABLE_INTERRUPTS();
    vPortInitialiseBlocks();

    xTaskCreate(           // cria a task
        vTASK0,            // ponteiro para a funcao que implementa a task
        "Task 0",          // texto para a task
        250,               // espaço para pilha de memoria RAM em Words
        NULL,              // não utiliza parâmetos
        1,                 // prioridade da task
        NULL );            // não usa task handle


    vTaskStartScheduler();     //inicia o Scheduler (escalonador) do RTOS
}

/*------------------ funcao executada pela task ------------------------*/

static void vTASK0( void *pvParameters ){

    while(1)
    {
            // minha tarefa aqui!!!
        
    }
}



Good Luck!