Κυριακή 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!

Σάββατο 4 Απριλίου 2015

Intel Galileo: Linux, SSH, Static Addresses and Other Tips

I've recently acquired an Intel Galileo Gen 2 development board. Intel Galileo (just in case you haven't heard about it) is Intel's answer to the Arduino driven hobbyist community. In fact, Galileo is (or supposed to be) pin compatible with Arduino Uno: you can even use Uno shields on it. Galileo is programmed using the same IDE as the Arduino (albeit patched by Intel) and the sketches - once recompiled - are (supposedly) compatible: You can just move your LCD display circuit from your Uno to your Galileo, recompile and upload the program and it should work. Well, for the most part that is...



So why buy a Galileo instead of (or in addition to) a standard Uno or other AVR based Arduino? The Galileo is using an Intel SoC (System on-a Chip) running at no less than 400MHz. It is equivalent in power to some older Pentium CPU. There is more to it: There is 256MB of RAM on board, a micro-SD card slot, an Ethernet port and even a micro PCI-Express underneath for your WiFi card. Galileo is admittedly over-specified for an Arduino. And with good reason: Even without any SD inserted, Galileo runs a small Linux version inside it. You will notice it as it takes some good time to start and appear on the USB connection. And there is an even more complete Linux version available as an SD card image. Linux and Ethernet easily make this device an IoT (Internet of Things) development board.

How would you access the Linux part of Galileo? Let's examine two scenarios:
  1. Access the built-in Linux. This is what runs on the Galileo if you don't insert any SD card.
  2. Access the SD card Linux (Download it from here, along with any other utilities you need).

Accessing the Built-in Linux via Telnet

If you look at most of the Galileo tutorials you will find more than a few ways to access the Linux part of your Galileo:

  • Use a serial cable and a (custom made) connector for the serial out pins (gen 2) or 3.5mm jack (gen 1). This is easy to do but most PCs lack proper RS-232 these days and I find USB to serial as a last resort scenario.
  • Run a sketch to reconfigure the USB port as a serial terminal and use that for connecting. There are a couple of problems with this approach: although it will supposedly work on the built-in Linux, it stops accepting input after you connect through i.e. PuTTy. You will get a login prompt and a shell but that's about it. It won't execute any commands. It works a little better with the SD card version of Linux but there is another serious drawback: the sketch permanently reconfigures the USB port for serial connection and you lose the ability to upload sketches.
What if you really want to have both Linux *and* your sketches running at the same time?

It turns out that the built-in Linux does not have an ssh daemon, so we will have to use telnet. No big deal. And instead of going the serial route, let's try that nice Ethernet port. Ethernet is a lot more common these days: just plug your Galileo into your home switch then upload a sketch that looks like the following:

void setup() {
  system("ifconfig eth0 inet 192.168.0.10 netmask 255.255.255.0 up");
  system("telnetd");
}

void loop() {
}

Obviously, you will have to change 192.168.0.10 to an address that matches your home setup. If you are using DHCP (very common on home routers) just make sure you assign it a static address outside the scope of the DHCP server (I assume that as a good admin you've kept a couple of addresses from being automatically assigned, haven't you?)

You are now ready to telnet into your device! Use PuTTy from Windows or the command line telnet client from another Linux box. This is what you will get:



Login as 'root'. There is no password set.
Now that you are in, there is no need for the script to keep executing. Use the top command:

# top


Find the process id for /sketch/sketch.elf and just kill it (it usually is at the top of the list):

# kill 929

Or you could simply upload another sketch to execute. Unlike the USB serial approach, your upload ability is not affected in any way.

Play with the built-in Linux as long as you like: you will soon find out it is pretty limited in what it can do. And the moment you unplug your Galileo all the settings are lost: your sketches are erased and the nice static IP you've assigned is gone. You will have to rerun the above sketch after every reboot.

Sooner or later (probably sooner!) you will decide to migrate to the SD card version of Linux.

Accessing SD Card Linux via SSH and making settings permanent

So you've created an SD card image of Yocto Linux using Intel's instructions. And now you want to SSH into it.
  • First, be patient. The SD card Linux may take more time to boot than the built-in version. You will know it has booted successfully when the USB connects to your PC (if you use Windows, it will make a sound)
  • The SD card Linux provides an SSH service. Even better, you can make your IP address (and other settings) permanent.
  • You will have to consider security if you leave your Galileo running and connected to the Internet.
As you can imagine, the script to get SSH access is even easier than before:

void setup() {
  system("ifconfig eth0 inet 192.168.0.10 netmask 255.255.255.0 up");
}

void loop() {
}


The SSH server is already running on SD card Linux, no need to restart it. Just assign your static IP and you are good to go! You can now login and make your settings permanent.

Use top and kill (like we did before) to stop the sketch from running. It is no longer necessary.  You may as well remove it so it won't run at next boot. We will make the configuration changes permanent anyway:

# rm /sketch/sketch.elf

The first thing you will want to do is assign a root password:

# passwd
Changing password for root
Enter the new password (minimum of 5, maximum of 8 characters)
Please use a combination of upper and lower case letters and numbers.
New password:
Re-enter new password:
passwd: password changed.

Change the /etc/network/interfaces file to assign your static IP address permanently. (It seems the only available editor is vi...) Find the following line:

iface eth0 inet dhcp

and change it to:

iface eth0 inet static
   address 192.168.0.10
   netmask 255.255.255.0
   gateway 192.168.0.250

The gateway part is only needed if you intend to give Galileo Internet access. You will also need to reconfigure /etc/resolv.conf for this (we will do it after a few more steps). The address on the gateway part is of course your home router's IP.

The above setting is not enough though: Galileo uses the Network Connections Manager (conman) to configure the network interfaces and the above file is ignored in this case. We will have to revert to the older method:

# cd /etc/rc5.d
# rm S05conman
# ln -s ../init.d/networking S05networking

Now reboot your Galileo:

# shutdown -r now

When it comes up again, just connect via SSH. No need to rerun the sketch as the changes to the files are permanent.

If you wish to connect your Galileo to the Internet, add this line to /etc/resolv.conf:

nameserver 192.168.0.250

Where 192.168.0.250 should actually be your router address. Or another available DNS server (if in doubt, use Google's DNS: 8.8.8.8).  For this to work, you must also have a valid gateway line in /etc/network/interfaces.
While still logged in as root, you may wish to change the weird 'clanton' hostname to something more cool. Just edit the /etc/hostname file and replace the contents with the name of your choice. Hostname will change on the next reboot.
If you wish to have a message of the day (motd) appearing at every login, create an /etc/motd file with your desired contents.

Securing your Galileo Linux

At a minimum, you will want to take a few security measures if you decide to connect your Galileo to the Internet:
  • Give the root user a password. We've already done that.
  • Disallow root logins via SSH.
  • Create a standard user account for 'normal' use.
Creating a standard user acoount is easy:
# useradd -g root johndoe

(Johndoe is actually not a good choice for a username, but you get the idea!). It is best to make your user a member of the root group. The permissions on some devices (like /dev/null) are read-write for the root user and group only and will hinder your ability to use some commands like scp unless your account belongs to the root group. Give your new user a password:

# passwd johndoe
Changing password for johndoe
Enter the new password (minimum of 5, maximum of 8 characters) Please use a combination of upper and lower case letters and numbers.
New password:
Re-enter new password:
passwd: password changed.

This is a good time to check whether the new account works. Just open a new SSH connection and try to use the new user instead of root to connect. If it all works, continue by disabling the root login via SSH:
Edit /etc/ssh/sshd_config. Find the line that shows

PermitRootLogin yes

And change yes to no:

PermitRootLogin no

Or, alternatively, just comment out the entire line. The default setting for SSH is to not allow root logins.
Just reboot your Galileo and you are good to go:

# shutdown -r now

From now on, you will use your new user account to connect via ssh. You can always use:
$ su -

to switch to root when needed.
Sudo would have been a nice addition to this Linux version, but it is not available by default and I haven't researched package management yet!
You could create some fancy bash startup files for your account. You may also use my version (a slightly simplified version of what I use on my FreeBSD machines). Just login as the user you created and:

$ wget http://www.freebsdworld.gr/files/galileo-dot.tar.gz
$ tar xvzf galileo-dot.tar.gz

You may need to press 'A' to overwrite an existing file. Logout and login again to apply the changes.

Getting an LCD Screen to Work with Galileo

LCD screens are very popular with Arduino 'users' as they add a whole new dimension to projects. The 16 character, 2 line variant seems to be the most common and it is the one I currently have.
Since Galileo is Arduino Uno compatible, all you would have to do is move your LCD circuit from your Uno to Galileo (to the same GPIO pins), recompile your program for Intel and upload it. Well, supposedly.
Because I followed these exact steps and got just a blank LCD staring at me. Apparently you need to update the LCD Driver libraries with the ones found here.
After unzipping the file, replace all the contents of the libraries/LiquidCrystal folder (in your Arduino installation folder) with the contents of the archive.

Rebuild and upload your project - your screen should now be working!


Happy coding!