Embedded Systems and Power Electronics

Total Pageviews

About Me

My photo
I am currently a PhD student at UC Berkeley, following a 6-year journey working at Apple after my undergrad years at Cornell University. I grew up in Dhaka, Bangladesh where my interest in electronics was cultivated, resulting in the creation of this blog.

BTemplates.com

Powered by Blogger.

Showing posts with label XC32. Show all posts
Showing posts with label XC32. Show all posts

Oct 30, 2014

Interfacing a color TFT display with the PIC32MX250F128B


I have been working on interfacing the PIC32MX250F128B with a small 2.2" TFT display from Adafruit. It's a nice little display that is fairly easy to communicate with, using SPI communication. The display I'm using is: http://www.adafruit.com/product/1480

Adafruit provides nice open-source libraries for their products. However, they are for Arduino and thus cannot be directly reused for the PIC32. I went through the library and ported it over for the PIC32, in C. I have attached my project file as a .zip file and you can download it to go through the library header and source files, as well as the demo code. I've tried heavily commenting the code so that it is self-explanatory.

As far as hardware goes, with the demo code, the pin connections for the display are:

BL (backlight): I left it unconnected, but you can connect it to 3.3V for backlight.
SCK: connected to RB14 on the PIC
MISO: left unconnected, since I'm not reading anything from the screen
MOSI: connected to RB11 on the PIC
CS: connected to RB1 on the PIC
SDCS: left unconnected as I'm not using the microSD card for this
RST: connected to RB2 on the PIC
D/C: connected to RB0 on the PIC
VIN: connected to 3.3V supply
GND: connected to gnd

The pins I used are defined in the code and you can easily change them as required.

I used my custom proto-board for testing on a breadboard. You can find details here: http://tahmidmc.blogspot.com/2014/02/pic32-proto-board-details-schematic-pcb.html


Here's a video showing the PIC32 running the demo code and doing some simple graphics on the screen. You can see that it runs fairly quickly and quite smoothly.


Project files with all source and header files:
https://drive.google.com/file/d/0B4SoPFPRNziHdksweU1vUkZ4SHM/view?usp=sharing
http://www.4shared.com/zip/O-LcEU0Ace/Adafruit_TFTX.html

If you have any comments, questions or suggestions, do let me know!

Oct 11, 2014

PIC32 SPI: Using the MCP4822 12-bit serial dual DAC


I recently got a few pieces of the MCP4822 DAC. You can check out the datasheet here: http://ww1.microchip.com/downloads/en/DeviceDoc/22249A.pdf

I found them to be neat little devices. In a small 8-pin PDIP package, the MCP4822 comes with 2 12-bit DACs, which you can easily configure over SPI. This was a great opportunity to get a simple PIC32 SPI application going. I worked on this today to see how fast I can get the DAC output going.

Here's the pinout of the MCP4822:
Fig. 1 - MCP4822 pinout (taken from datasheet)

The MCP4822 can be supplied a voltage in the range of 2.7V to 5.5V. Since I use 3.3V for my PIC32, I used the same 3.3V supply for the VDD for the MCP4822. Pin 5 is the active low signal LDAC that is used to synchronize the two DAC channels. When this pin is brought low, the data in the DAC's input register is copied to the output and both outputs are updated at the same time. I just had this tied to ground. VoutA and VoutB are the two output pins. The other pins are the regular pins for SPI communication - CS (active low) chip select, SCK serial clk, SDI serial data in.

The datasheet provides a nice diagram explaining the timing and pin functions very nicely:
Fig. 2 - Write command for MCP4822 (taken from datasheet)

The write command to the MCP4822 is a 16-bit wide command sent over SPI. Bit 15 (A/B) selects which channel you're sending data to: 1 signifies channel B, 0 signifies channel A. Bit 13 (GA) selects the gain. The MCP4822 has an internal 2.048V reference it uses for the DAC. So, that means that with a gain of 1, the maximum possible output voltage is 2.04975V (4095/4096 * Vref). If a higher output is required, the gain can be increased. The MCP4822 has a configurable gain of 1 or 2. When GA = 1, gain = 1; when GA = 0, gain = 2. Bit 12 SHDN is the shutdown signal. When SHDN is low, the output of the DAC is shut down. The 12 data bits from there on: D11 to D0 ([D11:D0], [bit11:bit0]) are the 12 data bits for the digital to analog conversion.

The transfer function is the very-simple, (almost) typical-for-DACs:
Vout = (D_12 / 4096) * 2.048V * Gain
D_12 is the digital value given by D11 to D0 in the write command, 4096 = 2^12 (12-bit resolution), 2.048V = internal voltage reference, gain = 1 or 2 depending on bit GA in write command.

While I typically use the registers and configure them manually, I decided to use the Microchip plib (peripheral library) here for the SPI module. The peripheral library consists of a lot of low-level functions and macros that essentially require understanding the peripheral but just make the code nicer and easier to read.

I decided to clock the MCP4822 at 20MHz (max for MCP4822) to get quick data transfers.

The SPI module can be initialized using one of 2 options:
1) Using the OpenSPIx(config1, config2) and SpiChnSetBrg(spi_channel, spi_brg) functions
2) Using the SpiChnOpen(spi_channel, config, spi_divider) function

These are both described in the plib documentation.

The DAC initialization routine I wrote is shown below:
//================================================================
// SS = PORTA4
#define SS      LATAbits.LATA4
#define dirSS   TRISAbits.TRISA4
void initDAC(void){
/* Steps:
 *    1. Setup SS as digital output.
 *    2. Map SDO to physical pin.
 *    3. Configure SPI control and clock with either of a or b:
 *        a. OpenSPIx(config1, config2) and SpiChnSetBrg(spi_channel, spi_brg)
 *        b. SpiChnOpen(spi_channel, config, spi_divider)
 */

    dirSS = 0;                    // make SS an output
    SS = 1;                        // set SS = 1 to deselect slave
    PPSOutput(2, RPB5, SDO2);    // map SDO2 to RB5

///////
#define config1 SPI_MODE16_ON | SPI_CKE_ON | MASTER_ENABLE_ON
    /*    FRAME_ENABLE_OFF
     *    ENABLE_SDO_PIN        -> SPI Output pin enabled
     *    SPI_MODE16_ON        -> 16-bit SPI mode
     *    SPI_SMP_OFF            -> Sample at middle of data output time
     *    SPI_CKE_ON            -> Output data changes on transition from active clock
     *                            to idle clock state
     *    SLAVE_ENABLE_OFF    -> Manual SW control of SS
     *    MASTER_ENABLE_ON    -> Master mode enable
     */
#define config2 SPI_ENABLE
    /*    SPI_ENABLE    -> Enable SPI module
     */
//    OpenSPI2(config1, config2);
    // see pg 193 in plib reference

#define spi_channel    2
    // Use channel 2 since channel 1 is used by TFT display

#define spi_brg    0
    // Divider = 2 * (spi_brg + 1)
    // Divide by 2 to get SPI clock of FPBDIV/2 -> max SPI clock

//    SpiChnSetBrg(spi_channel, spi_brg);
    // see pg 203 in plib reference

//////

//////

#define spi_divider 2
/* Unlike OpenSPIx(), config for SpiChnOpen describes the non-default
 * settings. eg for OpenSPI2(), use SPI_SMP_OFF (default) to sample
 * at the middle of the data output, use SPI_SMP_ON to sample at end. For
 * SpiChnOpen, using SPICON_SMP as a parameter will use the non-default
 * SPI_SMP_ON setting.
 */
#define config SPI_OPEN_MSTEN | SPI_OPEN_MODE16 | SPI_OPEN_DISSDI | SPI_OPEN_CKE_REV
    /*    SPI_OPEN_MSTEN        -> Master mode enable
     *    SPI_OPEN_MODE16        -> 16-bit SPI mode
     *    SPI_OPEN_DISSDI        -> Disable SDI pin since PIC32 to DAC is a
     *                            master-to-slave    only communication
     *    SPI_OPEN_CKE_REV    -> Output data changes on transition from active
     *                            clock to idle clock state
     */
//    SpiChnOpen(spi_channel, config, spi_divider);
//////
}
//================================================================

The code block above has code written using both the initialization functions (one is commented out). Essentially, the configuration is that SPI channel 2 is enabled as a master, it is configured for 16-bit data transmission, the SDI pin is disabled, it is configured for serial output change from active high (1) to active low (0) as required by the MCP4822 (see Fig. 2) and the clock divisor is set to 2 so that SPI clock = 20MHz.

The SCK pins for the PIC32 are mapped physically to the RB15 (SCK2) and RB14 (SCK1) pins (check pinout on page 4 in datasheet). The SDO and SDI pins are remappable pins and thus require you to map them to physical pins. The SDI pin here is unused since the PIC32-to-MCP4822 is a one way communication with the PIC32 as the master and the MCP4822 as the slave.

The datasheet provides the table for all the PPS (peripheral pin select) mappings. The relevant section for the SDO is:
Table 1 - PPS configuration for SDO

I decided to use RPB5:

PPSOutput(2, RPB5, SDO2);    // map SDO2 to RB5

The connections I used for the MCP4822 are:


Fig. 3 - MCP4822 connections


The chip select / slave select line (CS as shown on the MCP4822 pinout, see Fig. 1) has to be controlled manually. (For a hardware-based processor-free control scheme, see PIC32 DMA+SPI+DAC : Analog output synthesis with zero CPU overhead.) This is an active low chip select signal. When data is being sent to the MCP4822, while the SPI transaction is occurring, the CS pin must be kept low. Initially I checked to see if there was a way the hardware would take care of that. I looked into the framed SPI mode. However, this did not serve my purpose. From what I've read, the framed SPI mode is an SPI mode where the clock is always output (instead of only during transactions as traditionally done). However, the hardware generates a low sync signal (by pulling CS low) before the data is transmitted from the PIC32. The problem here was that the CS pin was pulled low and kept low for one SPI clock period before raising CS high as data is transmitted out from SDO. This isn't going to work for the MCP4822 since the chip requires that CS be held low during the entirety of data transmission (see Fig. 2). So I just decided to use RA4 as the pin for CS. Before starting any transmission, I pull CS low in software and raise it high at the end.

Here's the code for writing to the DAC:

inline void writeDAC(uint16_t data){
    SS = 0; // select slave device: MCP4822 DAC
    while (TxBufFullSPI2()); // ensure buffer is free before writing
    WriteSPI2(data);   // send the data through SPI
    while (SPI2STATbits.SPIBUSY); // blocking wait for end of transaction
    SS = 1; // deselect slave device, transmission complete
}

Since I called this function from the ISR in my code, I decided to make it an inline function to eliminate function call overhead.

In my test code, I just wanted to see how fast an output I can get. So I clocked the MCP4822 at 20MHz and tried to maximize the frequency of the output signal I generate: I used channel A to generate a sine wave output and channel B to generate a triangle wave output. I used a timer (Timer 1) to control the timing and in the ISR, I just called the writeDAC inline function to generate outputs as required from two pre-generated tables.

Here are the different waveforms and outputs I generated:

Fig. 4 - Generating the outputs with timer period = 400kHz, sine table entries = 64



Fig. 5 - Generating the outputs with timer period = 550kHz, sine table entries = 32



Fig. 6 - Generating the outputs with timer period = 550kHz, sine table entries = 64



Fig. 7 - SPI clock and data transmission
You can clearly see the SPI clock during transmission here. From the measurement panel on the right you can see that the SPI clock is 20MHz. There are also 16 pulses you can count - since a write command to the DAC consists of 16 bit transfers. CH2, on the bottom, shows the data being transmitted. Since the first signal (leftmost) is a 1, and since this corresponds to bit 15, this is a snapshot of data being transmitted to DAC channel B.


Fig. 8 - DAC steps - zoomed in


Fig. 9 - DAC steps - zoomed out


Fig. 10 - Hardware test setup

For the PIC32 proto board, I used my own custom proto board: http://tahmidmc.blogspot.com/2014/02/pic32-proto-board-details-schematic-pcb.html


Here are the header and source files for my test program:

config.h: https://drive.google.com/open?id=0B4SoPFPRNziHdk5KT2hWNUNCckE
main.c: https://drive.google.com/open?id=0B4SoPFPRNziHWFc0Y01qSW5XUkE


While this was a quick test I did to test the PIC32 SPI and the MCP4822, this is in no means a complete evaluation of the MCP4822. For example, I updated the DAC more quickly than I should have, to push for speed, as this didn't give enough of a settling time. However, I was satisfied with the results and so, stuck with that. I will do some further testing on this later.

For more details of the PIC32MX250F128B SPI module, refer to the datasheet and reference manual. For more details on the MCP4822, refer to its datasheet.

If you have any questions, feel free to ask. Let me know what you think, in the comments section below!

Note: Updated September 10, 2015

Jun 23, 2014

PIC32MX250F128B ipl7: odd shadow register set behavior and observations


This issue has now been solved. Scroll to the bottom for the update.

I started working on a pure sine wave inverter based on the PIC32MX250F128B. The first stage was to just get the SPWM working and test that before proceeding to add the power stage, feedback and other control, etc.

This led me to some interesting observations regarding the PIC32MX250F128B interrupts, especially the use of the shadow register set and a related problem.

I set up Timer 2 to be the time base for sine wave generation (DDS/SPWM) using OC1. In the Timer 2 interrupt, the duty cycle update request is performed (OC1RS is updated). Timer 2 interrupt priority was set to 7.
This all worked fine. The initial ISR definition was:

void __ISR(_TIMER_2_VECTOR, ipl7) T2int(void) {
.....
}


However, when I used the ADC (input from potentiometer for amplitude control - a start at implementing feedback), accessing any of the ADC registers in the while (1) loop in main stopped the PIC32 from working. 

I then added a line of code in main to continuously toggle RA0 (PORTA bit 0). This would stop when trying to access the ADC registers as well. (It worked fine if I removed the code that accessed the ADC.) This meant that the core was being stopped. So, I thought that it might be some kind of exception being thrown (?).
However, changing the timer 2 interrupt priority from 7 (which I had initially) to anything else fixes the problem. My guess was that something went wrong when the shadow register set was being used for interrupt priority level 7 (?).

So I did some more tests and came up with this:

The way I have the ISR defined initially selects the "AUTO" mode of selection where, I believe, the compiler decides whether to use the shadow register set or software for context save/restore.
Forcing the compiler to use the software context save/restore instead of the shadow register set seems to fix it:

void __ISR(_TIMER_2_VECTOR, ipl7SOFT) T2int(void) {
.....
}


I forced the shadow register set just to confirm:

void __ISR(_TIMER_2_VECTOR, ipl7SRS) T2int(void) {
.....
}
and sure enough it didn't work.

So, since it worked with ipl6, my guess was that for ipl6 (and for any ipl except 7), the compiler chooses software for AUTO, whereas for ipl7, the compiler chooses SRS.

So, I forced the shadow register set on ipl6:

void __ISR(_TIMER_2_VECTOR, ipl6SRS) T2int(void) {
.....
}
and sure enough, it didn't work.

Forcing software for ipl6 fixes it (as does AUTO).

I looked through the errata of the chip and couldn't find anything. (The errata is an interesting read.)  I am also a little surprised since I did have ipl7 running fine previously. Maybe something weird happens with a certain combination of peripherals (?) that I unfortunately happened to use. I'll still see if I can find this documented, and I'll have to check whether an exception is thrown and if so, what type. If nothing else, at least it was a nice, albeit frustrating, lesson. Hopefully, it'll help someone else who might run into a similar problem.

UPDATE/SOLUTION: It turns out that the PIC32MX250F128B does not have a shadow register set, as mentioned in the datasheet. I seemed to have missed that while concentrating on the reference manual which talks about the shadow register set for the PIC32 series. Thus, from the point of view of my 'experiments', the lesson learnt could very well just be that when using ipl7, force the compiler to use software instead of the default AUTO mode (which may make the compiler try to use the shadow register set, which doesn't exist - explaining the problem I faced earlier).

---------------------------------------------------
DDS = direct digital synthesis
ipl = interrupt priority level
ISR = interrupt service routine 
SPWM = sinusoidal pulse width modulation
SRS = shadow register set

Feb 11, 2014

PIC32 Proto Board: Details, Schematic, PCB and Pictures




I previously showed you my PIC32 proto board I made on verroboard (http://tahmidmc.blogspot.com/2014/02/pic32-development-proto-board-on.html). To make the proto board “more of a product” and easy to reproduce, I was working to make the proto board on a PCB.

I used ExpressSCH to draw the schematic, and used ExpressPCB to design the PCB. Once designed, Professor Bruce Land got the PCB made from ExpressPCB themselves.

The PCB is just to be a basic board with the PIC32MX250F128B placed on it. The power supply connections are provided as are external oscillator connections (if needed). Additionally, there is a nice convenient power supply input connector (standard 2.5mm jack/plug). All the IO pins along with power (Vin and +3.3V) and ground are placed on a SIL connector at the edge of the board so that the board can be conveniently placed on a breadboard for experimenting and prototyping (see pictures below).

It's a nice little 2-layer PCB measuring only 3.1 inches by 1.8 inches. I chose to use all through-hole components to make soldering and construction easy for everyone. Now let's look at the schematic, PCB mechanical view and some pictures of the actual PCB itself.

Here is the schematic:
Fig. 1 - Schematic (Click on image to expand/zoom)

Here is a mechanical diagram of the PCB:

 Fig. 2 - Mechanical diagram of PIC32 proto board PCB

You can find the ExpressSCH and ExpressPCB schematic and PCB design files at the end of this article.

There are some key things to note here.

  • Use a ua78M33C or similar regulator for wide range voltage. Use an LDO voltage regulator if there is intention to power off of USB. Be careful about the LDO maximum input voltage rating. Currently, as it stands, the USB is not going to power the microcontroller (at least not reliably) due to the dropout voltage of the ua78M33C regulator. A regulator that can be used in its place so that the board can be powered either off of an external supply or the USB is the MIC2940A-3.3. Here’s the datasheet if you’re interested: http://www.micrel.com/_PDF/mic2940.pdf
  • I used the 0.4in spacing PDIP28 component in ExpressPCB. I used a socket that allowed for that. But you may want to change it to a 0.3in spacing PDIP 28 package. It’s fine and working now. But I will change it in a later revision.
  • C4 is VCAP. It is required for the stable operation of the PIC32MX250F128B. Use a low-ESR capacitor: defined by Microchip as having an ESR lower than 1
  • Mount X1, C6 and C7 onto the PCB only if there is a plan to use the external oscillator. Here the external oscillator is a standard crystal oscillator. If the internal oscillator is being used, don’t mount X1, C6 and C7 so that the associated IO pins can be used. Since the PIC32MX250F128B is only a 28-pin device, every single IO pin is valuable.
  • Variable resistor VR1 is used to supply a variable voltage output to the PIC32MX250F128B pin 26, which is RB15 which is also AN9. This is just to provide a variable voltage to the PIC32MX250F128B for testing with ADC. There is a switch/jumper between the wiper of the variable resistor and the PIC32MX250F128B RB15. When the switch is not closed or the jumper is not shorted, the wiper is disconnected from the PIC32MX250F128B so that RB15 can be used for other purposes, eg external input voltage sensing, use as digital IO, etc.
  • “Debug LED” is connected to RA0 (PORTA bit 0 --> pin 2) of the PIC32MX250F128B.


Here are some pictures of my PCB:

Fig. 3 - PCB just being mounted with components


  Fig. 4 - PCB reverse side


 Fig. 5 - PCB top view (ignore the glare)



Fig. 6 - PCB placed onto breadboard


 Fig. 7 - PCB placed onto breadboard - front view



 Fig. 8 - PCB placed on table - you can see the IO pins



Fig. 9 - PICKIT3 connected to PCB


Here are links to the .sch ExpressSCH schematic file:
https://drive.google.com/file/d/0B4SoPFPRNziHU3pKMFFWSEdWOGs/edit?usp=sharing

You need the ExpressPCB software package to view and edit the .sch and .pcb files. You can get it from here: http://www.expresspcb.com/ExpressPCBHtm/Download.htm

Let me know what you think and I’d love to see what you do with this board. I’ve done quite a few projects with my verroboard proto board and I'll be doing a series of small projects with this board. I’ll post them here from time to time.