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 am a 2025 Paul & Daisy Soros fellow. 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 PIC32MX. Show all posts
Showing posts with label PIC32MX. Show all posts

Aug 2, 2015

PIC32 Tic-Tac-Toe: Demonstration of using touch-screen, TFT and the Protothreads threading library






I had previously used the Adafruit TFT display using my library (ported from the Adafruit Arduino library). I decided to optimize the library to improve drawing speed. The same display I use comes with a 4-wire resistive touch-screen as well. I decided to write a simple library for the touch-screen and give Protothreads a try. To incorporate all this, I thought it would be cool if I used these to make a simple game. Tic-tac-toe came to mind as a fun little demo.


I'm sure everyone's familiar with the game so I won't explain the rules there. The touch-screen is simply two resistive sheets placed on top of each other on top of the TFT screen. When it is pressed down at a given place, the two sheets make contact and a voltage divider is formed. Using the IO's and the ADC, this voltage is read in the X and Y directions to register a touch.

Here is a very good pictorial depiction of the resistive touch screen (taken from the Atmel AVR341 document):

So in order to read the touch, the X+ and X- points are applied power, and one of Y+ or Y- is read to read the x-coordinate. Then Y+ and Y- are applied power and one of X+ or X- is read to read the y-coordinate. X+, X-, Y+ and Y- are connected to four GPIO pins on the PIC32 that are configured to outputs when driving the touch-screen and analog inputs when reading. Every time the IO pin switches state, a long delay is provided to allow the outputs to stabilize. Alternately, the ADC is significantly slowed down to negate effects of capacitive charging by high source impedance. The library is written in the form of a simple state machine cycling through its states every few milliseconds, decided by the application calling the library functions. In my application, I use 5 milliseconds.

To organize the game, I've made use of the Protothreads threading library. Protothreads is a very light-weight, stackless, threading library written entirely as C macros by Adam Dunkels. Bruce Land has ported Protothreads over for the PIC32. You can find more details on his excellent site: http://people.ece.cornell.edu/land/courses/ece4760//PIC32/index_Protothreads.html

There are two main executing threads, one is the main game thread and the other is a clock thread that keeps track of, and displays, time since the program was started. There is a third thread used to retrieve touch information. It is spawned by the main game thread when touch input is required. The main Protothreads functions (macros) I've made use of are:

PT_setup()
PT_INIT()
PT_SCHEDULE()
PT_SPAWN()
PT_WAIT_UNTIL()
PT_YIELD_TIME_msec()
PT_GET_TIME()

Pin connections:

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
X+: connected to RA4 on the PIC
X-: connected to RB13 on the PIC
Y+: connected to RB5 on the PIC
Y-: connected to RB15 on the PIC
VIN: connected to 3.3V supply
GND: connected to gnd

Here is a demo of the game:



Besides the game itself, you can see the running clock on the bottom left right above the players' scores. To the bottom right you can see a flickering circle that is either green or red, depending on if it's player 1 or 2's turn, respectively. Once the game is over, you have the option of playing another game while score is being tracked.

Here is a link to the MPLABX project with all required header and source files:
https://drive.google.com/file/d/0B4SoPFPRNziHbURwVWVSN1c3VVE/view?usp=sharing

I have commented the code to make it fairly self-explanatory. If you have doubts or questions about anything, let me know and I'll add more detail. Let me know what you think!

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 16, 2014

PIC32 DMA+SPI+DAC : Analog output synthesis with zero CPU overhead


I have previously shown how to use the PIC32 SPI module to use the 12-bit DAC MCP4822: http://tahmidmc.blogspot.com/2014/10/pic32-spi-using-mcp4822-12-bit-serial.html. While that does allow you to generate analog outputs as desired, it requires you to use CPU cycles to process the timer interrupt and accordingly drive the SPI module.

Since the PIC32 contains DMA channels, the process can be completely offloaded from the CPU. For an idea of the PIC32 DMA module, refer to my previously written article: http://tahmidmc.blogspot.com/2014/05/simple-pic32-dma-example.html

Fig. 1 - The generated sine wave at fpwm = 400kHz and 32 elements in the sine table

So, the simple way of offloading the SPI update to the DMA module would be to let the DMA channel transfer data to the SPI buffer. The SPI module is configured for 16-bit data transfer (since the MCP4822 write command requires 2 bytes). This means that the cell size for the DMA channel has been set to 2 (2 bytes to transfer once triggered). The DMA transfer is triggered by a timer interrupt. Unlike the previous example where I used Timer 1 and its interrupt for the SPI transfer, here I use Timer 2. The reason for this is that, if I want the entire process to be offloaded from the CPU, the SS (Slave Select) or CS (Chip Select) also has to be done entirely in hardware. For that I used the Output Compare 1 module. To use the OC1 module, either Timer 2 or Timer 3 (or the combined 32-bit timer) has to be used. So, I just went with Timer 2.

Configuring the DMA module for transferring data to the SPI buffer was the simple part. I found the configuration of the SS/CS pin the more challenging part. The idea here was to use the OC module in "dual compare mode continuous output pulses" mode. The OC module in this mode generates continuous pulses - the output pin OC1 - which I used as CS/SS - is set high one PBCLK (peripheral bus clock) after the Timer value reaches OC1R; the OC1 pin is cleared one PBCLK after the Timer value reaches OC1RS. Since SS/CS is active low, I set ( (period register) - 4) to be OC1RS and a variable CSlength to be OC1R. CSlength was chosen to be 80% of the period register. What this meant was that. One PBCLK after the Timer reached the (period register - 4), the OC1 pin went low (CS/SS went low) "selecting" the DAC. After about 0.80*(period register) from there, the OC1 pin went high. This means that the CS pin is low for 80% of the period - it goes low a small time right before the DMA transfer happens and is raised high late enough, after the DMA transfer occurs. I determined that 80% the period was enough time since that is higher than the time required to shift out 16 bits of data at 20MHz SPI clock. See Fig. 2 below for an illustration of the operation of the output compare module in the "dual compare mode continuous output pulses" mode:

 Fig. 2 - Output Compare module in Dual Compare Mode: Continuous Output Pulse mode (taken from PIC32 reference manual, figure 16-16)

Beyond that, the idea is simple. There is a sine table that is the DMA source. The key thing to remember here is that the 12-bit data must be OR-ed with 0x3000 since that is required for the DAC (to set gain=1, shutdown = 0 and channel = A):

void generateTables(void){
    uint8_t i;
    for (i = 0; i<TABLE_SIZE; i++){
        sineTable[i] = (short) (2047.0 * sin(6.2832*((float)i)/(float)TABLE_SIZE));
        sineTable[i] = sineTable[i] + 2047;

        sineTable[i] = 0x3000 | sineTable[i];
    }
}

Since the entries in the sine table are of "short" data type (each element occupies two bytes), the source size (in bytes) is twice the number of elements. The destination source size is two bytes since I'm transferring two bytes to the SPI buffer register. The cell size is two bytes since the DMA channel has to transfer two bytes (16 bits) at a time to the SPI buffer register. The DMA configuration is:

    DmaChnOpen(0, 3, DMA_OPEN_AUTO);
    // (ch, ch priority, mode)
    DmaChnSetTxfer(0, sineTable, &SPI1BUF, TABLE_SIZE*2, 2, 2);
    // (ch, start virtual addr, dest virtual addr, source size, dest size, cell size)
    DmaChnSetEventControl(0, DMA_EV_START_IRQ(_TIMER_2_IRQ));
    // (ch, trigger irq)
    DmaChnEnable(0);

A point of note is that, the DmaChnSetTxfer( ) takes in the virtual addresses of the source and destination, not the physical addresses. The virtual-to-physical address conversion is done by the function itself as opposed to it being required manually when doing register level operations (as done in my previous DMA example article).

To demonstrate that the DAC control is done with no CPU overhead, in the main( ) function, I have an infinite loop that is just toggling RA0. The output is checked on an oscilloscope:

Fig. 3 - RA0 toggle being demonstrated

Observe that the frequency of the square wave is 4.0MHz - the same that would be observed if all the PIC was doing was the pin toggling.

This also gave better performance than my previous experiment where I did not use DMA. The output sine wave has a higher frequency than observed before and this matches exactly as expected: 400kHz/32 = 12.5kHz as seen (see Fig. 1).

The rest should be very easy to understand and self-explanatory. If you have any questions or suggestions, feel free to comment!

Here are the source and header files:
config.h: https://drive.google.com/file/d/0B4SoPFPRNziHcmlxMmg2Si0zWjQ/view?usp=sharing
main.c: https://drive.google.com/file/d/0B4SoPFPRNziHcmlxMmg2Si0zWjQ/view?usp=sharing

Apr 5, 2014

Hacking the PIC32 Comparator Reference to obtain a DAC



The PIC32MX250F128B has a myriad of peripheral features that makes this cheap little 28-pin 32-bit microcontroller extremely powerful. However, it does lack a digital-to-analog converter (DAC). A simple approach to digital-to-analog conversion is to use one of the PWM channels and then to use an RC low-pass filter at the output.

However, there is another neat little feature of the device that can be exploited or rather utilized to obtain a rather crude DAC – the analog comparator module. Rather, the analog comparator reference module. The PIC32MX250F128B contains an internal voltage reference module that was created to be used as a reference voltage for the internal analog comparator module. However, it does allow you to output this reference voltage to an output pin. Analog voltage output with digital control? Sounds like a DAC.

The voltage reference module is built off of a 16-tap resistor ladder network with two selectable ranges – from 0 to 0.67 CVREF or from 0.25 to 0.75 CVREF. CVREF is the reference voltage for the module and can be connected to VDD (or an external VREF+). Thus there are 32 possible voltage combinations. However, there are some voltages present in both ranges, and additionally, “interleaving” the two ranges does not give a linear set of 32 values. Thus this cannot be used to achieve a full 5-bit resolution DAC. Cleverly selecting the values from the two ranges can, however, lead to more than 16 steps. 16 steps is the number of steps achievable from either range.

The stabilizing time for the internal reference module is listed in the datasheet as 10µs. However, this is defined as the time required to stabilize for a transition from 0000 to 1111 in the voltage selection bits (4bits = 16steps). This means that this can be pushed to relatively high speeds (in the tens of kilohertz) pretty easily depending on the range of the swing of the voltage.

I have received good results with frequencies in the tens of kilohertz. At about 100kHz (10µs between samples), I can see the waveform “curve” a bit but even then it doesn’t look too bad and is definitely useable.

Why use this as a DAC? Well, it’s a nice little tool available to you. Consider the fact that this outputs an analog value with no required additional filtering. Additionally, if you don’t need anything that requires a high resolution (ie no need for a high resolution DAC), this will allow you to leave a valuable output compare / PWM channel to use for something else. If not for anything else, it’s just a fun thing to explore.

I have written a sample piece of code to test this. There are four modes of operation here:


  • Sawtooth mode - Generate sawtooth waveform with 16 steps (only 1 DAC range) (see Fig. 1 below)
  • DAC_Out mode - Output all the values of the DAC full range (32 steps) - this clearly illustrates the non-linearity I was talking about. (see Fig. 2 below) Observe the apparently linear region in the middle.
  • Sine_1 mode - Generate half sine wave output with 16 point sine table. The 16 DAC points are used for the entire sine half wave. DAC used with 16 steps (see Fig. 3 below)
  • Sine_2 mode - Generate half sine wave output with 32 point sine table (16 step DAC mode) - ie this uses the 16 DAC points for half of a sine half wave and then repeats these for the second half, utilizing the 16 step DAC more fully (see Fig. 4 below)
Here are some pictures from my experiments:

Fig. 1 - Sawtooth mode  


Fig. 2 - DAC_Out mode


Fig. 3 - Sine_1 mode


Fig. 4 - Sine_2 mode

Here are download links to the source code:

Source code (main.c):
https://drive.google.com/file/d/0B4SoPFPRNziHZUd5NHM5UDhiSGs/edit?usp=sharing
http://www.4shared.com/file/HaU5syz-ba/main.html

Any ideas? Comments? Feedback? Let me know in the comments section below!

Jan 2, 2014

A Comparative Study between two 32-bit microcontrollers - the Atmel AT91SAM3X8E and the Microchip PIC32MX250F128B


As previously mentioned (http://tahmidmc.blogspot.com/2013/09/200000-views-ithaca-arm-and-dmips.html) I’m doing an independent study under the supervision of Professor Bruce Land here at Cornell University. A semester has passed and I will be continuing my independent study next semester.

The independent study (that I'm doing and will be continuing) is on exploring and comparing the peripheral modules of the Microchip PIC32MX250F128B (on the Microstick II platform) and the Atmel AT91SAM3X8E (on the Arduino Due platform). This semester, I've done a good amount of introductory exploration of the two 32-bit microcontrollers.

Here are the links to the datasheets of the two microcontrollers on which my independent study is based:

PIC32MX250F128B: http://ww1.microchip.com/downloads/en/DeviceDoc/61168E.pdf

The Microchip PIC32MX250F128B is a 32-bit RISC microcontroller based on the MIPS M4K core. In this independent study, I have used the Microstick II platform provided by Microchip.  The  Atmel  AT91SAM3X8E  is  a  32-bit  ARM  microcontroller  based  on  the Cortex-M3 core. In this independent study,  I have used the Arduino Due platform (which is based on the Atmel AT91SAM3X8E microcontroller) provided by Arduino.

Here is the report of my independent study for the first semester, where I have presented my findings and learning:





After writing up the independent study, I have been playing more with both the controllers and experimenting on a bunch of stuff, including (but not limited to) tinkering with different compilers (mikroC PRO for PIC32 and XC32), a mini oscilloscope using the AT91SAM3X8E which I hope to expand into an ECG device, a similar project with the PIC32 and documenting all the different peripherals I'm working on.

I have posted my independent study report in the hope that it will help others who are studying on these two 32-bit controllers (PIC32MX250F128B and AT91SAM3X8E) and hope that it will help them get introduced to the controllers, the two microcontroller series (PIC32 and AT91SAM3) and the corresponding platforms (Microstick II and Arduino Due) mentioned in the independent study report. I will be posting more as I continue my independent study. Please let me know what you think in the comments section below!