Search Microcontrollers

Saturday, July 28, 2012

MSP430G2 - (USCI) SPI interface 1

I have been testing the UART on the MSP430G2553 (using the launchpad) not long ago.
I managed to build a very simple RS485 interface and test it.
Links to that part here :
http://fortytwoandnow.blogspot.ch/2012/06/msp430g2-serial-communication-1.html
http://fortytwoandnow.blogspot.ch/2012/06/msp430g2-serial-communication-2-rs485.html

Today I am dealing with a SPI device, in my case a MCP4131 digital potentiometer.
If you don't know what SPI is, or you want to dig a bit more into it, I suggest you read here :[wikipedia].

A digital pot is quite a simple device which receives commands on the serial bus (SPI in this case, it's pretty common) and switches a resistor network emulating the wiper of a potentiometer.
It is an handy device used in i.e. hifi equipment to digitally set the volume.

The device I use is from Microchip, it's the quite popular MCP4131 -103



Anyhow, today I will focus on the lancuhpad part, I am not really checking if the values are set correctly on the pot, that will be a task for later.

The MSP430G2 microcontrollers have two peripherals to handle the hardware serial communications : the USI and the USCI.
Depending on which exact device you are using, you may have one or the other.
"High end" devices such as the G2553 will have USCI.

A list of devices with details on which is supporting USCI and which USI can be found here (TI website).

The basic difference is that USCI will support hardware TTL UART on top of I2C and SPI.
Since USCI and USI use different registers (they are actually significantly different implementations of hardware serial interfaces), this post will not be helpful if your device needs to be programmed using USI.

The first thing to find out is where to connect the MISO, MOSI and SCK lines on the microcontroller.


The device specific datasheet reports the various pins with the functionality they support.
If you followed my previous posts (or any other instruction material on these MCUs) you probably know that each pin can be configured to provide different functions.
In this case we find that the pin P1.4 also supports the hardware serial port A0 (UCA0) clock (CLK) signal.
Normally we need to specifically set the "direction" of each pin we select, however in this case the datasheets notifies us that the USCI interface will manage that.
This is because the USCI can be configured as SPI master (this will be our case) or SPI slave and in the first case it will OUTPUT a clock signal, while in the second one it will RECEIVE a signal from the master (the pin direction is different in the two cases)

We also notice that the UCA0CLK is "mode 3", so it is selected setting high the bit 4 in both the P1SEL and P2SEL registers.


In a partially failed attempt to confuse me, TI called the MISO (Master In Slave Out) "SOMI" and the MOSI (Master Out Slave In) "SIMO".
Anyhow we can find them at pin P1.1 and P1.2, still mdoe 3 and direction automatically set by USCI.

The SPI bus also needs a CS (Chip select) which is normally generated via a normal GPIO port.
This is needed when you have many devices connected on the same SPI bus (SPI supports multiple slaves), normally you want to communicate to each one of them individually, so a different CS line will be used to enable only one at a time.
In this experiment we only have 1 device, so we do not need to dynamically "select" it.

Let's get started with some code.
First we need to set up the cpu clock, I will go "full throttle" at 16MHz (just because we can, don't think it's needed nor smart for this specific application).
I plan to use SMCLK to generate the clock for the serial interface and a quick look to the MCP4131 tells me it won't work at 16MHz as it is rated for 10MHz maximum.
4MHz sounds reasonable, so SMCLK will be MCLK / 4.

If you don't know how to operate the MSP430G2 clock (and you want to know more about it), you can check here.

/*
 * main.c
 */


#include <msp430g2553.h>

unsigned char potLevel;


void clockConfig()
{
 // configure the CPU clock (MCLK)
 // to run from DCO @ 16MHz and SMCLK = DCO / 4
 BCSCTL1 = CALBC1_16MHZ; // Set DCO
 DCOCTL = CALDCO_16MHZ;
 BCSCTL2= DIVS_2 + DIVM_0; // divider=4 for SMCLK and 1 for MCLK
}

The second thing will be to set mode 3 for pins 1,2 and 4

void pinConfig()
{
 // set the pin mode 3 for pins 1  2 and 4 of port 1 (USCI mode)
 P1SEL = BIT1 + BIT2 + BIT4; // low bit = 1 for pin 1 and 2 4. BIT 3 is 0 (CS via GPIO)
 P1SEL2 = BIT1 + BIT2 + BIT4; // high bit = 1 for pin 1 and 2 4 BIT 3 is 0 (CS via GPIO)

 P1DIR |= BIT3; // p1.3 set to output to drive CS
 P1OUT &= ~BIT3; // pull p1.3 to low - CS low
}


I also decided to use pin 1.3 to drive the CS signal if needed.
Finally we have the most interesting part : configure USCI to work as a SPI Master.
Turns out it's pretty easy to achieve this, we will just need to :
  1. set the Control Register 0 for port UCA0 to be master, mode 0 and synchronous
  2. Select in the CR 1 the clock source to be SMCLK (UCSSEL_2) 
  3. Set the Baud Rate registers for any additional divider we may need
  4. Disable any modulation 
  5. Initialize the USCI 
// USCI
void spiConfig()
{
 UCA0CTL0 |= UCCKPL+ UCMST + UCMODE_0 + UCSYNC; 
  // synchronous (=SPI) master 3 wire SPI, clock polarity High
/*SPI mode is selected when the UCSYNC bit is set and SPI
mode (3-pin or 4-pin) is selected with the UCMODEx bits.*/

 //use SCLK : 4MHz (MCP4131 supports up to 10MHz write via SPI)
 UCA0CTL1 |= UCSSEL_2;
 // set baud rate = SMCLK, no further division
 UCA0BR0 = 0;
 UCA0BR1 = 0;
 UCA0MCTL = 0; // No modulation
 UCA0CTL1 &= ~UCSWRST; // **Initialize USCI **
}  
Clock polarity can be set "high" or "low" using the UCCKPL bit in CR 0, to better understand what that means I suggest you check the video embedded below.

Finally I add a simple procedure to send out the SPI command to the digital pot.
According to the MCP4131 datasheet, to move the wiper (7 bit resolution) of the pot, we need to send command 0 (1 byte) followed by 1 byte with the value of the wiper position (0-127).
I added a small delay between the two bytes as that makes it easier for me to read the signal on the oscilloscope, might need to increase, lower or remove that delay in normal operations.


// drives a MCP4131 digital potentiometer via SPI
void setPotValue(unsigned char dataOut)
{
while (!(IFG2 & UCA0TXIFG)); // wait for TX buffer ready
UCA0TXBUF = 0;  // Send command 0
__delay_cycles(50);
while (!(IFG2 & UCA0TXIFG)); // wait for TX buffer ready
UCA0TXBUF = dataOut; // Send wiper level
__delay_cycles(50);
}

and finally a main procedure that puts everything together.


void main(void)
{
// setup
 WDTCTL = WDTPW + WDTHOLD;
 clockConfig();
 pinConfig();
 spiConfig();
    // program execution loop
 while (1)
 {
for (potLevel=0;potLevel<128;potLevel++)
  {
setPotValue(potLevel);
__delay_cycles(100000); // I know, there are better ways...
  }
for (potLevel=127;potLevel>0;potLevel--)
  {
setPotValue(potLevel);
__delay_cycles(100000);
  }
 }
}


Time to build and load into the launchpad.

I connected my digital oscilloscope (100MHz, dual channel) to the clock and to MOSI.
The first thing I wanted to check (after verifying that indeed some clock and some data are actually sent over the SPI bus) is the clock frequency.




Manually placing the measurement cursors at the end of the rising edge of the clock, I found 4.032MHz, which is pretty close to the 4MHz we expected (need to account for some manual error in the way I placed the cursors and some tolerance in the DCO frequency).

Then I checked that the value passed as wiper level was changing over time, this is better visualized in the video I recorded



Now that it seems data is flowing through the SPI bus, I need to check it is correct and see if the MCP4131 receives it correctly, by monitoring he value of it's resistance... and this will be the topic of a future post, probably :)










Thursday, July 26, 2012

Seriously?

No, I don't get it.
Is our economical system THIS fuzzy?

We know, since some months the situation in Europe is really critical, something went really wrong... first with Greece, than Italy, Spain.
We (the citizens) understood that those that were supposed to manage and watch over our economy failed dramatically, most of them piling up quite some richness by doing that.
Fine, we got that part I guess, one day we might even figure out how to use that information.

The result is that the Euro is losing ground which in the end might even be a good thing for the European economy, or at least for those countries that are in trouble, but that's another point.

Few minutes ago this news item popped out in most of the web news sites.




It basically says that Draghi, head of the European Central Bank, confirmed that the BCE will defend the Euro.
"We will do anything to save the euro, and it will be enough".

So, what's the plan chief?
"Anything" means just that : whatever it takes... so?
I kind of believed this was already decided since the BCE was constituted, did not seem anything new to me.

The part I don't get is this :


believe it or not, this was the (incredible) immediate reaction of the markets to Draghi's statement.
Seriously?
No bullshit : almost 1% recovered in few minutes after he said the most obvious thing. 
Still no plan in the air, but maybe these guys pulling the levers of this crisis have some more news that we don't.

Or it is just a kind of game where currencies go up and down depending on how good the communication department of the central banks is and we have to accept a "few" casualties in this process.
And the worst part in it is that those people moving billions they do not actually own can be tricked by cheap advertisements like the dumbest of the consumers. 

I don't know how it works for you, but I don't have a good feeling about this.

Tuesday, July 24, 2012

Oscilloscope - Owon SDS7102 DSO

I just received my new toy : a Digital Storage Oscilloscope

I am not an expert in oscilloscopes, I know how to use them for the basic functions (which is what I need), I never owned one  until today even if I used a few in some labs.
I bought an Owon 100MHz double channel 1G/s, the SDS7102, after comparing a few models.



I cannot provide an in-depth review here because I received it about two hours ago (will record a quick review video soon for this), instead I want to talk a bit about the user interface.
I am extremely happy with the user interface of this toy, that's the main reason I chose it.

The key spec that made me chose this model is it's screen.
That might sound silly to you, but you probably can understand better my choice if I tell you that my eyes have serious troubles.
A big, highly readable screen is for me the difference between being able or not to use an instrument.

The SDS7102 features a 8" TFT screen 800x600  while most of its competitors (in the same price-range) feature a 5.7" 320x400 or 7" widescreen with a slightly higher resolution (still lower than 800x600).

Unfortunately my eyes are doomed to get worse and worse in the next years, at a point where even a 8" screen might prove to be "small".
And this is where this DSO helps me out a lot : it has a (S)VGA output, I can connect it to a 37" TV set!
How cool is that?!
I did not see any other scope (but they might exist even in this price-range) with this feature.

I have been reading, before my purchase, some reviews from experienced users, comparing this model mainly to Atten or Rigol scopes.
There seems to be a consensus on the fact that regarding the screen there is no match : the Owon wins.

About the firmware and especially how it handles the user interface, some were not really happy with the Owon.
I cannot argue as they are way more experienced than myself, plus I never used a Rigol or Atten, I can only say that, despite being a total noob, I immediately figured out how to work with the two channels, how to do measurements, zoom, pan, operate the trigger, activate the FFT mode, enable the external VGA etc... took me about 5 minutes without reading the manual (still sealed :) ).

I can agree that the look and feel of the graphical interface may not look really "elegant", but it  feels really snappy with no fancy "slow transitions".
That actually works a treat for me : there is a lot of space on the screen and each item has its proper space around.

"Elegant" interfaces use "smoother" colors and typically pack a lot of information in small spaces.
This one really reminds the good old CGA colors (although it is not THAT ugly:) ) , if you are old enough to remember that technology, you probably remember the cyan/magenta "bird sized" pixels.
I hate elegant interfaces for that exact reason : too many colors and poor spacing mess up with my eyes a lot.
High contrasting colors make it easier to take precise measurements I believe, on that I think the Owon is a real winner.
On the 37" TV set it is amazing, probably an overkill, but still does not pixelate too much thanks to the 800x600 resolution.
Plus, I guess nobody can get geekier than hooking the DSO to the stereo output in the living room and outputting the two channels on the TV, maybe in a PIP rectangle :)

Anyhow, a few general specs can be found here : http://www.owon.com.cn/eng/smartDS.asp

Will probably post a video in the next days.

update : you can see it in action here :


Tuesday, July 10, 2012

MOSFETs


Recently I needed to better understand MOSFTETs so I have been experimenting a little.

MOSFET (Metal Oxyde Semiconductor Field Effect Transistors) are extremely interesting devices and in the end quite simple to understand.
They are transistors, but work slightly in a different way from traditional transistors, plus they can drive easily significative currents and voltages.
Basically they are used to control electronically the current flow from the SOURCE to the DRAIN by generating a "channel" between them.
This channel is created by attracting electrical charges (electrons or "holes", depending on the type of MOSFET) via a metallic plate connected to the GATE.

This metallic plate is insulated and works similarly to a capacitor plate, storing charges that polarize the near region in the semiconductor substrate, which generates a "conenction" between source and drain, allowing electrons to flow.

Finally it works like a valve that we can open by supplying charges to the gate o close by discharging it.
The interesting part is that a rather small amount of charges are needed to operate the gate, so, while we can easily have on a  rather small device a 20Amps current with 100V potential between Source and Drain, we can simply operate the gate with a couple of volts between source and gate.

There is not much energy depletion in charging the gate, because once charges are provided, they tend to stay there, untill we remove them.

There are two types of MOSFETS, depending of the semicoductor substrate used, they are called P-Channel and N-Channel Mosfets.

The two symbols represent a P-Channel device (top) and a N-Channel One (bottom)

Source and drain are connected to semiconductor regions of the same kind (P/N) and of the opposite type of the substrate between them.


In the picture above, a N-Channel device is represented.
In this kind of device the gate is charged positively to recall electrons in the upper part of the P semiconductor substrate, generating a thin channel with negative charges (N) that connects Source and drain.

On a P channel device the gate would be charged negatively and this would "push away" electrons from the upper part of the N Substrate, creating a positive channel between S and D (which would also be  connected to P type regions).

I have seen some papers on this subject stating that on a P-Channel you will connect the Drain to the ground and Source to Vdd and then in order to open the channel the Gate needs to be pulled to ground.
Others would instead keep the same connections as for N-Channel ones and assume the Vgs is negative.
It is technically the exact same thing and I do prefer the second approach as it is easier for me to understand and remember.
Once you understand that he gate needs to be charged negatively for P channel ones and positively for N channel ones, you should be all set.

While theory is cool, I tend to understand better with a little practice, plus it's much more fun, so I got myself a couple of P-channel mosftes from ebay (IRF9540) for less than one dollar each, shipment included all the way from Mighty China to Europe.

Hey, what's better than something that costs less than a coffee and even makes me less nervous than caffeine?
This is my little experiment and -incredibly- practice confirmed the theory.
Something I did not expect was that the gate tends to stay charged for quite some time, good to know.
This means that if you need it to go off quickly you definitely need a pull-down resistor between Gate and Source.



Notice in the video I also state that I would use a negative voltage from Source to Drain (not only to charge the Gate).
Technically, in a MOSFET, once the channel is open, is open in both directions, so we could have electrons flowing in either way (with positive or negative currents from S to D).
However these devices normally have an internal diode between Source and Drain, therefore they can stop the current in one single direction, in the other one they will always conduct.



So, cool tiny devices, now what?
Since we can drive these devices with small currents and small voltages, they can quite easily be interfaced with digital outputs of microcontrollers.
Moreover the gate can be charged and discharged extremely quickly allowing the implementation of PWM techniques to control electric motors, switching power supplies, inverters etc.
And that's my target, I need a step down "buck" converter driven by a microcontroller, these circuits are  commonly used in battery chargers and other power devices.

I might tell a bit more about that after some experiments.
Do you like physics, electronics and technology? Get yourself a couple of mosftes, you can have a lot of fun with them!

Note : while these devices can handle high voltages and amps between source and drain (check the datasheet of each specific device you plan to use for that), they normally tolerate much lower voltages on the gate (usually <12V, again check the datasheet. Apply more than that and they can go "KABOOOM").