real-time applications using ms - yury magda

Upload: esteban

Post on 07-Jul-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    1/132

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    2/132

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    3/132

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    4/132

    Real-Time Applicationsusing MSP432P401R LaunchPad

    and Raspberry Pi

    By Yury Magda

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    5/132

    Copyright © 2015 by Yury Magda. All rights reserved.

    The programs, examples, and applications presented in thisbook have been included for their instructional value. Theauthor offer no warranty implied or express, including but not limited to implied warranties of fitness or merchantability forany particular purpose and do not accept any liability for any

    loss or damage arising from the use of any information in thisbook, or any error or omission in such information, or anyincorrect use of these programs, procedures, and applications.

    No part of this publication may be reproduced, stored in aretrieval system, or transmitted in any form or by any means,

    electronic, mechanical, photocopying, recording, or otherwise,without the prior written permission of the author.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    6/132

    Contents

    Contents

    Introduction

    Disclaimer

    Raspberry Pi GPIO pins

    Designing Real-Time applications: project 1

    Designing Real-Time applications: project 2

    Designing Real-Time applications: project 3Designing Real-Time applications: project 4

    Designing Real-Time applications: project 5

    Designing Real-Time applications: project 6

    Designing Real-Time applications: project 7

    Designing Real-Time applications: project 8

    Designing Real-Time applications: project 9

    Using an MSP432 32-bit timer in Real-Time applications

    Designing Real-Time applications: project 10

    Designing a Digital-to-Analog converter with MSP432

    Designing Real-Time applications: project 11

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    7/132

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    8/132

    Introduction

    A popular Raspberry Pi miniature computer is often used for designing measurement andcontrol systems by professionals and hobbyists. Such systems can be driven via a general-purpose input/output port (GPIO) with pins accessible through header J8 on the RaspberryPi board. With GPIO, user applications can process signals from various sensors andcontrol external loads (relays, motors, etc.).

    The only drawback is that Linux OS running on the Raspberry Pi is not suited forprocessing signals travelling via GPIO pins in real time. This prevents the Raspberry Pifrom using in real-time applications that should process signals in a very short time.Meanwhile, Linux provides a powerful high-level environment for the development ofGUI applications performing high-level data processing. It would be attractive to combineLinux high-level interfaces with real-time signal processing while building real-timeapplications.

    One way to build real-time applications is to apply a combination of the Raspberry Pi anda stand-alone microcontroller (MCU) board capable of performing real-time tasks. In thisconfiguration, the MCU board could process signals from sensors in real time, drivemotors and actuators, etc. Such development board could execute commands from the

    Raspberry Pi and return data via some interface (parallel, UART, SPI, I2C, etc.).

    On the other hand, the Raspberry Pi could perform non-critical operations including high-level processing the data obtained from an MCU board, data visualization and networking.

    Such configuration can be used, for example, in image, video and audio processingsystems. In those systems, the Raspberry Pi could process the image or video fromcameras, while a stand-alone microcontroller module could control a precision motorpositioning a camera.

    This book is dedicated to designing real-time applications using the Raspberry Pi 2 boardand very low-cost but effective MSP-EXP432PR401 ™ LaunchPad by Texas Instruments.

    There are a few reasons why MSP-EXP432P401R could be selected for developing real-time applications described in this book.

    1. This is a very powerful board with the MSP432P401R (Cortex-M4F) processorand numerous peripherals for only $12.99.

    2. There are advanced (and free) development tools available for users. We can useeither the Energia MT IDE (Arduino-like IDE) or very powerful Code Composer

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    9/132

    Studio ™ (CCS) v.6.1.0 .3. A developer can achieve better performance for an application by direct

    programming CPU and peripheral registers using simple and clear commands andmacros. Well-organized MSP432 Technical Reference Manual may come in handy.

    The demo projects of real-time application described in this book may be used as thetemplates for building various measurement and control systems. Each project includesboth hardware and software accompanied by the detailed description of what is doing.

    The material of the book assumes that the readers are familiar, at least, with basics ofdesigning and assembling electronic circuits. For most projects having some basic skills inelectronics and low-level MCU programming will serve the readers well and allow themto understand what is going on behind the scenes. Each project is accompanied by thebrief description that helps to make things clear.

    All projects were designed using the Raspberry Pi 2 board running Raspbian OS, althoughdevelopers can use the earlier versions of the Raspberry Pi board as well. All of the sourcecode for the Raspberry Pi projects was developed in the Python environment running inRaspbian OS. The program code for MSP-EXP432P401R LaunchPad was developedusing Energia MT IDE and Code Composer Studio 6.1.0 by Texas Instruments. Mostprojects described in this guide can be easily improved or modified if necessary.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    10/132

    Disclaimer

    The design techniques described in this book have been tested on the Raspberry Pi 2 boardand MSP-EXP432P401R LaunchPad without damage of the equipment. I will not acceptany responsibility for damages of any kind due to actions taken by you after reading thisbook.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    11/132

    Raspberry Pi GPIO pins

    Development platforms like Raspberry Pi provide an environment for software andhardware experimenting. This is possible because availability of General PurposeInput/Output pins (GPIO) on the Raspberry Pi 2 board.

    The Raspberry Pi 2 is equipped with the header labeled J8. This header runs along theedge of the board and has 40 pins. Most GPIO pins can operate in different modes thusaccommodating different possible functions. Note that digital pins must be either high orlow.

    Each GPIO pin may be put in input or output mode. When output, a pin can be pulledeither LOW (log.”0”) or HIGH (log.”1”) by a program, so it is possible to control externalcircuitry connected to this pin. Log.“0” corresponds to the voltage level close to 0 volts,while the log.”1” corresponds to 3.3 volts. Reading the state of a loose pin returns theunpredictable result. All the GPIO pins can also be reconfigured to provide alternatefunctions (SPI, PWM, I 2C, etc.).

    Note that GPIO voltage levels are 3.3 V and are not 5 V tolerant. The 3.3 V logic levelof the Raspberry Pi 2 assumes that external logic components use only 3.3 volt.

    The Raspberry Pi board has no over-voltage protection – the intention is that peopleinterested in serious interfacing will use an external board with buffers, levelconversion and analog I/O rather than soldering directly onto the main board.

    Chances are that external circuitry are be poorly assembled and have short circuits,so I highly recommend you to apply a stand-alone DC 3.3V power supply forpowering your electronic circuits to prevent the permanent damage of the RaspberryPi.

    Another aspect of interfacing the Raspberry Pi is maximum allowable currentthrough a single GPIO pin. The current has to be less than 8 mA, so any load thatdraws more current can damage the board. When connecting external circuits to theRaspberry Pi, you have to apply some CMOS buffer IC (for example, 74HC00,74HC08, 74HC14, etc.) which isolates external circuitry from low-current GPIOpins.

    Be very careful when wiring the GPIO pins – it would be a good idea to strip shortpieces of insulation off a wire and push them over the 3.3V pins so you don’taccidentally short them with a probe.

    When attaching your electronic circuits to the Raspberry Pi GPIO pins use short

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    12/132

    wires (10-12cm long) so that to ensure minimum distortion of digital signals. Usinglong wires may cause your circuit to stop functioning properly.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    13/132

    Designing Real-Time applications: project 1

    This section contains the first project of a real-time application using the Raspberry Pi andMSP432P401 LaunchPad. Before we start off, let’s consider in brief the key aspects ofdeveloping real-time applications.

    Nowadays, a growing number of microcontroller applications use Real-Time OperatingSystems (RTOS).

    As you may know, common microcontroller/microprocessor (MCU) applications whenrunning use sequential processing loops and state machines. This approach works quitewell when a microprocessor board is performing a rather limited number of functions. Adifferent approach is required when an application involves more memory and peripherals.If the application is about 64KB in size or less, there is no need to use an RTOS.Conversely, if the size of the application reaches 1 MB, an RTOS should likely be used.

    Using an RTOS gives a few key advantages.

    Mostly an RTOS uses a “preemptive multitasking” approach which allows to increase theperformance of complex real-time applications, especially those with a code base that isprogressively enhanced in each release. The key driver of RTOS adoption is applicationcomplexity. An RTOS will often be used when there are more interrupt sources, morefunctions, and more standard communications interfaces that need to be supported.

    A “preemptive multitasking” approach makes response-times to each real-time eventrelatively independent of each other. As a result, new functions can be introduced withoutdisrupting existing hard real-time ones. This is impossible in a sequential processing loopwhere each event is checked by polling, so the addition of a new event will affect theresponse times for all events.

    Although real-time response for critical events can be handled using background orforeground loops to more frequently poll critical events, such approach significantlycomplicates the maintenance of complex real-time applications.

    Using an RTOS also allows to use MCU resources more efficiently. A simple loop-basedapplication typically does a lot of polling to check if interrupts have occurred. As a result,a great deal of processor time is occupied doing nothing. Multitasking RTOS-basedapplications are interrupt-driven, so it is possible to largely eliminate polling from theapplication. This frees up processor resources for useful work and enables power-savingmodes to be invoked during idle periods.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    14/132

    As an application becomes more complex, it can cause a growing number of problemssuch as excessive memory usage or leaks, delayed response to real-time events, or greaterthan expected MCU loads, etc. Such problems are often difficult to diagnose since theyrequire a high-level understanding of system behavior and resource usage. Most RTOSshave associated system-level debugging tools allowing to examine application behaviorand resource usage.

    Our next projects will use the Real-Time Operation System by Texas Instruments calledTI-RTOS. TI-RTOS has associated tools that enable developers to look at stack usage andcompare it against how much stack was assigned to a task. This makes it straightforwardto detect stack overflows or to optimize task stack sizes to free up RAM for other parts ofthe application.

    To process analog and digital signals in real time we will use the MSP-EXP432P401RLaunchPad™ by Texas Instruments ( Fig.1 ).

    Fig.1

    This is an easy-to-use Evaluation Module (EVM) that is based upon the MSP432P401Rmicrocontroller. It contains everything needed to start developing on the MSP432 low-power and high performance ARM 32-bit Cortex-M4F microcontroller (MCU), including

    on-board emulation for programming, debugging, and energy measurements. TheMSP432P401R device supports low-power applications requiring increased CPU speed,memory, analog, and 32-bit performance.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    15/132

    The MSP-EXP432P401R™ LaunchPad will be configured to run real-time tasks using themultitasking capability of the free Energia MT IDE environment (the newest version0101E0016 was used).

    The Energia MT IDE is the open-source prototyping platform that uses the Wiring andArduino framework for programming Texas Instruments launchpads. The Energia MTIDE is the cross platform and supported on Mac OS, Windows, and Linux. Energia MTincludes an integrated development environment (IDE) that is based on Processing.

    Together with Energia MT , LaunchPad can be used to develop interactive objects, takinginputs from a variety of switches or sensors, and controlling a variety of lights, motors,and other physical outputs. LaunchPad projects can be stand-alone (only run on the TargetBoard, i.e. your LaunchPad), or they can communicate with software running on yourcomputer (Host PC). Much more details about Energian can be found on http://energia.nu .

    Multitasking is the ability to run multiple tasks or threads concurrently on amicrocontroller. In Energia MT , multitasking is achieved by treating each tab as aseparate task (thread) and letting TI-RTOS and Energia take care of the rest. Currently,multitasking is supported on the MSP-EXP432P401R LaunchPad.

    Below is a brief desription of the multitasking capability of the Energia MT environment.Each tab in Energia MT will be treated as a new task, assuming the tab has a setup() andloop() function with a matching and unique name. For example, an application with 2tasks could be called setupTask1() / loopTask1() and setupTask2() / loopTask2() .Energia MT will look for these keyword pairs and automatically turn them into tasks. Itis also important that each setup/loop pair should be placed in a file with a “.ino”extension. Setup/loop pairs that are in “.c” files will not be treated as a new task andtherefore will not execute at run time.

    Interprocess communication between tasks can easily be done by using global variables.Global variables are truly global (so you cannot use the variable name again in any othertab) and globals must be declared in the first tab. The examples of multitasking can befound in Energia MT IDE under File -> Examples -> MultiTasking .

    Our demo project illustrates how a multitasking application works. In this project, a redLED (pin P2.0 ), green LED (pin P2.1 ) and blue LED (pin P2.2 ) of the MSP-EXP432P401R board are driven by three separate threads. All LEDs are enabled whilethe signal on pin P1.6 of MSP432 stays HIGH. The LOW level on P1.6 disables blinking.

    The control signal to pin P1.6 comes from pin GPIO18 of the Raspberry Pi. The LOWlevel on pin GPIO18 disables all LEDS, while the HIGH level enables blinking. The

    http://energia.nu/

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    16/132

    circuit diagram for this system is shown in Fig.2 .

    Fig.2

    The MSP432 MCU application was developed in Energia MT IDE . The source code ofthe main thread (file LED_MultiBlink.ino ) is shown in Listing 1 .

    Listing 1 .

    int inState;

    int blinkON = 1;

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    17/132

    void setup() {

    pinMode(15, INPUT); // Pin P1.6 is set as input to pick up the signal on pin GPIO18

    }

    void loop()

    {

    inState = digitalRead(15);

    if(inState != 0x0)

    blinkON = 1;

    else

    blinkON = 0x0;

    delay(1000);

    }

    In this application, pin P1.6 (15) of MSP432P401R LaunchPad is configured as input. Thesignal level on this pin is read into the inState variable. When this signal is LOW, the

    inState is assigned 0x0, otherwise inState is assigned 0x1. The blinkON variable is usedto simultaneously enable/disable all threads driving LEDS.

    The source code of the thread driving the blue LED (file BlueLed.ino ) is shown inListing 2 .

    Listing 2 .

    #define LED BLUE_LED

    void setupBlueLed() {

    pinMode(LED, OUTPUT);

    }

    // the loop routine runs over and over again forever as a task.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    18/132

    void loopBlueLed() {

    if (blinkON)

    {

    digitalWrite(LED, HIGH); // turn the LED ONdelay(100); // wait for 100 ms

    digitalWrite(LED, LOW); // turn the LED OFF by pulling the LED pin LOW

    delay(100); // wait for 100 ms

    }

    }

    With this source code, the pin corresponding to the blue LED is configured as ouput. Theloop() procedure repeatedly evaluates the value of the global variable blinkON . The LEDwill be blinking only if blinkON = 1.

    The source code of the thread driving the green LED (file GreenLed.ino ) is shown inListing 3 .

    Listing 3 .

    #define LED GREEN_LED

    void setupGreenLed() {

    // initialize the digital pin as an output.

    pinMode(LED, OUTPUT);

    }

    // the loop routine runs over and over again forever as a task.

    void loopGreenLed() {

    if (blinkON)

    {

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    19/132

    digitalWrite(LED, HIGH); // turn the LED ON

    delay(500); // wait for half a second

    digitalWrite(LED, LOW); // turn the LED OFF by making the voltage LOW

    delay(500); // wait for half a second

    }}

    This source code is almost the same as that shown in Listing 2 , except the pin numberused by the green LED.

    The source code of the thread driving the red LED (file RedLed.ino ) is shown in Listing4.

    Listing 4 .

    #define LED RED_LED

    void setupRedLed() { // initialize the digital pin as an output.

    pinMode(LED, OUTPUT);

    }

    // the loop routine runs over and over again forever as a task.

    void loopRedLed() { if (blinkON)

    {

    digitalWrite(LED, HIGH); // turn the LED ON

    delay(1000); // wait for a second

    digitalWrite(LED, LOW); // turn the LED OFF by making the voltage LOW

    delay(1000); // wait for a second }

    }

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    20/132

    The simple Python application running on the Raspberry Pi simply stops/resumes blinkingthe LEDS by pulling pin GPIO18 HIGH/LOW, respectively. The source code of the scriptis shown in Listing 5 .

    Listing 5 .

    from time import sleep

    import RPi.GPIO as GPIO

    GPIO.setwarnings(False)

    GPIO.setmode(GPIO.BCM)GPIO.setup(18, GPIO.OUT)

    while (True):

    GPIO.output(18, GPIO.HIGH)

    sleep(5)

    GPIO.output(18, GPIO.LOW)sleep(5)

    The Energia MT IDE window will look like the following ( Fig.3 ).

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    21/132

    Fig.3

    As it is seen, there are 4 tabs opened in our project. You should place all source files of theproject in the same directory. The Energia MT with the built-in TI-RTOS allows to buildthe multitask application where each tab represents its own task. Recall that a task in suchapplication can communicate with each other using global variables.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    22/132

    Designing Real-Time applications: project 2

    The following demo project of a real-time application illustrates low-level programmingtechniques and using interrupts and threads in a system with the Raspberry Pi andMSP432P401R MCU.

    The circuit diagram of the project is shown in Fig.4 .

    Fig.4

    In this circuit, the signals from pins GPIO18 and GPIO23 of the Raspberry Pi willcontrol two on-board LEDs of the MSP432P401R LaunchPad. The input pins P1.6 andP1.7 of MSP432P401R are configured as the interrupt sources activating by a falling edgecoming from GPIO18 and GPIO23 , respectively.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    23/132

    Each interrupt when activated calls an associated interrupt service routine (ISR) whichdrives a corresponding LED ON/OFF.

    The Energia MT source code of the application consists of three modules. The sourcecode of the main thread (file MSP432_P1_6_7_ISR.ino ) is shown in Listing 6 .

    Listing 6 .

    #include “msp.h”

    volatile int redSW, blueSW;

    void setup(){

    Serial.begin(9600);

    // put your setup code here, to run once:

    WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer

    // Configuring pins P1.6 and P1.7

    P1DIR &= ~BIT6; // Set P1.6 as inputP1DIR &= ~BIT7; // Set P1.7 as input

    P1OUT |= BIT6 | BIT7; // Allow pull-up resistor on pins P1.6 and P1.7

    P1REN |= BIT6 | BIT7; // Select pull-up mode for pins P1.6 and P1.7

    P1IES |= BIT6 | BIT7; // P1.6 and P1.7 are active by a falling edge

    P1IFG = 0; // Clear all P1 interrupt flagsP1IE |= BIT6 | BIT7; // P1.6 and P1.7 interrupts enabled

    // Configuring pins P1.0 and P2.2

    P1DIR |= BIT0; // P1.0 is set to output (Red LED)

    P2DIR |= BIT2; // P2.2 is set to output (Blue LED);

    redSW = 0;

    blueSW = 0;

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    24/132

    attachInterrupt(15, P16_ISRHandler, FALLING); // Interrupt is activated

    // when pin P1.6 (15) goes from HIGH to LOW

    attachInterrupt(14, P17_ISRHandler, FALLING); // Interrupt is activated

    // when pin P1.7 (14) goes from HIGH to LOW

    }

    void loop(){}

    // Interrupt service routine for pin P1.6

    void P16_ISRHandler() {

    P1IFG &= ~BIT6; // Clear P1.6 IFG

    P1OUT ^= BIT0; // P1.0 is toggled

    redSW = 1;

    }

    // Interrupt service routine for pin P1.7

    void P17_ISRHandler() {

    P1IFG &= ~BIT7; // Clear P1.7 IFG

    P2OUT ^= BIT2; // P2.2 (Blue LED) is toggled

    blueSW = 1;

    }

    In this source code, we include the header file “ msp.h ” containing definitions for theMSP432P401R MCU hardware resources. When assigned 1, the global variables redSWand blueSW enable data transfer through a serial interface in the corresponding threads.

    When the P16_ISRHandler() interrupt handler is entered, it clears the correspondinginterrupt flag by the statement:

    P1IFG &= ~BIT6;

    This is followed by

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    25/132

    P1OUT ^= BIT0;

    which drives pin P1.0 ON/OFF. The last statement enables the data transfer in thecorresponding thread:

    redSW = 1;

    The P17_ISRHandler() interrupt handler when entered clears the corresponding interruptflag by the statement:

    P1IFG &= ~BIT6;

    This is followed by

    P2OUT ^= BIT2;

    which drives pin P2.2 ON/OFF. The last statement enables data transfer in thecorresponding thread:

    blueSW = 1;

    The source code used for switching the red LED (file Thread1.ino ) is shown in Listing 7 .

    Listing 7 .

    void setupRed()

    {

    // put your setup code here, to run once:

    Serial.begin(9600);

    }

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    26/132

    void loopRed()

    {

    // put your main code here, to run repeatedly:

    if (redSW != 0)

    { Serial.println(“Red LED was toggled.”);

    redSW = 0;

    }

    }

    This thread is idle until the variable redSW holds 0. After redSW has been assigned 1 bythe P16_ISRHandler() interrupt handler, a text string is transferred via a serial interface.Then the variable redSW is cleared to avoid transferring data repeatedly.

    The source code responsible for switching the blue LED (file Thread2.ino ) is shown inListing 8 .

    Listing 8 .

    void setupBlue()

    {

    // put your setup code here, to run once:

    Serial.begin(9600);

    }

    void loopBlue()

    {

    // put your main code here, to run repeatedly:

    if (blueSW != 0)

    {

    Serial.println(“Blue LED was toggled.”);

    blueSW = 0;

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    27/132

    }

    }

    This thread is idle until the blueSW variable holds 0. When blueSW ia assigned 1 by theP17_ISRHandler() interrupt handler, a text string is transferred via a serial interface. Thevariable blueSW is cleared to avoid transferring data repeatedly.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    28/132

    Designing Real-Time applications: project 3

    The demo project in this section illustrates how to control PWM signals generated byMSP432P401R microcontroller. The MSP432 application produces two PWM pulse trainswhose duty cycles can be adjusted on “the fly” by the Raspberry Pi application.

    To generate PWM signals we will use a built-in module Timer_A of MSP432. Below is abrief description of the module taken from the MSP432P401R datasheet. Timer_A has afew 16-bit timers/counters with up to seven capture/compare registers. The Timer_Amodule can support multiple capture/compares, PWM outputs, and interval timing. Thismodule also has extensive interrupt capabilities. Interrupts may be generated from thecounter on overflow conditions and from each of the capture/compare registers.

    Timer_A features include:Asynchronous 16-bit timer/counter with four operating modes;Selectable and configurable clock source;Up to seven configurable capture/compare registers;Configurable outputs with pulse width modulation (PWM) capability;Asynchronous input and output latching;

    The block diagram of a single 16-bit timer/counter of the Timer_A module is shown inFig.5 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    29/132

    Fig.5

    Operation of each timer in the Timer_A module can be configured programmaticallyusing the set of registers associated with this device. Timer_A can operate in one ofmodes listed below. Note that all operations with peripheral devices of MSP432P401R

    MCU are completely determined by values written to the control registers dedicated tothese devices.

    There may be multiple instantiations of Timer_A on a given device. The prefix TAx isused, where x is a greater than equal to zero indicating the Timer_A instantiation. Fordevices with one instantiation, x = 0. The suffix n , where n = 0 to 6, represents thespecific capture/compare registers associated with the Timer_A instantiation.

    For example, the abbreviation “ TA0CTL ” means that we refer to the control register oftimer TimerA_0 in the Timer_A module. The abbreviation “ TA0CCR1 ” means that werefer to the compare/capture register CCR1 of timer TimerA_0 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    30/132

    When operating as a 16-Bit Timer Counter , the 16-bit timer/counter register, TAxR ,increments or decrements (depending on mode of operation) with each rising edge of theclock signal. TAxR can be read or written by software. Additionally, the timer cangenerate an interrupt when it overflows. TAxR may be cleared by setting the TACLR bitin the TAxCTL control register. Setting TACLR also clears the clock divider and countdirection for up/down mode.

    When we need to modify the Timer_A registers, it is recommended to stop the timerbefore modifying its operation (with exception of the interrupt enable, interrupt flag, andTACLR ) to avoid errant operating conditions.

    When the timer clock is asynchronous to the CPU clock, any read from TAxR shouldoccur while the timer is not operating or the results may be unpredictable. Alternatively,the timer may be read multiple times while operating, and a majority vote taken in

    software to determine the correct reading. Any write to TAxR takes effect immediately.

    The timer can operate in one of modes described below.

    The Capture mode is selected when bit CAP of the corresponding TAxCCTLx controlregister is set. Capture mode is used to record time events. It can be used for speedcomputations or time measurements. The capture inputs CCIxA and CCIxB areconnected to external pins or internal signals and are selected with the CCIS bits. The CMbits select the capture edge of the input signal as rising, falling, or both. A capture occurson the selected edge of the input signal. If a capture occurs:

    The timer value is copied into the TAxCCRn register.The interrupt flag CCIFG of the register TAxCCTLx is set.

    The Compare mode is selected when the CAP bit of the corresponding TAxCCTLx controlregister is clear (=0). The compare mode is used to generate PWM output signals orinterrupts at specific time intervals. The desired value to be compared is written by

    software in the corresponding TAxCCRn register, where n represents the specificcapture/compare register.

    When the value in the corresponding TAxR counter register reaches the value held in theTAxCCRn register, the following events occur:

    Interrupt flag CCIFG is set;Internal signal EQUn = 1;EQUn affects the output according to the output mode;The input signal CCI is latched into SCCI .

    Timer_A can be fed by a clock source ACLK, SMCLK, or externally via TAxCLK orINCLK. The clock source is selected with the TASSEL bits in the TAxCTL register. The

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    31/132

    selected clock source may be used directly by the timer or divided by 2, 4, or 8, using theID bits of TAxCTL . The frequency of the selected clock source can be further divided by2, 3, 4, 5, 6, 7, or 8 using the TAIDEX bits of the TAxEX0 register. The timer clockdivider logic is reset when bit TACLR of the TAxCTL register is set.

    The timer may be started or restarted in the following ways:The timer counts when MC field (bits 4-5 of the TAxCTL control register) isgreater than 0 and the clock source is active. Note that depending on these bits thetimer can be put into one of the following modes: stop, up, continuous, andup/down.When the timer mode is either up or up/down, the timer may be stopped by writing0 to the TAxCCR0 register. The timer may then be restarted by writing a nonzerovalue to TAxCCR0 . In this scenario, the timer starts incrementing in the up

    direction from zero.

    Let’s back to our project.

    Our system will produce two PWM pulse trains whose duty cycles will be configuredprogrammatically. While developing an application running on MSP432 MCU, we willperform the following steps:

    1. Select a timer/counter block. We want to use TimerA_0 , so the associated controlregister for this block will be TA0CTL .2. Select two channels to generate PWM outputs. There will be channel 1 and 2, so

    we need to configure the associated control/capture control registers { TA0CCTL1 ,TA0CCR1 } and { TA0CCTL2 , TA0CCR2 }, respectively.

    3. Assign the PWM functions to output pins P2.4 (TA0CCR1 ) and P2.5(TA0CCR2 ). The PWM pulse trains will appear on these pins after TimerA_0 hasstarted.

    TimerA_0 will be configured to operate in the “ Up ” mode (MC bits = 01) when the timercounts up to the value written in the TA0CCR0 register. The value in this register and theclock source determine the frequency of PWM signals.

    In our application, we select the ACLK clock source (32768 Hz) for TimerA_0 bywriting 1 to the TASSEL field (bits 8-9 of the TA0CTL control register). We also write avalue 100-1 to the TA0CCR0 register that gives us the period of both PWM signals equalto 3 mS. This corresponds to the frequency of 32768/100 or ≈330 Hz. The TA0CCR1 and

    TA0CCR2 registers determine the PWM duty cycle for each output signal.To generate PWM signals we must configure TA0CCTL1 and TA0CCTL2 controlregisters to operate in the Compare mode by clearing their CAP bits ( CAP = 0).

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    32/132

    The duty cycle of each PWM signal will be configured using an 8-bit binary code readfrom port P4 of MSP432 MCU. The data byte to port P4 goes from the GPIO pins of theRaspberry Pi board.

    The circuit diagram of this demo project is shown in Fig.6 .

    Fig.6

    The connections between the MSP-EXP432P401R LaunchPad and the Raspberry Pi aredetailed in the table below.

    Raspberry Pi 2 J8pin

    MSP432P401R LaunchPad pin

    GPIO18 P4.0 (bit 0 of the 8-bit code)

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    33/132

    GPIO23 P4.1 (bit 1 of the 8-bit code)

    GPIO24 P4.2 (bit 2 of the 8-bit code)

    GPIO25 P4.3 (bit 3 of the 8-bit code)

    GPIO8 P4.4 (bit 4 of the 8-bit code)

    GPIO7 P4.5 (bit 5 of the 8-bit code)

    GPIO12 P4.6 (bit 6 of the 8-bit code)

    GPIO20 P4.7 (bit 7 of the 8-bit code)

    GPIO26 P1.5 (interrupt line to control TA0.1)

    GPIO19 P1.6 (interrupt line to control TA0.2)

    The PWM duty cycle of each output signal is adjusted via 8 signal lines ( GPIO18 ,GPIO23 , GPIO24 , GPIO25, GPIO8, GPIO7, GPIO12 and GPIO20 ) of the RaspberryPi. The binary code on these lines can range from 0 through 255, although our applicationwill operate in the range 0 – 90. This allow us to set the duty cycle for any PWM signal inthe range 5 – 95% using the formula

    Duty_cycle = 5 + [bit7:bit0]

    To adjust the duty cycle of the signal on pin P2.4 (register TA0CCR1 ) the Raspberry Piapplication should activate the interrupt line P1.5 by bringing the level on pin GPIO26from HIGH to LOW. The duty cycle for the signal on pin P2.5 (register TA0CCR2 ) willbe configured after activating the interrupt on pin P1.6 . In this case, the GPIO19 pin goesHIGH, then LOW. It is seen, that both interrupts are activated by the falling edge on thecorresponding line.

    The Energia TM source code of the main thread of the MSP432P401R application isshown in Listing 9 (file TwoPWM_Control_ISR.ino ).

    Listing 9 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    34/132

    #include “msp.h”

    int bDuty;

    volatile int IF15 = 0; // Interrupt flag for P1.5volatile int IF16 = 0; // Interrupt flag for P1.6

    void setup()

    {

    // put your setup code here, to run once:

    WDTCTL = WDTPW | WDTHOLD; // Stop WDT

    // Assign the timer outputs to pins P2.4 - P2.5

    P2SEL0 |= BIT4 | BIT5;

    // Configure all bits of port P4 as inputs

    P4DIR = 0x0; // Port P4 is input

    P4REN = 0xFF; // Select pull-up mode for P4

    P4OUT = 0xFF; // pull-up resistors on P4

    // Configure P1.5 & P1.6 Interrupts

    P1DIR = 0x0;

    P1REN |= BIT5 | BIT6; // Select pull-up mode for P1.5/P1.6

    P1OUT |= BIT5 | BIT6; // pull-up resistors on P1.5/P1.6

    P1IES |= BIT5 | BIT6; // P1.5 Hi/Lo edge

    P1IFG = 0; // Clear all P1 interrupt flags

    P1IE |= BIT5 | BIT6; // P1.6 interrupt enabled

    // Initialize LFXT1

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    35/132

    PJSEL0 |= BIT0 | BIT1; // Select for LFXT ports

    CSKEY = 0x695A; // Unlock CS module for register access

    CSCTL2 |= LFXT_EN;

    // Loop until XT1, XT2 & DCO fault flag is cleareddo

    {

    // Clear XT2,XT1,DCO fault flags

    CSCLRIFG |= CLR_DCORIFG | CLR_HFXTIFG | CLR_LFXTIFG;

    SYSCTL_NMI_CTLSTAT &= ~ SYSCTL_NMI_CTLSTAT_CS_SRC;

    } while (SYSCTL_NMI_CTLSTAT & SYSCTL_NMI_CTLSTAT_CS_FLG); // Testoscillator

    // fault flag

    CSKEY = 0; // Lock CS module from unintended accesses

    // Setup TimerA_0

    TA0CCR0 = 100-1; // PWM Period

    TA0CCTL1 = OUTMOD_7; // CCR1 reset/set

    TA0CCR1 = 45; // CCR1 PWM initial duty cycle

    TA0CCTL2 = OUTMOD_7; // CCR2 reset/set

    TA0CCR2 = 55; // CCR2 PWM initial duty cycle

    TA0CTL = TASSEL_1 | MC_1 | TACLR; // selection: ACLK, up mode, clear the

    counter and reset

    attachInterrupt(7, p15_ISRHandler, FALLING); // interrupt on P1.5

    attachInterrupt(15, p16_ISRHandler, FALLING); // interrupt on P1.6

    }

    void loop(){}

    void p15_ISRHandler()

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    36/132

    {

    P1IFG &= ~BIT5;

    bDuty = P4IN;

    IF15 = 1;

    }

    void p16_ISRHandler()

    {

    P1IFG &= ~BIT6;

    bDuty = P4IN;

    IF16 = 1;

    }

    In this code, all definitions are determined by the msp.h header file. The MSP432 MCUregisters are accessed through the variables with the same names. The variable bDutyholds the 8-bit code for configuring the duty cycle of both PWM signals. bDuty takes itsvalue from port P4 using the following statement:

    bDuty = P4IN;

    Once Port P4 is used as input, it should be configured by the following sequence:

    P4DIR = 0x0;

    P4REN = 0xFF;

    P4OUT = 0xFF;

    The output PWM signals appear on pins P2.4 and P2.5 , so we need to associate these pinswith TimerA_0 outputs by the statement:

    P2SEL0 |= BIT4 | BIT5;

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    37/132

    The following statement writes the value of the period of both PWM signals in the registerTA0CCR0 :

    TA0CCR0 = 100-1;

    The TimerA_0 is fed by the ACLK clock source with a frequency of 32768 Hz, so thefrequency of both PWM signals will be 32768 Hz / 100 = 328 Hz.

    The sequence

    TA0CCTL1 = OUTMOD_7;

    TA0CCR1 = 45;

    configures the parameters of the PWM signal that appears on pin P2.4 . HereOUTMOD_7 enables the reset/set output mode for the CCR1 signal (bits 5 – 7 of thecontrol register TA0CCTL1 ). The TA0CCR1 variable is assigned the value equal to 45that determines the initial duty cycle of signal on pin P2.4 .

    The sequence

    TA0CCTL2 = OUTMOD_7;

    TA0CCR2 = 55;

    configures the PWM output on pin P2.5 associated with CCR2 . The initial duty cycle ofthe PWM signal on pin P2.5 is 55% .

    Configuring TimerA_0 is performed by setting the corresponding fields in the TA0CTLcontrol register:

    TA0CTL = TASSEL_1 | MC_1 | TACLR;

    The TASSEL_1 parameter is (=1, bits 8 – 9 of TA0CTL ) selects ACLK (32768 Hz) as aclock source for the TimerA_0 timer. Parameter MC_1 (=1, bits 4 – 5 in TA0CTL ) puts

    TimerA_0 in Up mode – in this mode, the timer counts up to the value kept in theTA0CCR0 register. TACLR (bit 2 of the TA0CTL control register) resets the TimerA_0timer.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    38/132

    Each counter of TimerA_0 will be controlled by activating the interrupt lines P1.5 andP1.6 . These interrupt lines are configured by the sequence:

    P1DIR = 0x0;

    P1REN |= BIT5 | BIT6;

    P1OUT |= BIT5 | BIT6;

    P1IES |= BIT5 | BIT6;

    P1IFG = 0;

    P1IE |= BIT5 | BIT6;

    We also need to configure two interrupt handlers, p15_ISRHandler() andp16_ISRHandler() , associated with interrupt pins P1.5 and P1.6 , respectively:

    attachInterrupt(7, p15_ISRHandler, FALLING); // interrupt on P1.5attachInterrupt(15, p16_ISRHandler, FALLING); // interrupt on P1.6

    Each interrupt is activated by the falling edge of a pulse arriving on the corresponding pin.Interrupts handlers are set the variables IF15 and IF16 thus enabling to process the 8-bitcodes in the corresponding threads. IF15 when set enables configuring the TA0CCR1register, IF16 enables configuring TA0CCR2 . Within the handlers, the variable bDuty is

    assigned the value read from port P4 .

    Each interrupt handler when entered has to clear its corresponding interrupt flags. This isdone by the statement

    P1IFG &= ~BIT5;

    for the p15_ISRHandler() interrupt handler and

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    39/132

    P1IFG &= ~BIT6;

    for p16_ISRHandler() .

    The source code of the thread configuring register TA0CCR1 is shown in Listing 10 (filePWM1_Thread.ino ).

    Listing 10 .

    void setup1()

    {

    // put your setup code here, to run once:

    }

    void loop1()

    {

    // set PWM 1 (P2.4) duty

    if (IF15 == 1)

    {

    IF15 = 0;

    if ((bDuty >= 0) && (bDuty

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    40/132

    PWM2_Thread.ino ).

    Listing 11 .

    void setup2(){

    // put your setup code here, to run once:

    }

    void loop2()

    {

    // set PWM 2 (P2.5) duty

    if (IF16 == 1)

    {

    IF16 = 0;

    if ((bDuty >= 0) && (bDuty

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    41/132

    GPIO.setwarnings(False)

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(18, GPIO.OUT) # bit0GPIO.setup(23, GPIO.OUT) # bit 1

    GPIO.setup(24, GPIO.OUT) # bit2

    GPIO.setup(25, GPIO.OUT) # bit3

    GPIO.setup(8, GPIO.OUT) # bit4

    GPIO.setup(7, GPIO.OUT) # bit5

    GPIO.setup(12, GPIO.OUT) # bit6

    GPIO.setup(20, GPIO.OUT) # bit7

    GPIO.setup(26, GPIO.OUT) # interrupt line P1.5 (P2.4/TA0.1)

    GPIO.setup(19, GPIO.OUT) # interrupt line P1.6 (P2.5/TA0.2)

    # configuring a duty cycle as 5 + [bit7:bit0]

    GPIO.output(26, GPIO.HIGH)

    GPIO.output(18, GPIO.HIGH)

    GPIO.output(23, GPIO.HIGH)

    GPIO.output(24, GPIO.HIGH)

    GPIO.output(25, GPIO.LOW)

    GPIO.output(8, GPIO.HIGH)

    GPIO.output(7, GPIO.LOW)

    GPIO.output(12, GPIO.HIGH)

    GPIO.output(20, GPIO.LOW)

    GPIO.output(26, GPIO.LOW) # activate interrupt on P1.5 of MSP432

    sleep(0.2)

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    42/132

    GPIO.output(19, GPIO.HIGH)

    GPIO.output(18, GPIO.HIGH)

    GPIO.output(23, GPIO.HIGH)GPIO.output(24, GPIO.LOW)

    GPIO.output(25, GPIO.HIGH)

    GPIO.output(8, GPIO.LOW)

    GPIO.output(7, GPIO.LOW)

    GPIO.output(12, GPIO.HIGH)

    GPIO.output(20, GPIO.LOW)

    GPIO.output(19, GPIO.LOW) # activate interrupt on P1.6

    With this source code, we can adjust the duty cycle for PWM signals on pins P2.4 andP2.5 of the MSP432 LaunchPad. As you know, the duty cycle is determined by the

    content of the TA0CCRx registers. The following sequence determines the value of 87 tobe written to the TA0CCR1 control register of MSP432P401R MCU:

    GPIO.output(18, GPIO.HIGH)

    GPIO.output(23, GPIO.HIGH)

    GPIO.output(24, GPIO.HIGH)

    GPIO.output(25, GPIO.LOW)

    GPIO.output(8, GPIO.HIGH)

    GPIO.output(7, GPIO.LOW)

    GPIO.output(12, GPIO.HIGH)

    GPIO.output(20, GPIO.LOW)

    The resulting duty cycle of the PWM signal on pin P2.4 thus will be 5 + 87 = 92%. Theinterrupt line ( GPIO26 ) is initially brought HIGH, then LOW thus allowing the new valueof the duty cycle to be written to TA0CCR1 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    43/132

    The duty cycle of the PWM signal on pin P2.5 is determined by the value written toTA0CCR2 :

    GPIO.output(18, GPIO.HIGH)

    GPIO.output(23, GPIO.HIGH)

    GPIO.output(24, GPIO.LOW)

    GPIO.output(25, GPIO.HIGH)

    GPIO.output(8, GPIO.LOW)

    GPIO.output(7, GPIO.LOW)

    GPIO.output(12, GPIO.HIGH)

    GPIO.output(20, GPIO.LOW)

    The resulting duty cycle will be 5 + 75 = 80. The interrupt line ( GPIO19 ) is initiallybrought HIGH, then LOW thus allowing the new value of the duty cycle to be written toTA0CCR2 .

    The Energia MT IDE window for this project is shown in Fig.7 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    44/132

    Fig.7

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    45/132

    Designing Real-Time applications: project 4

    Using a stand-alone microcontroller board allows a developer to realize real-timealgorithms that don’t require any intervention from the Raspberry Pi. MSP432P401RMCU can perform some specific tasks completely within a separate thread – suchapproach can increase the overall performance of the system consisting of the MSP432and Raspberry Pi. The following project illustrates such approach.

    This project is based upon the previous one just discussed. Here we will develop theapplication running an additional thread processing an analog signal. This signal will befed to the channel A1 (pin P5.4 on the MSP432 board). This thread will perform analog-to-digital conversion and drive the on-board red LED (pin P1.0 ) ON when the inputvoltage exceeds 1.4V.

    As the input voltage drops below this threshold (1.4), the red LED is driven OFF. Thethread driving the red LED will operate without any interaction with the Raspberry Pi andindependently of other sections of the MSP432 program code.

    The circuit diagram of the project is shown in Fig.8 .

    Fig.8

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    46/132

    The connections between the MSP-EXP432P401R LaunchPad and Raspberry Pi 2 aredetailed in the table below.

    Raspberry Pi 2 J8pin

    MSP432P401R LaunchPad pin

    GPIO18 P4.0 (bit 0 of the 8-bit code)

    GPIO23 P4.1 (bit 1 of the 8-bit code)

    GPIO24 P4.2 (bit 2 of the 8-bit code)

    GPIO25 P4.3 (bit 3 of the 8-bit code)

    GPIO8 P4.4 (bit 4 of the 8-bit code)

    GPIO7 P4.5 (bit 5 of the 8-bit code)

    GPIO12 P4.6 (bit 6 of the 8-bit code)

    GPIO20 P4.7 (bit 7 of the 8-bit code)

    GPIO26 P1.5 (interrupt line to control TA0.1)

    GPIO19 P1.6 (interrupt line to control TA0.2)

    In this circuit, the analog signal to the channel A1 is fed from the wiper of thepotentiometer Rp connected as a voltage divider.

    The MSP432 MCU source code of the main thread of the application is shown in Listing13

    (file Two_PWM_Control_ISR_w_ADC_5_4.ino ).

    Listing 13 .

    #include “msp.h”

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    47/132

    int bDuty;

    volatile int IF15 = 0; // Interrupt flag for P1.5

    volatile int IF16 = 0; // Interrupt flag for P1.6

    void setup()

    {

    // put your setup code here, to run once:

    WDTCTL = WDTPW | WDTHOLD; // Stop WDT

    // Configure pins P2.4 - P2.5

    P2SEL0 |= BIT4 | BIT5;

    // Configure all bits of port P4 as inputs

    P4DIR = 0x0; // Port P4 is input

    P4REN = 0xFF; // Select pull-up mode for P4

    P4OUT = 0xFF; // pull-up resistors on P4

    // Configure P1.5 & P1.6 Interrupts

    P1DIR = 0x0;

    P1REN |= BIT5 | BIT6; // Select pull-up mode for P1.5/P1.6

    P1OUT |= BIT5 | BIT6; // pull-up resistors on P1.5/P1.6

    P1IES |= BIT5 | BIT6; // P1.5 Hi/Lo edge

    P1IFG = 0; // Clear all P1 interrupt flags

    P1IE |= BIT5 | BIT6; // P1.6 interrupt enabled

    // Initialize LFXT1

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    48/132

    PJSEL0 |= BIT0 | BIT1; // Select for LFXT ports

    CSKEY = 0x695A; // Unlock CS module for register access

    CSCTL2 |= LFXT_EN;

    // Loop until XT1, XT2 & DCO fault flag is cleareddo

    {

    // Clear XT2,XT1,DCO fault flags

    CSCLRIFG |= CLR_DCORIFG | CLR_HFXTIFG | CLR_LFXTIFG;

    SYSCTL_NMI_CTLSTAT &= ~ SYSCTL_NMI_CTLSTAT_CS_SRC;

    } while (SYSCTL_NMI_CTLSTAT & SYSCTL_NMI_CTLSTAT_CS_FLG); // Testoscillator

    // fault flag

    CSKEY = 0; // Lock CS module from unintended accesses

    // Setup TimerA_0

    TA0CCR0 = 100-1; // PWM Period

    TA0CCTL1 = OUTMOD_7; // CCR1 reset/set

    TA0CCR1 = 45; // CCR1 PWM initial duty cycle

    TA0CCTL2 = OUTMOD_7; // CCR2 reset/set

    TA0CCR2 = 55; // CCR2 PWM initial duty cycle

    TA0CTL = TASSEL_1 | MC_1 | TACLR; // ACLK, up mode, clear the

    counter and reset

    attachInterrupt(7, p15_ISRHandler, FALLING); // interrupt on P1.5

    attachInterrupt(15, p16_ISRHandler, FALLING); // interrupt on P1.6

    }

    void loop(){}

    void p15_ISRHandler()

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    49/132

    {

    P1IFG &= ~BIT5;

    bDuty = P4IN;

    IF15 = 1;

    }

    void p16_ISRHandler()

    {

    P1IFG &= ~BIT6;

    bDuty = P4IN;

    IF16 = 1;

    }

    In this source code, the variable bDuty is assigned the 8-bit binary code for configuringthe duty cycle of PWM signals (pins P2.4 – P2.5 ).

    The MSP432 source code of the thread configuring the TA0CCR1 register (filePWM1_Thread.ino ) is shown in Listing 14 .

    Listing 14 .

    void setup1()

    {

    // put your setup code here, to run once:

    }

    void loop1()

    {

    // set duty of TA0.1 output on pin P2.4

    if (IF15 == 1)

    {

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    50/132

    IF15 = 0;

    if ((bDuty >= 0) && (bDuty = 0) && (bDuty = 0) && (bDuty

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    51/132

    }

    }

    With this code, the IF16 global variable when set allows to configure the duty cycle ofTimerA_0 output 2. The duty cycle will be adjusted between 5% ( bDuty = 0) and 95%(bDuty = 90) using the statement:

    if ((bDuty >= 0) && (bDuty

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    52/132

    // ADC14 on

    ADC14CTL1 = ADC14RES_2; // Use sampling timer, 12-bit conversionresults

    ADC14MCTL0 |= ADC14INCH_1; // A1 ADC input select; Vref = AVCC(3.3V)}

    void loop3()

    {

    ADC14CTL0 |= ADC14ENC | ADC14SC; // Start sampling/conversion

    while (ADC14BUSY == 0x1); // waiting until A/D conversion is completebinCode = ADC14MEM0;

    vout = LSB * binCode;

    if (vout > 1.4)

    P1OUT |= BIT0; // P1.0 = 1

    else

    P1OUT &= ~BIT0; // P1.0 = 0Serial.print(“A1 input, V: “);

    Serial.println(vout, 3);

    delay(5000);

    }

    Here the following two statements allow to configure pin P1.0 as output and write 0 to thispin:

    P1DIR |= BIT0;

    P1OUT &= ~BIT0;

    The next statements configure pin P5.4 as an analog input:

    P5SEL1 |= BIT4;

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    53/132

    P5SEL0 |= BIT4;

    The statement

    ADC14CTL0 |= ADC14SHT0_2 | ADC14SHP | ADC14ON;

    configures several A/D conversion parameters through the ADC14CTL0 control register.The ADC14SHT0_2 field (bits 8-11 of ADC14CTL0 ) determines a sample-and-holdtime. These bits define the number of ADC14CLK cycles in the sampling period forconversion memory register ADC14MEM0 . In our particular case, we take the number ofcycles equal to 16.

    The ADC14SHP parameter (bit 26 of ADC14CTL0 ) allows to select the source of thesampling signal ( SAMPCON ) to be either the output of the sampling timer or the sample-input signal directly. If ADC14SHP is clear (= 0), the SAMPCON signal is sourced fromthe sample-input signal.If ADC14SHP is set (= 1), the SAMPCON signal is sourced from the sampling timer. Inour case, we take the sampling timer ( SAMPCON = 1).

    Both parameters, ADC14SHT0_2 and ADCC14HP , can be applied only when theADC14ENC parameter (bit 1 of ADC14CTL0 control register) is equal to 0.

    Several parameters of A/D conversion are configured using the control registerADC14CTL1 . The statement

    ADC14CTL1 = ADC14RES_2;

    selects the 12-bit resolution (bits 5 – 4 of ADC14CTL1 ). Other bits of the control register

    ADC14CTL1 are left unchanged.The result of A/D conversion appears as a 12-bit binary code that is stored in the memoryregister ADC14MEM0 (by default). Before conversion, we also need to indicate thephysical channel to pick up the input signal. This is done by using the control registerADC14MCTL0 associated with the ADC14MEM0 memory register. The followingstatement selects the channel A1 as the input to be measured:

    ADC14MCTL0 |= ADC14INCH_1;

    We also need to select the desired reference voltage Vref that is used for calculating the

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    54/132

    Least Significant Bit (LSB). In this application, we use the default Vref that is AVcc(3.3V). You can select other values of Vref by setting the bits 11 – 8 of the fieldADC14VRSEL in the register ADC14MCTL0 .

    The A/D sampling/conversion process itself is executed within a loop3() function.

    The statement

    ADC14CTL0 |= ADC14ENC | ADC14SC;

    allows the sampling/conversion process to begin. The application needs to know whenA/D conversion is complete, therefore the flag ADC14BUSY (bit 16 in the controlregister ADC14CTL0 ) is continuously checked. This bit indicates an active sample orconversion operation. The ADC14BUSY flag stays LOW (log.”0”) when no operation isactive. While A/D sampling/conversion is active, this bit stays HIGH (log.”1”).

    The following while() loop repeats until A/D conversion is complete:

    while (ADC14BUSY == 0x1);

    Then the calculated value of the analog input (variable vout ) is compared with thethreshold selected to 1.4 (in volts). Once the threshold is exceeded, pin P1.0 is driven ON,otherwise P1.0 stays OFF. The value on the A0 analog input is also transferred through theserial interface to the Raspberry Pi.

    The Energia MT IDE window for this project is shown in Fig.9 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    55/132

    Fig.9

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    56/132

    Designing Real-Time applications: project 5

    This project illustrates transferring data from MSP432P401R microcontroller to RaspberryPi using several serial virtual channels. The MSP432 application reads the state of inputsP2.3 , P2.4 and P2.5 and transfers the data obtained via serial interfaces. Each of pins P2.3

    – P2.5 is processed by a separate thread.

    The circuit diagram for this project is shown in Fig.10 .

    Fig.10

    In this circuit, pins P2.3 – P2.5 pick up signals simulated by mechanical switches orelectronic circuits. Before transferring data to the Raspberry Pi, we should first identifythe serial interfaces available in Raspbian OS by the following command:

    pi@raspberrypi ~/Developer/MSP432 $ ls -l /dev/ttyA*

    crw-rw–T 1 root dialout 166, 1 Aug 6 13:44 /dev/ttyACM1

    crw-rw–T 1 root dialout 166, 2 Aug 6 13:44 /dev/ttyACM2crw-rw–T 1 root dialout 204, 64 Jan 1 1970 /dev/ttyAMA0

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    57/132

    Here the /dev/ttyACM 1 – /dev/ttyACM2 devices are associated with the MSP432P401Rserial interfaces. We can use /dev/ttyACM 1 in our application.

    The Python application running on the Raspberry Pi is represented by the following sourcecode ( Listing 17) .

    Listing 17 .

    from time import sleep

    import serial

    s1 = serial.Serial(port=’/dev/ttyACM1’,

    baudrate=9600,parity=serial.PARITY_NONE,

    stopbits=serial.STOPBITS_ONE,

    bytesize=serial.EIGHTBITS,

    timeout=1)

    try:

    while 1:rLine = s1.readline()

    print rLine

    except KeyboardInterrupt:

    print ” Terminating the application on Ctr-C…”

    s1.close()

    sys.exit(0)

    This application reads the data via the serial interface /dev/ttyACM1 until Ctrl-C has beenpressed.

    The Energia MT source code of the main thread running on MSP432P401R MCU isshown in Listing 18 .

    Listing 18 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    58/132

    int done = 0;

    int p23State, p24State, p25State;

    void setup()

    { pinMode(34, INPUT); // P2.3 is set as input

    Serial.begin(9600);

    }

    void loop()

    {p23State = digitalRead(34);

    while (done != 0);

    done = 1;

    Serial.print(“Pin P2.3 is “);

    if (p23State == 0x0)

    Serial.println(“LOW”);else

    Serial.println(“HIGH”);

    done = 0;

    delay(1000);

    }

    In this application, the program code reads the state of the digital input 34 (pin P2.3 ) ofMSP432 by the statement:

    p23State = digitalRead(34);

    p23State will then contain either 0 or 1 depending on the signal level on pin P2.3 . Thevalue of p23State will be transferred through a serial interface.

    In this source code, the global variable done is used for synchronizing threads. The datatransfer over a serial interface takes some time, so we need to exclude overlapping and

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    59/132

    possible data loss when the particular thread is transferring the data.

    Any of the threads can use the serial interface only when it is free ( done = 0x0). Thereforethe while() loop

    while (done != 0);

    repeats until done is set to 0. This statement is included in the source code for each thread.

    Once done = 0, this means the resource (a serial device) is free and can be used by thethread. To prevent from using the resource by other threads, the current thread assigns 1 tothe done variable.

    After data has been processed, done is cleared ( done = 0), so other threads can access aserial interface.

    The data taken from the digital input 38 (pin P2.4) of MSP432 are processed by the threadwhose source code is shown in Listing 19 .

    Listing 19 .

    void setup2(){

    pinMode(38, INPUT); // P2.4 is set as input

    Serial.begin(9600);

    delay(200);

    }

    void loop2()

    {

    p24State = digitalRead(38);

    while (done != 0);

    done = 1;

    Serial.print(“Pin P2.4 is “);if (p24State == 0x0)

    Serial.println(“LOW”);

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    60/132

    else

    Serial.println(“HIGH”);

    done = 0;

    delay(1000);

    }

    The data taken from the digital input 19 (pin P2.5) of MSP432 are processed by the threadwhose source code is shown in Listing 20 .

    Listing 20 .

    void setup3()

    {

    pinMode(19, INPUT); // P2.5 is set as input

    Serial.begin(9600);

    delay(400);

    }

    void loop3()

    {

    p25State = digitalRead(19);

    while (done != 0);

    done = 1;

    Serial.print(“Pin P2.5 is “);

    if (p25State == 0x0)

    Serial.println(“LOW”);

    else

    Serial.println(“HIGH”);

    done = 0;

    delay(1000);

    }

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    61/132

    The Energia MT IDE window for this project is shown in Fig.11 .

    Fig.11

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    62/132

    Designing Real-Time applications: project 6

    Many real-time applications need to read several digital inputs at a time. This could be acase when an application should process signals from sensors of the same type. Thefollowing demo application illustrates reading several digital inputs of MSP432P401RMCU at a time and transferring the data obtained to the Raspberry Pi via a serial interface.

    The circuit diagram of the application is shown in Fig.12 .

    Fig.12

    In this circuit, three digital inputs (pins P2.5 – P2.7 ) of MSP432P401R MCU are readafter an interrupt on pin P2.4 of MSP432 has been activated by the falling edge on pinGPIO18 of the Raspberry Pi.

    The Energia MT source code of MSP432 application consists of two parts. One of themrepresenting a main thread (file Reading_ParallelInput.ino ) is shown in Listing 21 .

    Listing 21 .

    #include “msp.h”

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    63/132

    int p2Read;

    int bReady = 0;

    void setup(){

    // put your setup code here, to run once:

    P2DIR = 0x0; // Port P2 is set as INPUT

    P2OUT |= BIT5 | BIT6 | BIT7; // Pull-up resistors on P2.5 - P2.7

    P2REN |= BIT5 | BIT6 | BIT7; // Select pull-up mode for P2.5 - P2.7

    attachInterrupt(38, P24IsrHandler, FALLING); // configuring the interrupt on pin P2.4 ofMSP432

    }

    void loop()

    {

    // put your main code here, to run repeatedly:

    }

    void P24IsrHandler(void)

    {

    P2IFG &= ~BIT4; // Clear interrupt flag for pin P2.4

    bReady = 1;

    }

    In this source code, the sequence

    P2DIR = 0x0;

    P2OUT |= BIT5 | BIT6 | BIT7;

    P2REN |= BIT5 | BIT6 | BIT7;

    configures pins P2.5 – P2.7 as inputs with the pull-up resistors attached. We also need to

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    64/132

    configure the interrupt handler processing events on pin P2.4 by the following statement:

    attachInterrupt(38, P24IsrHandler, FALLING);

    The interrupt handler P24IsrHandler when entered clears the interrupt flag assigned tothe P2.4 interrupt line and set the bReady flag to 1 thus allowing the data transfer to theRaspberry Pi.

    The Energia MT source code of the thread processing digital inputs (fileSerial_Thread.ino ) is shown in Listing 22 .

    Listing 22 .

    void setup1()

    {

    // put your setup code here, to run once:

    Serial.begin(9600);

    delay(500);

    }

    void loop1()

    {

    // put your main code here, to run repeatedly:

    if (bReady == 1)

    {

    p2Read = P2IN;

    p2Read = p2Read >> 5;

    Serial.print(“BITS 7-5 of port P2: 0x”);

    Serial.println(p2Read, HEX);

    bReady = 0;

    }

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    65/132

    }

    The program code of the thread is running within the loop1() function. If the globalvariable bReady = 1, the state of digital inputs P2.5 – P2.7 is saved in bits 0 – 2 of thep2Read variable. The value obtained is then transferred to the Raspberry Pi through a

    serial interface.

    The project window in Energia MT IDE looks like the following ( Fig.13 ).

    Fig.13

    The source code of the Python application running in Raspbian OS is shown in Listing 23 .

    Listing 23 .

    from time import sleep

    import RPi.GPIO as GPIOimport serial

    import sys

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    66/132

    GPIO.setwarnings(False)

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(18, GPIO.OUT)

    s1 = serial.Serial(port=’/dev/ttyACM0’,

    baudrate=9600,

    parity=serial.PARITY_NONE,

    stopbits=serial.STOPBITS_ONE,

    bytesize=serial.EIGHTBITS,

    timeout=3)

    try:

    while 1:

    GPIO.output(18, GPIO.HIGH)

    GPIO.output(18, GPIO.LOW)

    rLine = s1.readline()

    print rLine

    sleep(5)

    except KeyboardInterrupt:

    print ” Terminating the application on Ctr-C…”

    s1.close()

    sys.exit(0)

    The application will perform two actions: activating an interrupt and reading the datathrough a serial interface. The object s1 associated with the serial interface /dev/ttyACM0will be used for reading data transferred by an MSP432 application. The GPIO18 pindriving the interrupt line to pin P2.4 is configured as output. The sequence

    GPIO.output(18, GPIO.HIGH)

    GPIO.output(18, GPIO.LOW)

    within the while loop activates the interrupt on line P2.4 . Then the data is passed through

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    67/132

    the serial interface and output on the screen by the sequence:

    rLine = s1.readline()

    print rLine

    The loop repeats infinitely every 5 s until Ctrl-C is pressed.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    68/132

    Designing Real-Time applications: project 7

    This section is dedicated to processing analog signals in real-time systems withMSP432P401R MCU and Raspberry Pi. Below is a brief description of the analog moduleof MSP432P401R CPU taken from the corresponding datasheet on the device.

    The MSP432P401R CPU contains the ADC14 module that supports fast 14-bit analog-to-digital conversions. The module implements a 14-bit SAR core, sample select control, andup to 32 independent conversion-and-control buffers. The conversion-and-control bufferallows up to 32 independent analog-to-digital converter (ADC) samples to be convertedand stored without any CPU intervention.

    ADC14 features include:

    • 1 Msps maximum conversion rate at maximum resolution of 14-bits;

    • Monotonic 14-bit converter with no missing codes;

    • Sample-and-hold with programmable sampling periods controlled by softwareor timers;

    • Conversion initiation by software or timers;

    • Software-selectable on-chip reference voltage generation (1.2 V, 1.45 V, or 2.5V) with option to make available externally;

    Software-selectable internal or external reference;• Up to 32 individually configurable external input channels, single-ended ordifferential input selection available;

    • Internal conversion channels for internal temperature sensor and ½ × AVcc andfour more internal channels available on select devices (see device data sheet foravailability as well as function);

    • Independent channel-selectable reference sources for positive reference;

    Selectable conversion clock source;• Single-channel, repeat-single-channel, sequence (autoscan), and repeat-sequence (repeated

    • Autoscan conversion modes;

    • Interrupt vector register for fast decoding of 38 ADC interrupts;

    • 32 conversion-result storage registers;

    • Window comparator for low power monitoring of input signals of theconversion-result register.

    The block diagram of ADC14 is shown in Fig.14 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    69/132

    Fig.14

    The above diagram may come in handy when configuring analog-to-digital converter forour application.

    The demo application is very simple – it will read 3 channels named A0 – A2 and transferthe data obtained via a serial interface to the Raspberry Pi. The circuit diagram of such asystem is shown in Fig.15 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    70/132

    Fig.15

    In this circuit, the analog signals on pins P5.5 – P5.3 are simulated by potentiometers Rp1 – Rp3 . Analog signals are taken from their wipers and fed to analog inputs of MSP432.

    The table below details the connections.

    MSP432P401R LaunchPad pin Analog channel ofMSP432P40R

    P5.5 A0

    P5.4 A1

    P5.3 A2

    The Energia MT source code of the main thread of the MSP432 application is shown inListing 24 (file A0_A1_A2_MT.ino ).

    Listing 24 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    71/132

    #include “msp.h”

    #define ADC14CSTARTADD_1 (1

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    72/132

    for (i = 0; i < 3; i++)

    {

    ADC14CTL0 &= ~ADC14ENC;

    delayMicroseconds(10);

    ADC14MCTL1 = 0x0;delayMicroseconds(10);

    ADC14MCTL1 += chs[i]; // Select an input channel from the chs array, Vref = AVcc

    delayMicroseconds(10);

    ADC14CTL0 |= ADC14ENC | ADC14SC; // Start sampling and conversion

    delayMicroseconds(10);

    while(ADC14BUSY == 0x1); // waiting until A/D conversion is complete

    bincode[i] = ADC14MEM1;

    vout[i] = LSB * bincode[i];

    delayMicroseconds(10);

    }

    cBusy = 0;

    delay(1000);

    }

    This source code uses definitions from the header file msp.h . The constant

    ADC14CSTARTADD_1 defined by the following directive

    #define ADC14CSTARTADD_1 (1

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    73/132

    where bincode[i] is a binary code for each channel ( A0 … A2) and LSB(Least Significant Bit) = 3.345/2 12 = 3.345/4096. The constant 3.345 determines areference voltage Vref (by default). In this particular case, the measured value of Vref turned out to be 3.345V.

    The array chs[3] contains the numbers of physical channels being selected via amultiplexor (see Fig.14 ).

    The variable cBusy is needed for synchronizing threads. When cBusy = 1, the A/Dconversion is still running. When cBusy = 0, A/D conversion is complete, so the result canbe transferred to the Raspberry Pi.

    The sequence

    P5SEL1 |= BIT3 | BIT4 | BIT5;P5SEL0 |= BIT3 | BIT4 | BIT5;

    configures pins P5.5 – P5.3 as analog inputs for channels A0 – A2 .

    The following statement configures the ADC14 mode through the ADC14CTL0 controlregister:

    ADC14CTL0 |= ADC14SHT0_3 | ADC14SHP | ADC14ON;

    The parameter ADC14SHT0_3 (bits 11 – 8 of ADC14CTL0 ) determines the sample-and-hold time of ADC14 . These bits define the number of ADC14CLK cycles in the samplingperiod for the memory registers ADC14MEM0 to ADC14MEM7 and ADC14MEM24 toADC14MEM31 . In our case, this parameter is selected equal to 3 that corresponds to 32clock cycles.

    This parameter can be modified only when ADC14 device is disabled by clearing theparameter ADC14ENC (bit 1 of ADC14CTL0 = 0).

    ADC14SHP (bit 26 of the ADC14CTL0 control register) allows to select sample-and-hold pulse-mode. This bit selects the source of the sampling signal ( SAMPCON ) to beeither the output of the sampling timer or the sample-input signal directly. In our case, theSAMPCON signal will be sourced from the sampling timer. This bit can be modified onlywhen ADC14ENC = 0.

    The ADC14ON parameter when set allows to drive ADC14 ON. Clearing this bit drivesADC14 OFF. In our case, ADC14 device is driven ON before A/D conversion begins.

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    74/132

    A/D conversion is executed within an for() loop running 3 iterations. In each iteration, theADC14 is initially disabled by the statement

    ADC14CTL0 &= ~ADC14ENC;

    After a short delay (about 10 uS) the program code clears the memory control register bythe statement:

    ADC14MCTL1 = 0x0;

    After a short delay, the program code selects the physical channel to be processed:

    ADC14MCTL1 += chs[i];

    This is followed by a delay of 10 uS. The next statement enables A/D conversion for theselected channel and starts sampling/conversion:

    ADC14CTL0 |= ADC14ENC | ADC14SC;

    Bit ADC14ENC in the above statement enables A/D conversion; bit ADC14SC startssampling/conversion process.

    To know when A/D conversion is complete, the application periodically checks bitADC14BUSY (bit 16 of the ADC14CTL0 control register). This bit indicates an activesample or conversion operation. If ADC14BUSY = 0, no operation is active. Otherwise, ifADC14BUSY = 1, a sample or conversion is active.

    The application is waiting until A/D conversion is complete by executing the followingstatement:

    while(ADC14BUSY == 0x1);

    The result of A/D conversion is saved in memory register ADC14MEM1 . The following

    statement moves the result to the element corresponding to the selected channel:

    bincode[i] = ADC14MEM1;

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    75/132

    The float value is then saved in the corresponding element of the vout array:

    vout[i] = LSB * bincode[i];

    After the for() loop terminates, the cBusy flag is cleared thus allowing the data transfer.

    The measurement cycle for A0 – A2 channels repeats each 1 s (the delay(1000)statement).

    The following source code (file Serial_Thread.ini ) represents the thread performing datatransfer over a serial interface to the Raspberry Pi ( Listing 25) .

    Listing 25 .

    void setup1()

    {

    // put your setup code here, to run once:

    Serial.begin(9600);

    delay(500);}

    void loop1()

    {

    // put your main code here, to run repeatedly:

    while (cBusy == 1); Serial.print(“A0 input, V: “);

    Serial.println(vout[0], 3);

    Serial.print(“A1 input, V: “);

    Serial.println(vout[1], 3);

    Serial.print(“A2 input, V: “);

    Serial.println(vout[2], 3);

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    76/132

    delay(3000);

    }

    The above code is periodically (every 3 s) transfers the data obtained from channels A0 – A2 through the serial interface after A/D conversion is complete ( cBusy = 0).

    The source code of the Python application for reading data from MSP432P401R is shownin Listing 26 .

    Listing 26 .

    from time import sleepimport serial

    s1 = serial.Serial(port=’/dev/ttyACM1’,

    baudrate=9600,

    parity=serial.PARITY_NONE,

    stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,

    timeout=1)

    try:

    while 1:

    rLine = s1.readline()

    print rLineexcept KeyboardInterrupt:

    print ” Terminating the application on Ctr-C…”

    s1.close()

    sys.exit(0)

    The Energia MT IDE window is shown in Fig.16 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    77/132

    Fig.16

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    78/132

    Designing Real-Time applications: project 8

    An application to be discussed in this section allows to continuously read 3 analogchannels on the MSP432P401R board. The data collected from all channels are transferredto the Raspberry Pi if interrupt signal on pin P1.6 of MSP432 is activated. The interruptline P1.6 is driven by pin GPIO19 of the Raspberry Pi.The circuit diagram for this project is shown in Fig.17 .

    Fig.17

    In this circuit, analog signals are fed to channels A0 – A2 from the wipers ofpotentiometers Rp1 – Rp3 . The interrupt line assigned to pin P1.6 of MSP432 isconnected to pin GPIO19 of the Raspberry Pi. The interrupt to MSP432 is activated whenGPIO19 goes from HIGH to LOW.

    The Energia MT source code for the application running on the MSP432P401R board isas follows ( Listing 27) .

    Listing 27 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    79/132

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    80/132

    ADC14CTL1 = ADC14RES_2 | ADC14CSTARTADD_1; // Use sampling timer,

    // 12-bit conversion results

    // and ADC14MEM1 memory reg.

    attachInterrupt(15, P16_ISRHandler, FALLING); // an interrupt is activated

    // when a falling edge arrives on pin P1.6 (15)bRead = 0;

    }

    void loop()

    {

    for (i = 0; i < 3; i++)

    {

    ADC14CTL0 &= ~ADC14ENC;

    delayMicroseconds(10);

    ADC14MCTL1 = 0x0;

    delayMicroseconds(10);

    ADC14MCTL1 += chs[i];

    delayMicroseconds(10);

    ADC14CTL0 |= ADC14ENC | ADC14SC; // Start sampling and conversion

    delayMicroseconds(10);

    while(ADC14BUSY == 0x1); // wait until A/D conversion is complete

    bincode[i] = ADC14MEM1;

    vout[i] = LSB * bincode[i];

    delayMicroseconds(10);

    }

    if (bRead == 1)

    {

    Serial.print(“A0 input, V: “);

    Serial.println(vout[0], 3);

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    81/132

    Serial.print(“A1 input, V: “);

    Serial.println(vout[1], 3);

    Serial.print(“A2 input, V: “);

    Serial.println(vout[2], 3);

    Serial.println(“–––––––”);

    bRead = 0;

    }

    delay(100);

    }

    void P16_ISRHandler()

    {

    P1IFG &= ~BIT6; // Clear P1.6 Interrupt flag

    if (bRead == 0)

    bRead = 1;

    }

    In this code, channels A0 – A2 are processed within the for(i = 0; i < 3; i++) loop every100 mS. If an interrupt on pin P1.6 has been activated, the variable bRead is set (=1) bythe P16_ISRHandler interrupt handler thus allowing to transfer the result of A/Dconversion via a serial interface.

    The binary codes corresponding to all analog inputs are held in the array bincode , thecalculated values of the analog inputs are held in the array vout .

    The source code of the Python application controlling the data transfer fromMSP432P401R MCU is shown in Listing 28 .

    Listing 28 .

    from time import sleep

    import RPi.GPIO as GPIO

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    82/132

    import serial

    import sys

    GPIO.setwarnings(False)

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(19, GPIO.OUT) # P1.6 control

    s1 = serial.Serial(port=’/dev/ttyACM0’,

    baudrate=9600,

    parity=serial.PARITY_NONE,

    stopbits=serial.STOPBITS_ONE,

    bytesize=serial.EIGHTBITS,

    timeout=3)

    try:

    while 1:

    GPIO.output(19, GPIO.HIGH) # activate interrupt on P1.6 of MSP432

    sleep(0.1)

    GPIO.output(19, GPIO.LOW)

    for x in range (0, 4):

    rLine = s1.readline()

    print rLine

    sleep(4)

    except KeyboardInterrupt:

    print ” Terminating the application on Ctr-C…”

    s1.close()

    sys.exit(0)

    To access the serial interface the application creates the object s1 with predeterminedparameters. In our case, s1 is associated with the /dev/ttyACM0 device. The sequence

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    83/132

    GPIO.output(19, GPIO.HIGH)

    sleep(0.1)

    GPIO.output(19, GPIO.LOW)

    within the while loop periodically (every 4 s) activates the interrupt on pin P1.6 ofMSP432 through GPIO19 . Then the for loop reads 4 lines from the serial interface andoutput the results on the console.

    The Python application provides the following outputs:

    pi@raspberrypi ~/Developer $ sudo python ReadingAnalog_ISR.py

    A0 input, V: 0.338

    A1 input, V: 0.958A2 input, V: 1.440

    –––––––

    A0 input, V: 0.338

    A1 input, V: 0.958

    A2 input, V: 1.450

    ––––––– A0 input, V: 0.337

    A1 input, V: 0.959

    A2 input, V: 1.450

    –––––––

    ^C Terminating the application on Ctr-C…

    The Energia MT IDE window of the project is shown in Fig.18 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    84/132

    Fig.18

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    85/132

    Designing Real-Time applications: project 9

    This section illustrates how to transfer a command to MSP432 from the Raspberry Piusing a serial interface. An application running on the MSP432P401R board will receivethe command, parse it and set the frequency of timer Timer_A3 .

    The circuit diagram of the project is shown in Fig.19 .

    Fig.19

    In this circuit, the output signals of timer TimerA_3 are taken from pins P10.5 (channel 1)and P8.2 (channel 2).

    The Energia MT source code for MSP432P401R MCU is shown in Listing 29.

    Listing 29.

    #include “msp.h”

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    86/132

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    87/132

    // fault flag

    CSKEY = 0; // Lock CS module from unintended accesses

    // Setup TimerA_3 TA3CCR0 = 80; // PWM Period (f = 409 Hz)

    TA3CCTL1 = OUTMOD_7; // CCR1 reset/set

    TA3CCR1 = 80 / 3; // CCR1 initial duty cycle = 33%

    TA3CCTL2 = OUTMOD_7; // CCR2 reset/set

    TA3CCR2 = 80 * 2 / 3; // CCR2 initial duty cycle = 66%

    TA3CTL = TASSEL_1 | MC_1 | TACLR; // ACLK = 32768 Hz, up mode, clear thecounter and reset

    }

    void loop()

    {

    while (Serial.available() > 0)

    {

    // look for the next valid integer in the incoming serial stream:

    cmd = Serial.parseInt(); // cmd line:

    if (cmd == 3) // 3 is a code of a TimerA_3 write command

    {

    freq = Serial.parseInt();

    if((freq >= 300) && (freq

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    88/132

    }

    }

    delay(1000);

    }

    In this source code, the constant pACLK is used for calculating a value being written tothe TA3CCR0 register. The variable freq holds the actual value of a frequency to beadjusted. The variable pA3 is assigned the value corresponding to the selected frequencyby the statement:

    pA3 = pACLK / freq;

    The TimerA_3 timer is configured by the sequence of commands, where first determinesthe initial frequency of TimerA_3 :

    TA3CCR0 = 80;

    With the value of 80, the initial frequency will be 32768 Hz / 80 = 409 Hz.

    The mode and duty cycle for the CCR1 output are configured by the statements:

    TA3CCTL1 = OUTMOD_7;

    TA3CCR1 = 80 / 3;

    The first statement of this sequence puts CCR1 in set/reset mode. The second adjusts the

    initial duty cycle to be about 33%.The CCR2 output is configured by the sequence:

    TA3CCTL2 = OUTMOD_7;

    TA3CCR2 = 80 * 2 / 3;

    The duty cycle of a signal on the CCR2 output will be close to 66%.The following statement enables timer TimerA_3 :

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    89/132

    TA3CTL = TASSEL_1 | MC_1 | TACLR;

    Here the TASSEL_1 parameter determines the clock source ( ACLK = 32768 Hz), theMC_1 parameter puts TimerA_3 in Up mode and TACLR clears the counter and resetsthe timer.

    The new value of a frequency of timer TimerA _3 is passed to an application through aserial interface in Comma-Separated Format (CSV):

    where value1 is the command (=3, in our case) and value2 is a new frequency. Forexample, the following sequence

    3, 500

    allows to adjust a frequency of 500 Hz for TimerA_3 .

    The data received by the MSP432 serial interface are parsed by the statements

    cmd = Serial.parseInt();

    . . .

    freq = Serial.parseInt();

    Off these statements, the former saves the command in the variable cmd , while the latter

    saves the value of a new frequency in the variable freq .

    The source code of a Python application controlling PWM sources is shown in Listing 30 .

    Listing 30 .

    from time import sleepimport serial

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    90/132

    s1 = serial.Serial(port=’/dev/ttyACM0’,

    baudrate=9600,

    parity=serial.PARITY_NONE,

    stopbits=serial.STOPBITS_ONE,

    bytesize=serial.EIGHTBITS,timeout=1)

    s1.write(“3,300”)

    sleep(5)

    s1.write(‘3,780’)

    sleep(5)

    s1.write(‘3,1140’)

    sleep(5)

    s1.close()

    In this code, the application associates the serial interface with an object s1. Theapplication writes three commands to the serial device. The first command determines the

    frequency of 300 Hz for TimerA_3 , the second determines the frequency of 780 Hz andthird determines the frequency of 1140 Hz.

    Below is one more Python source code for controlling PWM. This application uses thecommand line parameters ( Listing 31 ).

    Listing 31 .

    # This script illustrates passing command line parameters

    # through a serial interface. The command line

    # arguments are as follows:

    # -t determines the timer (3 = Timer_A3)

    # -f is the frequency to be set

    # Cmd line: sudo -t 3 -f

    # Example: pi@raspberrypi ~/Developer $ sudo python Set_Freq.py -t 3 -f 340

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    91/132

    import serial

    import time

    import argparse

    parser = argparse.ArgumentParser(description=‘Configuring the frequency of a PWMsignal’)

    parser.add_argument(‘-t’, ‘—timer’, help=‘timer’, required=True)

    parser.add_argument(‘-f’, ‘—frequency’, help=‘Desired frequency’, required=True)

    args = parser.parse_args()

    str1 = args.timer + ‘,’ + args.frequency

    s1 = serial.Serial(port=’/dev/ttyACM0’,

    baudrate=9600,

    parity=serial.PARITY_NONE,

    stopbits=serial.STOPBITS_ONE,

    bytesize=serial.EIGHTBITS,

    timeout=1)

    time.sleep(1)

    s1.write(str1)

    time.sleep(1)

    s1.close()

    The Python application takes two parameters and forms a CSV data line like thefollowing:

    ,

    This is done by the statement:

    str1 = args.timer + ‘,’ + args.frequency

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    92/132

    The command string str1 is then transferred to the MSP432P401R board through theserial interface associated with the s1 object. After 1 s delay the serial device is closed.These operations are performed by the following sequence:

    s1.write(str1)time.sleep(1)

    s1.close()

    The Python application is invoked by:

    pi@raspberrypi ~/Developer $ sudo python Set_Freq.py -t 3 -f 340

    This command sets the frequency of 340 Hz for timer Timer_A3 .

  • 8/19/2019 Real-Time Applications Using MS - Yury Magda

    93/132

    Using an MSP432 32-bit timer in Real-Time applications

    This section is dedicated to configuring and using an MSP432 32-bit timer calledTimer32 . This built-in device provides the basis for implementing various timingfunctions in real-time applications. Below is the brief description taken from anMSP432P401 datasheet.

    MSP432P4xx Timer32 is an AMBA compliant SoC peripheral developed, tested, andlicensed by ARM Limited. The Timer32 module consists of two programmable 32-bit or16-bit down counters that can generate interrupts on reaching zero. The key features ofTimer32 include:

    • 2 independent counters each configurable as 32-bit or 16-bit counter size;

    • Three different timer modes supported for each counter;

    • Prescaler to divide the input clock by 1, 16 or 256;

    • Independent Interrupts from each of the counter, as well as, a combinedinterrupt from both the counters

    Two independent timers are available as part of Timer32 . For each of the times, thefollowing modes of operation are available:

    • Free-Running mode: The counter wraps after reaching its zero value, andcontinues to count down from the maximum value. This is the default mode.

    • Periodic timer mode: The counter generates an interrupt at a constant interval,reloading the original value after wrapping past zero.

    • One-Shot timer mode: The counter generates an interrupt once. When thecounter reaches zero, it halts until reprogrammed by the user. This can be achievedby either clearing the One-Shot Count bit in the control register, in which case the

    count proceeds according to the selection of Free-Running or Periodic mode, orby writing a new value to the Load Value register.

    Each timer has an identical set of registers and the operation of each timer is also identical.The timer is loaded by writing to the load register and, if enabled, counts down to zero.When a counter is already running, writing to t