Friday, June 12, 2015

PIC18f system clock and delay routine using C18

I just started with the PIC18f, so I planning to go into fundamental. With bunch of tutorials and forum discussions online, I still encounter some difficulties to get started with PIC18f.
Simple problem, yet I do a lot of readings before I successfully compile the led blinking (with 1 second delay).

The first problem is setting the system clock. And the second problem is using the C18 default delay routine.

The PIC18f4550/PIC18f4553 has three clock blocks which are primary oscillator, secondary oscillator, and internal oscillator.




The primary oscillator is normally used for high speed oscillator (>=4MHz), secondary oscillator for low speed oscillator such as 32.768kHz. Internal oscillator has two different clock signals; main output is an 8 MHz clock source and second clock source is the internal RC oscillator provides a nominal 31 kHz output.

Primary oscillator has 4 modes which are HS, HSPLL, XT, XTPLL. Depending of frequency of oscillator, suitable mode need to be assigned as shown as table below:

Resonators Freq
Mode
4.0MHz
XT
8.0MHz/16.0MHz
HS

Crystal Freq
Mode
4.0MHz
XT
4.0MHz/8.0MHz/20.0MHz
HS

For some projects, MCU doesnt need to operate at high speed, config CPUDIV can be used to scale the operating frequency into lower speed.

For some applications that require high speed clock, MICROCHIP provides PLL (phase locked loop) function, it is a frequency multiplier to generate a fixed 96MHz from a fixed 4MHz input. On top of that, a PLLDIV is assigned to divide the oscillator frequency to 4MHz which enable the adoption of oscillator with various frequency range.

















The PIC18f's maximum allowable frequency is 48MHz, so after the PLL the 96MHz is divided into half to suit the MCU operating frequency.

The overall setting for CPU frequency is as follow:
1:      #pragma config PLLDIV  = 5                        // (20 MHz crystal)
2:      #pragma config CPUDIV  = OSC1_PLL2    // Divide 96MHz with two
3:      #pragma config USBDIV  = 2                      // Clock source from 96MHz PLL/2
4:      #pragma config FOSC   = HSPLL_HS         // HS oscillator, PLL enabled (HSPLL)  

For more information on setting, open the mplab, go to Help->Topics...->PIC18 Config Settings. From there, choose selected microcontroller, and all settings are listed and explained.

........................................................................................................................................
For PIC18f4553/4550, maximum CPU Speed is 48 MHz (12 MIPS) which means at CPU operating frequency of 48 MHz, it is able to run 12 millions instruction per second. So one instruction need 4 cycles to process.

In order to have one second delay, you need to do nothing for 12 millions instruction time.
For one micro second delay, 12 instructions of _do_nothing are needed. Which in turn,  two micro second delay, 24 (12x2) instructions of _do_nothing are needed.

Microchip c18 provides <delays.h> library to help set the timing, the <delays.h> is located at
"C:\Program Files (x86)\Microchip\mplabc18\v3.47\h\delays.h"

I wrote my own routine on top on <delays.h> and name it as "delay.h"
For one micro second -
#define delay1MicroSecond()    {Delay10TCYx(1); Delay1TCY(); Delay1TCY();}
// delay 12 instructions

#define delay10MicroSecond() Delay10TCYx(12)      // delay 120  instructions

#define delay1MiliSecond() Delay1KTCYx(12)     //delay 12000 instructions

#define delay100MiliSecond() Delay10KTCYx(120) //delay 1,200,000 instructions

#define delay200MiliSecond() Delay10KTCYx(240) //delay 2,400,000 instructions

All delay routines are in the multiplication of 12 (provided that the CPU operating frequency is 48MHz).

For other CPU frequency, scaling is needed to get the correct timing.
Examples:
                  48MHz = 12 MIPS        // for one micro second, delay 12 instructions
                  32MHz =   9 MIPS        // for one micro second, delay   9 instructions
                  24MHz =   6 MIPS        // for one micro second, delay   6 instructions
                  16MHz =   3 MIPS        // for one micro second, delay   3 instructions

..............................................................................................................................................

To blink led,
the pic18f has one general rule to read/write IO - read from port and write to latch.

First set the IO pin to output,
#define mInitAllLEDs()     TRISBbits.TRISB6=0; TRISBbits.TRISB7=0; //define output
//pic18f rule for input/output is
//0 = output;
//1 = input;

#define mLED_1              LATBbits.LATB6    // write to particular bit (pin b6)
#define mLED_2              LATBbits.LATB7    // write to particular bit (pin b7)

// to on led just assigned mLED_1 = 1;
// to off led just assigned mLED_1 = 0;
..............................................................................................................................................

Now you can start with blinking led, all the source codes can be downloaded at github.




Saturday, May 9, 2015

PIC18f - USB - CDC

The most two common USB protocols are HID and CDC. Most of the popular open source projects which use the microchip are using the CDC for interfacing with PC. For example, the popular bus pirate, logic scrimp, ir toy are using CDC. The dangerous prototype has their open source USB stack so the bus pirate, logic  scrimp, logic pirate are all using the Honken USB Stack source. Another popular open source stack is M-Stack (Free USB Stack for PIC 16F, 18F, 24F, and 32MX Microcontrollers), it has more organised source code and more detail commented. However it only has support on x series compiliers like xc8, xc16, and xc32.
Last, is the microchip default USB stacks, the most common, least problem and abundant of examples. Shouldn't be troublesome if you are using microchip library and microchip compiler. In this tutorial, I am using microchip library.

     I like CDC over HID because it has higher transfer rate, and it appeared as serial communication. The latter feature ensures all of the terminal software can be used. My favourite terminal software is termite,

it is easy to use, no installation required, auto detect and auto configure the serial port.
There are other popular terminal software like tera-term, and real term. Both of these are popular among hobbies as the functions provided are vast and stable. Nevertheless, the learning curve for both software are longer. Whereas, Termite is like a software for dummy, basically no learning curve at all.
To start a project USB CDC project, the easiest way is modifying the Microchip example. Leaving the example file as it is, copy all the source codes to your workspace as shown in the figure below.


It is hard to locate all source file but you can refer back to here, it is more or less the same.

For the USB to run at full speed, the USB need to operate at 48Mhz. The below configuration is to scale the frequency to 48Mhz (everything is at the example file).

This example is going to do three things,
First is the detection of button pressed,

 and if the button is pressed, then "Button Pressed" is printed as shown at code above.

Second is the sending the exact strings with a plus one back to PC as shown at code below:


The third thing is the indication of USB states.



Since the CDC acts like series communication, at the usb_function_cdc,c mentions the serial communication configuration:

You can try to modify the parameters but after some googling, I found out that these parameters are dummy and has not effect when you setting up the serial communication.

...................................................................................................................................................................
After you program everything into PIC, and plug the PIC into PC you will see this message,


You need to go device manager and manually detect the USB driver, you need to click "Browse my computer for driver software"

the driver is provided by MICROCHIP
Usually located at "C:\microchip_solutions_v2013-06-15\USB\Device - CDC - Basic Demo\inf".

If the driver is successfully installed, following will be appeared


.................................................................................................................................................................
Time to play, double click on the Termite terminal software, and you will see the following

Everything is automatically configured. If you click at the "Settings" icon, you can see this
which is different from what we programmed in PIC. It can be concluded the setting in source code doesnt effect the setting at PC side.

Try type any character in the termite terminal and you can the exact plus one back from PIC.


I am using the cytron development kit SK40c, so when I press the SW2 button on the board, I can get the string "Button Pressed"

Since I solely supply the board using the supply from USB, I didnt test the USB status led blinking.

The source file created for SK40c is shared in github.





Thursday, March 26, 2015

Isolated current sensing using LA25-NP

Another popular sensor used in my laboratory is current sensor LA25. In power electronic research, we tend to use sensor with safety standard. LA25 seem to fit in.


This sensor has nominal sensing current of 25A, and peak sensing current is 36A.
It needs +/- 15V supply voltage, and output current is 25mA.

It can be configured to change the sensing range in order to get more accurate result.
I draw each of the configuration on real picture as it will be more visual-able compared with datasheet.

25 AMP configuration

Pins 1 to 5 are connected together for "input sensed current", 
while pins 6 to 10 are connected for "output sensed current". 
M is the measurement, while +/- is for +/-15V supply.

12 AMP configuration
Pins 1 to 3 are connected together for "input sensed current", 
pins 4, 5, 8, 9, 10 are linked together. 
Last pins 6 and 7 are connected for "output sensed current".

8 AMP configuration
Pins 1, 2 are connected together for "input sensed current", 
pins 3, 9, 10 are connected together, 
pins 4, 5, 8 are connected.  
Last pins 6 and 7 are connected for "output sensed current".

6 AMP configuration
Pins 1 is for"input sensed current", 
pins 2, 10 are linked together, 
pins 3, 4, 9 are connected, 
pins 5, 7, 8 are also connected.  
Last pins 6 is for "output sensed current".

5 AMP configuration
Pin 1 for input,
Pin 6 for output,
Pins 2 and 10 are connected, pins 3 and 9 are connected, pins 4 and 8 are connected, pins 5 and 7 are connected.

The inner resistance change with each configuration, the lower the sensing range, the higher the internal resistance.
The supply voltage and output signal configuration are same as LV25











Isolated AC voltage sensing using LV25-P

Voltage sensing is one fundamental thing in embedded system design.
The simplest and cheapest way to sense the high voltage is using the voltage divider to scale the voltage into ADC allowable sensing range.

Additional filter capacitor (0.1uF) can be added in between VADC and ground to eliminated the noise.

Voltage divider sensing is easy to implement, has good accuracy, and sensing range can be customised. By adding a trimmer in between R1 and R2, a more precise measurement range can be obtained.

The only drawback of this method is that common ground issue, the ground from sensing voltage needed to be grounded together with microcontroller. In this regard, there might be safety issue, when measuring >100V. Also, by common ground, it is easier to induce noise to your circuitry especially in power converter applications.


Isolated sensing should be used in high voltage and noisy measurement. The LEM LV25-P is a hall-effect voltage sensor. It has galvanic isolation in between the sensing voltage, and signal output. It has safety certification (EN 50178: 1997), thus make it a very expensive device.

The price from Element14 is around RM294.91.

Above is basic layout of LV25 and it's pins descriptions. The signal is connected to +HT and -HT, "+" and "-" sign need +/- 15V supply voltage. M is the output signal. 

The basic circuit connection for LV25-P is as follow:

Although LV25 is a voltage sensor, but it actually sense current. A sense resistor is needed to limit the current before fed into LV25. The equation to select the suitable resistor is dividing the maximum sensing voltage with 10mA. The 10mA is the nominal current rms LV25 can tolerance. So, LV25 can withstand primary current, measuring range from 0 to ± 14mA.

The output of LV25 is current (Secondary nominal current rms 25mA). However,  ADC module only accepts the voltage signal instead of current signal. A resistor is placed at the output side to convert the current to voltage. The resistor value must be less than 300 ohm, else the linearity will change at difference voltage range. It is advisable to add an op-amp to amplify the signal instead of using a trimmer at the output to vary the gain.

If you are sensing DC voltage, the output signal range is from zero to positive value. 

If AC voltage, you will get a bipolar output, an offset circuitry (suggestion: use differential amplifier) is needed to shift the voltage range from +/-, to 0/+.






Wednesday, March 25, 2015

VC830l multimeter teardown

I have one broken unit of VC830l, and since it is no doing any good. I was so tempted to open it and I did.

I use two tools - Philips test pen and Proskit SD-803. That two are basically what I have in hand.


This is the back PCB of the multimeter and I do some guessing myself.


Above is the back cover, I think that is a buzzer, and it is connected to PCB using the two springs. 


Further unscrew, back PCB and front PCB. 

Front PCB has that nice looking circular track.


And we have the rotary thing with copper coupled.


This is the front cover, and there are two ball bearings.

The whole pcb look simple, and I only saw two ICs,
the controller and ST-GZ 344. 

Although, I never tear a fluke multimeter, but I think this pcb is simple. Maybe that why Victor can sell it at such low price. 





Review of VC830l multimeter

Previously when I want to buy VC830l, I try to google for the review on this multimeter. The result come out zero. Maybe this thing is too cheap to be reviewed, most people just use and toss. So I do a review myself.

The casing of VC830l felt hard and empty, firm hand grip. Maybe I was bias, so I treat it softly. Robustness wise, no idea. Well, is new, I havent drop it yet.

This multimeter has stand, but it is not perfectly aligned. It make "click" sound when you open and close it, especially when you close it.

The buzzer sound was loud and clear, it is actually quit high pitch. But I like the loud indication.

To test the accuracy, I have tested it with Fluke 73III. Some might argue that you cant compare RM30 with >RM1000. Actually Fluke is not famous for accuracy as you can see below:

Instead, the safety features, the sturdiness are Fluke main selling points. 

Even the fluke probe is still fine, after being roll over by chair with a 60kg person sitting on it. 

An accuracy comparison between both is a fair comparison.
First, it is tested with AC voltage. Fluke shows 239.9V, while VC shows 240V. 
VC only has two ranges for AC voltage, 600V and 200V. I use 600V to measure AC.


Fluke has higher precision, VC only has 2000 counts. Nevertheless, the result is acceptable.

Secondly, it is tested with 3V coin cell. Some thing, Fluke has higher counts, but reading until 2 decimal points for 20V testing is good enough.


After that, I measure the 12V battery, the reading is exactly the same.

I was happy to see that. 
A comparable accuracy with branded multimeter.
I mostly work with the DC voltage which is less than 100V such 5V supply, 3.3 signal, +15/-15. So this multimeter comes in handy.

Following that, I test the 1.5k. 0.25w, 1 percent tolerance, resistor.
I start with 200k ohm range, 


the 20k ohm range, I get extra decimal point accuracy.

the 2k ohm range, 3 decimal points accuracy.

I also have tested the resistor with Fluke,

only 0.002 difference, For me, that is acceptable, resistor tolerance can up to 5 percent. Most designs use 5 percent tolerance resistor. So the resistance measurement is good.

Just out of curiosity, I change to 20 mega ohm range, well, it get zero.

After that, I change to 200 ohm, it is over the measurement limit. The VC over-limit indication is not OL, rather, is a 1 on most left hand side.

Overall, I like this multimeter as it has all the basic useful functions, but I will treat it softly, not so harsh as Fluke. Btw, another bright side of VC830l is the big lcd display, it is really a plus.

Pros:
Has all the crucial functions which work well.
Big lcd display.
Acceptable accuracy.
Cheap.
has stand.

Cons:
Manual.
No capacitance measurement.
Only two range for AC measurement.




Tuesday, March 24, 2015

Buying a multimeter

I was thinking to buy a multimeter for myself. I am using the fluke multimeter in lab, it is a very good, solid, reputable multimeter.

But fluke is not something affordable and I am not using multimeter for safety critical work, so fluke is like an overkill.

I am surveying some cheap multimeters online, and I was extra cautious. Cheap thing doesnt come with quality.

After reading some reviews, I am planning to buy mn35, manual multimeter from Extech.
It has features like:
Type K Temperature
1.5V and 9V Battery test function
Data Hold locks reading in the display.

Beside that, the reviews from amazon are good, make it a valid reason as it is a decent multimeter for that price.

Conveniently, it is also sold at Mouser Malaysia for RM81.96. After registered with mouser, and put the multimeter in cart and proceed to checkout. I notice there is a shipping fee required, RM20.
That mean I have to pay extra quarter for multimeter.
Element14 and RS have free shipping, so I was hoping to get free shipping if I buy more than RM100, so I add another item in the cart. Nope, also no free shipping.

I choose to buy the second in my list. Cheaper one but with similar functions, vc830l. It is made by China manufacturer "Victor", it is considered a branded multimeter in China aside Atten, and Uni-t. I was sceptical, but sparkfun is selling it for a very long time. There must be a good reason why sparkfun is selling it? Maybe. Sparkfun has custom white colour skin vc830l - look nicer, and there are a mixed reviews on this multimeter, but I decided to give it a try. After all, you cant argue with the price - RM32 at Cytron.

Myduino is selling the exact model (vc830l) but white colour version. The price is RM58.00 which is almost double than the yellow colour version. I decided to go with fluke yellow look alike multimeter. Appearance is not important.

After I make a purchase on cytron website, I saw another teardown review on a Taiwan blog. For the one he bought, the rotary part get loss, and he adds another paper below to tighten it. Starting to doubt at my decision.

For the one I received vc830l from cytron, look good.

Unfortunately, it is broken.



Luckily I will get the replacement from cytron.

I get the reply in one day, that is very efficient.

Since, I will get a new multimeter, I will tear the broken vc830l in the coming few days.