Εμφάνιση αναρτήσεων με ετικέτα programming. Εμφάνιση όλων των αναρτήσεων
Εμφάνιση αναρτήσεων με ετικέτα programming. Εμφάνιση όλων των αναρτήσεων

Σάββατο 4 Ιουλίου 2015

LCD Display Library for Tiva and Stellaris Launchpads

Liquid Crystal Displays (LCDs) are great for creating impressive (and sometimes, useful!) microcontroller projects. The 16 characters / 2 lines display is very cheap and directly supported by the arduino LiquidCrystal library (also works in  MSP430 with Energia).

In this post we implement similar functionality for the Tiva C series and  Stellaris launchpads. This version of the library works in CCS and can be used with Stellaris LM4F120, TivaC TM4C123G and Tiva C Connected TM4C1294 launchpads with minimal changes.

LCD library in action. Also current state of Greek economy :)


You may download the complete project from my github page.

The HD44780 specification

LCDs that use the HD44780 drivers are commonly called COGs (Chip on Glass) as they contain all the necessary circuits to drive the LCD segments and communication with the host processor is generally limited to the following pins:
  • DB0 to DB7 Data bus. The bus is used to communicate commands or characters to be written to the screen, one byte at a time. To save MCU pins, the interface can be configured for 4 bit operation, where only the DB4 to DB7 lines are used.
  • An RS (Register Select) pin. Specifies whether the data bus is carrying a command to be executed or a character to be displayed. When RS is low,  data on the bus represents a command, otherwise it represents a character.
  • An EN pin. This is a strobe pin, It has to be pulsed Low-High-Low for the LCD to accept the data in the bus.

When using 4 bit mode, the above connections require 6 pins of your MCU.

The LCD display will also require additional pins to be connected to Vcc or GND, including:
  • Power and ground for the LCD and HD44780 ICs.
  • Power and ground for the LCD backlight (if applicable)
  • Ground connection of the R/W pin (to enable writing to the LCD).
  • A potentiometer between Vcc and GND to pin 5 for adjusting display contrast. 
Here is the pinout used in my version of the LCD library for the TivaC launchpad. Pin assignment can be easily reconfigured using the appropriate #define statements in display.h file:

LCD pin       TivaC
-------------------
DB4           PD0
DB5           PD1
DB6           PD2
DB7           PD3
RS            PE4
EN            PE5

The Code

Let's have a look at how the library works. It is based on the HD44780 spec and heavily influenced by a similar work for the MSP430 published in the Co-Random Thoughts blog. The display.h file defines some useful macros to represent the pins and ports we use:

#define RS GPIO_PIN_4 // Energia Pin 5
#define EN GPIO_PIN_5 // Energia Pin 6
#define D4 GPIO_PIN_0 // Energia Pin 23
#define D5 GPIO_PIN_1 // Energia Pin 24
#define D6 GPIO_PIN_2 // Energia Pin 25
#define D7 GPIO_PIN_3 // Energia Pin 26
#define ALLDATAPINS  D7 | D6 | D5 | D4
#define ALLCONTROLPINS RS | EN

#define DATA_PORT_BASE GPIO_PORTD_BASE
#define CMD_PORT_BASE GPIO_PORTE_BASE
#define DATA_PERIPH SYSCTL_PERIPH_GPIOD
#define CMD_PERIPH SYSCTL_PERIPH_GPIOE

The DATA_PORT_BASE points to Port D which is configured for the data bus. CMD_PORT_BASE points to Port E, configured for the RS and EN signals.

To start up the LCD in 4 bit data mode, we have to send the following command to the D4-D7 pins twice:

D7 D6 D5 D4
 0  0  1  0

For this, we need to pull RS low, send the command, strobe the LCD via the EN pin, wait a bit and repeat. After this step the LCD is switched to 4 bit mode. All subsequent 8bit commands / characters are sent as  a pair of nibbles.

Here is the relevant code in initLCD:

void initLCD(void)
{
SysCtlPeripheralEnable(DATA_PERIPH);
SysCtlPeripheralEnable(CMD_PERIPH);
GPIOPinTypeGPIOOutput(DATA_PORT_BASE,  ALLDATAPINS);
GPIOPinTypeGPIOOutput(CMD_PORT_BASE, ALLCONTROLPINS);
GPIOPinWrite(DATA_PORT_BASE, ALLDATAPINS ,0);
GPIOPinWrite(CMD_PORT_BASE, ALLCONTROLPINS ,0);

SysCtlDelay(10000);

setCmd();
SysCtlDelay(15000);
GPIOPinWrite(DATA_PORT_BASE, ALLDATAPINS, 0b0010);
pulseLCD();
GPIOPinWrite(DATA_PORT_BASE, ALLDATAPINS, 0b0010);
pulseLCD();

PulseLCD is a simple function that pulses EN to Low-High-Low states:

void pulseLCD()
{
// Go Low -> High -> Low
GPIOPinWrite(CMD_PORT_BASE, EN, 0);
GPIOPinWrite(CMD_PORT_BASE, EN, EN);
GPIOPinWrite(CMD_PORT_BASE, EN, 0);
}

Similarly the setCmd() and setData() functions switch the RS pin to low / high respectively.

After successfully initializing the LCD to 4bit mode, we sent a few more commands:

sendByte(0x28,FALSE);  // Set two lines
cursorOffLCD();       // Cursor invisible
sendByte(0x06, FALSE); // Set insert mode

After setting insert mode, the LCD is ready to accept characters for printing. The sendByte function sends a byte as a pair of nibbles:

void sendByte(char byteToSend, int isData)
{
if (isData)
setData();
else
setCmd();
SysCtlDelay(400);
GPIOPinWrite(DATA_PORT_BASE, ALLDATAPINS, byteToSend >>4);
pulseLCD();
GPIOPinWrite(DATA_PORT_BASE, ALLDATAPINS, byteToSend);
pulseLCD();
}

The high nibble is set first followed by the low nibble. The display is strobed to accept each nibble. RS is set accordingly for data (high) or command (low).
Timing is important: with the delays currently in the program, the LCD works fine when running at 25MHz frequency. If you need to run at the full 80MHz of the TivaC (or more for the TivaC Connected) you will need to introduce more SysCtlDelay statements  or the display will fail to catch and garbled text will be shown!

Printing to the LCD is  very simple: Just send the characters of your string one by one to the sendByte function:

void printLCD(char *text)
{
char *c;
c = text;

while ((c != 0) && (*c != 0))
{
sendByte(*c, TRUE);
c++;
}
}

The library implements a few more command of the HD44780 protocol. Here are a few interesting hex codes to try:

Function Definition    Hex Code
Set 4 bit mode         0x0
Scroll one char right  0x1E
Scroll one char left   0x18
Goto Home position     0x02
Go one char left       0x10
Go one char right      0x14
Underline cursor on    0x0E
Blinking cursor        0x0F
Invisible cursor       0x0C
Blank display          0x08
Clear display          0x01
Set next position      0x80+Address

More details are available in the HD44780 datasheet.

Happy coding!

Κυριακή 31 Μαΐου 2015

Clocking the MSP430F5529 Launchpad, Part II: The Assembly Way

We have already discussed a nice way to clock your launchpad using the mspware library of functions provided by TI. How about trying the same thing in assembly language?

Assembly allows you precise control over the MCU although it is arguably more involved than plain C (or mspware assisted) programming. Let's revisit our previous clocking examples and try to implement them in MSP430 assembly.

Before we Start

To do any serious assembly work, you will need to study at least three documents:


The Family User's Guide shows all the appropriate registers and operations needed for tasks like setting the clocks, raising Vcore, working with timers, GPIOs and so on.  It also describes the internals of  the MSP430 and the assembly language instructions. The Assembly Language Tools User's Guide will get you started on the assembler provided with CCS. The F5529 datasheet provides info specific to the chip we are programming. There are also some nice tutorials available on the Internet to get you started with assembly programming on the MSP430.  And don't miss out on the examples installed on your development system either:
Have a look in C:\ti\msp430\MSPWare_2_00_00_XX\examples\devices\5xx_6xx (or wherever you installed mspware). Check for  folders named Assembly_CCS.  You may not find one for the F5529, but there are plenty of examples for other similar devices.

Default Clocks

As we already know, the default MSP430 clock is about 1MHz. Here is some code to prove it:

bis.b #BIT2,&P2DIR ; Set P2.2 as output
bis.b #BIT2,&P2SEL ; Set P2.2 as peripheral output
; P2.2 is multiplexed with SMCLK
; This will output SMCLK to P2.2
  bis.b #BIT7,&P7DIR ; Set P7.7 as output
bis.b #BIT7,&P7SEL ; Set P7.7 as peripheral output
; P7.7 is multiplexed with MCLK
; This will output MCLK to P7.7
                          ; P7.7 is not present in the headers
; of the launchpad. It is output pin 60
; on F5529. Top right corner ;)

bis.b #BIT7,&P4DIR ; Set P4.7 as output (Green LED)
bis.b #BIT0,&P1DIR ; Set P1.0 as output (Red LED)
mov.w #3787, R15 ; Delay parameters
  mov.w #22, R14
blink xor.b #BIT0,&P1OUT
call #delay
jmp blink

Download the complete project files here. 'Delay' is a subroutine that mimics the behavior of the __delay_cycles() intrinsic of the C compiler. With the values specified here (in R14 and R15 registers), delay will  waste about 250000 cycles (check out comments in the source code and you will figure it out) allowing us to watch the red LED blinking!

If you have a scope, you may connect it to P2.2 where SMCLK is output. Here is what you will see:


If you feel lucky, you may also probe (carefully!) port 7.7. This is MCLK (same frequency as SMCLK here). It is pin no 60 of the F5529, but it is not output on any header pin.

Direct clocking with Crystals

Clocking with crystals is mostly straightforward. Download the complete project files here. We connect the 32.768KHz crystal to ACLK and the 4MHz crystal to MCLK/SMCLK:

       bis.b #BIT4+BIT5,&P5SEL   ; Connect XT1 to P5.5, P5.4
                                ; by configuring the ports 
                                ; peripheral function
       bis.b #BIT2+BIT3,&P5SEL   ; Connect XT2 to P5.3, P5.2
                            ; by configuring the ports for
                            ; peripheral function

The crystal pins are multiplexed with GPIOs in F5529. We have to first select them as peripheral pins using the P5SEL register.

bic.w #XT1OFF, &UCSCTL6  ; Turn on XT1
bic.w #XT2OFF, &UCSCTL6  ; Turn on XT2

We then turn on the crystals, by clearing their OFF bits in the UCSCTL6 register. UCSCTLx registers define the behavior of many aspects of the Unified Clock System (UCS).

bis.w #XCAP_3, &UCSCTL6  ; Internal load capacitor for XT1

 We connect an appropriate capacitor to the low frequency XT1.

waitclear   bic.w   #XT2OFFG | XT1LFOFFG | DCOFFG, &UCSCTL7
; Clear XT2,XT1,DCO fault flags  (XT1 and XT2 only here)
            bic.w   #OFIFG,&SFRIFG1         ; Clear fault flags
            bit.w   #OFIFG,&SFRIFG1         ; Test oscillator fault flag
            jc      waitclear

We have to wait for the crystals to start and stabilize. We continuously clear and test the oscillator fault flag until it is no longer set.

     bic.w #XT1DRIVE_3,&UCSCTL6  ; XT1 is now stable, reduce drive
                                 ; strength. Low frequency crystals 
                                 ; take some time
                                 ; to start and stabilize
     bic.w #XT2DRIVE_0,&UCSCTL6  ; XT2 Drive strength reduced to
                                 ; level 0    
; for 4-8MHz operation

 Finally, we set the right drive strengths for both crystals. The low frequency crystal takes some time to start-up and stabilize. After this time, the drive strength is reduced. This prolongs the life of the crystal and also reduces power consumption.

We are now ready to assign the crystals to our clocks:

      mov.w #SELA_0|SELS_5|SELM_5,&UCSCTL4

UCSCTL4 is the register that sets the source for each clock (ACLK, SMCLK, MCLK). SELA_0 selects XT1 for ACLK, while SELS_5 and SELM_5 select XT2 for MCLK and SMCLK. You can easily see the difference by using your scope as before:



Also note the LED blinks a lot more rapidly now, as the MCLK frequency is 4MHz :)

Using the DCO and FLL

Going beyond the crystals we need to configure DCO and provide it with an FLL reference. Going above 8MHz also requires setting  Vcore to a higher level. Fortunately, there is an assembly language example in the samples provided by TI. We have implemented this as a subroutine and call it three times to set Vcore to the maximum level (download the complete project files here):

  mov.w #PMMCOREV_1,R12
call #setvcore
mov.w #PMMCOREV_2,R12
call #setvcore
mov.w #PMMCOREV_3,R12
call #setvcore

Here is a diagram showing the required Vcore by frequency, as shown in the F5529 datasheet. Launchpad supplies 3.3V to the F5529, so we can clock it up to its maximum operating frequency, as long as we raise PMMCOREV to 3:

 TI states that Vcore should only be raised one level at a time, hence the three separate calls here.

Having  connected and started the crystals in our previous example, we are halfway to our target already! 

; Default settings in UCSCTL3: SELREF = 000b -> FLLREF = XT1CLK
;                              FLLREFDIV = 000b -> FLLREFCLK / 1

bis.w   #SCG0,SR       ; Disable the FLL control loop
        clr.w   &UCSCTL0       ; Set lowest possible DCOx, MODx
        mov.w   #DCORSEL_7,&UCSCTL1   ; Select range for 20MHz
        mov.w   #FLLD_2 + 639,&UCSCTL2 ; Set DCO multiplier
                                       ; for DCOCLKDIV
        ; (FLLN + 1) * (FLLRef/n) * FLLD = DCOCLK
        ; FLLD_2 = 4
        ; FLLRef=32768 and n=1
        ; (n=FLLREFDIV)
        ; DCOCLKDIV = DCOCLK/FLLD = (FLLN+1)*(FLLRef/n)
        ; Default settings are DCOCLKDIV for MCLK/SMCLK

        bic.w   #SCG0,SR ; Enable the FLL control loop

UCSCTL3 contains important settings: The clock source to use for the FLLREF (default is the low frequency crystal, XT1CLK) and FLLREFDIV which allows FLLREFCLK to be further divided by 1, 2, 4, 8, 12 or 16. We just use the defaults here.

Before changing the DCO setting, we first disable the FLL control loop and clear the UCSCTL0 register. This register will be set automatically after we adjust the FLL parameters.  We need to look at the documentation of F5529 to choose the appropriate DCO range. The F5529 datasheet will help us find this one:



For 80MHz operation, we need to go up to the last range, DCORSEL_7 and store it in register UCSCTL1. We set the multiplier and frequency bits in UCSCTL2.

Multiplier is FLLD_2 which is 4
FLLN is 639.
Thus, DCOCLK =  (639+1) * (32768/1) * 4 = 83886080 Hz (84MHz)

DCOCLK is not used directly on MCLK/SMCLK (that would be one hell of an overclocking!). DCOCLKDIV is used instead:

DCOCLKDIV = DCOCLK / FLLD  = 83886080 / 4 =  20971520 Hz or about 21 MHz.


Although DCO is now set, the actual frequency will take sometime to stabilize.  Our delay subroutine comes handy again:

; Worst-case settling time for the DCO when the DCO range bits 
have been changed is n x 32 x 32 x F_fLLREFCLK cycles.
; n = FLLREFDIV
; 1 x 32 x 32 x 20.97152 MHz / 32.768 KHz = 655360  
; MCLK cycles for DCO to settle

mov.w #9930,R15
mov.w #22,R14
call #delay

; Total cycles: setup 6+6+2=14
; Internal Loop: 9930*3*22=655380
; Outer loop: 22*5 = 110
; Total: 110+655380+14 = 655504

And we also clear the oscillator fault flag and loop until it no longer sets itself:

; Loop until DCO fault flag is cleared

delay_DCO   bic.w   #DCOFFG,&UCSCTL7    ; Clear DCO fault flags
            bic.w   #OFIFG,&SFRIFG1     ; Clear fault flags
            bit.w   #OFIFG,&SFRIFG1     ; Test oscillator fault flag
            jc      delay_DCO

Finally, we assign the clock sources to their respective clocks (these are in fact the default settings for UCSCTL4):

mov.w #SELA_0|SELS_4|SELM_4,&UCSCTL4

Checking SMCLK with the oscilloscope:



For this last example, we have adjusted the  LED delay loop to 1 million cycles, so we can still watch it blinking!

Guess what - assembly is great for lots of happy afternoons :)

Σάββατο 23 Μαΐου 2015

Programming Target and Breakout Boards using a Launchpad

Using the launchpad as a spy bi-wire programmer is not new: People have been doing it with the value line launchpads for ages. But how about using a launchpad to program a chip in LQFP-64, LQFP-80 or LQFP-100 package (or in other SMT style packages). These chips cannot be directly breadboarded but compared to the THT MSPs, they are a lot more powerful, hence a lot more desirable :)

As I found out, there is more than one way to use your trusty launchpad to program these.

The Target Board

Texas Instruments sells boards equipped with ZIF (Zero Insertion Force) sockets for just about every package type they produce an MSP in. The boards alone sell for about 80-100 USD officially, but you can get much better prices on ebay. The target board will allow you to insert your MSP, connect it to a JTAG programmer (sold separately), program it and then remove it and use it in your PCB or prototype board.
Guess what: you don't really need to buy the JTAG programmer (FET interface), since you already have the launchpad!
I recently acquired an LQFP-100 target board (MSP-TS430PZ100B) and a couple of MSP430F6736 and set out to find how to program them using the F5529 launchpad.  It turned out to be pretty easy:


Launchpad to Target board

The connections are straightforward:

Launchpad to target board schematic
Your launchpad will program and also power the chip in the target board. Don't forget to set your target board configuration to Spy bi-wire. There is usually a set of jumpers that you have to move to the SBW position:


While a target board is handy, it will only allow you to program specific types of chips (unless you start collecting target boards, which might become a rather expensive hobby). But there is another way to program MSPs and use them for prototyping too: the breakout boards.

Programming a Breakout Board

Fortunately, eBay is full of sellers for breakout boards of any type. I ordered ten LQFP-100 boards from a seller in China. These were promptly delivered and I soldered a couple of F6736 chips on them:


After soldering some headers on it, I set out to find the minimum circuit that would allow this little board to work and get programmed by my launchpad. It basically comes down to this:


You will have to look at the datasheet for your specific MSP to find out which pins to connect and where. There will be more than a couple of pins that need to be tied to Vcc and GND and also a few that will require capacitors to GND. The spy bi-wire interface needs a few additional components (you can probably ommit the 330 Ohms resistor though). And this is how it looks like:

Launchpad to breakout board

Yes, it's a big mess of wires. But it works!
And of course if you are designing your own PCB, you can just provide a port for the spy bi-wire pins and program your MSP directly in circuit. Either way, MSP programming is a lot of fun!

Κυριακή 12 Απριλίου 2015

Clocking the MSP430F5529 Launchpad

The MSP430F5529 Launchpad is a tinkerers dream! Powerful and complicated, will provide you with many happy afternoons ;) In this post we examine the UCS (Unified Clock System) and how you can use to it clock your Launchpad up to it's maximum speed.



The MSP430F5529 launchpad offers plenty of clock sources and three different clocks to work with:

  • MCLK, the Master Clock - Used for the CPU. Usually fast.
  • SMCLK, the Sub-Master Clock, used for peripherals. Usually fast (equal to MCLK, or a fraction of it).
  • ACLK, the Auxiliary clock, usually slow and used for peripherals when very low power is needed.

And what do you feed to these clocks?

  • VLOCLK: On-chip, very low frequency oscillator. Around 10 KHz and not accurate at all!
  • REFOCLK: Reference oscillator at the usual 32768 Hz (the common RTC frequency). Medium accuracy, again provided on chip.
  • DCO: Digitally Controlled Oscillator. On chip, fast oscillator source.
  • XT1: Onboard crystal at 32768 Hz (like REFOCLK but more accurate, since it is a crystal).
  • XT2: Onboard crystal at 4 MHz.


The above sources can be combined in a bewildering number of ways: different sources to different clocks, divided by a number of dividers or used to synthesize and fine tune the DCO up to the 25MHz maximum clock of the F5529.

Let's see how we can use and set these using the DriverLib (part of MSPWare) provided by TI.

Important Note: TI has changed some function names in the recent version of MSPWare. To follow our examples download the latest CCS (Code Composer Studio) and MSPWare (I've tried to show the differences in the listings).

Initial Investigation


What are the default clocks of your F5529 Launchpad if you make no settings at all? Let's investigate. Create an empty DriverLib project and paste the following code. Use the expression watch in the debugger to examine the values of the three variables (mclk, smclk, aclk):

#include "driverlib.h"

uint32_t mclk = 0;
uint32_t smclk = 0;
uint32_t aclk = 0;

int main(void) {
    WDT_A_hold(WDT_A_BASE);
    aclk=UCS_getACLK();
    mclk=UCS_getMCLK();
    smclk=UCS_getSMCLK();
    while (1);
    return (0);
}

And the results are:

  • MCLK: 1048576 Hz (1 MHz)
  • SMCLK: Same as MCLK
  • ACLK: 32768 Hz

If you never touched your launchpad clocks, you are only running at 1 MHz. We can do a lot better than that!

Setting Clocks using Internal Clock Sources (the simple way)


The two "simple" clock sources are the REFOCLK and the VLOCLK. In a pinch, you
can use some simple functions to change any of the clocks using them as sources. For example, setting the ACLK to use the REFOCLK:

#include "driverlib.h"

void initClocks();

uint32_t mclk = 0;
uint32_t smclk = 0;
uint32_t aclk = 0;

int main(void) {
    WDT_A_hold(WDT_A_BASE);
    initClocks();
    aclk=UCS_getACLK();
    mclk=UCS_getMCLK();
    smclk=UCS_getSMCLK();
    while (1);
    return (0);
}

void initClocks(){
    UCS_initClockSignal( // clockSignalInit in previous driverlib
UCS_ACLK,  // Set the auxiliary clock, using the
UCS_REFOCLK_SELECT, // reference oscillator (32768 Hz) and
UCS_CLOCK_DIVIDER_2 // divide it by this value.
    );
}

Using a divider of 2, yields an ACLK frequency of 16384. You are welcome to try other values for the divider (in powers of 2 up to 32) as well as trying to set MCLK and SMCLK the same way (just substitute UCS_ACLK with UCS_MCLK or UCS_SMCLK). The syntax is  no different with VLOCLK (from now on we only show different versions of the initClocks function):

void initClocks(){
    UCS_initClockSignal(
UCS_ACLK,
UCS_VLOCLK_SELECT,
UCS_CLOCK_DIVIDER_32
    );
}

With a clock divider of 32, we can go as low as 312 Hz!

Using the Crystals - The easy way


The crystals provide very accurate timing and their basic usage is very easy. We need to actually configure the pins where they are connected (they are normally configured for GPIO), start them, and then use them the same way we used the internal sources.

void initClocks(){
    // Important First Steps: Configure Pins for Crystals!
    // All to port P5
    // PIN5 -> XT1 OUT
    // PIN4 -> XT1 IN
    // PIN3 -> XT2 OUT
    // PIN2 -> XT1 IN

    GPIO_setAsPeripheralModuleFunctionInputPin(
GPIO_PORT_P5,
GPIO_PIN4+GPIO_PIN2
    );

    GPIO_setAsPeripheralModuleFunctionOutputPin(
GPIO_PORT_P5,
GPIO_PIN5+GPIO_PIN3
    );

    // YOU HAVE to inform the system of the crystal frequencies
    // You probably want to use #defines for these values

    UCS_setExternalClockSource(
32768,  // Frequency of XT1 in Hz.
4000000 // Frequency of XT2 in Hz.
    );

    // Initialize the crystals

    UCS_turnOnXT2( // was UCS_XT2Start in previous driverlib
UCS_XT2_DRIVE_4MHZ_8MHZ
    );

    UCS_turnOnLFXT1( //was UCS_LFXT1Start in previous driverlib
UCS_XT1_DRIVE_0,
UCS_XCAP_3
    );

    // Use the crystals to set the clocks

    UCS_initClockSignal(
UCS_MCLK,
UCS_XT2CLK_SELECT,
UCS_CLOCK_DIVIDER_1
    );

    UCS_initClockSignal(
UCS_SMCLK,
UCS_XT2CLK_SELECT,
UCS_CLOCK_DIVIDER_2
    );

    UCS_initClockSignal(
UCS_ACLK,
UCS_XT1CLK_SELECT,
UCS_CLOCK_DIVIDER_1
    );
}

We have just used the 4 MHz XT2 to set MCLK to 4 MHz and SMCLK to 2MHz. We also used the 32768 Hz XT1 to set ACLK.  This method will allows to clock our system up to the XT2 frequency of 4MHz. To clock up to the full 25 MHz we need to set the DCO, the Digitally Controlled Oscillator.

Setting the DCO


To set the DCO we must initialize the Frequency Locked Loop (FLL) inside the F5529 using either the crystals or the internal clock sources.  Let's try with the internal reference oscillator first (32KHz). We'll start with a few defines which should normally be at the top of your listing:

// MCLK = Master Clock (CPU)

#define MCLK_FREQ_KHZ 4000

// Reference frequency (Frequency Locked Loop)

#define FLLREF_KHZ 32

// Ratio used to set DCO (Digitally Controlled Oscillator)

#define MCLK_FLLREF_RATIO MCLK_FREQ_KHZ/FLLREF_KHZ

Our initClocks function now looks like this:

void initClocks(){
    UCS_initClockSignal(
UCS_FLLREF, // The reference for Frequency Locked Loop
UCS_REFOCLK_SELECT, // Select 32Khz reference osc
UCS_CLOCK_DIVIDER_1
    );

    // Start the FLL and let it settle
    // This becomes the MCLCK and SMCLK automatically

    UCS_initFLLSettle(
MCLK_FREQ_KHZ,
MCLK_FLLREF_RATIO
    );

    /* Option: Further divide the frequency obtained for DCO

    UCS_initClockSignal(
UCS_MCLK,
UCS_DCOCLKDIV_SELECT,
UCS_CLOCK_DIVIDER_4
    ); */

    // Set auxiliary clock

    UCS_initClockSignal(
        UCS_ACLK,
UCS_REFOCLK_SELECT,
UCS_CLOCK_DIVIDER_1
    );
}

We first initialize the FLL reference to the 32 KHz of the reference oscillator (REFOCLK). We then initialize the FLL itself and let it settle (the call returns when the FLL has acquired a stable frequency and all faults are cleared). When initFLLSettle completes, both MCLK and SMCLK are set to the frequency of the DCO. Optionally, we can use the DCOCLKDIV to set the clocks to fractions of the DCO. In a pinch, you could change just one line to speed up to 8 MHz:

#define MCLK_FREQ_KHZ 8000

Keep in mind that going to frequencies higher than 8 MHz requires you to set the core power mode. We are currently at PMM_CORE_LEVEL_0, the default core power mode. Insert this line at the top of the initClocks function:

PMM_setVCore(PMM_CORE_LEVEL_0);

and modify it according to the following table:

up to  8 MHz => PMM_CORE_LEVEL_0
up to 12 MHz => PMM_CORE_LEVEL_1
up to 20 MHz => PMM_CORE_LEVEL_2
up to 25 MHz => PMM_CORE_LEVEL_3

Not all frequencies are available at all operating voltages, but this is not a problem for Launchpad users which always run at the full 3.3V. If you try to set the frequency higher than the current core level would allow, the initFLLSettle function may never return.

We have used the on-chip reference oscillator as the source for the FLL reference. We can also use XT1 or XT2 for the same purpose.

Using XT1/XT2 as the FLL reference


Combining the knowledge we gained in the last two sections we can use either of the crystals as a reference for the FLL. Let's use XT2 to clock our Launchpad to a whopping 20 MHz.

Our initial defines are as follows (delete the ones defined previously if you wish to test this):

// Desired MCLK frequency

#define MCLK_FREQ_KHZ 20000

// On board crystals frequencies (in Hz)

#define XT1_FREQ 32768
#define XT2_FREQ 4000000

#define XT1_KHZ XT1_FREQ/1000
#define XT2_KHZ XT2_FREQ/1000

// Ratio used to set DCO (Digitally Controlled Oscillator)
// We are setting the FLL reference to 1 MHz (XT2/4)
// Remember to use the same divider in UCS_initClock

#define MCLK_FLLREF_RATIO MCLK_FREQ_KHZ/(XT2_KHZ/4)

Our initClocks function is now a little more involved:

void initClocks(){

  // Set core power mode

  PMM_setVCore(PMM_CORE_LEVEL_3);

    // Connect Pins to Crystals

    GPIO_setAsPeripheralModuleFunctionInputPin(
GPIO_PORT_P5,
GPIO_PIN4+GPIO_PIN2
    );

    GPIO_setAsPeripheralModuleFunctionOutputPin(
GPIO_PORT_P5,
GPIO_PIN5+GPIO_PIN3
    );

First we set the power mode to the highest one (level 3) for 20 MHz operation.
Then we set the pins where the crystals are connected.

    // Inform the system of the crystal frequencies

    UCS_setExternalClockSource(
XT1_FREQ,  // Frequency of XT1 in Hz.
XT2_FREQ   // Frequency of XT2 in Hz.
    );

    // Initialize the crystals

    UCS_turnOnXT2( 
UCS_XT2_DRIVE_4MHZ_8MHZ
    );

    UCS_turnOnLFXT1(
UCS_XT1_DRIVE_0,
UCS_XCAP_3
    );

We inform the system of the crystal frequencies and initialize the two crystals (For failsafe operation you are advised to check the 'WithTimeout' variants of these functions).

  UCS_initClockSignal(
UCS_FLLREF,  // The reference for Frequency Locked Loop
UCS_XT2CLK_SELECT,  // Select XT2
UCS_CLOCK_DIVIDER_4 // FLL ref. will be 1 MHz (4MHz XT2/4)
  );

We set the FLL reference frequency to 1 MHz by dividing the XT2 frequency by 4. We have already accounted for that in our MCLK_FLLREF_RATIO.

  UCS_initFLLSettle(
MCLK_FREQ_KHZ,
MCLK_FLLREF_RATIO
  );

We initialize the FLL and wait for it to settle. This will set the DCO (and subsequently, MCLK and SMCLK) to our desired frequency of 20 MHz. Optionally, we can set SMCLK to a lower frequency by using the DCOCLKDIV:

    // Optional: set SMCLK to something else than full speed

  UCS_initClockSignal(
UCS_SMCLK,
UCS_DCOCLKDIV_SELECT,
UCS_CLOCK_DIVIDER_1
  );

Finally, we set the ACLK as well:

  // Set auxiliary clock

  UCS_initClockSignal(
UCS_ACLK,
UCS_XT1CLK_SELECT,
UCS_CLOCK_DIVIDER_1
  );
}

You may download this final complete example here.
Happy programming!

Τρίτη 16 Σεπτεμβρίου 2014

MSP430/ARM Development on Linux: Installing CCS 6.0

Code Composer Studio (or CCS as it is widely known), is Texas Instruments' own development tool for their series of MCUs like the well known MSP430 and the Stellaris/Tiva (ARM based) series. Texas Instruments also provides a number of inexpensive development / demo boards known as launchpads. I am the happy owner of two of them: the MSP430 one (F5529) and the ARM based Stellaris launchpad (LM4F120).

Texas Instruments provides some instructions on installing CCS 6.0 on Linux. We will provide additional instructions for installing Tivaware (or stellarisware).

Basic Install

Install your favorite *buntu variant. I've chosen Xubuntu 14.04 since it is lightweight enough and the speed is tolerable on my tiny 2009 Acer Netbook. (While I have beefier machines for development, the netbook is very convenient as it fits perfectly on my rather small electronics workbench).
Make sure to install the updates, either during installation or immediately afterwards by running:

sudo apt-get update; sudo apt-get upgrade

Downloading CCS6.0

Download CCS6.0 for Linux from this page:


It is preferable to download the full version rather than the web based installer.

Installing Dependencies

Before running the installation program, some dependencies need to be installed. In general the instructions in TI's wiki apply:

sudo apt-get install libc6:i386 libx11-6:i386 libasound2:i386 libatk1.0-0:i386 libcairo2:i386 libcups2:i386 libdbus-glib-1-2:i386 libgconf-2-4:i386 libgdk-pixbuf2.0-0:i386 libgtk-3-0:i386 libice6:i386 libncurses5:i386 libsm6:i386 liborbit2:i386 libudev1:i386 libusb-0.1-4:i386 libstdc++6:i386 libxt6:i386 libxtst6:i386 libgnomeui-0:i386 libusb-1.0-0-dev:i386 libcanberra-gtk-module:i386

Some of these are already installed, apt-get will inform you about this.

Note the wiki refers to the 64bit version, but CCS runs without any problem in Ubuntu 32bit too (as you may have noticed, all the above dependencies are 32bits anyway). Create the required symbolic link:

sudo ln -s /lib/i386-linux-gnu/libudev.so.1 /lib/libudev.so.0

Running the Installation

Change to your Download folder (or wherever you placed the downloaded CCS6.0 archive):

cd ~/Downloads

Extract the files:

tar xvzf CCS6.0.1.00040_linux.tar.gz

(replace with actual filename of downloaded file, may differ if a new CCS version is released)

Change to the folder of the extracted files and run the installer:

cd CCS6.0.1.00040_linux

./ccs_setup_6.0.1.00040.bin


There is no need to run the installer as root (with sudo), unless you wish to install it for multiple users. Otherwise, just run it as a standard user and install CCS in a subdirectory of your home directory. After accepting the license, you will be prompted to select an installation directory. Assuming your username is 'user', install CCS to /home/user/ti (the location is automatically suggested by the installer).

You will then be greeted by the processor support dialog:



It is wise to select all the MCUs that you intend developing for. For this example we selected MSP and Tiva/Stellaris development:



You won't have to change the default emulators selected in the next dialog. In the App Center dialog, select at least the MSP430Ware:



Installing the Drivers

After the CCS installation is complete and before plugging in your USB launchpad, install the necessary drivers:

cd ~/ti/ccsv6/install_scripts

sudo ./install_drivers.sh

Running CCS for the First Time

The first time you run CCS, you will be asked to select a workspace (and maybe set it as default). We have chosen /home/user/tidev here but you are welcome to choose your own or accept the default. Make a note of this as you will need it later.



On the first run the App Center will automatically download any options you selected during install (like the MSP430ware) and will also update other components. If you only intend to develop for MSP430, your setup is now complete. For Stellaris/Tiva, read on.

Installing Tivaware (Stellarisware)

Developing for tiva or stellaris requires the Tivaware library and some additional settings in CCS. Note that you can use Tivaware to develop for stellaris (LM4F devices) and there is no need to install stellarisware:

Download Tivaware from TI:

Tivaware download page

If for some reason you prefer stellarisware (for example, developing for LM3S devices):


Tivaware is provided as an EXE file, but is actually a self extracting ZIP. Unzip to a subdirectory of your CCS6.0 install path:

cd ~/ti
mkdir tivaware
cd tivaware
unzip ~/Downloads/SW-TM4C-2.1.0.12573.exe


(the actual filename may vary)

There are several ways to include tivaware in your projects. In order to minimize required settings on each project, create a vars.ini file in your workspace. Remember this is /home/user/tidev in our example:

cd ~/tidev
vi vars.ini


(obviously, use your favorite editor instead of vi to create this file)

A single line is needed:

TIVAWARE_INSTALL=/home/user/ti/tivaware

 

Configuring Your Project for Tivaware

The vars.ini file creates an environment variable for the /home/user/tidev workspace (where the file is saved). To configure your project to use tivaware successfully:

  • Import the vars.ini file as source for CCS Build variables
  • Add an "include files" path to the compiler using the TIVAWARE_INSTALL variable
  • Add the driverlib.lib file to the project.

Go ahead and create a new project (File => New => CCS Project). Use the following screenshot as a guide:




When finished, select File => Import => Code Composer Studio => Build Variables:


Select the vars.ini file previously created:




Next, right click on your project name in the project explorer. Select properties, ARM Compiler, Include Options and add the following directory path:



Finally, add (actually, link) driverlib.lib to your project. Right click on your project name in the project explorer and select add files:




The full path for driverlib.lib as shown: /usr/ti/tivaware/driverlib/ccs/Debug. On the next dialog, select link to file:


We are done! Here is our BlinkTheLed project (from the Tiva Workshop workbook), successfully built:

 
Since the drivers for the in-circuit debug interface are installed as well, you can actually connect your launchpad and run a debug session on the device.
And now you can continue running your development environment on your lean and mean Linux machine. Happy coding!