More Circuit Schematic

Written by Lim Siong Boon, last dated 08-Dec-09.


 

 

Click on the picture to enlarge the Schematic.

DC Motor Driver using L6203

L6203 a H-bridge driver for dc motor control. It  can drive up to a 4A rating motor. There is very few external component, and it is easy to implement. For high current driving from 1A to 4A, it is advisable to mount a heat sink to prevent overheating to the IC L6203.

Speed control can be achieve by various duty cycle control signal. In robotic maneuver speed control is necessary to accelerate and de-accelerate the robot. If there is no speed control, the robot can easily skid or experience slow acceleration.

The schematic consist of 3 dc motor driver for Spotronic use. Two driver for left/right wheel’s motor, and the third one is for camera rotation motor.

 

Click on the picture to enlarge the Schematic.

DC Motor Driver using Relay

DC motor control using relay is very simple compare to using transistor. It can drive very high current rating motor (depending on the relay current rating). However the relay is mechanical driven contact (produce sound), and can wear out over time.

There is not much control, only clockwise, anti-clockwise and stop.

 

Stepper Motor Controller/Driver Selection
Stepper Motor IC
Volt Range
Internal Mosfet
Interface
Thernal Shutdown
Micro Stepping
Rds(on)
Package
Price
Comments
L6228
8-52V
2.8A (peak), 1.4A
Logic
Yes
No
0.73Ω PowerDIP24,
PowerSO36,
SO24
S$10-S$12

DRV8825
(***)
8.2-45V
2.5A Logic Yes
Yes
0.25Ω HTSSOP (28)
S$6.03 Overcurrent protection, fault detection pin, microstep up to 1/32
A3979
35V
2.5A
Logic Yes Yes 0.28Ω TSSOP (28)
S$7.34 Cross-current protection
A4979
50V
1.5A
SPI, Logic
Yes Yes 0.50Ω TSSOP (28) S$7.88 Cross-current protection, diagnostic information
A4989
(***)
12-50V Ext Logic
Yes
TSSOP (38) $5.62
Cross-current protection, current limit
































Dual FULL BRIDGE MOTOR DRIVER
L6207
L298

FULL BRIDGE MOTOR DRIVER
ISL83204A

Stepper Motor Controller
L297

Single FULL BRIDGE DC MOTOR DRIVER
MC33886



www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

Singapore Customized, custom made Electronics Circuits & Kits

 

 

Click on the picture to enlarge the Schematic.

 

DC Powered UPS System

This is a simple DC un-interrupt power system for DC powered device. When there is external power connected, the system will tap power from the external source and charged the internal battery at the same time.

When external power is withdraw, the relay will switch over which enables the internal battery to continue supplying power to the device.

The capacitor value is chosen, depends on the device. It function as a temporary supply source while the relay switches to another power source. This buffer ensure that there is no sudden dip to the power supply during the transition. If the device consume high power, a higher capacity capacitor should be use. Voltage rating of the capacitor as a guide, should be about 2 times the voltage of the supply.

The diode act as a block to prevent activation of the relay by the battery supply source. The current rating of the diode, as a guide should be about 2 times the connected device rating.

 

Click on the picture to enlarge the Schematic.

Signal Switching Circuit

IC ADG451 is an analog switch. It can be used to switch signal on/off or can be configure to act as a signal multiplexer. There are other configuration of analog switch from this series (ADG451 ADG452 ADG453). ADG451 consist of 4 analog switches (active high), while ADG452 consist of 4 analog switches (active low) and ADG453 is a mixture of 2 active high/low.

This circuit is designed for switching Ethernet LAN signal.

 

Click on the picture to enlarge the Schematic.

Adjustable PWM Generator Circuit

Design Dated: 17 Oct 2006

This is a PWM circuit which generate duty cycle rectangle pulses using the IC 555 timer. The duty cycle is adustable by a potential meter (variable resistor) from 0%-100%. PWM signal can be used to switch on/off power transistor, which can then be use to control Motor speed, LED brightness, controlled power supply, and many more. Vcc power supply to the circuit is 7V for the LED. Power supply range is quite wide for IC 555. The IC can operate with voltage within 5V to 16V.

This circuit is designed to control the brightness of LED without the use of transistor to drive. For more information on using transistor to drive high current device, you can refer to project “Switch” at siongboon.com

Piezo Buzzer Interface Circuit

Design Dated: 19 Aug 2012

This is a very basic circuit to interface to a piezo buzzer. The input is a PWM rectangular wave driving the sound/tone of the buzzer. Lower frequency result in a lower tone.

Click on the picture to enlarge the Schematic.

PWM DC Motor Speed/Direction Control Circuit

Design Dated: 19 Aug 2012

This circuit can control a DC motor forward/reverse. The PWM input control the speeed of the DC motor.

 

Click on the picture to enlarge the Schematic.

Serial to Parallel output 16 channel

Design Dated: 20 Nov 2006

This is a serial data input to parallel output circuit. The circuits using 3 signal line, namely the data, data clock and latch clock to send the data to the IC 74HC595. Sometimes more output lines is required for control. With the constraint of limited ports from a microcontroller chip, this circuit comes handy in a project to extend the number of output ports up to infinity.

Each 74HC595 IC support 8 bit latched output, which can be cascaded to infinity number of 74HC595 IC, through is able to provide unlimited number of output ports. The trade-off for such a feature, comes with a delay time, and a relative longer firmware coding.

If the delay is not of an issue, this circuits can helps to extend the number of output ports, from 3 bit port output.

Attached is a function call routine to send the serial data to the circuit’s output. Written for the microcontroller PIC16F877a. ASM source code is here.

Click on the picture to enlarge the Schematic.

Parallel to Serial input 16 channel

Design Dated: 20 Nov 2006

This is a parallel input to serial output circuit. The circuits using 3 signal line, namely the data, data clock and parallel latch enable to read in the parallel data from the IC 74HC166. This circuit comes handy in a project to extend the number of input ports for a microcontroller.

Each 74HC166 IC support 8 bit latching parallel input, which can be cascaded to infinity number of 74HC166 IC, through is able to provide unlimited number of input ports similar to the serial to parallel circuit shown above. The trade-off for such a feature, comes with a delay time, and a relative longer firmware coding.

If the delay is not of an issue, this circuits can provide the microcontroller with more inputs, from 3 bit port input.

Attached is a function call routine to read in data from the circuit’s port to the microcontroller. Written for the microcontroller PIC16F877a. ASM source code is here.

 

Click on the picture to enlarge the Schematic.

2 Channel Delay Timer

 

 

Click on the picture to enlarge the Schematic.

Typical PIC16F877 Schematic

 

 

Various type of circuit interface (3.3V↔5V)

The schematic illustrate various method of interfacing line between a 3.3V and 5V digital circuits.

 

 

 

 

The information presented is from,

Download full article: 3V Tips ‘n Tricks, 41285A.pdf

 

 

 

 

 

Circuit design for interface (3.3V→5V)

 

 

 

 

 

 

 

 

 

 

 

 

 

Interface using commercial available level shifter IC (3.3V→5V)

 

 

Circuit design for interface (5V→3.3V)

 

 

12Vdc-230Vac circuit (100W

)

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

Singapore Customized, custom made Electronics Circuits & Kits

 

 

by Lim Siong Boon


 

Energy Saving Light Bulb

It is all about energy saving light bulb/lamps for lighting.

Edited by Lim Siong Boon, last dated 22-Jan-2012.

Topic Discussion Overview

  1. Lamp Characteristic
    • LED ceiling lamp
    • Electronic PL lamp bulb G24 base
    • Energy Saving T8 fluorescent tube
    • LED strips
  2. Various Lamps Technologies
  3. Color Temperature
  4. Lamp Shape & Base

 

1. Lamp Characteristic

 

LED is the latest lightings technology in town. I was excited about LED lights for the energy efficiency it can bring. Using less energy to light up the place. After exploring the technology, and conducting a series of experiments, I realised that LED is not as wonderful as I think it should be. The truth is, not all LED lighting lamp is efficient. It depends mainly on your application. Fluorescent lamp can have efficiency equal or better than LED lamp. For some applications LED will be better.

The following presents a list of energy saving lightings products that I have considered the best among the other alternative solution. The list consist of LED as well as fluorescent, because some fluorescent bulb solution can be as good or even better than LED bulb in terms of energy saving.

With a better understanding about the lighting technologies, it can help you make a better economical choice towards saving your electricity bill. The subsequent sections will present various energy saving products and some detail analysis. Alternative technologies will also be presented in a table format for easy comparison.

Most of the solutions that are presented are products from saveOne. The company has a strong focus in energy efficient products. Most of the efficient lightings or energy saving solution can be found there, be it LED or fluorescent. They also provide experiments and measurements to allow consumer to have a better understanding of various light bulb technologies. Some of the informations is made available for comparison with the help from their technical support. Besides lighting products, the company also sells other energy saving products. The main focus here is only on the lightings, so let us begin.





Dated : 2011-02-15

This was the very first set of LED bulb that I have tested. My boss actually wanted to showcase LED bulb in our smart home.

(Click image for larger view)  
There is this two model that caught my attention. One is 12W and 7W model.
This 7W LED bulb measures to be about 6W
This model measures about 8.9W
This is a 12W CFL (compact fluorescent lamp) bulb and the consumption is 11W

The power consumption is a bit lower, but the Philips LED bulb price is quite high. The price that I have purchase at that time is about $40++. This is about 8-10 times price difference when compared to a CFL bulb (compact fluorescent lamp, or energy saving bulb).

These LED bulb do generate some heat. You can easily see it from the way the bulb is designed. Between the bulb and the screw, you can find the heavy chunk of metal. This is actually the heatsink which helps to dissipate the heat from the bulb. The lamp uses high power LED. These LED can generate very bright lights, but at the cost of the heat produce. Not all the electrical energy is converted to lights.

 

LED Ceiling Lamp

Product code: LEDCL2417

LED ceiling lamps

LED Ceiling Light (Surface, Round, 98*LED)
Wattage: 8W
Color: Daylight (6500k)

 

 

available from

saveOne Pte Ltd

saveOne Pte Ltd, Singapore, www.saveone.com.sg

 

 

 

My home toilet is bright using the LED ceiling lamps. (Installed on Jan 2012)

The LED ceiling lamps is make up many small LED bulbs. This 8W LED ceiling lamp provide brighter illumination at the center than the old CFL. The old 18W CFL (E27 base) that I used to have provides a brighter illumination on the ceiling than the LED lamp. There are pro & cons. LED is rather directional which is why the ceiling looks darker. However lightings to the floor area is very bright.

This LED ceiling lamps uses many little low power LED bulbs. The heat generated by these low power LED bulb is insignificant when compare to the fluorescent lamp. They do not generate heat, and no heat sink is required. The low heat lighting also means that the components and material can last longer when compare to heat generating lighting technology. In short, low power LED lightings is more efficiency compare to high power LED, fluorescent and other lighting technologies.

Measurement (for 8W LED ceiling lamp)

LED ceiling lamps
Wattage:6W
Current: 0.049A
Power Factor: 0.61

 

Measurement (my old 18W CFL bulb that was used to be in my toilet)

Wattage: 18.3W
Current: 0.118A
Power Factor: 0.664

There are other type of LED lamps that uses high power LED. These lamps uses only a few high power LED bulbs but can dissipate quite high heat. High power LED requires a heat sink (usually aluminium material) to be attached which helps to disspate heat.

 

LED Ceiling Lamp

Product code: LEDCL4015

LED Ceiling Light (Burger, Round, 208*LED)
Wattage: 15W
Color: Daylight (6400k)
Size: Dia 350mm

 

 

available from

saveOne Pte Ltd

saveOne Pte Ltd, Singapore, www.saveone.com.sg

 

 

2012-05-16 Upgrade My Kitchen Ceiling lamp.

I have been using the saveOne electronics ballast to power up my 2x kitchen’s ceiling fluorescent lamp for about 2 years. I wanted to change these fluorescent tube to LED but they are still functioning good. Finally one of the fluorescent (I think it is at least 5 years old) dies off. The very next moment, I ordered 2x LED ceiling lamps. Finally my kitchen is upgraded to LED.

The LED lamp itself is make of plastic, and the weight is very light. It is easy to install. I have managed to reuse the mounting holes from my old lamp by drilling holes on the plastic LED lamp base.

The lamp that is nearer in the picture is the new LED burger lamp that I have installed. The further end is the old fluorescent lamp powered by the energy saving electronic ballast. I wanted to compare the two type of lamp side by side before I change both my ceiling lamp to LED.

The LED version is very bright. Brighter than my old fluorescent lamp.

Another photo taken. The exposure is less, and we can see both the lamps clearer.

You can click on the photo for a larger view.

Lamp view from bottom up.

This is the 15W LED lamp with the cover removed. You can see that it consist of many little LED bulbs. They do not generate much heat even when operating for a long period of time. Your environment temperature can be a little cooler because of this lighting.

Typical heat generated by a magnetic ballast can be very hot. You can try to touch your magnetic ballast after operating for 10 mintues at home. It will be very hot.

The actual lamp with its plain cover.
A close up view of how the inside looks like. There are a total of 208 small little LED bulbs.

Both my kitchen lamp used to be powered by magnetic ballast. The consume was about 40W for each lamp.

The changed to electronic ballast has reduced the energy consumption to about 25-27W.

The installation of LED lamp has reduce the consumption to only 15W. This is only 38% of my old 40W lamp. These LED does not generate much heat, through expected to last longer as well. Bright and efficient, I love it.

Next LED lighting to go will be my rooms.

 

available from

saveOne Pte Ltd

saveOne Pte Ltd, Singapore, www.saveone.com.sg

 

Other interesting LED ceiling lamps products.

These lamps are integrated with motion & LUX sensor. The lamps gets to operates in the dark. When the lamp sense motion, it will switch on it’s LED light automatically. When there is no activity for about a minute, it will switch off the light automatically. These features makes it suitable for your storage room, toilet and corridor.

 

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

 

 

Electronic PL lamp bulb G24 base (PLC)

Product code: CFLSI2154

saveOne

Lamp base: G24
Wattage: 15W
Color: 6500k, Daylight

 

click here for product brochure

 

available from

saveOne Pte Ltd

saveOne Pte Ltd, Singapore, www.saveone.com.sg

 

 

 

Dated: 2012-01-15

It was quite difficult for me to accept the fact that in this technological era we are still using lighting technology that are so out dated. I was not so aware about our current lighting products and technology, until I had this chance to conduct experiment on saveOne’s product.

At first look, this product is no difference from the PL bulb that we normally use in our home or office building. I did not understand what is so special about this product, until I do my some market research.

The current PL bulb that we have in our home or offices actually uses the old magnetic ballast technology. It works exactly the same as a typical magnetic ballast with a normal fluorescent tube. You can read something about the old fluorescent technology here.

http://www.siongboon.com/projects/2010-08-22%20electronic%20ballast/index.html

The old fluorescent technology requires 3 components to work.

a starter , a magnetic ballast and a fluorescent tube to work.

This old technology has a number of disadvantage.

– Use more electricity energy.
– Need to wait for the starter to kick start the bulb.
– Generate more heat due to inefficiency (draw in more current).
– Operating at lower frequency.

The typical PL fluorescent bulb from Philips that you can find in the market does not requires external starter. Most consumer will find it a very convient product over the conventional fluorescent that requires a starter to operate. What most the consumers do not realise is that it is no difference from the old traditional inefficient fluorescent bulb.

So where is the starter? The reason that you don’t get to see any starter in the setup is because the starter has already been built into the bulb itself. A typical fluorescent tube has 4 pins. PL bulb has only 2 pin because the 2 other pin is used for a mini starter installed below the tube (near the socket). This also means that if either the tube or the starter component get damaged due to wear and tear, you will have to replace the whole PL bulb. The old setup allows you to change either the starter or tube if one of them is not working. PL bulb is easy to use but there is wastage. Not that eco-friendly. A working tube can ends up in your trush bin, just because the starter that was integrated into the PL bulb was not working.

Click on the photo to enlarge the picture.

One of the saveOne PL lamp setup. (click to see a larger picture of this setup)

Click on the photo to enlarge the picture.

The typical PL lamp setup. What is inside a typical PL bulb? (click to get a larger picture of this setup)

 

You can easy tell if you have the old PL bulb install in your home/office. The lamp will flicker on and off for a few seconds before it can be fully turned on. The flickering is actually cause by the starter’s attempts to start up the lamp.

So what is so special about saveOne PL lamp?

Let’s do some technical measurement, to explain the differences.

This was a measurement that I took, comparing saveOne PL with a typical PL lamp + magnetic ballast.

 

Lamp Photo Wattage Current PF
10W saveOne PL bulb saveOne 9.1W 0.066A 0.63
typical 10W PL bulb + magnetic ballast 14.3W 0.158A 0.38

 

saveOne has designed the electronics to replace away with the magnetic ballast and starter system. The electronic control is more efficient consuming only 9.1W during the measurement. The PL lamp consume 9.5W at start up and drop down to 9.1W (steady state) after the tube gets to warm up. In contrast the typical PL bulb begins at 13.9W and rise up to 14.3W during the steady state.

saveOne PL lamp is driven by electronics. Users do not need to worry about the type of ballast to match with the lamp. The magnetic ballast PL bulb has a typical higher wattage consumption; this is especially true if the magnetic ballast is not match to the fluorescent tube wattage. In some cases, it wattage consume can even be higher. For the best efficiency in brightness, power consumption and lamp’s lifespan, the typical PL lamp has to match with the ballast of the correct wattage.

The current drawn by the magnetic ballast setup is also higher at 0.158A. Compare to the saveOne PL bulb 0.066A, it is about 2.4 times higher. The reason why a magnetic ballast draws more current is because of its inductive nature. Inductive load is actually an energy storage device and will draws/returns more current than its actual consumption. Unconsumed energy will be returned to the grid. This results in a higher current flowing through the magnetic ballast. The higher current flowing through a finite cable diameter will generate heat compare to a efficienct bulb that uses less current. These are actually energy losses. If you attempt to touch a magnetic ballast after switching your lights on for about 10 minutes, you will feel how hot it can be.

The power factor for the saveOne PL bulb is high at 0.63; the reason for the low current drawn. Power factor of 1.0 (which is the maximum possible reading) indicates that a device will draw the actual current it needs for its operation. Higher power factor means better efficiency.

The heat generated from the magnetic ballast is a waste of energy, and will tends to wear out the various component more. The heat will have indirect impact on the environment temperature and aircon electrcity wastage as well. If you feel the heat surrounding the old PL bulb, you can feel the heat. When you change old PL bulb, you might also find that the tube has the tendency to drop off from the base or the glass tube can break easily. These wear and tear can also expose the dangerous mecury content inside the florescent tube, which will contaminate your home/office environment.

saveOne PL lamp uses electronics to switch the fluorescent lamp. The higher operating frequency also plays a part in the efficiency of the lamp.

The saveOne PL bulb replacement over the old PL bulb is easy. There is no need to do any rewiring. Simply change the bulb. The electronics built into saveOne PL lamp is able to work with existing installed magnetic ballast. I was sceptic about its claim and also did a measurement on its performance when it is used with a magnetic ballast.

Measurement (for saveOne 10W PL bulb + magnetic ballast)
Wattage: 8W
Current: 0.042A
Power Factor: 0.74

The result was quite unexpected when I first do the measurement. The performance is even better without removing your existing magnetic ballast. This product is designed specially for consumer using the old magnetic ballast PL lamp, helping them to switch over to a more energy efficient saveOne PL lamp.

Click to enlarge the picture.

saveOne PL bulb setup without removing your existing magnetic ballast. (click here to see a larger picture of this setup)

 

Even though the magnetic ballast was installed with the saveOne bulb, it does not generate much heat as compared to the old PL bulb. This is much expected with the low current that the bulb is drawing.

saveOne tube is designed in a spiral shape which allow more lights to be projected out. The fluorescent tube also contains triphosphor material which allows the tube to generate brighter light using less electricity energy.

This patented product from saveOne really earns my respect for the innovation that they have put in the area of energy saving. It changes my views about the old lighting technology that we are still using in Singapore. Many places are still using the olf PL bulb.

 

See the following comparison table for more information.

 

Buy this Energy Saving PL Lamp Now at the PIC-store

 

Comparison among various energy saving lightings for PL fluorescent lamp. (updated Jan 2012)

Description

saveOne

Name Electronics
PLC Lamp

LED PL Lamp

Magnetic
PL Lamp

Lastest Energy Saving Lamp 15W 12-18W 18W
Electricity Energy Cost Per Year
see footnote.
$36.25 $29.00 – $43.50 $43.50
Electricity cost saving per month
(when the old magnetic PL lamp is replaced)
$0.60/mth = ($43.50-$36.25)/12 $0 – $1.21/mth = ($43.50-$29.00)/12  
Lamp Cost about $8-12 about $30-50 about $4-6
Fast ROI
(Return-On-Investment, when replaced with ballast + PL Lamp)
Lamp Cost ÷ Electricity cost saving per month
about 13 months about 25 months
Brightness Triphosphor
Lower Heat Generated magnetic ballast generate a lot of heat.
Easy to Install/Replace
Low Maintainance Cost
Instant On (no need starter) `
Safety (robust mechanical design) robust tube design no mercury content crack easily and loosen due to heat stress
Integrated Ballast (save space) external ballast is required
High Power Factor magnetic ballast has low power factor
Estimated Lifespan 7,000hr 30,000hr 7,000hr
Brand name in Singapore
– Philips
– PowerPac
– saveOne

saveOne Pte Ltd

saveOne Pte Ltd

footnote:
(assuming 24 hour operation per day, base on Singapore’s Electricity Tariffs rate of $0.2759 cents as of Jan 2012)
Electricity Cost Per Year = Bulb Watt (W) x 24 Hour x 365 days ÷ 1000 x Electricity Tariff Rate ($/KWh)

 

 

 

Energy Saving T8 fluorescent tube

SuperTube

Product code: FLRSL1644
saveOne Pte Ltd

Lamp base : T8
Length: 4ft
Wattage: 16W
Color: Daylight (6500k)

click here for product brochure

 

available from

saveOne Pte Ltd

saveOne Pte Ltd, Singapore, www.saveone.com.sg

 

 

 

 

When I first got to know of this energy saving T8 fluorescent tube, it looks just like any ordinary T8 lightings. I have learned over a series of measurements and experiements that this is no ordinary T8 fluorescent tube. It has the performance comparable to a LED T8 tube, but at a cost much lower. The design also overcome some of the shortcoming of an ordinary fluorescent tube that are available in the current market. These have make it one of the most efficient and economical lighting tube among the rest (LED T8 and T5).

Taking a closer look, the product is actually a T5 fluorescent tube, covered with a protection covering. T5 is quite well known for its lighting efficient. The T5 tube is coated with triphosphor material helps the tube project out more light using less energy..

The product’s covering provides an extra protection over the fragile tube to reduce contamination due to the leakage of mercury vapor; a common substances that is contain inside all fluorescent tube. This protection is especially important in the kitchen area where food preparation work will be done. It is also desirable for low ceiling workplace where the tube can easily be damaged. Mercury is a health hazard substances, and it important that we handle fluorescent tube with care. The covering design reduce the chance of mercury containmination.

Actual measurement was conducted shows that the wattage of this product has the same wattage consumption to a typical LED tube. This energy saving performance comes from the electronic ballast that is integrated into the lamp product itself. With the integrated electronic ballast, the tube can be connected directly to your Live and Neutral electrical wire. This simplifies the electrical connection. It means that you can save more space. A normal T8 or T5 fluorescent tube which requires a starter and external electronic/magnetic ballast in order to work with, and this will take up precious space.

Normal T8 housing can be very bulky. Magnetic ballast, starter and starter holder are housed inside the enclosure.

 

Space saving T8 fluorescent tube socket for direct electrical connection. Useful for ceiling/wall cove lightings where space are very tight. Setup is cheaper as well without the enclosure, starter, starter holder and magnetic ballast.

 

The product’s built-in integrated ballast is also designed to work with your existing magnetic ballast. This means that you do not have to change any wiring or remove the magnetic ballast from your existing setup. Simply change the old T8 tube with this new energy saving tube, and remember to remove away the starter. The new lamp turns on its light instantly without the need for any starter.

You might wonder that with the magnetic ballast working together with this new product, will it affect the energy consumption? I had the same thought as well. Measurement were taken. By using the magnetic ballast together with the product, it has insignificant changes to its performance and energy consumption. In fact the power and current drop a bit. These can be explain by the measurement result which will be presented shortly.

The power factor of the ordinary T8 tube setup is poor. This is mainly due to the magnetic ballast which is an inductive component (which is only wire coil). The poor power factor results in higher current being drawn from the electrical grid. The current drawn is 4 times higher than the saveOne’s T8 energy saving product. With such a high current flowing through the magnetic ballast, it will generate heat. This is also why it feel burning hot when you try to touch the magnetic ballast which has been operating for more than 10 minutes. This is wasted energy as a form of heat. The heat also affect your environment temperature indirectly.

In contrast, this energy saving T8 lighting product uses much less current. Less heat will be generated. Even if this low current flows through your existing magnetic ballast, it will not generate much heat. The low current is transparent to your existing magnetic ballast; there are no loss.

This is a ordinary T8 fluorescent lamp using a magnetic ballast.

The temperature is 71.8°C is taken just behind the casing housing the magnetic ballast. It is so hot even on the outside. You can imagine how hot is the ballast inside.

The whole lamp housing was removed from the ceiling and is placed on the floor. This ballast has been resting for about 10-20min. The temperature reading taken on the magnetic ballast surface is still hot at 61.0°C.

Click on the picture to enlarge.

A big contrast, another ceiling lamp housing was fitted with the saveOne T8 energy saving fluorescent tube. The magnetic ballast is still inside. Starter was removed and no wiring change was done. It has been turned on for the whole day. The temperature reading behind the lighting enclosure is only 35.0°C. This is only slightly more then the normal room temperature in Singapore. The heat is propably only from the fluorescent tube itself. The fluorescent tube itself when switched on, do produce some heat.

  As we can see, the drop in temperature is quite significant. The generated heat from the old T8 is simply a form of wasted energy.

 

The following measurement result shows that the power consumption for the saveOne T8 product is almost the same as a typical LED T8. Given the similar performance, the ROI (return of investment) of the product will be much better because the LED cost is high.

 

Lamp Photo Wattage Current PF
saveOne T8 fluorescent tube saveOne Pte Ltd 16.1W 0.082A 0.953
LED T8 tube 16W 0.080A 0.952
ordinary T8 fluorescent tube 43W 0.429A 0.439

Note: wattage various around 36W- 45W depending on the magnetic ballast

 

The product has indeed impressed me for its efficiency when compared to a LED T8 tube. I have also done up a product comparison table to compare against other type of lightings solution to replace the old T8 magnetic ballast fluorescent lamp.

See the followings for more information on the comparison between more types of alternative replacement solution for T8 lightings.

 

Comparison among various energy saving lightings for T8 4FT fluorescent lamp replacement. (updated Jan 2012)

Description saveOne Pte Ltd

saveOne Pte Ltd

 

 

Name SuperTube LED T8 to T5 Adaptor Electronic Ballast Magnetic Ballast
Lastest Energy Saving Lamp 16 – 20W 16 – 20W 23 – 28W 28 – 40W 36 – 45W
Electricity Energy Cost Per Year
see footnote.

$38.67

$38.67

$55.59

$67.67

$87.01

Electricity cost saving per month
(when the old T8 tube is replaced)

$4.03/mth = ($87.01-$38.67)/12mth

$4.03/mth = ($87.01-$38.67)/12mth

$2.62/mth = ($87.01-$55.59)/12mth

$1.61/mth = ($87.01-$67.67)/12mth

Lamp Cost about $18-$25 about $60-$90 about $12-$18 about $8-$12 about $5-$9
Fast ROI
(Return-On-Investment, when replaced with ballast + PL Lamp)
Lamp Cost ÷ Electricity cost saving per month
about 4-6 months about 15-22 months about 5-7 months about 5-7 months
Brightness Triphosphor Triphosphor
Lower Heat Generated
Easy to Install/Replace
Low Maintainance Cost
Instant On (no need starter)
Safety (robust mechanical design) protection against mercury leakage no mercury content
Integrated Ballast (save space)
High Power Factor
Estimated Lifespan 7,000hr 30,000hr 7,000hr 7,000hr 7,000hr

Brand name in Singapore
– Philips
– AZ e-lite
– Megaman
– PowerPac
– saveOne

saveOne Pte Ltd

saveOne Pte Ltd

 

saveOne Pte Ltd

28-32W electronic

footnote:
(assuming 24 hour operation per day, base on Singapore’s Electricity Tariffs rate of $0.2759 cents as of Jan 2012)
Electricity Cost Per Year = Bulb Watt (W) x 24 Hour x 365 days ÷ 1000 x Electricity Tariff Rate ($/KWh)

 

Comment:

As based on the comparison among various lamps technology, the latest energy saving LED and SuperTube lamp are both very energy efficient lamp.

LED is known to last longer than the fluorescent technology but the cost of the lamp is much higher. That is why the ROI (return on investment) is poor when compare to the fluorescent technologies.

The fluorescent technologies have similar ROI although the cost price is different. This is because the new fluorescent design has achieved an efficiency close to the LED technology..

SuperTube design has a cost slightly higher, but it offer more electricity saving, with a better protection against mercury contamination than the other fluorescent technology.

In terms of cost and efficiency, the SuperTube lamp offers a better choice over the lamps. If you are interested to find out about saveOne’s SuperTube lamps, you can contact them or visit their office for a demonstration or an experiment experience.

 

 

 

 

 

Product picture taken from saveOne Pte Ltdand

 

 

LED candle and chandelier bulb (compare to incandescent bulb)

 

Lamp base: E12, E14
Wattage: 0.3W (candle bulb 6xLED) , 0.6W (candle bulb 12xLED), 3W (chandelier)
Color: Red, White, Warm, Green

 

 

available from

saveOne Pte Ltd

saveOne Pte Ltd, Singapore, www.saveone.com.sg

 

I love these LED candle bulb. These E12 bulbs are usually used for the praying lamp on our Taoist altar table. It simulate the olden days of using candle flame..

 

Candle bulb with its holder.

A simple altar table using candle bulb.

 

Compare to the normal incandescent bulb 16W, these LED bulb only uses 0.3W. That is about 50 times saving in energy. The incandescent bulb can be very hot after turning on for a few seconds, and these can be quite dangerous especially with naughty children running around the house. These LED bulb remains cool after operating for the whole day. The lifespan of these LED bulb is much much longer compare to the incandecent version.

LED candle bulb (0.3W, E12), cool and longer lifespan Old type, incandescent bulb (16W, E12), very hot and short lifespan. Cheaper.

 

The old incandescent bulb cost less than a dollar, a lot cheaper then the LED bulb which cost about S$5 to S$8. Considering the 16W energy that the incandecent bulb will consume, it will actually cost more to maintain it. This is even more significant if you operate the lamp for 24 hours per day. The electricity bill that you save within 2 months of operation can easily help you recover the cost of the LED bulb purchased. Per bulb would have save you about S$3 to 4 base on the electricity tariff rate of S$0.30/Kwh. Lifespan of incandescent bulb can be short, as the heat and frequent switching on/off can burn off the filaments inside.

For these LED bulbs the brightness is lower and will not be suitable if you have a lamp covering. The cover will reduce the brightness. Considering the energy saving, temperature, safety and lifespan that this LED bulb brings, it is a much more economical choice over a incandescent bulb.

 

Buy this LED Candle Bulb Now at the PIC-store

 

 

 

 

Another great bulb that I will like to introduce is the LED chandelier bulb which uses only 3W compare to the incandescent version which uses 40W.

A LED chandelier bulb (3W E14), hot but much better than the incandescent bulb. The LED bulb when it is switched off.

 

The photo on the left is an old incandescent chandelier bulb (40W E14), very hot and short lifespan. You can see the thin filament inside the bulb.

 

This LED incandescent chandelier bulb uses a high power LED. The light is very bright and look very much like the incandescent bulb’s filament. The high power LED bulb do generate some heat but it is a lot less than the incandescent version. This LED bulb 3W uses about 13 times less energy than the conventioanl incandescent bulb of 40W.

These LED bulbs are worth recommending for their higher effciency, lower heat generated, safer and longer life span over the conventional incandescent bulbs.

 

Buy this LED Chandelier Bulb Now at the PIC-store

 

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller


 

LED lighting strips

 

Lamp base: Bare wire strip
Wattage: 4.8W, 9.6W, 14.4W, 28.8W per meter
Color: White, Warm, Green, Red, Blue, Orange, Yellow, Purple, Cyan, Pink, RGB multi-color

LED bulb: 5050, 3528
Package: IP67, IP65, IP44

1meter/reel, 50mm cuttable section

30/60/120 LED per meter

 

 

 

 

 

 

 

Last updated: 2012-03-13

LED strip is getting more and more popular nowsaday. Unlike other lighting, the led strip is very flexible allowing it to bend over corner and curve. They usually comes in a roll of 5m per reel and can be easily extended or cut to length in a section of 50mm.

There is usually a black line to indicate the cutting point. The line is usually between the copper pad.

You can actually cut anywhere along the strip. If the strip is not cut on the indicating line, you will end up losing about 3 LED at the strip end not lightting up. This is because the strip is usually design to have 3 LED connected in a series circuit.

 

The installation and wiring is very simple. It using a low voltage of 12V which is very safe to handle. There are also strip using 24V. You will not get electrical shock by touching the pair of 12V wire using your bare hand; neither will it cause nasty short circuit when it gets in contact with water. This make it suitable for installation near water or where it can easily get in contact with water or the user. Special area like toilet basin, aquarium tank lighting, floor area, bed side and lower section of the cabinet. It is much safer than any 230Vac lighting; about 20 to 30 times lower.

There are many style of installing the strip. You can lay the strips simply on the shelf. Some strips has sticker/adhesive tape on its back, allowing it to sticks itself to most surface. Remember to clean the surface before sticking the strips on it. There are also accessories which you can extend or secure the strips. The strips allows installation where traditional lamp installation is not possible.

Non-silicon jacket strip comes with adhesive on the back of the strip.
Mounting silicon bracket accessories to secure the LED strip.

Connector to extend the LED strip.

Another type of connector design.

Connector can be used for the wire as well.

 

The LED strip comes in a reel of 5m and comes with a wire dangling from both end of the strip. The strip can be cut into length. If a connection is required after the cut, there is also a connector available to join up the strip.

The connection is simple and quick. No soldering of strip or wire will be required.

 

LED strip’s socket to fit to the typical power supply adaptor’s DC barrel jack (OD=5.5mm, ID=2.1mm)

 

 

The strip is usually drive by a 12V switching regulator or power supply adpater. Like a battery, you should never short the positive and negative terminal of power adapter; the adaptor can be damage. A 12V power supply adaptor comes in various current rating. A longer strips requires more energy to light up, therefore a higher current rated power supply will be needed to drive it. A meter of 14.4W strips requires about 1.2A. If you are getting 3 meter, the current needed will be about 3.6A. The power adaptor that will be required has to be a minimum of 12V 4A. Usually I will give the power adapter more buffer. A rating of 12V 5A or more will be safer. If you use a lower current rated supply, for example 12V 2A, you will likely to cause internal damage to the power adaptor. Higher current rated power supply is better in performance, but is generally more expensive.

Power Supply Adapter or Switching Voltage Regulator

Form factor: Wall Plug
usually available for low current rating

Form factor: Desktop
usually available for high current rating

 

LED strip circuit is a relatively simple design. It is unlikely that you will damage the strip using a wrong rated power supply. Even if you connect the positive/negative priority in reverse, neither the strip nor the power supply will be damaged. The strip operates on 12V, and can tolerate minor voltage difference (10-13V). A voltage too high applied to the strip can damage the LED bulb.

There is a limit to how long the strip can be extended. 10m is the recommended maximum continous strip length. Extending it longer, you will find that the light intensity near the far end of the strip will become much dimmer than the other end that is near the power source. If your eye are sharp enough, you should notice the intensity difference within a 5m long strip itself. This flaw is due to the slim and narrow strip design (resistance), restricting the high current flow, preventing current to reach to the far end of the strip. The high resistance on the strip design also result in slight heat generated. This problem is more obvious with the high power strips.

You can improve the intensity at the far end of the strip by connecting the end back to the power supply. This will allows the current to reach the far end of the strip directly, without passing through the whole LED strips. To achieve a more consistant intensity, it is recommended to connect the strip in a shorter section of 2m each. Each 2m section should be connected directly to the power supply in a star wiring configuration.

The exact current consumption of the LED strips is slightly difficult to compute because of this flaw. Depending on the strip connection in series or parrallel the consumption can varies. The exact consumption can only be determine by a current meter. In general, the computation method as introduced eariler would be more than enough to drive the strip.

There are many type of strips, and they are usually classified by the following 4 characteristic.

– LED bulb size (5050, 3528)
– Number of LED per meter (30, 60, 120)
– Strip package (IP67, IP65, IP44, IP20)
– Color (Warm (2700k), Cool (6500k), other specific color)
 

The LED bulb or chip size 5050, 3528 is actually a number code for EIA standard footprint size. These standard footprint allows PCB designer to draw the correct pad size so the the LED can be mounted properly onto the PCB board. For some reason, these code has becomes a standard when ordering LED strips. 5050 actually also defines the LED size in two dimension 5.0 x 5.0mm. For 3528, LED size is 3.5 x 2.8mm. As a general guidance, 5050 LED has bigger chip size, and is expected to have a higher intensity (brighter) and wattage (consume energy) than the 3528 chip.

5050 led chip
5x5mm
(Brighter and consume more energy)

3528 led chip
3.5×2.8mm

 

IP code (Ingress Protection Rating) is standard define a series of code to label product’s strength of resistance against dust and water.

IP20
 no cover

IP44
covered with epoxy
IP65
covered with silicon jacket
IP68
covered with expoxy & silicon jacket
(offer no protection from water)
(dustproof, water resistance, splashing water cause no harm)
(dustproof, waterproof)
dustproof, watertight, immersion into water

<- IP protection standard reference

http://en.wikipedia.org/wiki/IP_Code

 

There are also LED strip that can change their color making use of RGB LED. There are also special LED strip that can generate lighting patterns. These strips will require a LED strip controller to work.

RGB LED strip looks no different from a single color strip. The noticable difference will be the 4 wire connector (black, green, red, blue).These lines will be connected to the RGB controller on the left, to allow color control of the whole strip.

This is another RGB LED. It is different from the RGB strip above. This strip can generate a pattern of colors on the strip. This means that multiple color can co-exist on the strip at the same time. The strip can be differential by the IC chip embedded onto the strip itself. Click on the photo to see the enlarged strip below. You will see the black rectangular block which is the controller IC. This strip will also need an external delicated color controller to drive its color. The external controller usually comes in a form factor of a box.

RGB pattern generating IC chip info

 

Funitures  
Shelf  
Cabinets  

Below Kitchen cabinet

– Provide some light during the night time

 
Rised floor platform  

Cove lighting

 

Toilet, and behind mirrors

LED strips operate at 12V, and is safer than T5 tube which operates at 230Vac. A normal T5 tube is made of glass and contain mecury content. Installing T5 behind the mirror which is reachable can be dangerous, comparing to the LED strip. The LED strip when submerge in water will not result in electrical short circuit. This will not be true for T5 tube.

 

 

Wardrobe

LED strips is slim and safe, allowing installation in tight space such as a closet or cabinet display.

 
Along or under the bed  

TV console  
Water features  

LED strips for aquarium. If the tank is deep, more strips may be required for the light to penetrate deep into the water.  
LED strip lights for plant  
Jewelry showcase  

PIR motion sensor accessories for LED strip  
LED strip installation guide  

 

reference:

http://jacksledprojects.blogspot.com/2011_10_01_archive.html

 

 

 

 

LED driver





Typical LED driver rating

   

 

Typical LED driver specification.

No. of LED in series
LED watt
Driver spec
Typical driver size
1 1W 3-4V / 300mA 35x24x19
3 1W 9-15V / 300mA 35x24x19
5 1W 15-20V / 300mA 42x24x19
6-9 1W 18-35V / 300mA 65x27x21
9-12 1W 25-45V / 300mA 108x24x19
12-15 1W 30-56V / 300mA 122x24x19
15-18 1W 40-68V / 300mA 145x24x19
18-24 1W 60-90V / 300mA 155x32x24
12-18 1W 30-70V / 300mA 112x28x24
18-24 1W 60-90V / 300mA 140x28x24
24-30 1W 70-110V / 300mA 155x32x24
30-36 1W 90-136V / 300mA 158x38x30
1 3W 3-4V / 650mA 35x24x19
3-4 3W 9-15V / 650mA 108x24x19
4-5 3W 15-20V / 650mA 122x24x19
5-6 3W 15-25V / 650mA 145x24x19
7-8 3W 20-30V / 650mA 155x32x24
6-9 3W 18-35V / 650mA 112x28x24
9-12 3W 25-45V / 650mA 140x28x24
12-15 3W 30-56V / 650mA 155x32x24
15-18 3W 40-68V / 650mA 158x38x30

 

 

 

 

 

 

 

2. Various Lamps Technologies





 
     

 

This is meant to be a general reference for various lamp technology available on the market. The following information is not comprehensive for a detail one to one comparison.

Type of lightings technology LED Fluorescent Induction Halogen Incandescent Plasma HID
Picture
Full Name Light Emitting Diode           High-intensity discharge lamp
Typical Application Room lighting Room, High Bay, Hall lighting Room lighting Display cabinet General lighting High Bay, Hall, Street lights High Bay, Hall, Street lights
Typical Wattage 10W 40W 40W 50W 40W    

Electricity Energy Cost Per Day
see footnote.

$0.0662 $0.2649 $0.2649 $0.3311 $0.2649    
Electricity Energy Cost Per Year $24.16 $96.65 $96.65 $120.82 $96.65    

footnote:
(assuming 24 hour operation per day, base on Singapore’s Electricity Tariffs rate of $0.2759 cents as of Jan 2012)
Electricity Cost Per Year = Bulb Watt (W) x 24 Hour x 365 days ÷ 1000 x Electricity Tariff Rate ($/KWh)

 

 

 

 

 

 

 

Manufacturer for Halogen and incandecent lamp products.

 

 

 


   

3. Color Temperature

 

color temp



color temp

colortemp

color index  

 

 

Defination used in Lightings

Name
SI units
Defination
Lumens
lm
A unit of luminous flux; overall light output; quantity of light, expressed in lumens.

Lamp Efficacy ( Lumens Per Watt)

lpw
The number of lumens produced by a light source for each watt of electrical power supplied to the light source. See Efficacy.
Luminaire

A complete lighting unit which contains a lamp, housing, ballast, sockets and any other necessary components.
Luminaire Efficiency

The ratio of lumens emitted by a luminaire to the total lumens emitted from the light source within the luminaire.
Luminance

Light reflected in a particular direction; the photometric quantity most closely associated with brightness perception, measured in units of luminous intensity (candelas) per unit area (sq ft or sq m)
LUX

A unit of illuminance equal to 1 lumen per square meter.
Ballast Factor (BF)
  It is the measured ability of particular ballast to produce light from the lamps it powers. It is derived by dividing the lumen output of a particular lamp/ballast combination by the lumen output of the same lamps on reference ballast. Hence, Ballast factor is the ratio of the luminous output of a lamp when operated on ballast to its luminous output when operated under standardized rating conditions. In other words, it is the percentage of rated lumens from the same lamp using commercial ballast as compared to ANSI reference ballast. Ballast factor is not a measure of energy efficiency. For example, a ballast factor of .96 means the commercial ballast produces 96% of light produced by ANSI reference ballast operating the same lamp. The ballast factor can be referred to in the catalogs from fluorescent or HID ballast manufacturers.
Ballast Efficacy Factor (BEF)
  It is the ratio of the ballast factor to input power of the ballast i.e. input watts. It identifies the efficacy of a lamp/ballast system in comparison to other systems using the same type and number of lamps. The higher the BEF within the same lamp-ballast type, the more efficient is the ballast. Unlike Ballast factor, it is the measure of efficiency of fluorescent lamp ballasts.

 

 

Color Temperature References:

http://www.feit.com/education/feitcolortemperature.html
http://micro.magnet.fsu.edu/optics/lightandcolor/colortemp.html
http://www.3drender.com/glossary/colortemp.jpg
http://www.theprojectorpros.com/images/learn/color_temperature_1.jpg
http://www.ofweek.com/Upload/News/2009-10/7/kelvin-color-temperature-scale.jpg

color%20temperature%20of%20lightings.png

 

 

4. Linear Fluorescent


reference:

http://www.answers.com/topic/fluorescent-lamp




Linear Fluorescent

Bulb Shapes

  • Circline
  • T5 (0.625″ dia, 15.9mm)
  • T6
  • T8 (1″ dia, 25.4mm)
  • T10
  • T12 (1.5″ dia, 38.1mm)
  • U-bend

 

 

 

 

Singapore commonly used bulb shape & base is highlighted in bold font.



Circular Fluorescent lampT5T6T8T10T12U-bend

 
Actual Length
Norminal Length (ft)
T5
T8 & T12
2
549mm
590mm
3
849mm
895mm
4
1149mm
1199mm

 

Base Types

  • Miniature Bi-Pin
  • Single Pin
  • Medium Bi-Pin
  • Recessed DC

Singapore commonly used bulb shape & base is highlighted in bold font.

  miniture bi-pinsingle pinmedium bi-pinrecessed dc

 

 

5. Compact Fluorescent

 

 

 

reference:

http://www.biddy-light.com.tw/lamp/PL-LAMP.htm


compact fluorescent

Bulb Shapes

  • Single Tube 2-Pin
  • Single Tube 4-Pin
  • Double Tube 2-Pin/4-Pin
  • Triple Tube 4-Pin
  • Flat Quad 4-Pin
  • Double 15mm
  • PLL 4-Pin
  • BR38
  • R20
  • R30
  • R40
  • R40 Plug-In
  • A
  • G Globe
  • PAR20
  • PAR30
  • PAR38
  • B13
  • GU24
  • Spiral
  • Spiral Plug-In
  • T20

 

 

 

Singapore commonly used bulb shape & base is highlighted in bold font.



Single Tube 2-Pin Single Tube 4-PinDouble Tube 2-Pin/4-PinTriple Tube 4-PinFlat Quad 4-PinDouble 15mmPLL 4-Pin

BR38R20R30R40R40 Plug-In

AG GlobePAR20PAR30PAR38

B13GU24SpiralSpiral Plug-InT20

Base Types

  • G23
  • GX23
  • GX23-2
  • G24q-1
  • G24q-2
  • G24q-3
  • G24d-2
  • GX24q-3
  • GX24q-4
  • GX24q-5
  • GX25d-3
  • 2G11
  • 2GX7
  • Medium E26 E27
  • E12

 

Singapore commonly used bulb shape & base is highlighted in bold font.

 

G23GX23GX23-2G24q-1G24q-2G24q-3G24d-2

GX24q-3GX24q-4GX24q-5GX25d-32G112GX7Medium E26 E27E12

G24 lamp & socket G24 lamp

 

 

6. Halogen


halogen

Bulb Shapes

  • AR111
  • BR
  • BT15
  • J Type Tubular
  • JC
  • JD
  • T10
  • JDR
  • JDR/S
  • MB
  • MR
  • MR-DC
  • MR-GU10
  • PAR14
  • PAR16
  • PAR20
  • PAR30
  • PAR36
  • PAR38
  • PAR46 PAR56 PAR64

Singapore commonly used bulb shape & base is highlighted in bold font.



AR111 BRBT15J Type TubularJCJDT10

JDRJDR/SMBMRMR-DCMR-GU10PAR14

PAR16PAR20PAR30PAR36PAR38PAR46 PAR56 PAR64

Base Types

  • Screw Terminal
  • DC Bayonet BA15d
  • G53
  • G6.35 or GY6.35
  • G8
  • G9
  • G4
  • GU5.3
  • SC Miniature Bayonet BA9s
  • GU10
  • Intermediate E17
  • Medium E26 E27
  • Mini-Can E-11
  • Mogul End Prong GX16d
  • Recessced Single Contact R7s
  • SC Bayonet BA15s

Singapore commonly used bulb shape & base is highlighted in bold font.

 

Screw TerminalDC Bayonet BA15dG53G6.35 or GY6.35G8G9G4GU5.3

SC Miniature Bayonet BA9sGU10Intermediate E17Medium E26 E27Mini-Can E-11Mogul End Prong GX16dRecessced Single Contact R7sSC Bayonet BA15s

Filament Types

  • CC-2V
  • C-6
  • C-7A
  • C-8

Singapore commonly used bulb shape & base is highlighted in bold font.

  CC-2VC-6C-7AC-8

 

 

7. Incandescent


incandescent

Bulb Shapes

  • A Arbitrary
  • BR Bulge Neck Reflector
  • B Cylinderical
  • CA8-CA10 Candelabra Base
  • B8-B10 Candelabra Base
  • CA8-CA10 Edison Base
  • ER Elliptical Reflector
  • B8-B10 Edison Base
  • F Flame
  • CA5 Candelabra Base
  • G Globe Candelabra
  • G Globe Medium
  • MB Mid-Break Reflector
  • PAR36 Parabolic Reflector
  • PAR Parabolic Reflector
  • PS Pear Straight Neck
  • R Reflector
  • S Straight Side
  • T Tubular

Singapore commonly used bulb shape & base is highlighted in bold font.



A ArbitraryBR Bulge Neck ReflectorC CylindericalCA8-CA10 Candelabra BaseB8-B10 Candelabra BaseCA8-CA10 Edison BaseER Elliptical ReflectorB8-B10 Edison BaseF Flame

CA5 Candelabra BaseG Globe CandelabraG Globe MediumMB Mid-Break ReflectorPAR36 Parabolic ReflectorPAR Parabolic ReflectorPS Pear Straight NeckR ReflectorS Straight SideT Tubular

Base Types

  • Screw Terminals
  • Slip-On Terminals
  • DC Bayonet BA15d
  • Cadelabra E12
  • E14
  • Intermediate E17
  • Medium E26 E27
  • Medium Side Prong
  • Medium Skirted E26/Skt
  • Mogul E39
  • Mogul End Prong

Singapore commonly used bulb shape & base is highlighted in bold font.

 

Screw TerminalsSlip-On TerminalsDC Bayonet BA15dCadelabra E12E14

Intermediate E17Medium E26 E27Medium Side ProngMedium Skirted E26/SktMogul E39Mogul End Prong

Filament Types

  • C-2V
  • C-3A
  • C-5
  • C-6
  • C-7A
  • C-8
  • C-9
  • C-9M
  • C-13

Singapore commonly used bulb shape & base is highlighted in bold font.

  C-2VC-3AC-5C-6C-7AC-8C-9C-9MC-13

 

 

8. HID lamps (High-intensity discharge)


HID lamps

Bulb Shapes

  • A23
  • BT37
  • BT56
  • ED17
  • ED18
  • ED23.5
  • ED25
  • ED37
  • PAR20 PAR30L
  • PAR38
  • R40
  • T6 T7 T8 Double Ended
  • T6 T7 Single Ended
  • T15 T16

 

 

Singapore commonly used bulb shape & base is highlighted in bold font.



A23 BT37BT56ED17ED18ED23.5ED25

ED37PAR20 PAR30LPAR38R40T6 T7 T8 Double EndedT6 T7 Single Ended T15 T16

Base Types

  • BY22d SC Bayonet
  • FC2
  • G12 Medium Bi-Pin
  • R7s Recessced Single Contact
  • POMB Position Oriented Mogul Base
  • EX39 Exclusionary Mogul Base
  • E39
  • E26 E27 Medium

Singapore commonly used bulb shape & base is highlighted in bold font.

 

BY22d SC BayonetFC2G12 Medium Bi-Pin R7s Recessced Single Contact

POMB Position Oriented Mogul BaseEX39 Exclusionary Mogul BaseE39E26 E27 Medium

 

 

9. Specialty


specialty

Bulb Shapes

  • ALR
  • C7/C9 LED
  • G6
  • G7
  • MR11 LED
  • MR13
  • MR16 LED
  • PAR16 LED
  • PAR20
  • PAR30
  • PAR36
  • PAR64
  • PAR46 PAR56 PAR64
  • RP11
  • R12
  • S8
  • T1.75
  • T2
  • T2.5
  • T3
  • T3.25
  • T3.25/T5
  • T4 E11
  • T4
  • T4.25
  • T5/T6
  • T6
  • T7

Singapore commonly used bulb shape & base is highlighted in bold font.



ALR C7/C9 LED G6G7MR11 LEDMR13MR16 LEDPAR16 LED PAR20PAR30

PAR36PAR64PAR46 PAR56 PAR64RP11R12S8T1.75T2

T2.5T3T3.25T3.25/T5T4 E11T4T4.25T5/T6T6T7

Base Types

  • E11 Mini-Can
  • E12
  • E17
  • E26 Medium
  • G4
  • G6.35
  • G5.3/GX5.3
  • G9.5/GZ9.5
  • P28s Medium Prefocus
  • R7s
  • SC Bayonet BA15s
  • DC Bayonet BA15d
  • SC Midget Flanged
  • SC Miniature Bayonet BA9s
  • Screw Terminals
  • Slip Terminals
  • Slide #5
  • Plastic Wedge
  • Wedge

Singapore commonly used bulb shape & base is highlighted in bold font.

 

E11 Mini-CanE12E17E26 MediumG4G6.35

G5.3/GX5.3G9.5/GZ9.5P28s Medium PrefocusR7sSC Bayonet BA15sDC Bayonet BA15d

SC Midget FlangedSC Miniature Bayonet BA9sScrew TerminalsSlip TerminalsSlide #5Plastic WedgeWedge

Filament Types

  • C-2F
  • C-2R
  • C-2V CC-2V
  • C-6 CC-6
  • CC-7A
  • C-8 CC-8

Singapore commonly used bulb shape & base is highlighted in bold font.

  C-2FC-2RC-2V CC-2VC-6 CC-6CC-7AC-8 CC-8

 

 

10. Others

 


 

Bulb Shapes

  • A-15
  • A-19
  • A-21
  • A-23
  • B-10 1/2
  • B-13
  • BA-9
  • BA-9 1/2
  • C-7
  • F-10
  • F-15
  • F-20
  • G-16 1/2
  • G-25
  • G-40
  • P-25
  • PS-35
  • BR-25
  • BR-30
  • BR-40
  • R-20
  • R-30
  • R-40
  • RP-11
  • S-8
  • S-11
  • S-14
  • PAR-16
  • PAR-20
  • PAR-30S
  • PAR-30L
  • PAR-36
  • PAR-38
  • PAR-64
  • PAR-84
  • T-4 1/2
  • T-5
  • T-6
  • T-8
  • T-10

Singapore commonly used bulb shape & base is highlighted in bold font.

 

Bulb Shapes

Base Sizes

  • Mini Cand Screw E11
  • Cand Screw E12
  • Intermediate E17
  • 3 Contact Med E26
  • Med Screw E26
  • Mog Screw E39
  • 3 Contact Mogul E39D
  • Mog Pf P40s
  • Med Skirt E26/50×39
  • Can DC Bay
  • Can SC Bay B15
  • 2-Lug Sleeve B22d
  • 3-Lug Sleeve B22-3
  • Med Pf P28s
  • Mogul BiPost G38
  • Screw Terminal
  • Disc Base
  • Single Contact
  • Med BiPost
  • Med Side Prong
  • Ext. Mog End Pr.
  • Mog End Prong

Singapore commonly used bulb shape & base is highlighted in bold font.

  Base Sizes

BA15s

BAU15s

BA15d

BAY15d

 

BAZ15d

BAZ15d-3

 

SBC B15d

BC B22d

Singapore commonly used bulb shape & base is highlighted in bold font.

 

BA15s BAU15s BA15d BAY15d

ba15sbau15sbay15dbaz15dbaz15d3

SBC B15d, BC B22d

MES E10

SES E14

ES E27

GES E40

Singapore commonly used bulb shape & base is highlighted in bold font.

  MES E10, SES E14, ES E27, GES E40
A-Shape   A-Shape
Chandelier   chandelier
Globe   globe
GU10   gu10
PAR30   PAR30
PAR38   PAR38
R20   R20

G4

GY6_35

  G4, GY6_35
MR16 G10   MR16 G10
MR16 G5.3   MR16 G4M16

 

   
     
     

 

 

Useful accessories for lamp installation

 

   

1) ETON Connectors

 

 




Reference:

Graphics in this webpage are re-compiled from the following website:

http://www.superiorlighting.com/Light_Bulb_Shape_and_Size_Reference_Guide_s/218.htm

http://www.ledlight.com/LED-Information.aspx

http://www.nzlightingltd.co.nz/Useful+Hints/Choosing+a+Bulb.html

http://www.customdynamics.com/bulb_identification_help.htm

http://www.homedepot.ca/webapp/wcs/stores/servlet/DisplayTemplate?storeId=10051&catalogId=10051&langId=-15&display=brand_philips

Keyword: Lamps, LED, Fluorescent, Singapore, Energy saving, Bulb shape and base


Java, commonly used coding examples

Edited by Lim Siong Boon, last dated 22-Sep-2010.

Content Summary
#JavaPrimitiveDataTypes
#JavaLanguageReferences
#JavaFundamentalReferences
#ByteManipulation
#IntegerStringManipulation
#StringManipulation
#Javastructuretogetthesingleinstanceofanobjectsingleton
#TimeDateCalendarTimer
#ArrayDataContainer
#Javadebuggingexceptionanderrorhandlingresources
#FileIOPropertiesConfigurationfile
#GetSystemorEnvironmentvariables
#Threadingprocesses
#JavaDestructorMethodShutdownHook
#ImportLoadingDLLtoJavacodeDynamicLinkLibrary
#LaunchingthedefaultapplicationbyopeningafilefromJava
#Executingaexeprogramfromthecommandpromptcommandlineinterpreter
#NetworkTCPIPcommunicationexample
#NetworkUDPcommunicationexampledatagrampacketlistening
#Multimedia
#JavaandSQL
#JavaCommandPattern
#JavaGUIProgramming
#JavaApplet
#JNIJavaNativeInterface
#MyJavaLibrary

 

Open Jar2Html.jar program.

Java Primitive Data Types
Type Contains Default Size Range
boolean true or false false 1 bit n.a.
char Unicode character unsigned \u0000 2 bytes (16 bits) \u0000 to \uFFFF or 0 to 216-1
byte Signed integer 0 1 byte (8 bits) -128 to 127 or (-27 to 27-1)
short Signed integer 0 2 bytes (16 bits) -32768 to 32767 or (-215 to 215-1)
int Signed integer 0 4 bytes (32 bits) -2147483648 to 2147483647 or (-231 to 231-1)
long Signed integer 0 8 bytes (64 bits) -9223372036854775808 to 9223372036854775807 or (-263 to 263-1)
float IEEE 754 floating point single-precision 0.0f 4 bytes (32 bits) 1.4E-45 to 3.4028235E+38
double IEEE 754 floating point double-precision 0.0 8 bytes (64 bits) 439E-324 to 1.7976931348623157E+308


Java Language References


Escape code for Java Regular Expression

http://www.wellho.net/regex/javare.html


Character Escape Codes Description
\n new line (0x0A)
\t tab (0x09)
\b backspace (0x08)
\r carriage return (0x0D)
\f form feed (0x0C)
\\ backslash
\' single quotation mark
\" double quotation mark
\?? octal
\x?? hexadecimal
\u?? unicode character
\0 0x00 null char

Java Regular Expressions   java.util.regex

My first encounter with regex happens when I was using String.split() function. The split char is represented by special char used by regex. I thought the function is easy to use but is spending a lot of time figuring why the string cannot be split. I was splitting the IP address which is separated by the '.' dot or period. My colleague drop me some notes from the website, and now I finally know what really happen. Great article I must say.

Class typically use for wild card search in String.

The following are some char keyword in used by the regular expressions class. In order to use the char, use \ followed by the char or insert the printable string between \Q and \E

metacharacters->   ([{\^-$|]})?*+.

There are more about regex than I thought after searching the web.

http://en.wikipedia.org/wiki/Regular_expression



String tx = "Delta values are labeled \"\u0394\" on the chart.";

regex example

String str = "This is a sentence. This is a question, right? Yes! It is.";
String delims = "[ .,?!]+";
String[] tokens = str.split(delims);

String str[] = result.split("HWaddr | \\. |inet addr:| \\. |Bcast:| \\. |Mask:| \\. |UP", 6);
This splits the following chunck of text into

eth0 Link encap:Ethernet HWaddr b8:27:eb:87:9e:02
inet addr:192.168.1.97 Bcast:192.168.1.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4670 errors:0 dropped:0 overruns:0 frame:0
TX packets:2034 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:526428 (514.0 KiB) TX bytes:257010 (250.9 KiB)

str[0] -> eth0 Link encap:Ethernet
str[1] -> b8:27:eb:87:9e:02
str[2] -> 192.168.1.97
str[3] -> 192.168.1.255
str[4] -> 255.255.255.0
str[5] -> BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4599 errors:0 dropped:0 overruns:0 frame:0
TX packets:1960 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:522426 (510.1 KiB) TX bytes:249420 (243.5 KiB)

 



Java Fundamental References

package sg.com.siongboon.mypackage; //Basic java class structure. Using a domain name as your package, ensures that it will likely to be a unique namespace.

public class ClassName
{
  private int myResult;

  static
  {
    //Similar to constructor which will be executed
    //before the object is created.
    //It can be use like a constructor for your static class object,
    //where a constructor is not allowed.
    //static initializer block, it is seldom used (see example on *.dll)
  } 

  public ClassName()
  { //class constructor
  }  

  public methodOne()
  { 
  }

  final public methodOne()
  { //method cannot be overriden by other class extending it
  }

  static public methodOne()
  { //method is the only instance. It will be common to all the class object
  }

  protected void finalize()
  { //method gets called when it is about to be delete by the garbage collector.
    //Should not be use as it is imposible to know when the object will get deletes.
  }

  public static void main(String args[])
  { //entry point for running this program
  }
}

This is an example of a typical Java coding structure and some Java naming convention for package, class, method, and variable.

//A simple illustration of Java access modifier, Private, Default, Protected, Public

java access modifier

Java access modifier:

public- Variables/methods using public modifier can be access easily by all objects.

protected- Protected members can be accessed by another package through inheritence. Class CC managed to access protected member C through inheritence. Class CC inherited Class AA, therefore member C becomes part of Class CC.

default- If there is no modifier specified, Java will treat it as the default modifier. Default members B gets a bit more difficult to access. Only classes within the same package can access to it. Member B using the default modifier can be access by Class BB. Class BB can creates an instance of Class AA or through static variable access to access to member B.

private- is the most restrictive modifier. The private member A can only be access within the class AA itselfs. Class AA being the creator, is able to access all it’s members A, B, C and D. It is recommended to start the data/method encapsulation using private modifier. Change the modifier when neccessary. There must be a good reason why private modifier is not use.

 

Future research the meaning on these defination:

public interface ClassName
protected interface ClassName
private interface ClassName
public void MethodName();
protected void MethodName();
private void MethodName();
abstract..

What do these defination really means?

 

//defining a common interface for objects
public interface LiftButton
{
  //define all the methods/interface in the class
  public void openLiftDoor();
  public void closeLiftDoor();
  public void pressLiftFloor(int floorLevel);
  public void alarm();
}

//Interface can extends/inherit many other interfaces.
//This is unlike abstract where only one class can be extend.
public interface LiftButton extends otherInterface, otherInterface2, otherInterface3
{
  //define all the methods/interface in the class
  public void openLiftDoor();
  public void closeLiftDoor();
  public void pressLiftFloor(int floorLevel);
  public void alarm();
}


//Object class implementing the interface. A class can implement many interface.
public class Lift implement LiftButton
{
}

Very often in our physical world, we share a common interface with many different type or brand of system.

Example is our elevator lift. The interface buttons are the same/similar in each brand of lift. The user need not require training in order to use the lift, because the operating procedure is the same as what the user has used before.

The same goes for our computer system. Each computer may be run by various brand/model of CPU/hardware/OS, but the keyboard/mouse interface remains the same.

Defining an interface helps us to define a common standard, such that when it comes a day where we need to swap an object (change CPU model), we can easily change it with minimal or without any effect on the system.

It is mentioned by Jim Waldo, in his book “Java The Good Parts”, that passing parameters through the method is evetually going to be of some sort of interface. You can pass parameters using object, but later down the road, there is a high chance that it will be later change to an interface as the coding grows comre sophisticated.

//defining an abstract class. Methods that do not has a body/codes will have to be abstract.
//Abstract methods are like interfaces.

public abstract class LiftButton
{
  abstract public void openLiftDoor();
 
abstract public void closeLiftDoor();
  //if any method is abstract, the class must be an abstract.

  public void pressLiftFloor(int floorLevel)
  {
    //codes that will be shared among those classes who inherit this abstract class.
  }
  public void alarm();
}

//An object class can only inherit/extends one abstract class.
public class MetalLiftButton extends LiftButton
{
}


When to use abstract class and when to use interface?

Use abstract clases and inheritance if you can make the statement “A is a B”.
Use interfaces if you can make the statement “A is capable of [doing] as”, or also, abstract for what a class is, interface for what a class can do.
For example, we can say a triangle is a polygon but it makes no sense to say a triangle is capable of being a polygon.
The design class could be a combination of abstract and interface. You will need to sort out the methods and variable belonging to the abstract class, and those who belongs to the interface.

Consider using abstract classes if any of these statements apply to your situation.
1) You have a common denominator codes that you want to share among several closely related classes (in a hierarchy). Share state or functionality.
2) Many classes that extend your abstract class have many common methods or variable, or you need to hide (private) from those classes
3) ???You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

Consider using interfaces if any of these statements apply to your situation.
1) You expect that unrelated classes would implement your interface.
2) You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
3) You want to take advantage of multiple inheritance of type.

   
Byte Manipulation  

//Java do not have unsigned data type
//Representation of the unsigned for a signed data type.
byte temp;
int result;
result=(int)(temp[0]&0xFF);  
//extract the unsigned value

long longNum = 289637082704667748;   //The literal 289637082704667748 of type int is out of range

long longNum = 289637082704667748L; //if the literal value is too big, L is required at the back

int result=(int)((1.26)+0.5);         //rounding off to the nearest integer



//'f' indicates that 1.5 is of data type float rather than a double.
//(any literal is intepreted as a double and not a float)
float x = 1.5f ;  
double x = 1.5;

//'l' indicates that 10000000000 is of data type long rather than a int .
//(any literal is intepreted as a int and not a long )
int x = 15 ;  
long x = 10000000000l;


//Casting a numeric value to a char
char c3 = (char)87;
char c1 = '\u0057';


//declare & allocate memory for byte & char array
byte remoteIP[] = new byte[4];
byte[] dataByte = new byte[]{(byte) 0xDB, (byte) 0xA1};
char[] dataBuf = new char[100];//declare & allocate memory for byte

//converting a byte array for string use

String dataStr = new String(dataByte,"ISO-8859-1");
//converting back to byte array after String manipulation

byte[] dataByte = dataStr.getBytes("ISO-8859-1"));

//Earlier method. (ineffective)
//Please note that byte data maybe lost after converting to string using this method.  
//The conversion uses a default charsetName; 
//if charset is not able to map the data to a char, it could convert it to the data 0x3F.
//In some case, a char 0xC2 may be inserted before a char which is > 0x7F.
String dataStr = new String(dataByte);
String dataStr = new String(dataByte,"US-ASCII");

//converting a string to byte[]
byte[] dataByte = dataStr.getBytes();
//converting a byte to char for string use (convert a byte to char)
char dataChar = (char) 0xDB;
//converting a byte to string for string use (convert a byte to String)
String str = String.valueOf((char)ch);

//more methods for dealing with bytes 
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
byteBuffer.put(0x01);


for information about charset encoding.

http://www.anyang-window.com.cn/tag/java-encoding/page/3/

 

byte[] dataByte = new byte[]{(byte) 0x01, (byte) 0xA1};
ByteBuffer wrapped = ByteBuffer.wrap(dataByte); // convert 0x01A1 to 417
short num = wrapped.getShort();                 // integer result = 417

byte[] dataByte = new byte[]{(byte) 0xD1, (byte) 0xA1};
ByteBuffer wrapped = ByteBuffer.wrap(dataByte); // convert 0xD1A1 to -11871
short num = wrapped.getShort();                 //
integer result = -11871
Convert 2 bytes array to integer
int hex = Integer.parseInt(HexString, 16);
String str = Integer.toHexString(79);
byte b = (byte) Integer.parseInt("192");

String str = Integer.toBinaryString(79);
//parse hex string. HexString="FFFF", result-> hex=65535
//convert number 79 to a hex string "4f"
//convert the string "192" into a byte 0xC0
//convert number 79 to a binary string "01111001"
//defining byte constant array
private static final byte[] MYCONSTANT = {0x04, 0x04, (byte)0xFF, 0x64};
//static means that there is only one instance for the variable
//final means that the variable cannot be overriden


//Bitwise Operator
>>>   //right shift without preserving the sign bit
>>    //right shift preserving the sign bit

<<    //left shift preserving the sign bit


   
Integer String Manipulation

int num = Integer.parseInt(String);
int hex = Integer.parseInt(HexString, 16);
String str = Integer.toString(79);
String str = Integer.toBinaryString(79);
String str = Integer.toHexString(79);
byte b = (byte) Integer.parseInt("192");
//Example: Convert from string to numerical value
//parse hex string. HexString="FFFF", result-> hex=65535
//convert number 79 to a string "79"
//convert number 79 to a binary string "01111001"
//convert number 79 to a hex string "4f"
//convert the string "192" into a byte 0xC0
   
String Manipulation  
String str = "Hello";             //correct proper way
String str = new String("Hello"); //creating unneccessary String object again. Waste CPU process.

//inserting octal or hex char into a string
String string = "hello\r\n"
String octal_String = "\150\145\154\154\157\015\012";      //same as "hello\r\n" 
String hex_String = "\u0068\u0065\u006c\u006c\u006f\r\n";    //same as "hello\r\n" (\u000d\u000a don't work) 


String str = "abc]123]XYZ";
String str2 = "abc|123";
String strAr[];
//split str "abc]123]XYZ" into 3 sub-string
//strAr[0]=="abc", strAr[1]=="123", strAr[1]=="XYZ"
strAr = str.split("]",3);
//split str1 into 2 sub-string
//strAr[0]=="abc", strAr[1]=="123"
strAr = str2.split("\\|");


s = s.replaceAll("\\s","");      //remove invisible \r \n char
s = s.trim();                    //remove white space

Removing invisible \r \n char and white space.
//compare & match string
String str = "This is my String."
boolean b = str.matches(regex);
int i = str.compareTo("my");
 
 

//formatting a string like printf or sprintf
String str = String.format("Number=%2d, %f", 5, 1.56); //result>"Number= 5, 1.56"

String str = String.format("Leading Zero=%04d", 5); //result>"Leading Zero=0005"
String str = String.format("Hex value=0x%04x", 79 ); //result>"Hex value=0x004F"

String formatter
Leading or padded zero
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
String strDecimalFormat formatV = new DecimalFormat("#.##");
String str = String str = formatV.format(1.246f); //result>"1.25"
special numerical formatting

DecimalFormat formatV = new DecimalFormat("###0.00");    //floating value to 2 decimal place
String str = String.format("%6s",formatV.format(value)); //right align
//value =  0.91, result -> "  0.91"
//value = 21.91, result -> " 21.91"
//value = 12   , result -> " 12.00"

//rounding off float double value to 2 decimal place
float unround = (float) 0.34456;
double roundOff = Math.round(unround*100)/100D;    //rounding off to 2 decimal place
logger.info((float)roundOff);                      //result = 0.34
    
float unround = (float) 0.34556;
double roundOff = Math.round(unround*100)/100D;    //rounding off to 2 decimal place
logger.info((float)roundOff);               

//convert a float or double to a more precision BigDecimal
BigDecimal precision = new BigDecimal(0.34556);    //try not to use a double or float converting to a BigDecimal. It will result in additional trailing numbers because floating number is never exact. Use String instead to be accurate.
BigDecimal precision2 = new BigDecimal("0.34556");

precision = precision.setScale(2, BigDecimal.ROUND_HALF_UP)//setup BigDecimal to 2 decimal place, and round up.

precision = precision.setScale(2, BigDecimal.ROUND_HALF_EVEN);//Banker's Rounding (rounding to the even if number is in the middle 0.5 or 0.05, etc...)
//example: 0.1265 (3 decimal place) should be round to 0.126
//example: 0.12651 (3 decimal place) should be round to 0.127
//example: 0.1275 (3 decimal place) should be round to 0.128
//example: 0.1285 (3 decimal place) should be round to 0.128

//division, it is always better to specify the precision. Example, 1/3 will result in 0.333... to infinity, which will throw you an exception.
//-> java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
MathContext mc = new MathContext(32, RoundingMode.HALF_UP); 
BigDecimal c = a.divide(b, mc);    //set the division result to 32 decimal place at most.
BigDecimal c = a.divide(b, MathContext.DECIMAL32);   //same


Right align a 2 decimal place floating number.

If encounter floating point error while using a variable of float data type, try changing to the data type double or use int data type instead. If precision is absolutely necessary, use the object BigDecimal.

String subStr = Integer.toBinaryString(str.charAt(x));
res = res + inBetween + String.format("%8s", subStr).replace(' ', '0');
//convert char/int to 8 bit binary
//to check/compare the data/object type of a unknown java object
boolean x = aAnimal instanceof Fish


private enum BonjourService
{    
  //use enum if there is a fix defined number of constant
  //enum can help to restrict the number input choice for
  //the programmer to feed it into the method
        CAMERA, HTTP, PRINTER, IPP, PDL_DATASTREAM
}

private String getServiceProtocolName(BonjourService service)
{
  String servStr;
        if(service==BonjourService.CAMERA)
            servStr = "_camera._tcp";
        else if(service==BonjourService.HTTP)
            servStr = "_http._tcp";
        else if(service==BonjourService.PRINTER)
            servStr = "_printer._tcp";
        else if(service==BonjourService.IPP)
            servStr = "_ipp._tcp";
        else if(service==BonjourService.PDL_DATASTREAM)
            servStr = "_pdl-datastream";       
}

String str = "(" + BonjourService.CAMERA + ")";
String str = "(" + BonjourService.CAMERA.toString() + ")";
//str="(CAMERA)", enum variables can also be used as String object.


public enum BonjourService
{
  CAMERA("camera"),
  HTTP("http"),
  PRINTER("printer");

  //constructor cannot be public
  //constructor allows multiple parameters, so that
  //the enum can represent more than 1 parameter.
  private final String name;

  private BonjourService(String name)
  {
    this.name = name;
  }

  public String toString()
  {
    return name;
  }
}

//Iterating through each element in the enum
for(BonjourService d: BonjourService.values())
{
  System.out.println(d);
}

//Get the literal string of the enum
String name =
BonjourService.CAMERA.name();

//Get the enum from a string
BonjourService bonjourServiceEnum = BonjourService.valueOf("CAMERA");

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.
Enum constants can be iterated, which allows you to write codes to scan through the enum defined.
public enum SerialBaudrate
{
    BPS_9600(9600), BPS_19200(19200), BPS_14400(14400);

    private SerialBaudrate(int i)
    {
      this.i = i;
    }
    
    private final int i;
    public int Id()
    {
      return i;
    }
    
    //converting number to a definite enum object
    static public SerialBaudrate getBaudrate(int baud)
    {
      if(baud == SerialBaudrate.BPS_9600.Id())
        return(SerialBaudrate.BPS_9600);
      else if(baud == SerialBaudrate.BPS_19200.Id())
        return(SerialBaudrate.BPS_19200);
      else if(baud == SerialBaudrate.BPS_14400.Id())
        return(SerialBaudrate.BPS_14400);
      else
        return(null);
    }
}
implementing a static method for use to convert the old int convention to enum type object.

Toolkit.getDefaultToolkit().beep(); //error beep tone (sound, bell)

A beep sound from your system buzzer/bell.
Object obj;
obj  = null;
Java has a garbage collector mechanism, which ease programmer having to allocate and de-allocate memory like as in C and C++ language. That does not means that your Java program will not have anymemory leak issue, neither does it means that you need not have to manage memory. Any memory reference (object’s reference) that still exits in your run time memory will make your garbage collector thinks that the memory allocated is still in use. If you keep on creating such objects, and happen to leave its reference in memory somewhere in your program, the memory resources will run out sooner or later. One way to ensure that the object is no longer in use is to put a null to your object’s reference if you no longer use it. Removing the link to the object reference indicates to the garbage collector that the object is no longer in use. The gabage collector will release the memory resource on its own some time later.
long heapsize=Runtime.getRuntime().totalMemory();
long freesize=Runtime.getRuntime().freeMemory();
long maxsize=Runtime.getRuntime().maxMemory();
Checking the heap size of the java. This can helps detect
Error can occur is there is not enough heap space “java.lang.OutOfMemoryError: Java heap space”. There are profiler (JProfiler) and heap dump analysis software (Eclipse MAT tool) which can help analyse the use of memory and detect memory leak issue.
Can also use “jconsole” provided under JDK/bin directory. It will give you a view of the memory usage, thread count, classes loaded, etc.

 

Java structure to get the single instance of an object (singleton)  
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Manager
{
  protected static transient final Log logger = LogFactory.getLog(Manager.class);

  private static Manager mgr = null;

  public static Manager getInstance()
  { //object can only create once. constructor method is private
    if(mgr == null)
      mgr = new Manager();
    return(mgr);
  }

  private Manager()
  {
  }

  public static void main(String[] args)
  {
  }
}
Quick template for singleton structure.
Please refer to some explaination in the following.
AutoScheduleManager myAsm = AutoScheduleManager.getInstance();

public class 
AutoScheduleManager implements AxisObserver
{
    protected static transient final Log logger = LogFactory.getLog(PcAdminService.class);

    AutoSchedule autoSche;
    PcAdminService pcA;
       
    private static AutoScheduleManager ass = null;   
   
    public static AutoScheduleManager getInstance(PcAdminService pcA)
    { //object can only create once. constructor method is private
        if(ass == null)           
            ass = new AutoScheduleManager(pcA);
        return(ass);
    }

    private AutoScheduleManager(PcAdminService pcA)
    {
        this.pcA = pcA;
        startScheduledShutdown(); //enable scheduled shutdown service when the service started.
    }
}

Singleton structure will ensure that the class object can only be created once. Constructor has to be defined as private while the class variable & getInstance method is static so that they can be access with the object being created.

This is the first question that I ask myself when designing a new class object even since I learned about it; whether it can be created with multiple instance or only a single static instance of the object. In some application, especially when working with hardware devices, single instance is the only proper way to built your class. It can helps you to prevent mis-written codes, resulting in less bugs/crush program when the class is used by another programmer.




Time, Date, Calendar, Timer

//Delay/sleep function
try{Thread.sleep(1000);}catch(InterruptedException e){}


//System time counting in millisecond. Measuring the cpu time to execute certain task
long sysMiliSecCount = System.currentTimeMillis( );
//do the task
long taskTime = System.currentTimeMillis( ) - sysMiliSecCount;


Instant timestamp = Instant.now();	//newer form of Timestamp method. (Java 8)
LocalDateTime timestamp2; //
LocalDate date; //immutable object. Cannot be changed once it is created (Java 8)
LocalTime time; //immutable object. Cannot be changed once it is created (Java 8)

LocalDate date = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");//formatter
String text = date.format(formatter); //format date
LocalDate parsedDate = LocalDate.parse(text, formatter); //parse date

//Timestamp string, output string "2010-03-08 14:59:30.252"
java.util.Date date= new java.util.Date();
logger.info(new Timestamp(date.getTime()));

Java 8 timestamp formatting, https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

//Calendar, Date, Time (data & formatting function)
Calendar cal;
cal = Calendar.getInstance();
int hourday = cal.get(Calendar.HOUR_OF_DAY);  //24 hour format
int hour = cal.get(Calendar.HOUR);            //12 hour format
int am_pm = cal.get(Calendar.AM_PM);          //
int minute = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int msec = cal.get(Calendar.MILLISECOND);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd (EEE)");
SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm:ss aaa");
String data = sdf.format(cal.getTime());               //Format string for date, time
String time = sdf2.format(cal.getTime());

DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
Date dataObj = df.parse("2014-02-25");                 //Parse string for date, time



//set periodic timer, Class need to implement Runnable
    Timer RFIDscanTimer = new Timer(“RFID Sort”);
    RFIDtagSort rfidTagSorting = new RFIDtagSort();
    logger.info(“Scan Period :  ” + RFIDscanPeriod);
    RFIDscanTimer.schedule(rfidTagSorting, 100, RFIDscanPeriod);
   
    private class RFIDtagSort extends TimerTask
    {
        public RFIDtagSort()
        {
        }

        @Override
        public final void run()
        { //Run function will be executed every RFIDscanPeriod interval
            logger.info(“timer routine.”);
        }
    }
Use the TimerTask for scheduling a periodic routine to execute .
//timeout implementation
int x = 0;
int timeoutSec = 3;    //set 3 seconds timeout
while(true)
{
  //stop and wait for ip & port number to be resolved           
  try{Thread.sleep(100);}catch(InterruptedException e){}
  x++;
  if(x==timeoutSec*10)
  {
    throw new TimeoutException("timeout occured");
  }
}
 
 



Array, Data Container
//ArrayList container example
ArrayList<String> a;
a.add(new String("Hello"));
Iterator<String> itr = a.iterator();
while(itr.hasNext())
{
    System.out.println(itr.next());
}

ArrayList provides insertion order. Insertion order means that is an object is inserted (added) first to the list, it will show first in the iteration process.
HashMap<Integer, Computer> map;
map.put(45,comp);
//Iterator using the HashMap's key

//Iterator<Integer> i=map.keySet().iterator();
//Iterator using the HashMap's value

Iterator<Computer> i=map.values().iterator();
while(i.hasNext())
{
    Computer c = (Computer)i.next();
    c.setSubnet(netInfo.getSubnetMaskAddr());
}

HashMap do not provide insertion order.
If unqiue key (ensure no duplication) and insertion order is needed, use LinkedHashMap collection.


Map do not allow object duplication in the key, but allow duplication in the value.
Set do not allow object duplication, ensure insertion order.
List allow duplication, ensure insertion order.
Collection
Maintain Insertion Order
Allow Duplication
Comments
ArrayList
Yes
Yes

HashMap
No
No (for Key), Yes (for Values)

LinkedHashMap Yes
No (for Key), Yes (for Values)
LinkedHashSet
Yes
No

TreeMap


Maintain order (for key). Data sorting feature. Object to be compared has to implement “Comparable”
Hashtable


is synchronized, in contrast to HashMap.

//Example: Ensure that the Array data container object is synchronized
ArrayList<objectName> myArrayList = new ArrayList();
List<objectName> mySyncList;
//Get the list that is synchronized from ArrayList

mySyncList = Collections.synchronizedList(arrayList);

//Another synchronized example for Map container
TreeMap<object1,object2> myMap = new TreeMap<object1,object2>();
Map<object1,object2> mySyncMap;
//Get the list that is synchronized from ArrayList

mySyncMap = Collections.synchronizedMap(myMap);
//Java ArrayList is NOT synchronized, meaning it is possible that any two process can access the un-sychronized data at the same time, causing runtime error. Two process may try to write data to the same memory location.

//Access the ArrayList through mySyncList object to ensure that there are no two or more simultaneously process accessing to the same ArrayList object. This is also applicable to other container objects. The mySyncList List object can be cast back to ArrayList, since it is originate from ArrayList.
String a = "string1";
String b = "string2";
String c = "string3";

ArrayList<String> list = new ArrayList<String>();
list.add(a);
list.add(b);
list.add(c);

//another short form of iterating the list
for (String temp : list)
{
  logger.info(temp);    //print out the list
}

//to delete an element in the list, use iterator object instead of the arraylist
Iterator<String> itr = list.iterator();
while(itr.hasNext())
{
    
String temp = itr.next();
    itr.remove();
    //list.remove(temp) will result in java.util.ConcurrentModificationException error
    //list object should not be access during the iteration process.
}




Java debugging, exception and error handling resources

New log4j2
Library Jar file needed for log4j2
– log4j-api-2.6.1.jar
– log4j-core-2.6.1.jar
– log4j-jcl-2.6.1.jar (for common logger use)
– log4j2.xml

log4j
Example: FactoryLog for logging info, error, debug, etc messages.

Similar to System.out.println();

Save to project folder /lib /lib (factory logger).zip

Save to project folder /resource /resource (factory logger).zip

(Details of log file setup can be found in the file “log4j.properties”.

Includes a 2nd example to config Log4j for logging in Tomcat.)

Log4j references:
http://logging.apache.org/log4j/1.2/manual.html
http://juliusdavies.ca/logging.html
http://www.laliluna.de/articles/log4j-tutorial.html


***new changes to org.apache.log4j.DailyRollingFileAppender
log4j.appender.WeightSensorLog.DatePattern=’.’yyyy-MM-dd-a

//Using LogFactory for debugging & logging example.
//Remember to include the path to "lib" & "resources" in the classpath
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

protected static transient final Log logger = LogFactory.getLog(ClassName.class);

logger.error("");
if(logger.isDebugEnabled())
    logger.debug("Class name:<" + getClass().getSimpleName() + ">");
logger.info("Class name:<" + this.getClass().getName() + ">");  //print out the class name

//print out the method name
logger.info("Method name:<" + new Exception().getStackTrace()[0].getMethodName() + ">");
logger.info("Method name:<" + Thread.currentThread().getStackTrace()[1].getMethodName() + ">");

How to add *.jar library?Encountered the following errors?log4j:WARN No appenders could be found for logger (javax.swing.JApplet).
log4j:WARN Please initialize the log4j system properly.
Remember to add in the libraries in your project classpath. For Eclipse IDE the classpath is indicated in the .classpath in the project root directory.Alternative you can add the lib as follows in Eclipse:1) Right click on your project name (under “Package Explorer”) and click “Properties” 2) Select “Java Build Path”, and choose tab “Source”. Add the folders “lib” & “resource” under your project folder. 3) Choose tab “Libraries”. Click “Add JARS…” and add the “commons-logging-1.1.jar” & “log4j-1.2.14” library files. 4) Done.

//A method to log seperately to two log file from a class
protected static transient final Log logger = LogFactory.getLog(ClassName.class);
protected static transient final Log loggerSpecial = LogFactory.getLog("LogAppenderName");
logger.info("Usual logging to the appender");
logger.infoSpecial("This log will be pushed to the appender name (LogAppenderName).");
How is the log4j.properties file looks like. The appender name can be anything. In this example, it is “LogAppenderName“.

log4j.logger.LogAppenderName=INFO,OrderLog
log4j.additivity.OrderServer=false
log4j.appender.OrderLog = org.apache.log4j.DailyRollingFileAppender
log4j.appender.OrderLog.File=${log.dir}/1-Order/Order

//Two examples to print out error messages:
e.printStackTrace();
System.out.println("Got an IOException: " + e.getMessage());

logger.error("Got an IOException: ", e);


public KnxSession() throws KnxCommException
{
    try
    {
        int port = getLocalSessionPort();
        udp = new DatagramSocket(port);
        logger.info("\t\topened UDP port: " + port + " (for session)");
    }
    catch(SocketException e)
    {
        logger.error("error while calling setupUdpService()",e);
        //catching a system exeception, and create our own customised exception
        //(error messages) into meaningful message, which will be thrown up again.
        throw new KnxCommException("error message");
    }
    finally
    {
        //"finally" section will be executed with or without exception occurred.
        //Contain codes that has to be executed even after an exception is caught.
        //It is usually used for cleaning up the situation,
        //releasing or closing any resources (example file, network or databse connection.
    }
}
Must read.
Top 20 Java Exception Handling Best Practices
http://howtodoinjava.com/best-practices/java-exception-handling-best-practices/#1
public class MyOwnException extends Exception
{
    public MyOwnException(String msg)
    {
        super(msg);
    }

    public MyOwnException(String msg, Throwable t)
    {
        super(msg, t);
    }
}
 
A simple exception class, that accept customised error messages.
//KnxCommExeception Class
package knxEib.knxException;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class KnxCommException extends Exception
{
    protected static transient final Log logger = LogFactory.getLog(KnxCommException.class);

    static private int errorCounter = 0;

    public KnxCommException(String msg)
    {
        super(msg);
        errorCounter++;
        printErrorCount();
    }

    public KnxCommException(String msg, Throwable t)
    {
        super(msg, t);
        errorCounter++;
        printErrorCount();
    }

    private int printErrorCount()
    {
        logger.error("exception history count : " + errorCounter);
        try
        {
            String filename = "resource\\" + getClass().getName() + ".txt";
            BufferedWriter out = new BufferedWriter(new FileWriter(filename));
            out.write(filename + "\r\n");
            out.write("Error Count = " + errorCounter + "\r\n");
            out.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return(errorCounter);
    }
}

A complex exception class that has more functions.



File I/O, Properties/Configuration file

Example: File Write

 

String filename = getClass().getName()+".txt";
try
{
    BufferedWriter out = new BufferedWriter(new FileWriter(filename));
    out.write(previousSessionID);
    out.write("\r\n");
    out.write("Session ID = " + previousSessionID + "\r\n");
    out.close();
}
catch(IOException e)
{
    e.printStackTrace();
}

//Example 2 writing to file
String content = "ABCD\n" + "EFG";
File file = new File("resource/");
try
{
    Files.write(file.toPath(), content.getBytes());
}
catch(IOException e)
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

BufferedReader in = null;
String filename = "resource\\output_mac2ip.txt";

try
{
    FileReader file = new FileReader(filename); // Open the file.
    in = new BufferedReader(file); // Tie 'input' to this file.
}
catch(FileNotFoundException x)
{ // The file may not exist.
    logger.error("File not found: " + filename);
    System.exit(2);
}

String linetext;
while( (linetext = in.readLine()) != null )
{
}

Very often to specify a file path using a string, we need to use double slashes instead of only one in Java string.

C:\\Users\\Harald\\Folder1\\Version1\\Folder2.

This is because a slash ‘\’ is a escape char in a string. In order to indicate a ‘\’ intention, we need to put 2 slashes. This means that it will be quite odd to a typical computer user as we usually uses only one slash.

One method is to use back slash instead of forward slash. The file object classes will automatically treat ‘/’ back slash as the normal ‘\’ slash in Window OS.

Old was of specifiying the path,

processDirectory=”D:\\doc\\Expenses Invoice”

A solution of specifying the path,

processDirectory=”D:/doc/Expenses Invoice”

This solution, means that the user need not specify double slash, which can be quite confusing.

Path fileToMovePath = f.toPath();
Path targetPath = sentFolder.toPath();                         
try
{
    Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
    logger.info("move file<" + f.getName() + "> to \"" + sentFolder + "\"");                   
}
catch(IOException e)
{
    logger.error("fails to move file<" + f.getName() + "> to \"" + sentFolder + "\"");                   
    e.printStackTrace();
}
(new Java7, 2016-05-31) copy file, move file.
Filename manipulation using Path.
Change folder name while the file name remains.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

File file;
Path source = file.toPath();
file = source.resolveSibling("newFilename").toFile();

Rename a file name without changing the directory. (change file name)
Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()),
StandardCopyOption.REPLACE_EXISTING);
Files.copy(source, newdir.resolve(source.getFileName()), StandardCopyOptionREPLACE_EXISTING);
Change the directory path without changing the file name. (change directory path)
file move
file copy
File dir = new File(“dir1/dir2/dir3/abc.txt”);
logger.info(dir.getParent());                           //get the File’s directory and prints out “dir1/dir2/dir3”
logger.info(dir.getParent()+File.separator);    //prints out path appended with the seperator “dir1/dir2/dir3/”
logger.info(File.pathSeparator);                     //prints out pathSeparator “;”
Get File directory. Get directory.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Test implements Serializable
{
  //A static ID number to identify this object
  private static final long serialVersionUID = 1L;
  
  private int a;
  private int b;

  public Test(int a, int b)
  {
    this.a = a;
    this.b = b;
  }
  
  public void print()
  {
    System.out.print("data a=" + a + ", b=" + b);
  }
  
  public static void main(String args[])
  { //entry point for running this program
    System.out.print("File read/write file location.\n");
    
    String fileName = "myObjFile.abc";
    String fileRoot = System.getProperty("user.dir");
    String fileDir = File.separator + "logFile" + File.separator;
    System.out.print("user.dir= \"" + fileRoot + "\"\n");
    File f = new File(fileRoot + fileDir + fileName);
    
    Test t = new Test(1, 2);
    
    try
    {
      if(!f.exists())
      {
        System.out.print("File not found." + "\n");
        try
        {
          //creting a new file
          f.createNewFile();
        }
        catch(IOException e)
        {
          //path directory not found
          System.out.print("Path not found, path= \"" + fileRoot + fileDir + "\"\n");
          System.out.print("Create new path, path= \"" + fileRoot + fileDir + "\"\n");
          f.getParentFile().mkdir();
          f.createNewFile();  //create the file again
        }
        System.out.print("Created a new file \"" + f.getName() + "\"\n");
      }
      else
      {
        System.out.print("File exist. file=" + f.getAbsolutePath() + "\n");
      }
      
      //write the object to a file
      //can also be use to find out the path that the file will be read
      ObjectOutputStream writeOut = new ObjectOutputStream(new FileOutputStream(f));
      writeOut.writeObject(t);
      
      //read the object back from the file.
      ObjectInputStream readIn = new ObjectInputStream(new FileInputStream(f));
      Test x = (Test) readIn.readObject();
      x.print();
    }
    catch(FileNotFoundException e)
    {
      // TODO Auto-generated catch block      
      e.printStackTrace();
    }
    catch(ClassNotFoundException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch(IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Writing an class object into a file, and reading the class obj back from the file. This acts as a means to permanently save the state or values store in the object that you have created.

There are also codes written to generate files, so that you can detect where your config files are stored in the user or project directory.



//monitoring new files added or removed from the file directory

import java.io.*;
import java.util.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DirMonitor
{
  protected static transient final Log logger = LogFactory.getLog(DirMonitor.class);

  private File dir;
  private Vector<File> filesVector = new Vector<File>();

  public DirMonitor(File dir)
  {
    this.dir = dir;
    MonitorTask task = new MonitorTask();
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(task, 0, 1000);
  }

  private class MonitorTask extends TimerTask
  {
    public void run()
    {
      /* get file list for this pass */
      File[] filesArray = dir.listFiles();
      Vector<File> newVector = new Vector<File>(filesArray.length);
      Collections.addAll(newVector, filesArray);

      /* copy the previous results */
      Vector<File> copyVector = new Vector<File>(filesVector.size());
      copyVector.addAll(filesVector);

      /* find out what files were removed */
      copyVector.removeAll(newVector);
      for(File file:copyVector)
      {
        System.out.println("Deleted file: " + file.getAbsolutePath());
        filesVector.remove(file);
      }

      /* find out what files were added */
      newVector.removeAll(filesVector);
      for(File file:newVector)
      {
        System.out.println("Added file: " + file.getAbsolutePath());
        filesVector.add(file);
      }
    }
  }

  public static void main(String[] args)
  {
    //new DirMonitor(new File(System.getProperty("user.home")));
    new DirMonitor(new File("C:\\Documents and Settings\\Administrator\\Desktop\\onOne software photos"));
  }
}
 

This class monitor new files added or removed from the directory. The class extends TimerTask which execute the run process every seconds.

Check out below (WatchService class) for newer methods of monitoring files and directory.

Detect file modification.pdf  
  protected void runProcess()
  {
    //setup for monitoring the file change
    WatchService watchService = null;
    Path monPath = null;
    try
    {
      monPath = skyXFile.getParent();    //extract the directory containing the file
      watchService = FileSystems.getDefault().newWatchService();
      monPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
    }
    catch(IOException e)
    {
      logger.error("Error setting up file watch service.", e);
    }
    
    logger.info("start monitoring the directory: \"" + monPath.toString() + "\"");

    //monitoring file change
    while((!isStopRequested()))
    {
      synProcess(); //thread will be blocked here if there is a request to hold the thread.

      try
      {
        key = watchService.take();    //blocking function waiting for file change
      }
      catch(InterruptedException e)
      {
        logger.error("Error in file watch service.", e);
      }  
      
      //get list of events for the watch key
      for(WatchEvent<?> watchEvent:key.pollEvents())
      {

        //get the filename for the event
        @SuppressWarnings("unchecked")
        final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;
        final Path filename = ev.context();

        //get the kind of event (create, modify, delete)
        final Kind<?> kind = watchEvent.kind();

        //print it out
        logger.info("file event detected <" + kind + "> from file <" + filename + ">");

        if(skyXFile.getFileName().equals(filename))
        {
          TelescopePosition tp = new TelescopePosition(skyXFile, skyX_charset);  //create a new TelescopePosition object
          telescopePositionEvent(tp);      //throw this to the event.
        }        
      }

      //reset the key
      boolean valid = key.reset();

      //exit loop if the key is not valid
      //e.g. if the directory was deleted
      if(!valid)
      {
        break;
      }
    }
    
    logger.info("stop monitoring file: \"" + skyXFile.getFileName() + "\"");
  }
Using the new WatchService class from Java7 to monitor files and directory.

 

//Reading a data stream with non-blocking mode 
private OutputStream out = null;
private InputStream in = null;
out = new DataOutputStream(sp.getOutputStream());
in = new DataInputStream(sp.getInputStream());
byte byteRead = in.read(); // -1 if there is no data 

Non-blocking mode is easy to write. I found it difficult when I learn that doing non-blocking input reading is so difficult using Java. I finally got the code to do the non-blocking reading of the input. Most Java examples that I saw were using blocking mode for their inputs. I think blocking mode would be better for long term maintenence. You might need to write extra thread just to handle those inputs under blocking mode; it may be more organised.
//convert String into InputStream
String str = "This is a String to be converted to an InputStream object later";
InputStream is = new ByteArrayInputStream(str.getBytes());
 
 
//reading input from a keyboard
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
while((line = br.readLine()) != null)
{
  logger.info(line);
}
 
Reading from a keyboard is similar to reading from a data stream. Infact data reading is always in the form of stream.
try
{
  int a;
  System.in.read(bArray);
  String s = new String(bArray);
  //put to website
  s = s.replaceAll("\\s","");      //remove invisible \r \n char
  s = s.trim();                    //remove white space
  logger.info("-><" + s + ">");
  
  if(s.toLowerCase().compareTo("exit")==0)
  {
    logger.info("Exit command accepted");
  }
}
catch(IOException e)
{
  e.printStackTrace();
}
Another method to get your user data from keyboard. It is just like the scanf (a blocking function) that we have in C/C++ programming. The code scan for input that the user key in from the shell console.

//reading the int data stream from a binary file
import java.io.*;
import java.util.*;

public class BinOutputFileApp
{
  public static void main(String arg[])
  {
    try
    {
      FileInputStream fis = new FileInputStream("binary.dat");
      DataInputStream in = new DataInputStream(new BufferedInputStream(fis));
      int a = in.readInt();
      int b = in.readInt();
      System.out.println(a); //print int "42"
      System.out.println(b); //print int "45"
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }

Project example: reading_int_datastream.zipExample of the data in the binary.dat file:0x00 0x00 0x00 0x2A 0x00 0x00 0x00 0x2DActual int content represented in the binary file above:42 45

 

InputStream is = null;
try
{
  is = new FileInputStream("resource/idkeydata.xml");
}
catch(FileNotFoundException e1)
{
  e1.printStackTrace();
}

Open an inputstream from a file in the resource folder.

Other very good reference:- http://www3.ntu.edu.sg/home/ehchua/programming/java/J5b_IO.html (very good NTU website on data stream by Chua Hock Chuan),

Java Input & Output Stream (by Chua Hock Chuan).pdf

 

 

//Example of reading configuration from a property file.
private void loadNetworkConfig()
{
    String filename = "/config.properties";
    InputStream is = getClass.getClassLoader().getResourceAsStream(filename);
    Properties myProperty = new Properties();

    try
    {
        myProperty.load(is);
        is.close();
    }
    catch (IOException ioe)
    {   //ensure that the file is in the classpath");
        logger.error("Error reading the properties file.");       
        System.exit(1);
    }

    String str;
    Int x;
    str = myProperty.getProperty("IP", null);
    x = myProperty.getProperty("PORT", null);
}


Note: There is another better generic methods to read *.properties. Read more about “Apache Common configuration”. Commons Configuration provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources. Commons Configuration provides typed access to single, and multi-valued configuration parameters.

Note:
Class loader resources are often read-only; i.e. held in read-only files / read-only directories.
ClassLoader cl = getClass().getClassLoader();
Unable to obtain classloader using a static class.

Use Java Preferences API instead for configurable preferences.

//Various method of loading file/resources
//The java code should obtain the resource using getClassloader() as the standard
//loading file that is located in the directory as specified in the classpath
InputStream is = getClass.getClassLoader().getResourceAsStream("file.txt");

//same as above (another way of writing the code)
InputStream is = getClass.getResourceAsStream("/file.txt");

//loading file that is located in the same directory as the *class file
//looking for file in the current class package
InputStream is = getClass.getResourceAsStream("file.txt");


More notes about getResource()

from
http://stackoverflow.com/questions/3209901/absolute-path-of-projects-folder-in-

You should really be using getResource() or getResourceAsStream() using your class loader for this sort of thing. In particular, these methods use your ClassLoader to determine the search context for resources within your project.

Specify something like getClass().getResource(“lib/txtfile.txt”) in order to pick up the text file.

To clarify: instead of thinking about how to get the path of the resource you ought to be thinking about getting the resource — in this case a file in a directory somewhere (possibly inside your JAR). It’s not necessary to know some absolute path in this case, only some URL to get at the file, and the ClassLoader will return this URL for you. If you want to open a stream to the file you can do this directly without messing around with a URL using getResourceAsStream.

The resources you’re trying to access through the ClassLoader need to be on the Class-Path (configured in the Manifest of your JAR file). This is critical! The ClassLoader uses the Class-Path to find the resources, so if you don’t provide enough context in the Class-Path it won’t be able to find anything. If you add . the ClassLoader should resolve anything inside or outside of the JAR depending on how you refer to the resource, though you can certainly be more specific.

Referring to the resource prefixed with a . will cause the ClassLoader to also look for files outside of the JAR, while not prefixing the resource path with a period will direct the ClassLoader to look only inside the JAR file.

That means if you have some file inside the JAR in a directory lib with name foo.txt and you want to get the resource then you’d run getResource(“lib/foo.txt”);

If the same resource were outside the JAR you’d run getResource(“./lib/foo.txt”);

//inside the file config.properties
IP=192.168.1.1
PORT=1234



Properties prop = new Properties();

try
{
  //set the properties value
  prop.setProperty("database", "localhost");
  prop.setProperty("dbuser", "mkyong");
  prop.setProperty("dbpassword", "password");

  //save properties to project root folder
  prop.store(new FileOutputStream("resource/config.properties"), null);
}

catch (IOException ex)
{
  ex.printStackTrace();
}
 

Create a property file, with its key and value data pair.

 


OMElement xml = null;
try
{
  xml = AXIOMUtil.stringToOM(data);
}
catch(XMLStreamException e)
{
  throw new XmlDataFormatException("XMLStreamException() occured.");
}
catch (DeferredParsingException e)
{
  throw new XmlDataFormatException("DeferredParsingException() occured.");
}
catch(Exception e)
{
  throw new XmlDataFormatException("Unknown Exception occured parsing data for XML format.");
}


OMElement typeTag = xml.getFirstElement();       

OMElement typeTag = xml.getFirstChildWithName(new QName("tagName"));  

String namespace = xml.getNamespaceURI();
OMElement typeTag = xml.getFirstChildWithName(new QName(namespace, "tagName"));
XML string/file decoder, emcoder
Using
– axiom-api-1.2.18.jar
– axiom-dom-1.2.18.jar
– axiom-impl-1.2.18.jar


//Writing or printing to PDF file.

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.util.PDFMergerUtility;

public class Test
{
  protected static transient final Log logger = LogFactory.getLog(Test.class);

  /**
   * create the second sample document from the PDF file format specification.
   * 
   * @param file
   *            The file to write the PDF to.
   * @param message
   *            The message to write in the file.
   * @param fontfile
   *            The ttf-font file.
   * 
   * @throws IOException
   *             If there is an error writing the data.
   * @throws COSVisitorException
   *             If there is an error writing the PDF.
   */
  public void doIt(final String file, final String message) throws IOException, COSVisitorException
  {
    // the document
    PDDocument doc = null;
    try
    {
      doc = new PDDocument();

      PDPage page = new PDPage();
      doc.addPage(page);
      PDFont font = PDType1Font.HELVETICA_BOLD;

      PDPageContentStream contentStream = new PDPageContentStream(doc, page);
      contentStream.beginText();
      contentStream.setFont(font, 12);
      contentStream.moveTextPositionByAmount(100, 700);
      contentStream.drawString(message);
      contentStream.endText();
      contentStream.close();

      doc.save(file);

      System.out.println(file + " created!");
    }
    finally
    {
      if(doc != null)
      {
        doc.close();
      }
    }
  }

  /**
   * This will create a hello world PDF document with a ttf-font. <br />
   * see usage() for commandline
   * @param args
   *            Command line arguments.
   */
  public static void main(String[] args)
  {
    Test app = new Test();
    Test app2 = new Test();
    try
    {
      app.doIt("D:/here.pdf", "hello");
      app2.doIt("D:/here2.pdf", "helloagain");
      PDFMergerUtility merger = new PDFMergerUtility();
      merger.addSource("D:/here.pdf");
      merger.addSource("D:/here2.pdf");
      OutputStream bout2 = new BufferedOutputStream(new FileOutputStream("D:/hereisthefinal.pdf"));

      merger.setDestinationStream(bout2);
      merger.mergeDocuments();
    }
    catch(COSVisitorException e)
    {
      e.printStackTrace();
    }
    catch(IOException e)
    {
      e.printStackTrace();
    }
  }
}

Using PDFBox.

Download library pdfbox-app-2.0.0.jar


//Example of using Java to read excel *.xls or calc *.ods file

import org.jopendocument.dom.spreadsheet.MutableCell;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;

//Getting the 0th sheet for manipulation| pass sheet name as string
spreadSheet = SpreadSheet.createFromFile(file).getSheet(0);
          
//Get row count and column count
int nColCount = spreadSheet.getColumnCount();
int nRowCount = spreadSheet.getRowCount();

System.out.println("Rows :" + nRowCount);
System.out.println("Cols :" + nColCount);
//Iterating through each row of the selected sheet
MutableCell cell = null;
for(int nRowIndex = 0;nRowIndex < nRowCount;nRowIndex++)
{
    //Iterating through each column
    int nColIndex = 0;
    for(;nColIndex < nColCount;nColIndex++)
    {
      cell = spreadSheet.getCellAt(nColIndex, nRowIndex);
      System.out.print(cell.getValue() + " ");
    }
    System.out.println();
}


 

//Example of using Java to write excel *.xls or calc *.ods file

final Object[][] data = new Object[6][2];
data[0] = new Object[] { "January", 1 };
data[1] = new Object[] { "February", 3 };
data[2] = new Object[] { "March", 8 };
data[3] = new Object[] { "April", 10 };
data[4] = new Object[] { "May", 15 };
data[5] = new Object[] { "June", 18 };

String[] columns = new String[] { "Month", "Temp" };

TableModel model = new DefaultTableModel(data, columns);

// Save the data to an ODS file and open it.
final File file = new File("records.ods");
try
{
  SpreadSheet.createEmpty(model).saveAs(file);
  OOUtils.open(file);    //open the spreadsheet
}
catch(FileNotFoundException e)
{
  logger.error(e);
  logger.error("Ensure that the file \"" + file + "\" is not in use by other process.");
}
catch(IOException e)
{
  logger.error("I/O error.", e);
}
 



package testProcess;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/* *
 * The following example provide a means to detect the processes or services currently running in Windows
 * To view the list of processes currently running on your Windows Operating System,
 * Key in "Ctrl"+"Alt"+"Del", then click on "Start Task Manager", then click on the tab "Processes"
 * This is the list of processes that can be detected by the following java program.
 */

public class Main
{
  protected static transient final Log logger = LogFactory.getLog(Main.class);

  public static void main(String[] args) throws Exception
  {
    String processName = "firefox.exe";
    boolean status = isProcessRunning(processName);
    logger.info("The process <" + processName + "> is " + (status?"currently running.":"cannot be found."));    
  }

  public static List<String> getCurProcessTaskList()
  {
    List<String> processes = new ArrayList<String>();
    try
    {
      String line;
      Process p = Runtime.getRuntime().exec("tasklist.exe /fo csv /nh");
      //Alternative sorted result   -> Process p = Runtime.getRuntime().exec("tasklist.exe /FO LIST");
      //Alternative unsorted result -> Process p = Runtime.getRuntime().exec("tasklist.exe");
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      while((line = input.readLine()) != null)
      {
        if(!line.trim().equals(""))
        {
          // keep only the process name
          line = line.substring(1);
          processes.add(line.substring(0, line.indexOf("\"")));
        }
      }
      input.close();
    }
    catch(Exception err)
    {
      logger.error("Error encountered in getCurProcessTaskList().",err);
    }
    return processes;
  }

  public static boolean isProcessRunning(String serviceName) throws Exception
  {
    //grab the list of the current processes, services running in the Windows.
    List<String> processes = getCurProcessTaskList();

    //check if the required service is in the list 
    Iterator<String> it = processes.iterator();
    int i = 0;
    while(it.hasNext())
    {
      String s = it.next();
      //display all the processes currently running in the system now
      //logger.info(s);
      if(serviceName.compareTo(s) == 0)
      {
        return(true);
      }
    }
    return(false);
  }
}

This example shows how you can use java to detect the processes running under the Windows Operating System. It can a mean to detect if another Windows application or service or task is currently running.

If can even list out all the currently running processes.

 

 

Get System or Environment variables  
String system_variable = System.getProperty("user.name");
//system_variable == "Administrator" 

//Enumerating through System Properties, prints out all the available keys & the corresponding values
Properties p = System.getProperties();
Enumeration e = p.propertyNames();
while (e.hasMoreElements())
{
  String key = (String)e.nextElement();
  System.out.prinln(key + " = " + p.getProperty(key));
}


The string user.name is the string key required to retrieve the system variables string. The following list present the other possible system variable that you can retrieve from System.getProperty(keyString);

Name String Example string result
“user.name” “Administrator”
“user.home” “C:\Documents and Settings\Administrator”
“user.dir” “E:\java projects\DslrCameraBonjour”
“os.name” “Windows XP”
“os.arch” “x86”
“os.version”  
“file.separator” “\”
“path.separator” “;”
“line.separator”  
“java.vendor” “Sun Microsystems Inc.”
“java.runtime.name” “Java(TM) SE Runtime Environment”
“java.version” “1.6.0_18”
“java.home” “C:\Program Files\Java\jdk1.6.0_18\jre”
“java.library.path” “C:\Program Files\Java\jdk1.6.0….. . . . ”
“java.vendor.url” “http://www.sun.com/”
“java.class.version” “45.3”
“java.class.path”  
“user.language” “en”
“java.vendor.url.bug” “http://java.sun.com/cgi-bin/bugreport…”
“file.encoding” “8859_1”
“user.timezone” “CST”

 

Add your own variables to the java environment system variables.

java YourProgram -D keyString=”mystring”.


example:
java myJavaProgram -D sg.myhomedir=”E:\myJaveProjects\”

You can also customised your java system variables, by adding the variable when you run the java command.
//Java code to get computer name, example "LSB-PC"
String computername = InetAddress.getLocalHost().getHostName();
 
 


import java.util.prefs.Preferences;

private void saveDirPathToRegistry(String dir)
{
   Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
   prefs.put(REGISTRY_KEY_NAME, dir);
   logger.info("Saved new directory selected \"" + dir + "\"");
}
   
private String getDirPathFromRegistry()
{
   Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
   String path = prefs.get(REGISTRY_KEY_NAME, null);
   if(path != null)
      logger.info("Detects last directory visited \"" + path + "\"");
   return(path);
}
Saving and retreiving Java application data to the operating system registry (example: Win7 registry regedit).

After running this Java program under Windows 7 (64 bits) the following error may be produced,
java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs
at root 0x80000002. Windows RegCreateKeyEx(…) returned error code 5.

The error occurs because java.util.prefs.WindowsPreferences is trying to save information in HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs instead of under HKEY_CURRENT_USER\Software\JavaSoft\Prefs.

The work around is to login as the administrator and create the following key HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

or you can use this *.inf script to install/create this key in the WindowsOS registry
Java Prefs registry setup.inf
Download this file. Right click and select “install”.
The key “HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs”
will be create in the Windows OS registry.

userRoot()
systemRoot()

Threading processes
 
//Useful code to track the number of thread running.
logger.info("Active thread count: " + Thread.activeCount());

//Threading example
public class myThreadClass extends Thread
{
  //flag to control process flow to be in syn with other critical function

  private static boolean fIsSynProcess=false;
  //object holding the reference to this thread

  private Thread thisThread = null;

  public myThreadClass()
  {
  }


  public void run()
  { //getting the thread process ID

    this.thisThread = Thread.currentThread();
    String threadName = getClass().getName() + ” : ” + this.thisThread.getName();
    logger.info(“…thread Started: ” + threadName);

    while((!isStopRequested()))
    {
        while((!isSynProcess())) 
        {
        }
    }
    logger.info(“…thread Stopped: ” + threadName);
  }

  private synchronized boolean isStopRequested()
  {
    if(thisThread==null)
      return(true);
    return(false);
  }
  
  public void requestStop()
  {
    Thread tempThread = thisThread;
    thisThread = null;
    //interrupt for used to exit from blocking function in the run() method's while loop

    if (tempThread != null)
      tempThread.interrupt();
  }

  private synchronized boolean isSynProcess()
  {
    return(fIsSynProcess);
  }

  private synchronized void holdThreadRun()    //prevent the run thread to terminate
  {
    fIsSynProcess=true;
  }

  private synchronized void releaseThreadRun()    //allow the run thread to terminate
  {
    fIsSynProcess=false;
  }
}

The coding examples on the left are the various style of using the Java threading features.


The thread example also illustrate the use of the keyword “synchronized“. The java run time will ensure that those methods which are labelled as synchronized will not be excuted in parallel. This is to prevent two or more processes to access the same variable/memory which will cause data corruption or process locked issue. A program base on threading algorithm is likely to face such problems that can be resolved by implementing “synchronized“.For more explaination on synchronized, please refer to the following,

http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

//Spinning off a new Thread process without writing inside a proper class file
Thread rescan = new Thread(new Runnable()
{
    public void run()
    {
        //ToDo: Place your code that
        //you need to run as another simultaneous process.

    }
});
rescan.start();

//Set a name for your thread, to easily track and debug it.
currentThread.setName("Processing-" + messageId);

//Another method of writing thread
Object obj = new Object();
new Thread(obj).start();
Object class must contain a method run();

//Object class must implements Runnable and that contains a method run();


Thread rf_reader = new Thread(rfid_reader);
rf_reader.setDaemon(true);
rf_reader.setName(“SmartIDReader task”); //Provide the thread with a threadName
rf_reader.start();

this.setDaemon(true); explains: setting daemon to true, will ensure that this thread is spin off from the main’s method thread. When a program execute from main entry point, main itself is actually a thread. If daemon is set to true, the sub-thread spinoff will be under the main thread. When the main thread is terminated, all sub thread will be terminated, shutdownhook can also be activated. If daemon is set to false, the thread spin off as another separated thread by its own. When the main thread is terminated, the sub thread will still exists (with daemon set to false).



Java Destructor Method – ShutdownHook
//This example continue from the previous myThreadClass example.
//ShutdownHook is registered for the myThreadClass thread process.

//If the java program terminate abnormally, shutdownhook will be activated.
//Shutdownhook will activate the ThreadClassShutdownHook which will start a thread
//to stop myThreadClass's thread tc.requestStop().

 private ThreadClassShutdownHook tcShutdownHook = null; //add this to the thread class variable
tcShutdownHook = new ThreadClassShutdownHook(tc);      //add this to the thread class constructor
Similar to C++, the implementation of a ShutdownHook can be like writing a destructor for Java. It can help to ensure that for any abnormal program termination, you can get to clean up and close all the resources in used.

public class ThreadClassShutdownHook extends Thread
{
  protected static transient final Log logger = LogFactory.getLog(ThreadClassShutdownHook.class);

  private myThreadClass tc;
  
  public ThreadClassShutdownHook(myThreadClass tc)
  {
    this.tc = tc;
    logger.info(this.getClass().getName() + " created. ShutdownHook registered.");
    Runtime.getRuntime().addShutdownHook(this);
  }
  
  public void remove()
  {
    Runtime.getRuntime().removeShutdownHook(this);
  }
  
  public void run()
  {
    if(tc != null)    {
      logger.info("ShutdownHook activated for " + this.getClass().getName()
      + ". Thread: " + Thread.currentThread().getName());
      tc.requestStop();
    }
    else
    {
      logger.info("ShutdownHook safely release for " + this.getClass().getName()
      + ". Thread: " + Thread.currentThread().getName());
    }

  }
}

 

public class Abc implements ShutdownHookClass
{
  protected static transient final Log logger = LogFactory.getLog(Abc.class);

  private myThreadClass tc;
  private Shutdownhook sdh;
  
  public Abc()
  {
    sdh.addShutdownHook(this);
  }

  @Override
  public void shutdownHookActivated()
  {
    close();
  }
  
  public void close()
  {

    if(sdh != null)
    {
      sdh.remove();

      sdh = null;
    }
  }
}

Implementing Shutdownhook using my utilities.jar file. Download the latest version from the section under “My Java Library

 

 

 

Import/Loading *.DLL to Java code (Dynamic Link Library)  
public class monitorController
{
  //A native function in monitorController.dll
  private native void triggerMonitor(int mode);

  // —————- Load Library —————–
  // To load dll file
  static
  {
    try
    {
      //get current directory
      String getPath = System.getProperty(“user.dir”) + File.separator + “LIB” + File.separator;
      System.load(getPath + “monitorController.dll”);
      logger.info(“monitorContoller.dll loaded..”);
    }
    catch(Exception ex)
    {
      logger.info(“Exception while loading monitorController.dll: “+ex);
    }
  }
  // —————- onMonitor () —————–
  // On Monitor
  public void onMonitor()
  {
    triggerMonitor(1);
  }
  // —————- offMonitor () —————–
  // Off Monitor
  public void offMonitor()
  {
    triggerMonitor(0);
  }
}
The example shows the loading of *.dll library into a Java code. The example also shows the static initializer block, which is used to load the dll library.

 

Launching the default application by opening a file from Java  

//-----------------------------------------------------------------------------
//Using Desktop class to open file, so that the code will be OS platform independent
//The default application will launch automatically with the file.
//-----------------------------------------------------------------------------
String fileName = "resource/documentation/operating manual.pdf";
try
{
  Desktop.getDesktop().open(new File(fileName));
}
catch(IOException e)
{
  logger.info("Error opening file " + fileName + ". The default program to open this file may not been set. Please set the default program.");      
}

//opening a file on the project root directory
Desktop.getDesktop().open(new File("image.gif"));
//opening a file relative to the project directory
Desktop.getDesktop().open(new File("imageDir\\image.gif"));
Desktop.getDesktop().open(new File("imageDir/image.gif"));
//opening a file using absolute file name
Desktop.getDesktop().open(new File("d:\\myproject\\imageDir\\image.gif"));
//opening a pdf file
Desktop.getDesktop().open(new File("d:\\mypdf.pdf"));

//-----------------------------------------------------------------------------
//Non platform independent code. (for Window OS)
//-----------------------------------------------------------------------------
//Open gif image file
Process p1 = Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL " + "d:\\myproject\\imageDir\\image.gif");
//Open pdf file
Process p2 = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler d:\\mypdf.pdf");

//force close the opened file
p1.destroy();


//-----------------------------------------------------------------------------
//Opening a Openoffice calc template (*.ots) as a calc file (*.ods)
//Using Desktop.getDesktop().open() will open the *.ots template file instead of a *.ods calc file
//-----------------------------------------------------------------------------

String sOfficeExe = "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe";
String calibrationTemplate = "resource/template.ots";
Process p = new ProcessBuilder(sOfficeExe, "-calc", calibrationTemplate).start();  //command line => "C:/Program Files (x86)/OpenOffice 4/program/soffice.exe" -calc "D:/programs/_workspace/macce/resource/Gauge Block Files/Calibration Files/_job no, Calibration Application Form Template.ots"
Machine.getInstance().delay(2000);    //allow some time for Process to execute
p.destroy();
 
Launching folder directory, network drive from Java

//-----------------------------------------------------------------------------
//Using Desktop class to open directory/folder, so that the code will be OS platform independent
//-----------------------------------------------------------------------------
//opening a local directory/folder.
Desktop.getDesktop().open(new File("D:\\programs\\eclipse\\_workspace\\InvoiceDataExtractor"));
//opening a remote network drive using network name/path.
Desktop.getDesktop().open(new File("\\\\BOB-PC\\Bob share folder"));
//opening a remote network drive using IP address.
Desktop.getDesktop().open(new File("\\\\192.168.1.95\\Bob share folder"));


//-----------------------------------------------------------------------------
//Non platform independent code. (for Window OS)
//-----------------------------------------------------------------------------
//open "InvoiceDataExtractor" folder
Process p = new ProcessBuilder("explorer.exe", "D:\\programs\\eclipse\\_workspace\\InvoiceDataExtractor").start();

//open "_workspace" directory and select "InvoiceDataExtractor" folder
Process p = new ProcessBuilder("explorer.exe", "/select,D:\\programs\\eclipse\\_workspace\\InvoiceDataExtractor").start();





Executing a *.exe program from the command prompt (command-line interpreter)  
//Other examples
//executing the fing program from the command prompt
String cmd = “fing -n 192.168.234.0/24 -r 1 –session scanLog.txt -o table,csv,”+scanResultFileName;
       
logger.info(“Fing is now scanning the network.”);
try
{
  Process p2 = Runtime.getRuntime().exec(cmd);
           
  InputStream is = p2.getInputStream();
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader in = new BufferedReader(isr);
       
  String str = “”;
  for(int x=0;str != null;x++)
  {
    str = in.readLine();
    if(str==null)    //typically last line is a null. Do not add null string to the list
      continue;
    else if(str.contains(“Error”))
      logger.error(“from Fing.exe: ” + str);
      //logger.debug(“Line: ” + x + ”  \tStr: ” + str);
  }
}
catch(Exception e)
{
  logger.error(“Check if Fing software is installed.”);
  logger.error(“Command line \””+ cmd +”\” read error.”, e);
  //halt 10 sec for user to read the error message.
  try{Thread.sleep(5000);}catch(InterruptedException e1){}
  System.exit(1);            //terminate the program
}
logger.info(“Fing scanning is completed.”);
 


Network TCP/IP communication example  
//object for storing IP address
InetAddress inetAddr = InetAddress.getByName("192.168.1.100");            //check proper internet address by InetAddress
int port = 80;

//comparing IP address
if(inetAddr.equals(inetAddr2))
{
       logger.info("IP address is the same");
}

//object socket for storing IP address & Port
InetSocketAddress socketAddr = new InetSocketAddress(inetAddr, port);    //data object for socket information (ip:port)
InetAddress ip = socketAddr.getAddress();
int port = socketAddr.getPort();
logger.info("Opening Modem <" + this.getClass().getSimpleName() + "> at IP<" + ip + "> Port<" + port + ">");
sock = new Socket(ip, port);                    //opening a new socket connection
logger.info("Modem is ready.");

Reference:http://docstore.mik.ua/orelly/java-ent/dist/ch02_01.htm

 

InetAddress i = InetAddress.getLocalHost();  //get IP address of the local machine
 
//Retreive all the network interface available in the system (Ethernet, WiFi, 2nd Ethernet port, etc...)
try
{
  Enumeration<NetworkInterface> n = null;

  //get all the network interface available on the system
  n = NetworkInterface.getNetworkInterfaces();
  while(n.hasMoreElements())
  {
    NetworkInterface ni = n.nextElement();
    String ii = ni.getName();
    System.out.println(ii);    //print all the available network interface name
  }

  //get the network interface from the physical network interface "eth0"
  NetworkInterface ni2 = NetworkInterface.getByName("eth0");
  //get the InetAddress information from the network interface
  Enumeration<InetAddress> eni = ni2.getInetAddresses();
  InetAddress actual_IA=null;

  while(eni.hasMoreElements())
  {
    actual_IA = eni.nextElement();
    String ii = actual_IA.getHostAddress();
    System.out.println(ii);    //print all the IP address
  }

  //opening a network socket
  serverSocket = new ServerSocket(port, 0, actual_IA.getByName(actual_IA.getHostAddress()));
  System.out.println("new serverSocket:"+serverSocket.getLocalSocketAddress());
}
catch (UnknownHostException ex) {}
catch (SocketException ex) {}
catch (IOException ex) {}

 

//Opening TCP/IP server socket
ServerSocket s = null;
try
{
  try
  {
    thisThread = Thread.currentThread();
    String myName = thisThread.getName();
      s = new ServerSocket(getServerListeningPort());
      logger.info("HID RFID Server ...\"START\"...   , Thread: " + myName);
    while((isSynProcess()) || (!isStopRequested()))
    {
      try
      {
        HidRfidReader hid;
        Socket incoming = s.accept();
        hid = new HidRfidReader(incoming);
        hid.setDaemon(true); //set this as a user thread. If startService thread ended, these user thread will end as well.
        hid.start();
      }
      catch(UnAuthorisedDeviceException e)
      { //ip address is not reconigze/registered. Print debug message and return to main loop to accept incoming socket connection
        logger.warn("Warning!!! <Unauthorised Access Detected> " + e);
        //detects authorised device access
        //return to check for other incoming connection
      }
    }
  }
  catch(Exception e)
  {
    logger.error("Unhandled Error: " + e, e);
  }
  finally
  {
    s.close();
  }
}
catch(IOException e)
{
  e.printStackTrace();
}
logger.info("HID RFID Server   ...\"STOP\"...");

 
//handling incoming client connection
    thisThread = Thread.currentThread();
    String myName = thisThread.getName();
    logger.info("Door connected    " + getObjectInfo()
            + "  ...STARTED thread: " + myName);

    // register shutdownhook for this object
    tcShutdownHook = new HidRfidReaderShutdownHook(this);

    try {
        int byteRead = 0;
        int previousByteRead = 0;
        StringBuffer data = new StringBuffer();
        int testConnectionTimer = 10000; // period interval in msec to test the connection
        byte[] checkAlive = new byte[] { '\000' }; // byte to test alive

        in = incoming.getInputStream();
        out = incoming.getOutputStream();
        // incoming.setKeepAlive(true);

        // send command to get the current security restrict mode
        byte[] getSecurityMode = new byte[] { '\003', 'G', 'S', '\r', '\n' };
        out.write(getSecurityMode); // send the command to get the security mode. The master controller device will reply with the current security restriction mode

        int timeElapse = 0;
        int timeElapseWithoutData = 0;

        while ((isSynProcess()) || (!isStopRequested())) {
            if (in.available() != 0) // if data is available to be read. use available() to avoid using read() which is blocking.
            { // using blocking mode with timeout exception will work on incoming stream but is will affect the outgoing socket timeout too.
                previousByteRead = byteRead; // therefore use available() is the proper way.
                byteRead = in.read(); // in.read() is a blocking function
                timeElapseWithoutData = 0; // reset counting the duration since the last incoming byte

                if (byteRead == 0x00) // searching for byte sequence 0x6E 0x00
                {
                    if (previousByteRead == 0x6E) {
                        // 2009-11-10 Strange issue detected. The HID RFID reader RW400 kept sending 0x6E 0x00 from each
                        // reader every 13 secs. This issue is not previously seen, therefore I
                        // guess there might be some data command that might have trigger it to happen.
                        // Setting the RW400 device to activate such a data ping.
                        // 2009-11-10 Email from asiasupport@hidcorp.com the 0x6E 0x00 is a reply response from the RW400
                        // device indicating an invalid command is sent to the RW400 device.
                        data.deleteCharAt(data.length() - 1);
                        logger.debug("caught data code 0x6E 0x00"
                                + ", from " + getObjectInfo());
                    }
                } else
                    data.append((char) byteRead); // must cast char else the int will be converted to ascii
            } else {
                try {
                    Thread.sleep(getDelayTimeElapse());
                } catch (InterruptedException e) {
                }
                timeElapseWithoutData++; // count the time elapsed
                timeElapse++;

                int dataLen = data.length();
                if (dataLen > 0) // if there is incoming data
                {
                    if (timeElapseWithoutData >= getMinimumTimeElapseLap())// if time is up
                    {
                        logger.debug("processing incoming data length: " + dataLen + " \"" + byte2AsciiHex(data.toString(), true) + "\"");
                        processData(data);
                        data.delete(0, data.length());
                    }
                }
            }
            // issue: When the client connection drop, the client will attempt to reconnect
            // This results in a multiple thread opened, while the old one is not closed.
            // Server is not aware that the connection has been closed.
            // By sending a test byte over, when the server cannot reaches the connection,
            // it will throw out the SocketException resulting in termination of the current thread.
            if ((timeElapse % (testConnectionTimer / getDelayTimeElapse())) == 0) // try detecting the connection once in a while
            {
                // logger.debug("         alive -> " + getObjectInfo());
                out.write(checkAlive);
            }
        }
        // no more incoming data, stop receiving
        incoming.close(); // close socket for that particular incoming thread
    } catch (SocketException e) {
        logger.error("Lost contact with the client door. "
                + getObjectInfo(), e);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Exception in " + myName + " " + e, e);
    } finally {
        try {
            incoming.close(); // close network socket
        } catch (IOException e) {
        }
    }
    logger.info("Door disconnected " + getObjectInfo()
            + "  ......STOP thread: " + myName);
 


Network UDP communication example (datagram packet listening)  
//UDP example, from EIB/KNX communication program
thisThread = Thread.currentThread();
String thisName = thisThread.getName();

logger.debug("-> started...   " + "knxData listener Thread: " + thisName);

byte data[]= new byte[100];    //allocate a larger buffer for receiving packet
DatagramPacket packet = new DatagramPacket(data, data.length, getRemoteIp(), getRemotePort());

int timeOut=100;
int debugCounter=0;
int debugAliveCount=(60*1000)/timeOut;

try
{
  udp.setSoTimeout(timeOut);

  while(!isStopRequested())    //while NOT end of transmission, which is terminate by the server side.
  {
    try
    {
      udp.receive(packet);
      debugCounter=0;
      if (logger.isDebugEnabled())
        logger.debug(StringUtil.padLeft("<- KnxDataComms packet received...", 35) + HexUtilities.print2Str(packet));
      
      decodePacket(packet);  //Please do not shift this code. Device immediate reply acknowledgement upon receiving data
                  //Ack reply too slow will result in the remote device trying to close the session
                  //thinking that there is a problem in this local computer.
    }
    catch(SocketTimeoutException e)
    {
      //timeout occur
      //do nothing. Just to unblock the receive function blocking mode
      //logger.debug("-> SocketTimeoutException" + getClass());
      debugCounter++;
      if((debugCounter%debugAliveCount)==0) {
        logger.debug("KnxDataComms thread is still alive.");            
      }
    }
  }
}
catch(ClosedByInterruptException e)
{
  logger.error("-> ClosedByInterruptException: " + e.getMessage(), e);
}
catch(IOException e)
{
  logger.error("-> IOException: " + e.getMessage(), e);
}
catch(KnxCommException e)
{
  logger.error("-> KnxCommException: " + e.getMessage(), e);
}
catch(SecurityException e)
{
  //requestStop() invoked Thread.interrupt()
  logger.error("-> SecurityException: " + e.getMessage(), e);
}
catch(Exception e)
{
  logger.error("-> General exception:: " + e.getMessage(), e);
}
finally
{  
  udp.close();
  requestStop();      //internal generated exception. Need to update requestStop variables to allow non thread function to terminate too.
  logger.error("-> stopped...   " + "knxData listener Thread: " + thisName);
}
 
byte[] data = LantronixDevice.queryFirmwareVer;
DatagramPacket packet = new DatagramPacket(data, data.length, bc, LantronixDevice.UDP_PORT);
DatagramSocket socket = null;

try
{
  socket = new DatagramSocket();
  //socket = new DatagramSocket(PORT, IP_ADDRESS);  //only for communication to a particaular remote IP & PORT
  //socket.setBroadcast(true);
  socket.setSoTimeout(timeoutSearch);
  socket.send(packet);
}
catch(SocketException e)
{
  // TODO Auto-generated catch block
  e.printStackTrace();
}
catch(IOException e)
{
  // TODO Auto-generated catch block
  e.printStackTrace();
}

UDP is a connectionless communication protocol and does not handle the integrity of the data being send. This does not mean that it cannot be implemented for communication that requires 100% error free communication. It simply means that the lower level protocol will not help you ensure that all your data bytes are being send over, and that your application will need to handle those error checking if you need it.

There are various way to setup your UDP communicates. Two methods are breifly state for your awareness.

– socket define wihtin DatagramSocket

– socket define within DatagramPacket.

For UDP communication to and only to one IP addressed device, you should define your socket in the object DatagramSocket. For packet communication with multiple UDP devices or acting as a listener, you can define your socket within the DatagramPacket object; there will be no restriction to which devices you can communicate within the network. UDP protocol is very flexible to implement.

For UDP broadcasting, use address 255.255.255.255, instead of the local broadcast address. The UDP message to address 255.255.255.255 will typically route to all IP address within the local network (LAN) and will be block by the router. UDP message usually don’t propagate beyond the LAN.  

Compute Broadcast address from IP address and network MASK

public String getBroadcastAddress(String ip, String mask)
{
  String broadcastAddr = null;

  String ipArr[] = ip.split("\\.", 4);
  String maskArr[] = mask.split("\\.", 4);

  byte ipByte[] = new byte[4];
  byte maskByte[] = new byte[4];
  byte bcByte[] = new byte[4];

  int x = 0;
  for(x = 0;x < 4;x++)
  {
    ipByte[x] = (byte) (Integer.parseInt(ipArr[x]) & 0xFF);//convert a string into a byte maskByte[x] = (byte) (Integer.parseInt(maskArr[x])&0xFF); //convert a string into a byte //ipByte[x] = Byte.parseByte(ipArr[x]); //convert a string into a byte 
    //maskByte[x] = Byte.parseByte(maskArr[x]); //convert a string into a byte
    bcByte[x] = (byte) (ipByte[x] & maskByte[x]); //mask out the subnet address
    bcByte[x] = (byte) (bcByte[x] | (maskByte[x] ^ 0xFF)); //form the subnet
    broadcastAddr = (((int) bcByte[0]) & 0xFF) + "." + (((int) bcByte[1]) & 0xFF) + "." + (((int) bcByte[2]) & 0xFF) + "." + (((int) bcByte[3]) & 0xFF);
  }
  return(broadcastAddr);
}
 
Using Java to send email, using this javax.mail.jar file

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

  String host = "siongboon.com";    //smtp host server
  String user = "username";    //smtp host server's user name
  String pass = "??????????";       //smtp host server's user password
  String to = "????@siongboon.com";     //recipient email address
  String from = "????@siongboon.com";    //sender email address
  String subject = "Test subject";     //subject
  String messageText = "Test body";     //email text
  boolean sessionDebug = false
  Properties props = System.getProperties(); 
  props.setProperty("mail.host", host); 
  props.setProperty"mail.transport.protocol", "smtps");
  pprops.setProperty("mail.smtps.auth", "true"); 
  props.setProperty("mail.smtps.port", "465"); 
  props.setProperty("mail.smtps.ssl.trust", host); 
  Session mailSession = Session.getDefaultInstance(props, null); 
  mailSession.setDebug(sessionDebug); 
  Message msg = new MimeMessage(mailSession); 
  try
  {
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = {new InternetAddress(to)}; 
    msg.setRecipients(Message.RecipientType.TO, address); 
    msg.setSubject(subject); 
    msg.setSentDate(new Date()); msg.setText(messageText); 
    Transport transport = mailSession.getTransport("smtps");
    transport.connect(host, user, pass); 
    transport.sendMessage(msg, msg.getAllRecipients()); 
    transport.close(); 
  }
  catch(MessagingException e)
  {
    // TODO Auto-generated catch block
    e.printStackTrace();
  } 

 

 

 

Multimedia  

Playing *.mp3 and *.wav audio/sound files

import java.io.File;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;


    Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
    Format input2 = new AudioFormat(AudioFormat.MPEG);
    Format output = new AudioFormat(AudioFormat.LINEAR);
    PlugInManager.addPlugIn("com.sun.media.codec.audio.mp3.JavaDecoder", new Format[] { input1, input2 }, new Format[] { output }, PlugInManager.CODEC);
    try
    {

      String file_location = "d:/mp3dog.mp3";
      System.out.print("start thread mp3 play: " + file_location + "\n");
      Player player = Manager.createPlayer(new MediaLocator(new File(file_location).toURI().toURL()));
      player.start();
      
      file_location = "d:/mp3siren.mp3";
      System.out.print("start thread mp3 play: " + file_location + "\n");
      Player player2 = Manager.createPlayer(new MediaLocator(new File(file_location).toURI().toURL()));
      player2.start();
      
      System.out.print("Two MP3 files playing together.\nNote that the media playing thread is still running.\n");
      
      //delay for 10sec before forcing thread to close
      try{Thread.sleep(10000);}catch(InterruptedException e){}
      
      System.out.print("Ending play thread.\n");
      player.close();
      player2.close();      
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }

Download the following
jmf.jar
mp3plugin.jar
mp3siren.mp3
mp3dog.mp3

 


 

 

 

Java and SQL  
Accessing mySQL using Java:
     When writing programs, there will be time we need to store data permanently. Usually writing data to files would be sufficient. When the data is becoming more and more complex, storing them in database might starts to make sense. SQL provides a standardize data access interface without having your program to manage the complexity of searching and storing the data.For this example, I am using the free database mySQL.

mySQL Software installation setup and library
------------------------------------------------

1) download and install the following software
     SQL1- mysql-essential-5.1.50-win32 (SQL database)
     SQL2- dotNetFx35setup (required for "mysql-workbench" software)
     SQL3- mysql-workbench-gpl-5.2.26-win32 (gui for mySQL)
     SQL4- mysql-connector-java-5.1.13 (sql interface/jar lib for java)
2)import "mysql-connector-java-5.1.13-bin.jar" to your java project
3) use the TestSql example to connect to sql database.


SQL connection pool:
     Why using a SQL connection pool to manage sql database connection. Opening & closing SQL connection takes quite a significant time delay. In order to reduce this delay (especially for high traffic applications), this class object will managed a limited pool of opened connection. When the application request for a SQL connection, this connection pool class will borrow the connection to the requester. When the requester wanted to close the connection, the pool class will retreive it back without actually closing the SQL connection. The pool will manage the SQL connection to provide a faster database access.

SQL connection pool (java library required for SQL connection pool)

------------------------------------------------
4) download the following jar libraries
      SQL5- commons-dbcp-1.4.jar
      SQL6- commons-pool-1.5.4.jar
5) import them to the java project for implementing the sql connection pool

Click here for SQL example


 

 

 

Java Command Pattern (or Design Pattern)  

Command Pattern: ExecutorService example: ExecutorService_Queue.java, ExecutorService_QueueJob.java Command Pattern: Observerexample1: Observer command pattern.pdfexample2: Observer pattern – Wikipedia, the free encyclopedia.pdfexample3: JavaWorld – October – How-to Java_ Observer and Observable.pdf


As you write more and more programs, you will realise the efficiency of re-using the codes. We call them functions. When we write more and more functions, we will realised that more codes can be consolidated; many codes are repeated. Then came the object oriented programming concept. Even when we apply object orientated programming, we can still see similar codes pattern or structure reoccurring. This calls for command pattern. It is a well design coding structures that helps programmer to simplfy commonly use, complex algorithm. When programming complex structure, think about the existing command patterns solutions. Knowing how to apply them can save you days of proramming headache. Many frequently used and efficient algorithms were already being thought of and were simplfied for us for implementation. Study the command patterns, simplfies to keep your coding short and neat. This is the true art of programming.
First create a task object that implements callable<return type>.
Cabllable objects contains a callable method (thread), which will be submitted to the executor service.
This allows the executable (SingleThreadExecutor()) to call this task object in the queue when its turn is up.
There are many type of executor available depending on your application. (example: newFixedThreadPool(3), newCachedThreadPool())

ExecutorService
//for ExecutorService, execute methods in a FIFO queue.

private final ExecutorService pool;       
//Executors object can helps to execute each task in a queuing sequence.
//A brand new pool object will be created here. Remember to shutdown each and every pool generated. Each pool is a thread by itself.
pool = Executors.newSingleThreadExecutor();       

//create an callable object to do the execution for the task in the queue.
//The callable method will be returning a boolean result.
Callable<Boolean> smsJob = new ModemManagerQueueJob(smsModem, smsMsg);   

//send sms to user
//process will stop at this block mode after submit. Once the thread complete its execution, it will return a value
//Loop through the submit to determine if all the jobs (or threads) are completed. (especially for non queue type of executor)
Future<Boolean> executorResult = pool.submit(smsJob);    //(use pool.execute(smsJob) for non blocking and no exception catch required.

//get the return sms result, replied from the mobile user (exception from the callable object can be catch here. e.getCause() to extract the exception)
boolean result = executorResult.get();

//always remember to shutdown executor thread
pool.shutdown();
or
pool.shutdownNow();

return(result);

try
{
  paymentSlip = paymentResult.get(); //waiting here for the payment result (payment receipt)
  logger.info("received paymentSlip");
}
catch(InterruptedException e)
{
  logger.warn(e.getClass().getName() + "() occurred");
  return;
}
catch(ExecutionException e)
{
  String msg;
  try
  {
    throw e.getCause();
  }
  catch(PaymentTimeoutException ee)
  {
    msg = ee.getMessage();
    logger.warn(ee.getMessage());
  }
  catch(PaymentMachineException ee)
  {
    msg = ee.getMessage();
    logger.error(ee.getMessage());
  }
  catch(UnknownPaymentException ee)
  {
    msg = ee.getMessage();
    logger.error(ee.getMessage());
  }
  catch(Throwable e1)
  {
    msg = e1.getMessage();
    os.sendStatus(OrderErrorCodeEnum.UNKNOWN, msg);
  }
}
catch(CancellationException e)
{
  String msg = "Payment process cancelled.";
  logger.info(msg);
}
Handling interrupt or exception from the running task (thread). Something may happen in the task that is running from the thread generated from the executor service. The left is an example how the exception can be handled.
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
List<Callable<?>> tasks; // your tasks
// invokeAll() returns when all tasks are complete. Any exeception from the callable object can be detected here
List<Future<?>> futures = taskExecutor.invokeAll(tasks);

ThreadFactory factory = new DefaultThreadFactory("Payment");
pool = Executors.newSingleThreadExecutor(factory); //Executors object can helps to execute each task in a queuing sequence.

//ThreadFactory class written as follows
public class DefaultThreadFactory implements ThreadFactory
{
    static final AtomicInteger poolNumber = new AtomicInteger(1);
    final ThreadGroup group;
    final AtomicInteger threadNumber = new AtomicInteger(1);
    final String namePrefix;

    public DefaultThreadFactory(String name)
    {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = name + poolNumber.getAndIncrement() + "-thr-";
    }

    public Thread newThread(Runnable r)
    {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if(t.isDaemon())
            t.setDaemon(false);
        if(t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}
DefaultThreadFactory helps to generate a unique name for the thread from the service executor pool which will be useful for troubleshooting. Using a default factory as shown above will generate a general thread.
//catching the exception that happens in the individual executor thread run.
      try
        {
            //blocking method waits for all cmd jobs to be completed
            logger.info(getId() + " starts executing all the <" + numOfTask + "> added tasks");
            futures = executorServ.invokeAll(tasks);       
            logger.info(getId() + " completed all <" + numOfTask + "> tasks.");
           
            //check for exception from the list of futures
            for(Future<CmdResponse> f: futures)
            {
                f.get();
            }
        }
        catch(ExecutionException e)
        {
            //catching the exception that happens in the executor thread run.
            if(e.getCause() instanceof CmdMonitoringTimeoutException)
            {
                String errorMsg = e.getCause().getClass().getSimpleName() + ": "+ e.getCause().getMessage();
                throw new ControllerCommandException(errorMsg,e);
            }
            if(e.getCause() instanceof ControllerCommandException)
            {
                String errorMsg = e.getCause().getCause().getClass().getSimpleName() + ": "+ e.getCause().getCause().getMessage();
                throw new ControllerCommandException(errorMsg,e);
            }           
            else
            {
                e.printStackTrace();
            }
        }

 

Creational Patterns:  
Abstract Factory  
Builder  
Factory  
Prototype  
Singleton Conciously running a single instance of an object. Ensuring that no duplicated instance is possible. This is useful when there is a need to encupsulate a hardware module. There is only one hardware module, making it singleton.
   
Structural Patterns:  
Adapter Add in a middle class so that an old program is able to temperary adapt to a new object method.
Bridge  
Composite  
Decorator  
Facade  
Flyweight  
Proxy  
   
Behavioral Patterns:  
Chain of Responsibility  
Command  
Interpreter Interpreter example use for paser or compiler.
Iterator Going through a list of objects collections
Mediator  
Memento  
Observer  Many other objects wanting to receive update from an object.
State State by state. Lifecycle.
Strategy  
Template Method  
Visitor  
   

references:
http://www.go4expert.com/articles/design-pattern-simple-examples-t5127/


 

read log4j ndc (log the individual instance of client thread connected to the server)

Design pattern reference:

java-design-patterns.pdf



Java GUI Programming
 JavaFX programming. Use JavaFX Scene Builder. Config Eclipse plugin and library to supprt JavaFX.  https://www.eclipse.org/efxclipse/install.html
Go to Eclipse>Help>Install New Software…>Add Repository>
Name: e(fx)clipse
Location: http://download.eclipse.org/efxclipse/updates-released/2.3.0/site
Install the plugin from the repository.

Create a *.FXML document.
Eclipse>File>New>Other>New FXML Document
Give this GUI layout file a name.
Right click the new *.FXML file, open it with SceneBuilder.

GUI & Event Listener example
– Create window
– Window listener
– Mouse listener
– Keyboard listener
– Observer (command pattern)

Use Observer command pattern (Observer, Observable) to implement any listener, events with multiple object listening to the same event.
– example interface, inherirt, abstract (pc, network projector project)

– http://www.javamex.com/tutorials/threads/invokelater.shtml
any swing component codes that requires periodically refresh need to apply this invoke function.
http://www3.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html


GUI programming notes:
GUI programming in java.pdf
Writing gui applications in java.pdf

int keyChar = evt.getKeyChar();
String debugStr = String.format("%1x", keyChar);
JOptionPane.showMessageDialog(null, debugStr, "Debug", JOptionPane.INFORMATION_MESSAGE);
Create a message dialog box that helps to debug data in hex code.
 

example to load image file to JPanel.
example- LoadAndShow (example to load image)

 

 

Java Applet  

Inserting applet into html file, where MyApplet.class is the java class to invoke, basecode “./” is the root directory the MyApplet.class is located.
<applet code=”MyApplet.class” codebase=”./” height=”600″ width=”600″></applet>

Without the *.class will also works
<applet code=”MyApplet” codebase=”./” height=”600″ width=”600″></applet>

If your MyApplet.class is located in the directory /appDir
html file location -> /index.html
apps file location -> /appDir/MyApplet.class
<applet code=”MyApplet.class” codebase=”./appDir” height=”600″ width=”600″></applet>

If the *.class to invoke is located inside a *.jar library archive file
<applet code=MyApplet.class archive=”JarFileName.jar” codebase=”./” width=width height=height> </applet>

 

How to signed a Java Applet for access to communication outside the server the applet reside on?

 

 

 

Applet

– Do not put the main Applet class in a package
– Do not do much coding in the Applet’s constructor, other than GUI initialisation. Codes should be place out of the constructor.

Problem:
– Applet hangs in the browser. Need to close the broswer and terminate the browser process to shutdown/restart the Java VM
Solution:
– Applet must use a thread to open new process, especially time consuming process. GUI programming has to be very much thread base.

Problem:
– The applet is able to send out UDP packet from Eclipse applet but not the same applet on the browser.
The browser is able to use the same UDP port to sent data out, but the applet using the same port cannot send the data out.
Solution:
– Remember the applet restrictions that unsigned applets may only access the host they were loaded from, for security purpose. To overcome this security restriction, you will need to signed the applet.

Browser test for Java Applet,
http://www.javatester.org/enabled.html

Note for Java applet,
Defining and Using Applet Parameters.pdf
Call a Applet Java method from Javascript.pdf
Call Javascript from a Java applet.pdf
Signed Applet Tutorial.pdf

Note for Java Jar file,
JAR files revealed.pdf



JNI Java Native Interface

 
Java is a high level secure language. The language do not allow low level hardware device access. Standard device interface like file access, HID mouse/keyboard, imaging, network, PCSC card access, etc… has been written in Java. There are many non standard hardware like RS232, propietary hardware that uses low level code access. Java do not have object that deals with this. The only option is to write the driver/software in low level language C/C++ and create a java native interface to access the low level object. Doing so will also means that you code is no longer portable to other operating system.  

Step 1) Write your normal java class implementing a native method as an abstract.

Myclass
{
  public Myclass()
  {
  }

  public void method1() //normal java method 
  {
  }

  private native void method2(); //native method 
}

 
Step 2) Build your java code to generate the Myclass.class from your Myclass.java.  

Step 3) Use the command “javah” to generate a header file from your class file. Go to your generated class directory.

example:
javah Mypackage.Myclass

A header file Mypackage_Myclass.h will be generated.

 
Step 4) Copy/Import the header file to your C project. Use this generated header to help you write your *.c source code. Also #include <jni.h> for your *.c use  

Step 5) Build the C project to generate a *.so library file.

You may encounter an error message
“error: parameter name omitted”
You may have left out the function’s (or method’s) parameter names which will not be generated in the *.h.
Provide your parametters with a variable name.

 

Step 6) Use the *.so file for the *.java file that you have created initially. This is for the system class loader

Myclass
{
  static
  {
    System.load("full-path-to-NetBeansProjects-dir/JNIDemoCdl/dist/libJNIDemoCdl.so");
  }

  public Myclass()
  {
  }

  public void method1() //normal java method 
  {
  }

  private native void method2(); //native method 
}
 
Step 7) Build and deploy the codes.  

Reference:
Java programming with JNI.pdf
Beginning JNI with NetBeans IDE and C_C++ Plugin on Linux.pdf

 

 

 


My Java Library

 
//Config.properties file content
processDirectory="D:\\Incoming doc\\Expenses Invoice"
processDirectory="D:/Incoming doc/Expenses Invoice"

//Using Utilities to retrieve config variables from config.properties file
ConfigFile cf = null;
String configFile = "config.properties";

cf = new ConfigFile(configFile);
String processFolderStr = cf.getPropertyQuote("processDirectory", "D:\\");
String archiveFolderStr = cf.getPropertyQuote("archiveDirectory", null);

String prop = cf.getProperty(key, defaultValue);
Boolean bool = cf.getPropertyBoolean(key, defaultValue);
Float f = cf.getPropertyFloat(key, defaultValue);
Integer i = cf.getPropertyInteger(key, defaultValue); 

This utilities.zip contains my frequent/common used Java library, which contains the follow object- HexUtilities.java- ShutdownHook.java, ShutdownHookClass.java

– UtilitiesThread.java

utilities.zip

utilities (2011-03-25).jar

utilities (2013-08-11).jar

utilities (2015-04-26).jar
utilities (2015-10-13).jar

nativePeripheral (2015-10-13).jar
nativePeripheral is meant for serial communication use.
public static void main(String[] args) throws IOException
{
    byte[] b = { 0x04, 0x04, (byte) 0xFF, 0x64 };

    //AsciiHexString ahs = new AsciiHexString("0102");
    AsciiHexString ahs = new AsciiHexString(b);

    //print example
    logger.info("Printing example:");
    String printStr;
      
    logger.info("1) print()");
    ahs.print();
    logger.info("2) original");
    printStr = ahs.toString();
    logger.info("\t\t\"" + printStr + "\"");
    logger.info("3) 0x format");
    printStr = ahs.toString(HexStringDisplayFormat._0X);
    logger.info("\t\t\"" + printStr + "\"");
    logger.info("4) space inbetween");
    printStr = ahs.toString(HexStringDisplayFormat.SPACE);
    logger.info("\t\t\"" + printStr + "\"");
    logger.info("5) bar inbetween");
    printStr = ahs.toString(HexStringDisplayFormat.BAR);
    logger.info("\t\t\"" + printStr + "\"");

    //short, int, long data example (hex/hexString to value)
    logger.info("");
    logger.info("Data type short, int, long example1:");
    try
    {
      byte[] byteA = { 0x04, 0x04, (byte) 0xFF, 0x64, 0x64, 0x64, 0x64, 0x64 };
      byte[] byteB = { 0x04, 0x04, (byte) 0xFF, 0x64 };
      byte[] byteC = { (byte) 0xFF, 0x64 };
      AsciiHexString numA = new AsciiHexString(byteA);
      AsciiHexString numB = new AsciiHexString(byteB);
      AsciiHexString numC = new AsciiHexString(byteC);
      
      logger.info("numA = " + numA.toString() + "\tLong = " + numA.toLong() + "\tanswer should be (long=289637082704667748)");
      logger.info("numB = " + numB.toString() + "\t\tInt = " + numB.toInt() + "\t\t\tanswer should be (int=67436388)");
      logger.info("numC = " + numC.toString() + "\t\tShort = " + numC.toShort() + "\t\t\tanswer should be (short=-156)");
      
      logger.info("numB Short = " + numB.toShort());
    }
    catch(HexValueOutOfRangeException e)
    {
      logger.error("numB cannot convert to short. " + e);
    }
    
    //short, int, long data example (value to hex/hexString)
    logger.info("");
    logger.info("Data type short, int, long example2:");
    long valueD = 289637082704667748L;                  
    int valueE = 67436388;
    short valueF = -156;
    AsciiHexString numD = new AsciiHexString(valueD);
    AsciiHexString numE = new AsciiHexString(valueE);
    AsciiHexString numF = new AsciiHexString(valueF);
    
    logger.info("valueD = " + valueD + " converted to hexString = \"" + numD.toString() + "\"");
    logger.info("valueE = " + valueE + " converted to hexString = \"" + numE.toString() + "\"");
    logger.info("valueF = " + valueF + " converted to hexString = \"" + numF.toString() + "\"");
}
Hex String ultilities contains in utilities.jar file
      String data = "03 53 29 00 30 60 29 A0 30";        //text of hex number copied from a software tool
      AsciiHexString ascii = new AsciiHexString(data);   //from a string of hex number
      byte[] byteArray = ascii.toHexByte();              //convert to byte array
Convert a text string copied from most software tool to a byte array for testing use. Very useful conversion of String Hex to byte array.
//example for using the ShutdownHook class 
public class DataComms implements ShutdownHookClass
{
  protected static transient final Log logger = LogFactory.getLog(DataComms.class);

  private Socket sock = null; //network connection socket reference for this object
  DataCommsRx dcr = null; //object for receiving data handling

  ShutdownHook sdh = null; //for shutdownhook

protected DataComms(InetSocketAddress socketAddr) throws IOException
{
  InetAddress ip = socketAddr.getAddress();
  int port = socketAddr.getPort();
  logger.info("Opening socket connection at IP<" + ip + "> Port<" + port + ">");
  sock = new Socket(ip, port); //opening a new socket connection

  //registering shutdown hook for this connection object
  sdh = new ShutdownHook(this); //add this to the thread class constructor
}
 
//example for using the TcpIpServerService class 
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.picControl.utilities.communication.TcpIpServerService;

public class TestTcpIp extends TcpIpServerService
{
  protected static transient final Log logger = LogFactory.getLog(TestTcpIp.class);

  public TestTcpIp(int port)
  {
    super(port);
  }

  @Override
  protected void clientHandler(Socket s)
  {
    logger.info("Client connected. " + s.toString());
    //Usual way of handling this Socket s here.
    //Multiple client may connect into this server.
    //For each and every client connection, this method will be invoked.
    //From here, you can spin off individual thread to handle the connection.
  }

  public static void main(String[] args)
  {
    TestTcpIp t = new TestTcpIp(10001);
    t.start();
   //Start the server, listening for incoming client connection.
    while(true)
    {
         try{Thread.sleep(100);}catch(InterruptedException e){}
    }
  }
}

KNX EIB communication for home automation server KNX source code
Example of a complex communication protocol and behavior handing.
TjLink TCP/IP communication for network Audio Video AV equipment (AV receiver, Projector) TjLink source code example.
Good example for learning Java inheritance (“extends”) and interface (“implements”)
HID RFID door access security program HID RFID source code
Example of server handling multiple clients
Server service to control all computers to wakeup or sleep Wake&Sleep
Example for Java serlvet, webserver (browser user interface)
SMS webservice server SMS server
Good example of job queue command pattern.
UDP communication with Xport, MatchPort Java UDP client for XPort
Network UDP example
Good java coding practise
JavaDoc
  /**
   * Converts bytes array to string<p>
   * Example if byteArr = 0x01 0x03 0x4A => AsciiHexString = "01034A"<p>
   * @param hexByte    array of bytes to be converted to string.
   * @return           the converted hex in string format
   */

Java standard of documenting your source code.
Java Serial Com Port Example (RS232), uses RXTXcomm.jar (gnu.io.SerialPort)

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.picControl.nativePeripheral.comm.SerialCom;
import com.picControl.nativePeripheral.comm.serial.SerialBaudrate;
import com.picControl.nativePeripheral.comm.serial.SerialCommException;
import com.picControl.nativePeripheral.comm.serial.SerialCommListener;
import com.picControl.nativePeripheral.comm.serial.SerialDataBit;
import com.picControl.nativePeripheral.comm.serial.SerialHardwareFlow;
import com.picControl.nativePeripheral.comm.serial.SerialParityBit;
import com.picControl.nativePeripheral.comm.serial.SerialStopBit;
import com.picControl.utilities.hexstring.AsciiHexString;
import com.picControl.utilities.hexstring.constant.HexStringDisplayFormat;

public class TestSerialCom implements SerialCommListener
{
  protected static transient final Log logger = LogFactory.getLog(TestSerialCom.class);

  private SerialCom serialCom;

  public TestSerialCom()
  {
    try
    {
      serialCom = new SerialCom("COM7", SerialBaudrate.BPS_19200, SerialDataBit.DATA_8, SerialParityBit.NO_PARITY, SerialStopBit.STOP1, SerialHardwareFlow.NO_HARDWARE_FLOW);
      serialCom.registerSerialComEvent(this);
    }
    catch(SerialCommException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  @Override
  public void serialCom_DataRx(byte[] dataByte)
  {
    AsciiHexString asciiStr = new AsciiHexString(dataByte);
    String dataStr = asciiStr.toString(HexStringDisplayFormat._0X);
    logger.info("(" + dataByte.length + ") " + dataStr);
  }
  
  public void send(byte[] dataByte) throws SerialCommException
  {
    serialCom.send(dataByte);
  }

  public void send(String data) throws SerialCommException
  {
    serialCom.send(data);
  }

  private void close()
  {
    serialCom.close();    
  }

  public static void main(String[] args)
  {
    byte[] outputCmd = new byte[] { '\003', 'O', 'C', '\r', '\n' };
    
    logger.info("Test Serial Com START...");
    
    //create a serial com object
    TestSerialCom tsc = new TestSerialCom();
    
    //sending data to serial com
    try
    {
      tsc.send(outputCmd);
    }
    catch(SerialCommException e1)
    {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    
    //listening to incoming data from serial com
    int timerEnd = 30;
    
    timerEnd = timerEnd * 10;
    for(int x=0 ; x < timerEnd ; x++)
      try{Thread.sleep(100);}catch(InterruptedException e){}
    
    tsc.close();
    
    logger.info("Test Serial Com END...");
  }
}
serialComPack (2015-10-13).zip
RXTXcomm.jar
rxtxSerial.dll (64bits)
rxtxSerial.dll (32bits)
nativePeripheral.jar

Setup
———————————————————
1) Copy the file “rxtxSerial.dll”
   (for 64bits system) from to folder “c:\windows\system32”
   (for 32bits system) from to folder “c:\windows\SysWOW64”



Click here for Serial Communication Tools


 

Java FFT to transform a time domain into a frequency domain

import edu.emory.mathcs.jtransforms.fft.DoubleFFT_1D;

    double[] input = new double[] { 1, -1, 1, -1, 1, -1, 1, -1 };
    DoubleFFT_1D fftDo = new DoubleFFT_1D(input.length);
    double[] fft = new double[input.length * 2];
    System.arraycopy(input, 0, fft, 0, input.length);
    fftDo.realForwardFull(fft);

    String data = "";
    for(double d1:input)
    {
      data += d1 + "\t";
    }
    logger.info(data);
    
    data = "";
    for(double d2:fft)
    {
      data += d2 + "\t";
    }
    logger.info(data);

//How to intepret the FFT results?

//time domain signal[8] =>    1.0    -1.0   1.0    -1.0    1.0    -1.0    1.0    -1.0   
//freq domain signal[9] =>    0.0    0.0    0.0    0.0     0.0    -0.0    0.0     0.0    8.0     0.0     0.0     -0.0    0.0     0.0     0.0     -0.0
//                            [0]    [1]    [2]    [3]     [4]     [5]    [6]     [7]    [8]
//Samples = 8, a total of 8 samples in the time domain.
//fs = Sampling Frequency (125Hz)
//[0] - DC component
//[1] - fs/2 * 1/samples    =    fs/(16)
//[2] - fs/2 * 2/samples    =    2fs/(16)
//[3] - fs/2 * 3/samples    =    3fs/(16)
//[4] - fs/2 * 4/samples    =    4fs/(16)
//[5] - fs/2 * 5/samples    =    5fs/(16)
//[6] - fs/2 * 6/samples    =    6fs/(16)
//[7] - fs/2 * 7/samples    =    7fs/(16)
//[8] - fs/2 * 8/samples    =    8fs/(16)
//Comment: no dc component. AC component which is half of the sampling frequency.

//time domain signal[8] =>    1.0   -1.0    4.0   -4.0     1.0    -1.0    4.0    -4.0   
//freq domain signal[9] =>    0.0    0.0    0.0    0.0    -6.0    -6.0    0.0     0.0    20.0    0.0     0.0     -0.0    -6.0    6.0     0.0     -0.0   
//                            [0]    [1]    [2]    [3]     [4]     [5]    [6]     [7]    [8]
//Comment: no dc component. AC component which is half of the sampling frequency, and also 1/4 of the sampling freq.

//time domain signal[16] =>   10.0   0.0    10.0   0.0     10.0    0.0    10.0   0.0     10.0   0.0    10.0   0.0    10.0   0.0    10.0   0.0   
//freq domain signal[17] =>   80.0   0.0    0.0    0.0     0.0     0.0    0.0    0.0     0.0   -0.0    0.0    0.0    0.0    0.0    0.0    0.0    80.0  ...

//                            [0]    [1]    [2]    [3]     [4]     [5]    [6]     [7]    [8]
    [9]    [10]   [11]   [12]   [13]   [14]   [15]   [16]
//Comment: With dc component, because there are no negative numbers. AC component which is half of the sampling frequency.



These formatted java source codes are generated by java2html_50.zip

My Java and Eclipse web reference

My reference guide to Java programming and Eclipse environment setup.

Edited by Lim Siong Boon, last dated 16-Feb-2010.

Topic Discussion Overview

  1. Setup Eclipse & Java
  2. Java Coding Example
  3. Java Webservice & Flex 3
  4. Java Servlet
  5. Apache Ant
  6. eXist (XML database)
  7. JUnit
  8. Java programming on Andriod


 

Introduction










The main concept in writing Java codes, is the understanding of object oriented programming (OOP). Java being a 100% OO programming language is quite fun to designed your software with. As simple as it seems to be, in fact took me years to learn what OO really means. It has been years, since 1997 since I first pick up the book on object oriented, and I am still learning as of today. I would think OO rather an art of designing software. There is no right or wrong, but a good OO designer is the one who can make a difficult software easy and fast to program. OO is really about memory management.

Among all the electronics hardware web pages that I have written, I find writing article about Java is rather difficult. I need to categorised a topic for section, else I may end up writing messy or end up writing the whole Java text book. Most Java program I wrote is rather low level, hardware oriented. Writing Java for low level application posed quite a number of challenges. Why? Java is not design for low level access. Any direct access to I/O is generally not available to Java. This is for the reason of security and compatibility issue, operating across different operating system platform. Here I will present some of the problem I face doing Java with the mindset of a C++ programmer. For now, this page will be more of my own frequent used Java references.

I hope to make this page useful to new Java programmer like I am.



Download you need for your developments


eclipse.gifeclipse.png

Java IDE, Eclipse, http://www.eclipse.org/downloads/


java-logo.gifsun-microsystems.gif

Java SDK, http://java.sun.com/javase/downloads








1. Setup Eclipse & Java

Setting up Eclipse and Java environment for development.


2. Java Coding Example

Java language reference & commonly used source code.


3. Java Webservice & Flex 3

Flex 3, Java webservice project step by step.


4. Java Servlet

Learn Java Servlet step by step


5. Apache Ant

Manage your java project with Apache Ant


6. eXist (XML database)

Write a database using XML structure


7. JUnit

http://www3.ntu.edu.sg/home/ehchua/programming/java/JUnit_Ant.html (Very good NTU website on Java, by Chua Hock Chuan)

JUnit java code testing (by Chua Hock Chuan).pdf

8. Java programming on Andriod

http://www3.ntu.edu.sg/home/ehchua/programming/android/Android_HowTo.html (Very good NTU website on Andriod, by Chua Hock Chuan)

How to Install Android SDK and Get Started (by Chua Hock Chuan).pdf


Useful Tools


java2html

Convert your java source code to HTML, RTF, TeX and XHTML with syntax highlighting.
1) open up the java2html_50.zip file ->.
2) double click on java2html.jar to execute the application program.
3) input files or source code text to convert them into html codes.

references:
http://www.java2html.de/

example: Input text source code
public class Example
{
    public void Example()
    {
    }

    public static void main(String args[])
    {
    }
}

example: Output results in HTML format
public class Example
{
  public void Example()
  {
  }

  public static void main(String args[])
  {
  }
}











Keyword: Java, Eclipse, library, configuration, shortcut

How Power Saver Works? or perhaps Don’t work.

Don’t be misleaded by my title. I know of many customers being believers

of how the power saver product can help them save on their electricity bill.

This article is NOT about how power saver works, but more about why power saver “Don’t Work”.

To understand how it don’t work, we have to understand how it works. Understanding Power Saver Scam in detail.

Edited by Lim Siong Boon, last dated 24-Jan-2012.

Topic Discussion Overview

  1. Power Saver
  2. Brands Available
  3. Microprocessor Power Saver
  4. Voltage Trimmer


Power Saver

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

When I first got to learn about this power saver product during an exhibition in Singapore, I was a little bit surprise about it. The meter measuring the current drop instantly when this power saver thing was turned on. The surprising part is not about its energy saving performance, but the fact that business people is really smart. How they are able to make use of a electrical physics to convince consumer into buying the product.

Myself, I am trained in Electrical & Electronics Engineer for my diploma and degree course. Although I have graduated from my university many years back, I had little experience in the field of the 230Vac single phase voltage system that we are using in our home. Nevertheless I am able to recognize what I was being presented in the exhibition. The power saver device is a scam. The purpose of dedicating this webpage is for me to present to those who have doubt in the device, to understand more about the power saver in a simple and experimental way. To let you see clearer how the scam works, and how you can see the fraud even at the exhibitor’s own setup.

Two things in common when power saver is presented to the consumer. You will always be presented with an instrument call ammeter (or current meter). The appliance used in the demonstration are of inductive property (eg. motor, fan, ballast lamp). These are the two main ingredients that will make the presentation looks convincing for a non-electrical trained consumer.

The ammeter was there to show the reading of the electrical current flowing through the power cable which is connected from the mains to the operating appliance. Higher current reading will means that more electrical current is being drawn from the electricity power grid. There are no tricks on this measurement, they are real. That was why everytime when the power saver is turned on, you were able to see the immediate drop in the electrical current. Most of the demonstration using a clamp ammeter. The meter is clamp to either the electrical live or neutral cable and is able to measure the magnetic field around the cable. The intensity of the magnetic field is proportional to the current flowing through the cable, that is why the current can be measured. The clamp meter is easy to setup and customer can easy be convince since the setup is clean not not hidden from the consumer’s sight.
A picture if the clamp-ammeter for measuring the current flowing through your electrical appliances. Clamp the live or neutral wire of your electrical cable to measure the current flowing.

The problem lies in the engineering knowledge which consumer is not aware about. Having the current reduced does not mean that the power consumption will be reduced. Most people will tends to link the idea of a reduce in current, to a reduce in energy consumption. This concept seems a bit illogical, but this is the real situation. Current and power are not directly related. Real energy consumption is determine by the wattage consumption, and not the current.

The actual technical terms are call real and imaginary power. They can be quite difficult to understand and I shall simplify it by not going too deep into the actual technical details.

There are 3 types of load/appliances that the electrical grid will deliver its power to. They are resistive, inductive and capacitive load. Inductive and capacitive are technically not efficient because extra current has to be drawn from the electrical grid in order to support the appliances. We call these load reactive load. Assuming a household appliance that consume 100W of power. No matter what type of load (resistive, inductive or capacitive) this appliance might be, the real power consumption of this appliance will be 100W. This means that the energy consumption should remains the same regardless of the load.

Most appliances that we have at home are of resistive and inductive nature.

Appliances at home that are Resistive in nature are,
– hot iron
– heater
– oven
– incandescent bulb

Appliances at home that are Inductive in nature are,
– fan
– fridge
– air-con compressor
– washing machine
– vacuum cleaner
– magnetic ballast fluorescent lighting

The only thing different between the type of load, is the current being drawn. For example this appliance is a 100W resistive load, drawing a current of 0.4A from the grid. This 0.4A will be the lowest current that a 100W load can go.

Example 1:

Power Supply —————————————–> 100W Resistive Appliances
Flowing Current 0.4A

If the 100W load is now inductive or capacitive in nature, we will expect a current reading more than 0.4A. This is because such a load requires more current to support the load. Inductive and capacitive load is a form of energy storage component for the electricity. The 100W inductive load though draw in more current from the power grid to fill its storage tank, it will not consume all the energy. The unused current will flow back to the grid. This extra in/out flow of the current is the reason for the rise in the current that we will measured.

Example 2:

Power Supply —————————————–> 100W Inductive Appliances
Flowing Current 0.6A

How much this extra current will be, will depend on the power factor. Power factor ranges from 0-1. It is an indication of the load type. A power factor of maximum 1.0 indicates a pure resistive load will have a minimum current. A power factor of 0.0 indicates a pure capacitive or inductive load will encounter the maximum current. Any power factor reading between 0.0 to 1.0 means that the load is a combination of both.

This power factor thing can be corrected like a see-saw as illustrated below..

Power factor 0.0————————–1.0 ————————–0.0
…………inductive————————resistive————————capacitive

Example 1 is a resistive load 100W 0.4A. The power factor will definitely be 1.0 .

Example 2 is an inductive load 100W 0.6A. The power factor could be let’s say 0.5.

The load being too much inductive with a power factor 0.5A can be corrected by installing a capacitive counter load in parallel. The correct capacitive load can pull up the power factor to 1.0. Too little capacitive counter load will not pull the load fully to the balanced power factor of 1.0. On the other hand, too much of the capacitive counter load will make the overall load capacitive in nature and hence power factor will also be lower than 1.0. The key to attain a power factor of 1.0 is by using the correct counter blance load. Attain a power factor of 1.0 will reduce the current to its minimum.

The power saver is actually a pure capacitance component inside with its value unknown. The demonstration appliance is typically a motor or magnetic ballast fluorescent lamp which is inductive in nature. When the inductive appliance is turned on, the current measured will consist of the extra current flow, therefore reading is higher. When the power saver is turned on at the same time, the load is though balanced with a power factor nearer to 1.0, therefore current is now lower. The closer the counter balance is matched, the low the current will be. The lowest current it can go will be based on its wattage as if it is a resistive load. But it is not easy to match it to exact power factor of 1.0 for a typical consumer.

As what I have understood, the power service provider do not charge consumer on the current that we have drawn, but on the real power that we have used up. It will not be fair if they charge us base on the current, because although we might draw higher current, we also returned the unused portion back to the grid.

For factory and industrial, the situation is slightly different. They will be charged on the extra current for the reactive load that they have introduce. Why is there such a different? This is because the industrial ususally draw very high current from the grid. If the current is high, the cable to support the high current has to be thicker. If the industrial user do not correct the factor of their manufacturing plant, it will be at the expense of the service provider to lay more cables for them. For industrial user, they will be charged base on the real power and the reactive power that they use. For home consumer, our usage is quite predictable and insignificant.

So unless your power meter measure and charges you on both the real and reactive power, you will not need to correct the power factor for your own house.

High current uses thicker cable. Cable not thick enough, heat will be generated. This is a form of cable loss. This is also how a safety fuse for electrical system works. The fuse will burn itself if the current is too high.

But wouldn’t that means that the cable out from the power station will be very very thick to support the whole population? Yes, but there is another solution. The voltage from the power station is very very high. Given a limited cable size, we can still deliver more power to the population by increasing the voltage. Power is the product of voltage and current. With the limit in cable size, hence the current, we can deliver more power by rising the voltage. That is why you can often see electrical sub-station around the place we live in. It is a big transformer inside which step down the very high voltage to a lower voltage that we can use. There are many stages of sub-station from a power station all the way to the end consumer.

You can think of the electrical system as the distribution for our water pipes. High voltage is similar to high pressure for the water pipe. Cable size or current is the water pipe size. Electrical power being the volume of the water. Having a limitation in the waterpipe size does not means that we cannot deliver more water to the population. We can still increase the water pressure so that the water is able to travel faster, hence deliver more water though the pipe out.


The Experiment

Now that we have know something about power factor correction, the following experiment setup will further illustrate the function of a power saver and how the thing works. I have done some reverse engineering work on the following 3 items shown in the picture consist of (from the left)

1) I have managed to salvage white cylindrical AC capacitor from an office fluorescent lighting using a magnetic ballast. I had remembered seeing such component connected to the setup and have dismantled one for the experiment. It is just an ordinary AC capacitor which electrical contractor sometimes used to correct the power factor of the lighting so that current flowing from the mains supply to the lamp can be minimum. The magnetic ballast is an inductive component. Having this counter balance capacitor load, the power factor can be improve, therefore reduce the current. This capacitor was connected to a 3 pin plug for the experiment. Using a multimeter, I managed to measure the capacitance to be 3.2uF, which is the same value as labelled on the component itself.

2) GAD1203 Extreme Power Saver (CX005). I have managed to open it up to understand further about it’s interior. The inside consist of a circuit and a black rectangular block. At a glance, it seems quite complicated circuit, but after careful examination, the circuit looks suspicious. The IC chip on-board is a logic gate IC which does not do any function. The black box is actually a 4.75uF capacitor component. The measured capacitance is 5.6uF which is quite close to the label. The incoming 2 pin Live and Neutral is connected parallel to the capacitor and the circuit. Without the circuit, the capacitor will be enough to act as a power factor correcting device.

3) GAD1202 Power Saver (CHT-001C), 2400W. This product is easier to do the reverse engineering. It consist of two black box connected in parallel to the AC Live & Neutral wire. The 2 black box is the capacitor measuring 5uF each which is the same as labelled on the component itself. Two capacitor means that the total capacitance is 10uF. There is a lamp indicator which is connected to the AC line, indicating that the device is connected to the AC mains.

 

I have this experiment and setup as below with help from saveOne Pte Ltd in Singapore. Their business is mainly in the Asia region Philippines, Thailand, Malaysia and China. This company sells a range of energy saving products, from energy saving lighting, energy saving electronic ballast to energy saving equipments. The picture shows a demonstration rack of their electronic ballast product for circular fluorescent lamp which I have also installed for my house. I like the product and have written an article about it quite some time ago. If you are interested, you can visit this link.

The reason I use this rack for the experiment because there was this magnetic ballast fluorescent lamp setup at the bottom of their rack. You can see from the picture, it is the lamp that is lighted up. Magnetic ballast component is an inductive load and is useful for our experiment.

The setup consist of 2x power meter to check on the wattage, current and power factor at 2 location along the power supply line from the mains to the magnetic ballast lamp. Right from the top, you can see a 4 way socket power extension. This is the point where I would tap the power from. The first thing that was connected is the power meter which was connected to the 2nd socket position. This power meter no.1 measures the electricity for the whole setup. The later setup that would be connected to this power meter will be measured. This means that we would be able to know the current flowing from the supply mains to this setup, and also the wattage consumption of the setup.

From the power meter no.1, a multi-plug socket was plugged on top of it to split the power outlet into 2. On the right side, it is where the power saver (capacitor under test) will be plugged. The front side is the 3pin plug which is from the cable extension drum. On top of the cable drum is power meter no.2. The magnetic ballast lamp is connected to this power meter no.2. Power meter no.2 measures the wattage, current and power factor for the lamp.

 

Measure Result from Power Meter no.1

S/N Power Saver or Capacitor connected Watt Current PF
0

Without any capacitor connected

 

44.2W 0.432A 0.42
1

Capacitor 3.25uF ±10% 250V
 

44.2W 0.242A 0.76
2

GAD1203 Extreme Power Saver (CX005), 5.6uF
 

45.1W 0.198A 1.0
3

GAD1202 Power Saver (CHT-001C), 10uF

45.3W 0.403A 0.47

0. Without any thing connected, the magnetic ballast lamp consume a wattage of 44.2W. Current is high at 0.432A. The power factor measured from the power meter is low at 0.42.

1. When the small 3.25uF capacitor is connected along the power line, the measurement from power meter no.1 shows that the power factor has improved to 0.76. The improve in power factor will also lead to a drop in the current. With this small capacitor, the current is now lower at 0.242A. The power consumption remains unchanged for the own setup.

2. Next comes the Extreme Power Saver GAD1203. The 5.6uF capacitance is higher than the previous 3.25uF. As shown in the measurement, the power factor is now exactly 1.0. This is a perfect match. The magnetic ballast requires 5.6uF capacitance to correct its power factor. The current is measured to be 0.198A. Since the power factor is perfect, this is the lowest current we can attain for the lamp. The power consumption goes slightly higher at 45.1W, probably due to the extra circuit that is in the Power Saver.

3. Next comes the GAD1202 Power Saver. The 10uF capacitance is among the highest of all the Power Saver under this test. When it is connected along the line, the power factor actually drop down to 0.47. This happens because we have over correct the power factor by putting in too high a capacitance value. The drop in power factor comes with an increase in the current flow of 0.403A. Putting too much Power Saver can degrade the performance. It is possible to create an even higher current than the original setup (without any thing connected along the line). This means that if too many Power Saver is connected along the line, you will expect an increase in current instead. You can try it out on the demonstration, requesting the salesman to install more Power Saver to the setup. The current will drop up to a certain point then increase more and more after that. The current will never drop back once the power factor is over corrected. You will need more inductive load to balance it back to a power factor of 1.0. I have tried it out before, and was able to see the increase in current once the second Power Saver was plugged in. The wattage is the highest among the rest at 45.3W. This might be due to the lamp indicator in the circuit which will also consume energy.

Measure Result from Power Meter no.2

Throughout the turning on and off of the Power Saver device, the reading remains the same. The reading is the same as the Power Meter no.1 as if no capacitor or power saver is connected. This shows that current from the Power Saver all the way to the inductive load (magnetic ballast fluorescent lamp) was not corrected and still remains high at 0.432A throughout the experiment.

 

Conclusion

The current was corrected only from the power supply mains to the Power Saver only. Current from the Power Saver to the inductive load remains the same. In order to keep the current minimum along the cable, the power saver will be better kept as close as possible to the load that requires power factor correction.

The use of a power factor correcting device helps to reduce current from the power mains to the device. Lower current means that the current carrying AC cable can be afford to be thinner. To put it in another way, more inductive appliances can be connected to the same AC cable if they are all power factor corrected. Lower current flowing through the cable also means less power loss on the cable it self. High current flowing through a thin cable can generate some heat (cable loss). However cable loss is usually insignificant.

To conclude, the power saver can help to reduce current flow. In order to reduce the current, you will need to understand your load and apply the correct counter load value. Over correcting an appliances will make it worst. In terms of energy saving, the saving will be insignificant. In fact, the experiment shows a slight increase in wattage. It is quite conclusive that the Power Saver product is a scam.

The following are some other sites from people who have similar knowledge and explaination. I have collected these website for your further understanding of how power saver works.

http://www.nlcpr.com/Deceptions1.php

For alternative power saving method, you may also like to find out about voltage trimmer from saveOne, which offers power saving solutions. Some of their products are listed below for reference.

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

 

 

Alternative name for Power Saver:

Energy Saver

Power Saving

Electric Saver

Current Stabilizers

Home Energy Saving Device

Power Factor Saver

Saving Saint

 

 

Forum comment:
http://www.janleow.com/life/electricity-energy-power-saving-device.html
http://ezinearticles.com/?Energy-Saving-Devices—Do-They-Work?&id=4556173
http://www.ideamarketers.com/?Energy_Saving_Devices_Do_They_Work&articleid=1210082&from=PROFILE
http://www.advancedenergy.org/buildings/knowledge_library/systems_approach/energy_saving_devices.html
http://www.physicsforums.com/archive/index.php/t-170023.html
http://www.nlcpr.com/Deceptions1.php
http://webdevsys.com/aussiePowerSaversScam.htm
http://forum.lowyat.net/topic/1071423/all
https://www.oag.state.tx.us/oagnews/release.php?id=2456
http://www.guardian.co.uk/money/2011/dec/01/trading-standards-bogus-energy-saving-plugs
http://forums.techarp.com/general-hardware/23800-electricity-saving-box.html
http://electricitysaver.com.au/home/index.php/how-does-it-work
http://forums.whirlpool.net.au/archive/1125316
http://forums.hardwarezone.com.sg/general-merchandise-bazaar-261/wts-gadget-save-electricity-mini-sun-power-saver-2191556.html

http://www.xtremeplace.com/yabbse/index.php?topic=78110.0

 

   
Brands Available


Mini Sun Power Saver

http://www.h2hgroup.org/

http://www.minisunsaver.com/

http://www.minisunpower.com/

http://powersaver.biz/

http://powersavermalaysia.blogspot.com/

 

Model: MS88, MS188, MS388

A German technology.

Tested by PSB (Singapore) & SIRIM (Malaysia)

click here to see PSB test report, click here to see SIRIM QAS test report

POWERGARD


http://homeenergysaver.net/

This one is CE certified, UL listed & tested, cULus.

GaoYiNeng Energy Saving Device

http://www.szgyn.com/

THE GUARDIAN

http://eccobest.com/

Joinwe Electricity saving box

http://joinwe.net/en/products-01.htm

sd-001 Electricity saving box

The Electric Saver 1200

http://electricsaver1200.com

POWER PANDA

http://thepowerpanda.com

Ecobrand Power Savers and Current Stabilizers


http://www.saving-electrics.com/

EcoWatt Energy

http://ecowattenergy.com/residential.php

Ultima Imaging Systems Pvt Ltd.
Power Saving Device
http://www.ultimaimaging.co.in/powersaver.html

Yueqing Chiny Import & Export Trade Co., Ltd
http://chinyichina.en.made-in-china.com/product-group/aMeJvjhEhTVo/power-saver-energy-saver-catalog-1.html
 

UBRIDGE Technology

http://ubridge.en.alibaba.com/product/358253955-206600002/Electric_Power_Saver_up_40_.html

 

Model: UBT6

   

Microprocessor Power Saver
If I am not wrong, these microprocessor power saver is similar to the passive power saver as presented above. The advantage is that it can constantly maintain the best power factor even when your load various. The intelligent controller will adjust accordingly to your load, though result in a minimum current flowing from the power station to your home. However, the current from your home to your appliance, should remain unchanged. The concept of power correction as presented in the previous section will still be apply. Minimizing current drawn from your power service provider does not mean you can have significant electricity saving.

Aztech ESAVER

aztech esaver www.esaver.net

 

brouchure

This is a possible microprocessor controlled power factor correcting equipment. It looks rather bulky. The automatic power factor correction should be real, but as for the electricity bill saving, I will doubt so.

Power Saver India

http://powersaverindia.com/

This product claims to be controlled by a microprocessor. I do have doubt if it has the intelligent to even correct the power factor.

http://aonepowersaver.com/

http://realpowersaver.com/

This product claims to be controlled by a microprocessor. I do have doubt if it has the intelligent to even correct the power factor.

 

 

www.pic-control.com, Singapore Research & Development R&D


Voltage Trimmer
This saveOne voltage trimmer equipment, is unlike a power factor correcting device which only reduces the current. It works by stablizing the voltage hence reducing the current drawn and reducing the actual power consumption to your appliance. The voltage trimmer has to match closely to your appliance. The technical personnel from saveOne will have to access your appliance in order for them to propose the correct equipment model for the energy saving to be effective.
saveOne Voltage Trimmer  
   


 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller





Keyword: Power Saver, Scam, home energy saving device, power saving products, cheating, fraud, swindle, trickery, mislead

PIC Microcontroller DIY

        Introducing PIC Microcontroller projects

 

Written by Lim Siong Boon, last dated 20-Oct-09.

 

 

PIC Microcontroller

 

 

References:

Microchip dsPic 30F Programming reference guide

microchip dspic quick reference guide

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

Singapore Customized, custom made Electronics Circuits & Kits

 

Development Tools History

 

 

PIC microcontroller Development Board

(Completed on 2006-10-28)

The ultimate PIC Microcontroller development board. After years of programming PIC microcontroller, I have finally design my super development board to program PIC microcontroller firmware. The automatic programming mode select and the 40 bits LED light bar display have ease my programming process and increase debugging speed by 10 times. I can easily do troubleshooting because of the 40 bits LED display. The LED allows display for 5 bytes of variables using only 3 bits of any output port. I used to allocate PORTD to display one byte of the memory. Debugging used to be slow and tedious. This board also features automatic select to programming mode when the board is powered down. This means that there is no need to do manual switching. The ICSP interface allows the firmware to be loaded to the microcontroller without inserting/removing IC chip.

Features

-Development for 18, 28, 40 pins DIP PIC microcontroller

-Serial Communication RS232, with Tx/Rx transmission activities indicator.

-Changeable microcontroller Crystal Clock

-ICSP programming pins

-Automatic switch to programming mode when board power is turned off.

-Proper labels and easy to view LED bar display, buffered from all the ports. Output pins from all the ports.

-Serial to parallel data latching to extend more output bits from 3 output pins. Output pins with easy to view LED bar display.

-Adjustable dc-dc power supply using LM2576-ADJ IC to cater for 5V and 3.3V power supply system.

-Features 74HC series logic family and Max232 IC for operating on 3.3V power supply. (see logic family selection guide)

-Fuse protection.

 

     

Click on the image for Circuit Schematic

For more information for extending microcontroller I/O (input/output) ports using “serial to parrallel” or “parallel to serial” circuit, you can refer to More Circuit Schematic.

 

The development board uses the following logic IC:

74HC595, serial to parallel with output latched

74HC244, octal logic buffer

MAX232, RS232 to TTL tranceiver

LM2576-adj, DC-DC voltage regulator

 

For more information on how to select logic family, see “Logic Selection Guide” from Texas Instrument.

Introduction: AUP, CBT-C, CB3T/Q, SSTU, VME, AUC, SSTV, GTLP, Little Logic, AVC, TVC, ALVT, CBTLV, ALVC, CBT, LVC, LV

Mature: AHC/AHCT, LVT-A, ABT, FCT, AC/ACT, HC/HCT, BCT, CD4000

Obsolescence: 74ALS, 74F, 74AS, 74LS, 74S, 74xx (oldest)

 

PIC microcontroller Programmer

(Completed in the year 2005)

My first own build programmer system. Spent quite a lot of time designing and fabricating the plastic box chassis. It works, but I never really work much with it after I brought myself a commercial version.

 

Microcontroller DIP IC Adaptor

(Completed in the year 2002-05-xx)

This is a interface board for fitting various model of PIC microcontroller to the programmer. The programming pins numer is different for every PIC microcontroller model. This interface board eliminate the need to build a new programmer board for different PIC microcontroller model.

 

PIC Programmer & Development board

(Completed in the year 2002-05-xx)

This board is design to be function as a multi purpose PIC microcontroller development board. I have build specially to trial run the microcontroller firmware I wrote. Bi-directional digital buffer are used, to protect the microcontroller from external device during interfacing. After working with microcontroller for some time, I find that this buffer interface is not necessary. Microcontroller I/O ports do not damage easily. When interfacing microcontroller with high powered or unknown devices, opto-coupler can be used instead. Opto-coupler provides maximum isolation as well as protection between the microcontroller and other devices.

Attached to the main PCB is a smaller PCB board. It consist of a MAX232 converting computer RS232 to microcontroller TTL serial signal. This small board also include a charge pump circuit that generate 12V from a 5V source for the purpose of programming the PIC microcontroller. This programmer design “Toolkit TK3 PIC programmer” was taken reference from my favourite hobby magazine “Everyday Practical Electronics“.

 

Development Board schematic & PCB layout

Programmer Board schematic & PCB layout

Microcontroller Essential Test Tools

(Completed in the year 2002-05-xx)

Input switches and Output LED test board interface. It is very useful when doing microcontroller project, because it can help to indicate if the firmware is running correctly inside the microcontroller. A must have kit when doing digital project.

 

 

PIC microcontroller selection references.

table updated in 26 May 2007

Number of Pin PIC16F series PIC18F series alternative
14 PIC16F688  
18

(all  models, not pin compatible)

PIC16F88, PIC16F648a, PIC16F628a, PIC16F84a PIC18F1320, PIC18F1220, PIC18F1330, PIC18F1230
28 PIC16F876a PIC18F2620, PIC18F2525, PIC18F2420
40 PIC16F877a PIC18F4620, PIC18F4525, PIC18F4420
40 USB supported Best features PIC18F4550

 

 

 

 

Microchip Microcontroller Common Function Pin Out.
The following table provides a quick overall view the various essential pins of microchip microcontroller, to allow the use of alternative part no., and allowing PCB design to suit the most common pin out.

  Specification ICSP pin out Vcap pin out OSC pin out UART fixed pin out  Preferred I/O use Comment
Microcontroller part no. Package /Pin no. Volt !MCLR Vdd (+) Vss (-) PGD1 PGC1 PGD2 PGC2 PGD3 PGC3 Vcap DisVreg OSC1 OSC2 TX1 RX1 TX2 RX2 Input Output  
                                             
64 pins                                            
PIC24HJ256GP206A TQFP/64 3V – 3.6V 7 10
19
26
38
57
9
20
25
41
18 17 47 48 16 15 56   39 40 33 34 32 31      
44 pins                                            
PIC24FJ64GA004 TQFP/44 2V – 3.6V 18 17
28
40

16
29
39

21 22 8 9 41 42 7 6 30 31             EEPROM
PIC24FJ64GA104 TQFP/44 2V – 3.6V 18 17
28
40
16
29
39
21 22 8 9 41 42 7 6 30 31              
PIC24FJ64GB004 TQFP/44 2V – 3.6V 18 17
28
40
16
29
39
21 22 8 9 19 20 7 6 30 31              
PIC24F32KA304 TQFP/44 1.8V – 5.5V 18 17
28
40
16
29
39
21 22 8 9 41 42 7   30 31 3 2 21 22      
PIC24FJ32MC104 TQFP/44 3V – 3.6V 18 17
28
40
6
16
29
39
21 22 19 20 33 34 7   30 31              
dsPIC30F2023 TQFP/44 3V – 5.5V 18 7
17
29
40
6
17
30
39
44 1 34 35 41 42     32 33 20 15 34 35      
dsPIC33FJ128GP804 TQFP/44 3V – 3.6V 18 17
28
40
16
29
39
21 22 8 9 41 42 7 6 30 31              No EEPROM
dsPIC33FJ32MC104 TQFP/44 3V – 3.6V                                        
dsPIC33FJ128MC804 TQFP/44 3V – 3.6V 18 17
28
40
6
16
29
39
21 22 8 9 41 42 7   30 31              
dsPIC33FJ16GS504 TQFP/44 3V – 3.6V 18

17
29
40

6
16
30
39
44 1 34 35 41 42 7   32 33              
dsPIC33EP128GM304                                           8x input capture, 12x PWM, 4x UART, 3x SPI, 18x ADC
Microcontroller part no. Package /Pin no. Volt !MCLR Vdd (+) Vss (-) PGD1 PGC1 PGD2 PGC2 PGD3 PGC3 Vcap DisVreg OSC1 OSC2 TX1 RX1 TX2 RX2 Input Output  
                                             
28 pins                                            
PIC24F16KL402 SOIC/28 1.8V – 3.6V 1 13
28
8
27
4 5 21 22 14 15     9 10 16 6 4 5      
PIC24F32KA302 SOIC/28 1.8V – 5.5V 1 13
28
8
27
4 5 21 22 14 15     9 10 16 6 4 5      
PIC24FJ64GA002 SOIC/28 2V – 3.6V 1 13
28
8
27
4 5 21 22 14 15 20 19 9 10              EEPROM
PIC24FJ64GA102 SOIC/28 2V – 3.6V 1 13
28
8
27
4 5 21 22 14 15 20 19 9 10              
PIC24FJ64GB002 SOIC/28 2V – 3.6V 1 13
28
8
27
4 5 21 22     20 19 9 10              
PIC24FJ32MC102 SOIC/28 3V – 3.6V 1 13
28
19
27
4 5 2 3 11 12 20   9 10              
dsPIC30F2010 SOIC/28 2.5V – 5.5V 1 13
20
28

8
19
27

17 18             9

10

 

17 18 11 12      
dsPIC30F2020 SOIC/28 3V – 5.5V 1 13
20
28
8
19
27
17 18 11 12 14 15     9 10 17 18 11 12      
dsPIC30F2012 SOIC/28 2.5V – 5.5V 1 13
20
28
8
19
27
17 18





9 10 17 18 11 12


dsPIC30F3010 SOIC/28 2.5V – 5.5V 1 13
20
28
8
19
27
17 18             9 10 17 18 11 12      
dsPIC30F3013 SOIC/28 2.5V – 5.5V 1 13
20
28
8
19
27
17 18             9 10 17 18 21
11
22
12
     
dsPIC30F4012 SOIC/28 2.5V – 5.5V 1 13
20
28
8
19
27
17 18             9 10 17 18 11 12      
dsPIC33FJ32GP102 SOIC/28 3V – 3.6V 1 13
28
8
19
27
4 5 2 3 11 12 20   9 10              
dsPIC33FJ128GP802 SOIC/28 3V – 3.6V 1 13
28
8
19
27
4 5 21 22 14 15 20   9 10              
dsPIC33FJ128MC802 SOIC/28 3V – 3.6V 1 13
28

8
19
27

4 5 21 22 14 15 20   9 10              
dsPIC33FJ09GS302 SOIC/28 3V – 3.6V 1 13
28
8
19
27
17 18 11 12 14 15 20   9 10              
dsPIC33FJ16GS502 SOIC/28 3V – 3.6V 1 13
28
8
19
27
17 18 11 12 14 15 20   9 10              
Microcontroller part no. Package /Pin no. Volt !MCLR Vdd (+) Vss (-) PGD1 PGC1 PGD2 PGC2 PGD3 PGC3 Vcap DisVreg OSC1 OSC2 TX1 RX1 TX2 RX2 Input Output  
                                             
20pins                                            
dsPIC33FJ12MC201                                           Quite mature product.
PIC16F18344
PIC16F18345
PIC16F18346
SSOP/20
1.8V – 5.5V 4 1
20
19
18








19
18




***new
Same series as PIC16F18325
                                             
18pins





















dsPIC30F3012 SOIC/18 2.5V – 5.5V 1 14, 18
13, 17 11 12





6 7 11 12



Mid number of I/O, operating at 5V.























14pins                                            
PIC24F04KA200 TSSOP/14 1.8V – 3.6V 1 14 13     3 2 6 7     4 5 11 12     10  

EEPROM
Code Protection
Warning!!!-> very very little memory, 4K only. Not enough for comfortable protocol processing. Please take note.

(Don’t use this in future. Use alternative PIC16F1825)

PIC24F08KL200  TSSOP/14 1.8V – 3.6V 1 14 13     3 2 6 7     4 5 11 12     10  

Compatiable to PIC24F04KA200, with more memory.
Face problem dealing with UART on its revision A0.

(Don’t use this in future. Having problem using the I/O pins as input (RA4, RB4, RA2, RA3), no access to AD1PCFG to enable digital input. Use alternative PIC16F1825)

PIC16F1825 TSSOP/14 1.8V – 5.5V
4
1
14
13
12






2
3
13
12
6
5


Wide voltage range for a middle size chip. 12x I/O pins. Internal weak pull-up don’t work too well as voltage starts to drop when too many pull-up gets loaded (better design with external pull up).
Not suitable for high speed signal processing (for <10us switching speed).
PIC16F18323
PIC16F18324
PIC16F18325
PIC16F18326
TSSOP/14 1.8V – 5.5V 4 1 14 13 12







13 12



***new
– EEPROM
Same series as PIC16F18345
                                             
8 pins                                            
PIC16F18313
SOIC/8 1.8V – 5.5V 4 1 8 7 6             2 3 7
6



compatiable to the 16F1832x, 34x series SOIC footprint.
PIC12F1840
(consider using cheaper PIC16F18313)
SOIC/8 1.8V – 5.5V 4 1 8 7 6             2 3 7
6         UART
PIC12F1822 SOIC/8 1.8V – 5.5V 4 1 8 7 6             2 3 7 6         UART
PIC12HV615 SOIC/8 2-15V 4 1 8 7 6             2 3             2-15V
PIC12F508 SOIC/8 2-5.5V 4 1 8 7 6             2 3             low cost
Microcontroller part no. Package /Pin no. Volt !MCLR Vdd (+) Vss (-) PGD1 PGC1 PGD2 PGC2 PGD3 PGC3 Vcap DisVreg OSC1 OSC2 TX1 RX1 TX2 RX2 Input Output  
                                             
6 pins                                            
PIC10F322 SOT23/6 1.8V – 5.5V 6 5 2 1 3             3           4, 6 1, 3 most powerful
PIC10F200 SOT23/6 2V – 5.5V 6 5 2 1 3                         4, 6 1, 3 low cost

Legend

Product Identification System (example)

dsPIC 33 FJ 16 MC1 02 T E / SP – XXX
—– — — — — — – –   —   —
1     2  3  4  5   6  7 8   9    10

1 – Microchip Trademark
2 – Architecture
    10 – 
    12 – 
    16 – 
    18 – 
    24 – 16-bit Microcontroller
    30 – 
    33 – 16-bit Digital Signal Controller
3 – Flash Memory Family
    FJ – Flash program memory, 3.3V
    F  – Flash
    EP – Enhanced Performance
    HJ – Flash program memory, 3.3V, High-speed
4 – Program Memory Size (Kbyte)
5 – Product Group
    GP? – General Purpose family
    MC1 – Motor Control family
    GS? – Switch Mode Power Supply (SMPS) family
6 – Pin Count
    01 – 18-pin and 20-pin
    02 – 28-pin and 32-pin
    04 – 44-pin
    06 – 64-pin
    10 – 100-pin
7 – Tape and Reel Flag
       – Standard packaging (tube or tray)
    T  – Tape and Reel
8 – Temperature Range
    I  – -40ºC to +85ºC  (Industrial)
    E  – -40ºC to +125ºC (Extended)
    H  – -40ºC to +150ºC (High)
9 – Package
    P  – PDIP  (Plastic Dual In-Line)
    SS – SSOP  (Plastic Shrink Small Outline)
    SP – SPDIP (Shinny Plastic Dual In-Line)
    SO – SOIC  (Plastic Small Outline)
    SN – SOIC  (8-Lead)
    SL – SOIC
    ML – QFN   (Plastic Quad, No Lead)
    MR – QFN   (Thin Quad Flatpack)
    MG – QFN   (Micro Lead Frame)
    MM – QFN-S   (Plastic Quad, No Lead)
    MV – UQFN
    PT – TQFP  (Plastic Thin Quad Flatpack)
    PF – TQFP  (Plastic Thin Quad Flatpack, 14x14mm)
    ST – TSSOP
    TL – VTLA  (Very Thin Leadless Array)
    MF – Micro Lead Frame (DFN)
    MC – DFN
    OT – SOT-23
10- Pattern
    QTP, SQTP, Code or Special Requirements

It is a headache trying to maximise the pin compatibility with a wider range of microcontrollers and applications,
such that firmware changes can be minimised.
The following are suggesting pins use for reference, base on the following microcontroller:

Microcontroller part no. Package /Pin no. Volt !MCLR Vdd (+) Vss (-) PGD PGC OSC1 OSC2 TX1 RX1 TX1
Ctrl
TX2 RX2 TX2
Ctrl
Output
Indicators
Input
Switch
Input
Analog
I/O PWM        
                                                 
44 pins                                                
PIC24FJ64GA002 TQFP/44 2V – 3.6V 18 17
28
40

16
29
39

21 22 30 31 44 1 3 8 9 10 33, 34, 41 21, 22 19,20 15, 14, 11, 10          
PIC24FJ64GA002 SOIC/28 2V – 3.6V 1 13
28
8
27
4 5 9 10 17 18 16 21
11
22
12
23 11, 12, 14 4, 5 2,3 26, 25, 24, 23          
PIC12F1840     4 1 8 7 6 2 3 7 6         7, 6 4, 7, 6 3, 5            
PIC10F322     6 5 2 1 3                 1, 3 6, 1, 3 1, 3, 4 4 1, 3        

 

 

 

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

Singapore Customized, custom made Electronics Circuits & Kits

 

 

PIC10F206 Microcontroller Schematic

source code:
2011-11-30 mini RGB microcontroller (c).zip
2011-11-30 mini RGB microcontroller (asm).zip


 

 

 

Microchip MPLAB microcontroller startup troubleshooting guide.

2009-10-08

Getting my “hello world” firmware loaded into my new hardware design pose the most difficult part of the process. Time consuming doing debugging, and it can takes from half a day to two. The most difficult part, to spent those precious engineering time in debugging. Debugging what I thought I should be good in since I have done so many microcontroller project. Till this day, I still have the problem every time I start microcontroller project after a few months break. The reason I have this guide written. To provide myself possible solution, that can help me, if I encounter the same issue again.

 

 

Setting up the environment for project using MPLAB v8.70

1) Create a project folder. Open the MPLAB IDE software.

2) Open a new Project. Project>New… and enter in a name for the project.

3) Select the microcontroller that is use in the project. Configure>Select Device… and select the microcontroller for your project.

4) Check the configuration mode ‘Release’. Project>Build Configuration>Release

5) Select the correct toolsuite for your project. Project>Select Language Toolsuite… for typical C lanaguage implementation, choose “MPLAB” C30 C Complier (pic-30-gcc.exe) v3.24

6) Add in the search path for your microcontroller’s header file. Project>Build Options…>Project>Directories>Include Search Path, choose add to add in the directory that contains the microcontroller’s header files. For my example, the header is located in the directory “C:\Program Files (x86)\Microchip\MPLAB C30\support\dsPIC33F\h”

7) Add in or create all the *.c & *.h files, to start your programming.

 

 
I use PICkit2 most of the time, because it is a small and compact programmer. Today, I tried out PICkit3. Well I am quite impress with the changes from PICkit2. I hope to get that one day. As for this article, the error messages is meant for PICkit2 use on the IDE Mplab version 8.36.

I do not have much problem doing the compilation of my C programs. The frustration comes during the loading of my hex codes into my newly design prototype circuit. Most of the time is due to human error, because my prototype board are mainly hand soldered, pin by pin.

On the left is the typical error message I encounter. I am scare of them to be frank. I see them almost every time.

 

Initialisation of PICkit2 when connected to Mplab

Initializing PICkit 2 version 0.0.3.63
Found PICkit 2 – Operating System Version 2.32.0
Target power not detected – Powering from PICkit 2 ( 3.30V)
PKWarn0003: Unexpected device ID:  Please verify that a PIC24FJ32GA004 is correctly installed in the application.  (Expected ID = 0x44D0000, ID Read = 0x0)
PICkit 2 Ready

Every time when I press the shortcut key Alt+G, G to program the controller, PICkit will attempt to read the device ID of the microcontroller. The microcontroller used in this example is PIC24FJ32GA004.

As you can see in the error on the right. PICkit is expecting the microcontroller with device ID 0x44D0000. The read by PICkit detects a ID of 0x0. In fact this same error is identical as if the PICkit programmer is not inserted to the ICSP programming pins at all.

This is a hard evident that the microcontroller is not wired properly or evenly not wired at all.

 

Error Encounter using PICkit2 version 2.63, MPLAB version 8.36

Programming Target (10/8/2009  4:37:06 PM)
PKWarn0003: Unexpected device ID:  Please verify that a PIC24FJ32GA004 is correctly installed in the application.  (Expected ID = 0x44D0000, ID Read = 0x0)
Erasing Target
Programming Program Memory (0x0 – 0x23FF)
   PE Error: Using ICSP
Verifying Program Memory (0x0 – 0x23FF)
   PE Error: Using ICSP
PK2Error0027:  Failed verify (Address = 0x0 – Expected Value 0x40200 – Value Read 0x0)
PICkit 2 Ready

 

1) The first thing to check if your hardware. It is most of the time the source of the problem. Check if the ICSP programming pins are wired correctly

ICSP pin out

Pin 1: !MCLR

Pin 2: Vdd (3.3V or 5V, depends on the device)

Pin 3: Vss (ground)

Pin 4: PGD (data line)

Pin 5: PGC (clocking line)

Pin 6: unused

 

Attached on the left is the basic schematic of the microcontroller PIC24FJ32GA004 if your wiring is exactly the same as what is shown, PICkit2 should be able to load the hex file into your controller without any problem.

An advise to you, don’t assume that your wiring is correct. Check 2 or more times to ensure. This is often one of my major mistake make. The schematic is typically correct, but because of the confident doing many similar project, the checking is often the lacking part.

For PIC24FJ series controller, there is a pin Vcap & DISVREG. Make sure that there is the capacitor there. !MCLR pin to be pull up to Vdd using a resistor about 10kohm.

The following pins are to be connected to PIC24FJ32GA004, in order for the ICSP programmer to download the *.hex files onto the microcontroller. Improper connection will definitely generate programming error messages.

 

Pins connection

Pin 18 connect to !MCLR
Pin 17, 28, 40 connect to Vdd (3.3V)
Pin 6, 16, 29, 39 connect to Vss (Gnd)
Pin 21 connect to PGD
Pin 22 connect to PGC
Pin 7 connect to as Vcap

 

Socket holder for PIC24FJ32GA004 TQFP-44 prototype board

Front

Back

 

TQFP-44 Prototype board or adaptor

This sub-board adaptor helps to convert small smd components to 2.54mm pitch for mounting onto pcb. The larger 2.54mm pitch will be easier to work with when doing prototyping. The board is available from PIC-CONTROL part no. PIC-200

pic-control smd adaptor http://www.pic-control.com/product/index.htm

 

 

2) Check if the header file declare in the source code is correct
#define    __PIC24FJ32GA004__
#include “p24fxxxx.h”

This actually informs the PICkit programmer what type of device it is going to encounter. This is also why the error message indicates the expected ID of 0x44D0000, which is the device ID for PIC24FJ32GA004 microcontroller.

Some example of other device ID for PIC24FJ series microcontroller.

Microcontroller          Device ID

PIC24FJ16GA002     0x00444

PIC24FJ32GA002     0x00445

PIC24FJ48GA002     0x004466

PIC24FJ64GA002     0x00447

PIC24FJ16GA004     0x0044C

PIC24FJ32GA004     0x0044D

PIC24FJ48GA004     0x0044E

PIC24FJ64GA004     0x0044F

You might double check if the microcontroller device is selected correctly under the menu “Configure”. It is probably not necessary as the device select is base on what is written with your source code.

 

 
3) Check if you have included the correct linker file for the microcontroller PIC24FJ32GA004. The file name goes something like this, “p24FJ32GA004.gld”. The file is available under the C30 folder “C:\Program Files\Microchip\MPLAB C30\support\PIC24F\gld”, after you installed the C30 compiler for your Mplab.

 

 
4) Do not solder capacitors on PGD, PGC pins. PGD PGC can be use for programming as well as I/O during operation. Due to the programming use, I will usually design this pin as an input during operational. This feature do free up the controller pins for other uses. Using it as an input, it does not have any load to worry about. There is one time I added capacitor across the input and ground, thinking that it may filter any switching noise from the switch input. The capacitor turns out to cause problem to the PGD PGC pins. It results in a slow slew rate causing data error during program loading.

 

Check out the following notes when designing ICSP on your microchip microcontroller.
Click to enlarge.

5) Ensure that your circuit is powered from it’s own power source. This is especially needed if you have a big load of components on our board. The PICkit programmer might not be able to support all those power. Sometimes the PICkit doesn’t provide the power. There should be a settings that allows your PICkit to supply the power.

 

 
Another similar error occur. This time round, the device ID is read as 0xFFFF0000. I found the problem and it happens that the ICSP pin 4 (PGD, data) and pin 5 (PGC, clock) has been wire wrongly. They are swapped. Programming Target (10/8/2009  6:13:18 PM)
PKWarn0003: Unexpected device ID:  Please verify that a PIC24FJ32GA004 is correctly installed in the application.  (Expected ID = 0x44D0000, ID Read = 0xFFFF0000)
Erasing Target
Programming Program Memory (0x0 – 0x23FF)
   PE Error: Using ICSP
Verifying Program Memory (0x0 – 0x23FF)
   PE Error: Using ICSP
PK2Error0027:  Failed verify (Address = 0x0 – Expected Value 0x40200 – Value Read 0xFFFFFF)

 

When the PICkit2 has sucessfully loaded the hex file into the microcontroller chip, you should see the message on the right. PICkit2 program loaded into microcontroller sucessfully

Programming Target (10/9/2009  10:30:46 AM)
PIC24FJ32GA004 found (Rev 0x3003)
Erasing Target
Programming Program Memory (0x0 – 0x23FF)
  (Using Programming Executive)
Verifying Program Memory (0x0 – 0x23FF)
  (Using Programming Executive)
Programming Configuration Memory
Verifying Configuration Memory
PICkit 2 Ready

   

 
   
   

 

Error Message Encountered Solution:

Error encountered while loading codes onto the chip:

“You are trying to change protected boot and secure memory. In order to do this you must select the “Boot, Secure and General Segments” option on the debug tool Secure Segment properties page. Failed to program device”

To program a chip that is code protected, need to set PICkit3 into a special mode.

go to project property>Conf:[default]>PICkit 3>Option categories>Secure Segment>Segments to be Programmed>Boot, Secure and General Segments

Try re-program the chip again. The new code should be able to over-write the old codes on the chip.

Alternative old solution method:
Solution: Goto Programmer > Settings > Secure Segment. Then do a “Earse Flash Device”


 

 

Useful C30 compiler pre-processor  
   

#define FIRMWARE_DATED __DATE__

//microcontroller dsPIC33FJ128GP804
#include “p33fxxxx.h”

#define CRYSTAL_MHZ 8
//#define CRYSTAL_MHZ 20

#define XBEE_BAUDRATE _115200bps

#define NUM_OF_LOADCELL 4
#if NUM_OF_LOADCELL == 4
   #define XXX
#elif NUM_OF_LOADCELL == 3
   #define XXX
#elif NUM_OF_LOADCELL == 2
   #define XXX
#elif NUM_OF_LOADCELL == 1
   #define XXX
#else
   #define XXX
#endif

//Features Check
#ifdef __HAS_EEDATA__
   #define XXX
#endif
   #define XXX
#ifdef __HAS_DSP__
   #define XXX
#endif
#ifdef __HAS_5VOLTS__
   #define XXX
#endif
#ifdef __HAS_CODEGUARD__
   #define XXX
#endif
#ifdef __HAS_DSP__
   #define XXX
#endif

#warning Testing only      //print warning message during compile time
#error “No Size 4”      //print error messageduring compile time

//Useful symbols which can be use to load the file name, code line and date of the code compilation
//__FILE__, __LINE__, __DATE__, __TIME__, __FUNCTION__ or __func__

 

 

 

Useful C30 codes  

Important, what to put in a header *.h.
macro definitions (preprocessor #defines)
structure, union, and enumeration declarations
typedef declarations
external function declarations
global variable declarations

Configuration Settings Reference

PIC18 Configuration Settings Addendum, 51537a.pdf

Configuration bits generator.
1) Open MPLABx, go to Window > PIC Memory views > Configuration Bits
2) A Configuration Bits section will be shown. Setup the configuration bits accordingly.
3) After the setting is done, click on the button “Generate Source Code to Output”
4) Copy and paste the configuration code to your source code.
List of interrupts

For XC8

void __interrupt(high_priority) Interrupt_ISR()


For XC16

void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _DefaultInterrupt(void)

Note: Be careful when implementing the “DefaultInterrupt”, as all interrupt vector may point to this rountine. (2016-02-05)


void __attribute__((__interrupt__,auto_psv,__shadow__)) _U1RXInterrupt(void)
void __attribute__((__interrupt__,auto_psv,__shadow__)) _U1TXInterrupt(void)
void __attribute__((__interrupt__,auto_psv,__shadow__)) _U2RXInterrupt(void)
void __attribute__((__interrupt__,auto_psv,__shadow__)) _U2TXInterrupt(void)

void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _IC1Interrupt() //input capture interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _IC2Interrupt() //input capture interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _CNInterrupt() //input change interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _INT0Interrupt() //external interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _INT1Interrupt() //external interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _INT2Interrupt() //external interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _INT3Interrupt() //external interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _INT4Interrupt() //external interrupt

void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T1Interrupt(void) //timer 1 interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T2Interrupt(void) //timer 2 interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T3Interrupt(void) //timer 3 interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T4Interrupt(void) //timer 4 interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T5Interrupt(void) //timer 5 interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T6Interrupt(void) //timer 6 interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T7Interrupt(void) //timer 7 interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T8Interrupt(void) //timer 8 interrupt
void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T9Interrupt(void) //timer 9 interrupt

void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _SPI1Interrupt(void);


Data type structure. Useful in creating access for data bits, byte or word. This helps saves memory space and data handling codes.

//Settings for individual channel

#define NUMOFCHANNEL 8
#define LED_CH_DATASIZE 8

typedef union
{
unsigned int words[LED_CH_DATASIZE]; //array arranged from low byte to high byte
unsigned char bytes[LED_CH_DATASIZE*2]; //array arranged from low byte to high byte
struct
{
//LSB
unsigned currentlimit:12; //set the absolute Led current rating. If value is 0, it means that current is allowed to shot to the max.
unsigned posEdge:1; //0-positive, 1-negative edge or level trigger
unsigned mode:3; //operating mode
unsigned pulsewidthlimit:16; //max pulse width permitted. (for pulsing mode use)
unsigned retriggerperiod:16; //periodic auto trigger of the pulse. (for pulsing mode use)
unsigned current:12; //current
unsigned stepNum:4; //number of steps before reset
unsigned pulsedelay:16; //the delay before pulse on the LED after a trigger. (for pulsing mode use)
unsigned pulsewidth:16; //pulse width of the pulse. (for pulsing mode use)
unsigned current_null:12; //calibrated current value.
unsigned unused:4; //unused
unsigned unused2:16; //unused
//MSB
};
}LED_CHANNELPROPERTIES;
LED_CHANNELPROPERTIES ledCh[NUMOFCHANNEL];        //creating a variable “ledCh” base on the data type structure LED_CHANNELPROPERTIES.

//Accessing data on the Data structure
ledCh[ch].mode = 0b001;        //accessing the bits (a group of 3 bits) under the variable member “mode”, without affecting the rest of the data in the structure.
ledCh[ch].posEdge = 0b0;        //accessing the bit under the variable member “posEdge”, without affecting the rest of the data in the structure.
ledCh[ch].words[0] = 0x0000;
ledCh[ch].bytes[0] = 0x00;

———————————————————–

//another example of a data type structure

typedef union
{
unsigned int words[NUMOFWORD_PERSTEP_PERCH];        //array arranged from low byte to high byte
unsigned char bytes[NUMOFWORD_PERSTEP_PERCH*2];        //array arranged from low byte to high byte
struct
{
//LSB
unsigned current:12;
unsigned enable:1; //on/off. 0-not in use, 1-in use
unsigned unused:3;
unsigned pulsedelay:16;
unsigned pulsewidth:16;
//MSB
};
}INTRIGGER_CHANNELPROPERTIES;
INTRIGGER_CHANNELPROPERTIES inTrigCh[NUMOFCHANNEL][MAX_NUMOFSTEPS][NUMOFCHANNEL]; //inTrigCh[input trigger channel][step no.][output LED channel]

//accessing the data structure
inTrigCh[inputCh][stepNum][outputCh].enable = 0b1;        //accessing the enable bit, without affecting the rest of the data in the structure.

 

———————————————————–

typedef union
{
//reset variables for dsPIC33FJ128GP804
unsigned int resetStates;
struct
{
unsigned POR :1; //Power-on Reset Flag bit
unsigned BOR :1; //Brown-out Reset Flag bit
unsigned IDLE :1; //Wake-up From Idle Flag bit
unsigned SLEEP :1; //Wake From Sleep Flag bit
unsigned WDTO :1; //Watchdog Timer Time-out Flag bit
unsigned SWDTEN :1; //Software Enable/Disable of WDT bit
unsigned SWR :1; //Software RESET (Instruction) Flag bit
unsigned EXTR :1; //External Reset (MCLR) Pin bit
unsigned LVDL :4; //Low Voltage Detection Limit bits
unsigned LVDEN :1; //Low Voltage Detect Power Enable bit
unsigned BGST :1; //Bandgap Stable bit
unsigned IOPUWR :1; //Illegal Opcode or Uninitialized W Access Reset Flag bit
unsigned TRAPR :1; //Trap Reset Flag bit
};
}RESET;
volatile RESET reset; //storage for configuration flags status

———————————————————–

typedef union
{
unsigned long reading[4]; //decimal reading value
unsigned char bytes[4][4]; //storage for data

// readingXXX.reading[0] = 0x00000123;
// readingXXX.reading[1] = 0x00004567;
// readingXXX.reading[2] = 0x000089AB;
// readingXXX.reading[3] = 0x0000CDEF;

//print seq 00 00 01 23 00 00 45 67 00 00 89 AB 00 00 CD EF
// uart1TX(readingXXX.bytes[0][3]);
// uart1TX(readingXXX.bytes[0][2]);
// uart1TX(readingXXX.bytes[0][1]);
// uart1TX(readingXXX.bytes[0][0]);
// uart1TX(readingXXX.bytes[1][3]);
// uart1TX(readingXXX.bytes[1][2]);
// uart1TX(readingXXX.bytes[1][1]);
// uart1TX(readingXXX.bytes[1][0]);
// uart1TX(readingXXX.bytes[2][3]);
// uart1TX(readingXXX.bytes[2][2]);
// uart1TX(readingXXX.bytes[2][1]);
// uart1TX(readingXXX.bytes[2][0]);
// uart1TX(readingXXX.bytes[3][3]);
// uart1TX(readingXXX.bytes[3][2]);
// uart1TX(readingXXX.bytes[3][1]);
// uart1TX(readingXXX.bytes[3][0]);

}DATAREADING;
DATAREADING reading;

———————————————————–

//Complex data union, data struct example

typedef enum
{
    CONFIG0=0,
    CONFIG1=1,
    CONFIG2=2,
    CONFIG3=3,
    CONFIG4=4,
    CONFIG5=5,
    MASK=6,
    RUN=7,
    Dianostic=8
}A4963_REGISTER;

typedef struct
{
    unsigned CL:1;
    unsigned CH:1;
    unsigned BL:1;
    unsigned BH:1;
    unsigned AL:1;
    unsigned AH:1;
    unsigned :1;
    unsigned VS:1;
    unsigned :1;
    unsigned LOS:1;
    unsigned OT:1;
    unsigned TW:1;
    unsigned WR:1;
    unsigned REG_ADDR:3;
}REG_DIAGNOSTIC;

typedef union
{
    //array arranged from low byte to high byte
    unsigned int words[9];       
    struct
    {
        //LSB
        struct
        {
            unsigned DT:6;
            unsigned BT:4;
            unsigned RM:2;
            unsigned WR:1;
            unsigned REG_ADDR:3;
        }config0;
        struct
        {
            unsigned VT:5;
            unsigned VDQ:1;
            unsigned VIL:4;
            unsigned IPI:1;
            unsigned PFD:1;
            unsigned WR:1;
            unsigned REG_ADDR:3;
        }config1;
        struct
        {
            unsigned PW:5;
            unsigned DGC:1;
            unsigned SH:2;
            unsigned CP:4;
            unsigned WR:1;
            unsigned REG_ADDR:3;
        }config2;
        struct
        {
            unsigned HT:4;
            unsigned HD:4;
            unsigned CI:4;
            unsigned WR:1;
            unsigned REG_ADDR:3;
        }config3;
        struct
        {
            unsigned SS:4;
            unsigned SD:4;
            unsigned SP:4;
            unsigned WR:1;
            unsigned REG_ADDR:3;
        }config4;
        struct
        {
            unsigned PA:4;
            unsigned SMX:3;
            unsigned SPO:1;
            unsigned SI:4;
            unsigned WR:1;
            unsigned REG_ADDR:3;
        }config5;
        REG_DIAGNOSTIC mask;
        struct
        {
            unsigned RUN:1;
            unsigned DIR:1;
            unsigned BRK:1;
            unsigned RSC:1;
            unsigned DI:5;
            unsigned ESF:1;
            unsigned CM:2;
            unsigned WR:1;
            unsigned REG_ADDR:3;
        }run;
        REG_DIAGNOSTIC diagnostic;
        //MSB
    };
}A4963_DATA;
volatile A4963_DATA a4963_data; //storage for configuration flags status

a4963_data.config0.DT = 0;
a4963_data.config1.VT = 0;
a4963_data.config2.PW = 0;
a4963_data.config3.HT = 0;
a4963_data.config4.SS = 0;
a4963_data.config5.PA = 0;
a4963_data.mask.CL = 0;
a4963_data.run.RUN = 0;
a4963_data.diagnostic.CL = 0;

———————————————————–

 

enum

Example1 of how to use enum. (see better example2)

Create a header file for Enum “Enum.h”, and place the following enum defintion,

enum BOOLEAN
{
    FALSE=0,
    TRUE=1
};

————————————————————–

For each of the *.c file that you want to use the enum BOOLEAN, include the header file “Enum.h”.

1) declare a enum variable
enum BOOLEAN flag = FALSE;

2) declare a function
enum BOOLEAN isDone()
{
    return(flag);
}

————————————————————–

For header *.h file that you want to use the enum BOOLEAN,

extern enum BOOLEAN;
enum BOOLEAN isDone();

####################################################################################

Example2 of how to use enum. (betterexample)

Create a header file for Enum “Enum.h”, and place the following enum defintion,

typedef enum
{
    FALSE=0,
    TRUE=1
}BOOLEAN;

————————————————————–

For each of the *.c file that you want to use the enum BOOLEAN, include the header file “Enum.h”.

1) declare a enum variable
BOOLEAN flag = FALSE;

2) declare a function
BOOLEAN isDone()
{
    return(flag);
}

————————————————————–

For header *.h file that you want to use the enum BOOLEAN,

(have problem here with enum. Prototype declare in the header cannot have the enum as data type.)

extern BOOLEAN;
BOOLEAN isDone();

enum PORTIN
{
CH1=0,
CH2=1,
CH3=2,
CH4=3,
CH5=4,
CH6=5,
CH7=6,
CH8=7,
IN1=0,
IN2=1,
IN3=2,
IN4=3,
IN5=4,
IN6=5,
IN7=6,
IN8=7
};

enum LED_MODE
{
CONTINUOUS=1,
SWITCH=2,
PULSE=3,
};

enum EDGE
{
POS_EDGE=0,
NEG_EDGE=1
};

//define enum type “EDGE”
typedef enum
{
POS_EDGE=0,
NEG_EDGE=1
}EDGE;

//declare a variable “myEdgeVar” of type EDGE
EDGE myEdgeVar = POS_EDGE;

//passing type through function
EDGE myFunction(EDGE myVar)
{
}
 

void initOscillator()
{
// Configure Oscillator to operate the device at 40Mhz
// Fosc= ((Fin/N1)*M)/N2, Fcy=Fosc/2
// N1=4, M=32, N2=2, Crystal = 20MHz
// Fosc= ((20M/4)*32)/2
// Fosc = 80Mhz for 20MHz input clock
// Fcy = Fosc / 2 = 40 MIPS

#ifdef dsPIC33FJ256GP506A
#ifdef FOSC_80MHZ
PLLFBDbits.PLLDIV = 30; // M=32
CLKDIVbits.PLLPRE = 0b00010; // N1=4
#endif
CLKDIVbits.PLLPOST = 0b00; // N2=2
OSCTUNbits.TUN = 0; // Tune FRC oscillator, if FRC is used
RCONbits.SWDTEN=0; // Disable Watch Dog Timer
while(OSCCONbits.LOCK!=1) {}; // Wait for PLL to lock
/*
#elif dsPIC33FJ128GP804
#ifdef FOSC_80MHZ
PLLFBDbits.PLLDIV = 38; // M=40
CLKDIVbits.PLLPRE = 0b00000; // N2=2
#endif
#ifdef FOSC_40MHZ
//Config for 40MHz temporary instead
PLLFBDbits.PLLDIV = 38; // M=40
CLKDIVbits.PLLPRE = 0b00010; // N2=4
#endif

CLKDIVbits.PLLPOST = 0b00; // N1=2
OSCTUNbits.TUN = 0; // Tune FRC oscillator, if FRC is used
RCONbits.SWDTEN=0; // Disable Watch Dog Timer
while(OSCCONbits.LOCK!=1) {}; // Wait for PLL to lock
*/
#endif

//PLL module, Fosc = Fin*(M/(N1*N2))
//= Fin * ((PLLDIV+2)/((PLLPRE+2)*2*(PLLPOST+1)))
//= 8Mhz * ((38+2)/((0+2)*2*(0+1)))
//= 8Mhz * (40/(2*2*1))
//Fosc = 80Mhz

//PLLPRE==2, PLLPOST==0, PLLDIV==78
//= 8Mhz * ((78+2)/((2+2)*2*(0+1)))
//= 8Mhz * (80/(4*2*1))
//Fosc = 80Mhz

//PLLDIV==37
//= 8Mhz * ((37+2)/((0+2)*2*(0+1)))
//= 8Mhz * (39/(2*2*1))
//Fosc = 78Mhz

}

//*************************************************
// IoPinMapping
//*************************************************
//local defination—————–
//define inputPin Function=RPxx pin number
//Input Peripheral pin
#define inputPIN_INT1 RPINR0bits.INT1R
#define inputPIN_INT2 RPINR1bits.INT2R
#define inputPIN_T2CK RPINR3bits.T2CKR
#define inputPIN_T3CK RPINR3bits.T3CKR
#define inputPIN_T4CK RPINR4bits.T4CKR
#define inputPIN_T5CK RPINR4bits.T5CKR
#define inputPIN_IC1 RPINR7bits.IC1R
#define inputPIN_IC2 RPINR7bits.IC2R
#define inputPIN_IC3 RPINR8bits.IC3R
#define inputPIN_IC4 RPINR8bits.IC4R
#define inputPIN_IC5 RPINR9bits.IC5R
#define inputPIN_IC7 RPINR10bits.IC7R
#define inputPIN_IC8 RPINR10bits.IC8R
#define inputPIN_OCFA RPINR11bits.OCFAR
#define inputPIN_OCFB RPINR11bits.OCFBR
#define inputPIN_U1RX RPINR18bits.U1RXR
#define inputPIN_U1CTS RPINR18bits.U1CTSR
#define inputPIN_U2RX RPINR19bits.U2RXR
#define inputPIN_U2CTS RPINR19bits.U2CTSR
#define inputPIN_SDI1 RPINR20bits.SDI1R
#define inputPIN_SCK1IN RPINR20bits.SCK1R
#define inputPIN_SS1IN RPINR21bits.SS1R
#define inputPIN_SDI2 RPINR22bits.SDI2R
#define inputPIN_SCK2IN RPINR22bits.SCK2R
#define inputPIN_SS2IN RPINR23bits.SS2R

//define RPxx pin number=outputPin Function
//RP pins
#define RP00 RPOR0bits.RP0R
#define RP01 RPOR0bits.RP1R
#define RP02 RPOR1bits.RP2R
#define RP03 RPOR1bits.RP3R
#define RP04 RPOR2bits.RP4R
#define RP05 RPOR2bits.RP5R
#define RP06 RPOR3bits.RP6R
#define RP07 RPOR3bits.RP7R
#define RP08 RPOR4bits.RP8R
#define RP09 RPOR4bits.RP9R
#define RP10 RPOR5bits.RP10R
#define RP11 RPOR5bits.RP11R
#define RP12 RPOR6bits.RP12R
#define RP13 RPOR6bits.RP13R
#define RP14 RPOR7bits.RP14R
#define RP15 RPOR7bits.RP15R
#define RP16 RPOR8bits.RP16R
#define RP17 RPOR8bits.RP17R
#define RP18 RPOR9bits.RP18R
#define RP19 RPOR9bits.RP19R
#define RP20 RPOR10bits.RP20R
#define RP21 RPOR10bits.RP21R
#define RP22 RPOR11bits.RP22R
#define RP23 RPOR11bits.RP23R
#define RP24 RPOR12bits.RP24R
#define RP25 RPOR12bits.RP25R

//Output Peripheral pin
#define outputPin_NULL 0
#define outputPin_C1OUT 1
#define outputPin_C2OUT 2
#define outputPin_U1TX 3
#define outputPin_U1RTS 4
#define outputPin_U2TX 5
#define outputPin_U2RTS 6
#define outputPin_SDO1 7
#define outputPin_SCK1OUT 8
#define outputPin_SS1OUT 9
#define outputPin_SDO2 10
#define outputPin_SCK2OUT 11
#define outputPin_SS2OUT 12
#define outputPin_OC1 18
#define outputPin_OC2 19
#define outputPin_OC3 20
#define outputPin_OC4 21
#define outputPin_OC5 22

/*
void ioPinMapping()
{
//__builtin_write_OSCCONL(OSCCON & 0xbf);
// Unlock Registers – MUST be in asm due to strict timing reqs
asm volatile( “MOV #OSCCON, w1 \n”
“MOV #0x46, w2 \n”
“MOV #0x57, w3 \n”
“MOV.b w2, [w1] \n”
“MOV.b w3, [w1] \n”
“BCLR OSCCON, #6 “);

#ifdef ETHERNET_COMMUNICATION
//map UART1 pins
inputPIN_U1RX=16; //link input U1RX =Pin no.
RP02=outputPin_U1TX; //link output Pin RP17= U1TX
AD1PCFGLbits.PCFG6=1; //ADC config, disable ADC on the pin for input. Input will be digital input instead of the default analog. Output is digital by default, therefore no ADc config on RX pin
AD1PCFGLbits.PCFG4=1; //ADC config, disable ADC on the pin for input. Input will be digital input instead of the default analog. Output is digital by default, therefore no ADc config on TX pin
#endif
#ifdef RS232_COMMUNICATION
//map UART1 pins
inputPIN_U1RX=18; //link input U1RX =Pin no.
RP17=outputPin_U1TX; //link output Pin RP17= U1TX
AD1PCFGLbits.PCFG8=1; //ADC config, disable ADC on the pin for input. Input will be digital input instead of the default analog. Output is digital by default, therefore no ADc config on RX pin
AD1PCFGLbits.PCFG7=1; //ADC config, disable ADC on the pin for input. Input will be digital input instead of the default analog. Output is digital by default, therefore no ADc config on TX pin
#endif

//map UART2 pins
// inputPIN_U2RX=18; //link input U1RX =Pin no.
// RP17=outputPin_U2TX; //link output Pin RP17= U1TX
// AD1PCFGLbits.PCFG8=1; //ADC config, disable ADC on the pin for input. Input will be digital input instead of the default analog. Output is digital by default, therefore no ADc config on RX pin
// AD1PCFGLbits.PCFG7=1; //ADC config, disable ADC on the pin for input. Input will be digital input instead of the default analog. Output is digital by default, therefore no ADc config on TX pin

//map SPI1 pins
inputPIN_SDI1=9; //link input SPI1 data IN =Pin no.
RP22=outputPin_SDO1; //link output Pin = SPI1 data OUT
RP08=outputPin_SCK1OUT; //link output Pin = SPI1 clock output
//RP08=outputPin_SS1OUT; //link output Pin = SPI1 slave select output

//config for input capture
inputPIN_INT1=1; //use input capture as an input1
inputPIN_INT2=21; //use input capture as an input2
inputPIN_IC1=19; //use input capture as an input3
inputPIN_IC2=20; //use input capture as an input4  

//__builtin_write_OSCCONL(OSCCON | 0x40);
// Lock Registers – MUST be in asm due to strict timing reqs
asm volatile( “MOV #OSCCON, w1 \n”
“MOV #0x46, w2 \n”
“MOV #0x57, w3 \n”
“MOV.b w2, [w1] \n”
“MOV.b w3, [w1] \n”
“BCLR OSCCON, #6 “);
}
*/

Clock frequency defination
FOSC – clock frequency (final system clock frequency)
FCY – instruction cycle clock (usually = 1/2 FOSC)
FP – clock frequency source to peripherals (usually = FCY)
Pointer to function.
(Callback function)
Callback structured the *.c file such that they provide services and not access another *.c for services. *.c calling each other can make the code very messy. Service providing class providing services and allow callback will means that calling of functions will allows be from the other class, and not the service providing class.

The example on the right shows a timer interrupt service. Other classes that need to use this interrupt class will register itself and waiting to get called from the registered callback. This means that the interrupt class coding can be written in a generic manner without referencing or calling other classes.
void (*timer1Callback)();             //declare variable for function callback

//register the function for timer callback
void registerTimer1CallBack(void (*f)())
{
    initTimer1();
    timer1Callback = f;
}

void __attribute__((__interrupt__, __shadow__, __auto_psv__)) _T1Interrupt(void)    //timer 1 interrupt
{
    if(timer1Callback != NULL)
        (*timer1Callback)();          //call the registered function.
    IFS0bits.T1IF=0;
}

void initTimer1(void)
{
    T1CONbits.TCKPS=0b11;   //1:256
    T1CONbits.TCS=0;
    T1CONbits.TGATE=0;      //disable TGATE
    T1CONbits.TSYNC=0;      //does not sync with external clock input
    T1CONbits.TSIDL=0;      //continue in idle mode
   
    //PR1=0x023F;             //set period for timer (set to 10ms timer interrupt)
    PR1=0x0039;             //set period for timer (set to 1ms timer interrupt)
 
    //set timer interrupt priority to level 1
    IPC0bits.T1IP=1;
    //clear timer interrupt flag T3IF bit
    IFS0bits.T1IF=0;
    //enable timer3 interrupt
    IEC0bits.T1IE=1;
    //starts the timer
    T1CONbits.TON=1;
}

//———————————————————–
//from another file doing the registration for interrupt to callback

#define RUN_TIMER_COUNT 100

void initRunTimer()
{
    registerTimer1CallBack(timer1msCallBack);     //function registrating a function which can be call back from the interrupt function.
}

void timer1msCallBack()
{
    //interrupt at 1ms interval
    static int runTimerCount = RUN_TIMER_COUNT;
   
    runTimerCount–;
    if(runTimerCount<=0)
    {
        runTimerCount = RUN_TIMER_COUNT;
          indicatorToggle(RUN);
    }
}
Accessing PORTB bits dynamically
Quoted from http://tutor.al-williams.com/pic-detail2.html

First, the I/O pins are tied to the PORT registers, as you’d probably guess. However, on reset, all port pins are set to inputs. If you want to use a port pin as an output, you’ll need to change the corresponding direction bit from a 1 (the default) to a 0. So to prepare PORTB pin 0 for output you might write:

	bsf status,rp0  ; rp0=1 - select bank 1
bcf trisb,0 ; port b direction bit 0 = 0
bcf status,rp0 ; rp0=0 - select bank 0

It is good practice to reset the bank to 0 as soon as you are done accessing another bank. So then if you wanted to set the output to 1 you might write:

        bsf portb,0  

The other quirky behavior is the interaction between INDF and FSR. INDF isn’t like an ordinary register. Instead, it mirrors another register indicated by the address in FSR. For example, location 0x6 is the PORTB register. Suppose you write:

        movlw 6     ; W=6
movwf fsr ; FSR=W

Now the INDF register is really an alias for PORTB. So you might write:

        bsf indf,0  ; set bit 0

 This instruction doesn’t really set bit 0 of INDF, it sets bit 0 of PORTB. Since FSR is an 8-bit register, it can contain a complete address from bank 0 or bank 1 (just treat bank 1 addresses as ranging from 0x80-0xFF). To access bank 3 and and bank 4 using FSR/INDF, you have to set the IRP bit in the STATUS register. RP0 and RP1 don’t apply to INDF access!


Preserving stack memory using inline
void main();
inline void init();
inline void loop();

void main()
{
    initPinMapping();       //peripheral pin select
    getResetType();
    init();
   
    INTCONbits.PEIE = 1;    //enable peripheral interrupt
    INTCONbits.GIE = 1;     //enable global interrupt
   
    while(1)
    {
        loop();
    }
}

inline void init()
{
    initIndicator();
    initProtocol();
    initAudioIn();
}

inline void loop()
{
 
}
Microchip software reset function
for XC16 compiler
asm(“RESET”);

for XC30 compiler
Reset();
Watchdog function
for XC30 compiler
ClrWdt();

 

 

 

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

Singapore Customized, custom made Electronics Circuits & Kits

 

 

Crystal Selection for Microcontroller’s UART
Common Baud Rate
2400bps
4800bps
9600bps
19200bps
38400bps
57600bps
115200bps
230400bps
2014-03-08 Today I realised something about the UART in microcontroller that I am not aware about, even many years of firmware programming. I was troubleshooting the UART in my microcontroller. The data that are sent or received are corrupted. The first char is always received correct. I realised that it could be that the microcontroller baud rate is having the problem. I have been using this 8MHz crystal for many of the project, but this time the data corruption is too serious to be ignored. I was using PIC24FJ64GA004 microcontroller.
From the UART peripheral datasheet (DS70000582E), I managed to recompute the baud rate and its error. The error is too high. I have no idea why that baud rate was peviously selected.

UxBRG = (Fp / (4 x Baud Rate)) – 1
Calculated Baud Rate = Fp / (4 x (UxBRG + 1))
Error = (Calculated Baud Rate – Desired Baud Rate) / Desired Baud Rate x 100%

I wanted to find out which clock frequency can provide the least error. To speed up the computation, I have create a spreadsheet using OpenOffice Calc (similar to excel spreadsheet).
2014-03-08_baudrate_computation_microchip.ods

When I try to input the other common crystal that I have on hand, I realised 7.3728MHz is computed to have an error of 0%. It is a perfect score. This makes me curious to find out more other crystal that is able to provide a 0% error for UART. It turns out that those crystal that have a multiple of 2400, will be able to provide the UART with a 0% error. The 2400 figure comes from one of the commonly use RS232 baud rate 2400bps which is the common denominator for all the commonly used baud rate. Crystal that have a frequency that is multiple of 2400 will be the best for the UART peripheral.

The following provides the commonly available crystal frequency that is suitable for UART peripheral operation.

Recommended Crystal for Microchip UART
3.6864 MHz
7.3728 MHz
11.0592 MHz
14.7456 MHz
14.74546MHz
18.432  MHz
22.1184 MHz
Quite close to perfect for UART
36.0 MHz
48.0 MHz

 

Keyword: Microchip PIC microcontroller prototype development, PIC programmer, Max232, ICSP programming interface, output buffer, LED indicator, 74LS595 74HC595, 74LS244 74HC244, DC-DC power supply, 40pins 28pins 18pins DIP IC

PIC18F4550, PIC18F452, PIC16F877a

PIC18F252, PIC16F876a

PIC16F88, PIC16F628a, PIC16F84a

Analog Electronics

Your reference guide to analog electronics for your electronics projects.

Edited by Lim Siong Boon, last dated 06-Jul-08.

 

Short cut to your reference guides and charts

  1. Op-amp
  2. Capacitor for Signal Filtering
  3. Transistor Switching

 

 

 

 

Op-amp  

Op Amps for Everyone, by Bruce Carter and Ron Mancini from Texas Instruments.

op amps for everyone (Texas Instrument).pdf

op amps for everyone third edition 2009 (Texas Instrument).pdf

op amps for everyone

 

Op-amp application notes from National Semiconductor,

An applications guide for op-amps.pdf

 

Single rail op-amp design from Texas Instruments

single power supply design.pdf

 

Various precision op-amp rectifier design.

http://sound.westhost.com/appnotes/an001.htm


From National Semiconductor and Texas Instruments
op_amp_circuit collection_AN-31.pdf
snla140a, Op Amp Circuit Collection.pdf

Others
op-amp awith offset (bias).pdf
Single Supply Op Amp Design.pdf
CH9 Paul Smith notes.pdf




Type of Op-amp circuit


1) Non-Inverting amplifier
2) Inverting amplifier
3) Unity Buffer amplifier (Voltage follower)
4) Differetial amplifier
5) Suming amplifier
6) Instrumentation ampilfier
7) Oscillator
8) Comparator
9) Threshold detector
10) Zero Level detector
11) Schmitt trigger
12) Integration
13) Differentiation
14) Rectifier
15) Logarithmic output
16) Exponential output

1) Non-Inverting amplifier

Vout = (1+ R2/R1) Vin
– high input impedance
– low output impedance
– higher bandwidth
– minimum gain of 1

A resistor R1||R2 = (R1 x R2) / (R1 + R2) is inserted just before the +ve terminal will keep the input current better balanced.
The added voltage divider has introduced a voltage offset to the output signal Vout.
   

2) Inverting amplifier

Vout = -(Rf/Rin) Vin
– gain can be less than 1

 

When analysing the op-amp as an amplifier (ideal op-amp), the +ve and -ve is to be having the same voltage potential.

A resistor Rin||Rf = (Rin x Rf) / (Rin + Rf) is inserted just before the +ve terminal will keep the input current better balanced.

The added voltage divider has introduced a voltage offset to the output signal Vout.
The voltage divider provides a voltage level which the amplification will be based from. Signal with the same voltage level will not be shift in position, while the rest of the voltage level will be amplified.
   

3) Unity Buffer amplifier (Voltage follower)

Vout = Vin
– high input impedance
– low output impedance

   

4) Differetial amplifier.

– Poor input impedance

Voltage follower added in the front of the input to improve the input impedance. This is also similar to an instrumental op-amp.

Instrumentation amplifier.

 

Op-amp Selection

Brand Part no. Power Supply Spec1 Spec2 Spec3 Comment Price
MAXIM MAX4242 1.8 to 5.5V (single rail) Precision 1
-40 to 85°C clean analog signal (best) X
intersil ISL28276 2.4 to 5.0V (single rail) Precision 2
-40 to 125°C clean analog signal X
Analog Devices AD8629 2.7 to 5.0V (single rail) Precision 3
-40 to 125°C

ok. Can be use for precision analog.(used for Hall sensor project)

X
Analog Devices AD8572 2.7 to 5.0V (single rail) Precision 4
Input Offset 1uV
  -40 to 125°C Seems better and cheaper than AD8629 X
Analog Devices AD8602 2.7 to 5.0V (single rail) Precision
Input Offset <0.5mV
  -40 to 125°C (used for LED controller project) ok
Analog Devices ADA4665-2ARZ 5 to 16V, ±2.5 to ±8V

Precision (CMOS)
Input bias current <1pA,Input offset 1-6mV

  -40 to 125°C (used for LED controller project) Fair
intersil ISL28218 3.0 to 40V (single rail) Precision
-40 to 125°C
Texas Instruments OPA2374 2.3 to 5.0V (single rail) Precision
-40 to 125°C X
Texas Instruments TLC272 4 to 16V (single rail) Precision Output will not reach ±Vcc 0 to 70 °C, -55 to 125°C

general use

ok
intersil CA3260 4 to 16V, ±2 to ±8V Normal
-55 to 125°C single/dual supply application X
National Semiconductor LM321, LM324 3 to 32V, ±1.5 to ±16V wide supply voltage
-40 to 85 °C single/dual supply application ok
National Semiconductor

LM158, LM258, LM358, LM2904

3 to 32V, ±1.5 to ±16V

Normal Output will not reach ±Vcc 0 to 70 °C, -55 to 125°C single/dual supply application. Encountered input offset issue. V+ < V- may result in a positive Vout ok
Texas Instruments TLV2402 2.5 to 16V (single rail) Normal
0 to 70 °C, -40 to 125°C general use X
Microchip Technology MCP6L02 1.8 to 6.0V (single rail)

Normal 1
Input Offset <1~5mV

Near full swing Vout -40 to 125°C

general use. Encountered input offset issue. V+ < V- may result in a positive Vout.

ok








Texas Instruments TL061 ±2V to ±15V Normal Output will not reach ±Vcc -40 to 85 °C, -55 to 125°C   ok
Texas Instruments TL071 ±4V to ±15V Normal Output will not reach ±Vcc -40 to 85 °C, -55 to 125°C   ok
intersil CA741, LM741 ±5V to ±15V Normal Output will not reach ±Vcc 0 to 70 °C, -55 to 125°C   ok
Texas Instruments LMV722IDR 2.2 to 5.5V (single rail)
Near full swing Vout -40 to 105 °C

On Semiconductor MC33202DR2G ±0.9V, 0V to 12V
Near full swing Vout -40 to 105 °C, -55 to 125°C

National Semiconductor LMP2022MA 2.2 to 5.5V (single rail) Precision
-40 to 125°C unable to it make operating
On Semiconductor MC33072 3 to 44V
Output will not reach ±Vcc -40 to 85°C, -40 to 125°C

 

(cheap precision op-amp)

Precision usually means a low input offset voltage, which is quite important for voltage comparator, or amplifying small differential input signal.
Input offset <0.5mV will be consider as precision op-amp.
Input offset guide from Analog Device “MT-037, Tutorial Op-amp Input offset voltage.pdf

   

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

Singapore Customized, custom made Electronics Circuits & Kits

 

 

Capacitor for Signal Filtering

 

The following article is a simplied understanding of signal filtering. Basic knowledge of signal filtering is still required before reading this section.

 

 Other references for signal conditioning / filtering
Analog Sensor Conditioning Circuits – An Overview – 00990a.pdf (from Microchip)

The simplest signal low pass filter (LPF) is presented on the right consist of a resistor and capacitor. It is commonly known as RC filter.

This RC layout is applied to circuit with low impedance input, high impedance output. The resistor will be required to complete the filter function. Signal oscillation may occured is the resistor is omitted.

One example would be LPF filtering at the output of the op-amp amplifier circuitry, where filtering is applied to the varying input signal/voltage.

The cutoff frequency of this RC filter
fc = 1/(2πRC)

R will need to be significantly small compare to the load. If the load impedence is high (infinity), then the value of R becomes not very important. If the load impedence is finite, R should be smaller than 1/10 of the load.

Click here for the calculator for the LC filter. frequency and time domain results are on the fly.
http://sim.okawa-denshi.jp/en/CRtool.php (generate freq/time domain graph on the fly)
http://www.2pif.com/high-low-pass-filter.php (simple calculator)

RC filter, the simplest low pass filter.

Another way of looking at the same RC filter.

Ideal analysis of the circuit
The signal in the DC or lower frequency signal can be fully transfered to the high impedence (open circuit) output, while the high frequency signal will be absorbed on the resistor (R) components.

What the high frequency signal will see:
AC signal see resistor as a load, capacitor as a short circuit, while inductor as an open circuit. High frequency signal is able to see the capacitor (C) component as a short circuit. The voltage potential of Vout is seen to be the same as the ground reference. This means that the AC signal will be completely absorbed by the resistor R component. High frequency component will not be available at Vout. They are filtered by the RC filter.

What the low frequency signal will see:
DC signal see resistor as a load, capacitor as an open circuit, while inductor as a short circuit. Low frequency signal is unable to see the capacitor (C) component well. The point Vout is seen to have a very high impedance load. This means that the DC signal will be completely transfer to the open circuit output load at Vout. The R component will be seen as small as compare to the open circuit output load. Using the voltage divider concept, most of the low frequency signal will fall on the output Vout. The low frequency signal managed to pass through the RC filter.

Please note that the above explaination is a simplfied analysis of a filter. Ideal analysis helps us to understand the circuit topology (function) at a glance without the need for detail computation. In reality, the open/short circuit represent the degree of attenuation faced by the signal. The degree of signal attenuation is dependant on the frequency of the signal and the capacitor’s capacitance.

 

This is another low pass filter consist of only a capacitor. This type of filter will work for current source input. Vin = Vout.

One example would be the capacitors that are found on typical dc power supply filtering at its input or output. Decoupling capacitors (100nF) that are normally found near the power input of an IC is also another example.

 

A capacitor as a low pass filter.
This is a simple high pass filter (HPF) using resistor and capacitor (RC) components. The ideal analysis is similar to the LPF as anaylzed eariler, allow high frequency signal to pass through while low frequency signal are attentuated. RC filter, the simplest high pass filter.

Capacitances required to attenuate or suppress signal of certain frequency. Please note that this formula and the table presented on the right is an approximation for filtering noise from a DC signal.

 

Xc = 1 / (2π f C)

C = 1 / (2π f Xc )

where Xc is the reactance of the capacitor. Xc of 1.0 for the capacitor (open circuit) is possible with lower fequency signal or lower capacitance. To attenuate the AC signal of a particular frequency, Xc has to be low with the correct capacitance implemented.

 

Example:

To attenuate a 50Hz signal by 10 times.

C = 1 / (2π x 50Hz x 1/10) = 31,830uF

This means that to attenuate the 50Hz component by 10 times requires about 33,000uF capacitor connected from the signal to the ground line. This capacitor will filter any frequncy >50Hz on the line.

The table on the right is a simplified guide, which recommend the capacitance to use as a low pass filter for attenuating a particular frequency.

Frequency to Attenuate
Attenuating Factor (Xc)

1/√2
1/2
1/10
1/100
50Hz
2200uF
6800uF
33000uF
330000uF
500Hz
220uF
680uF
3300uF
33000uF
1KHz
113uF
330uF
1600uF
16000uF
10KHz
11uF
33uF
160uF
1600uF
100KHz
1.1uF
3.3uF
16uF
160uF
1MHz
113nF
330nF
1.6uF
16uF
10MHz
11nF
33nF
160nF
1.6uF
100MHz
1.1nF
3.3nF
16nF
160nF
1GHz
113pF
330pF
1.6nF
16nF

 

Max frequency for capacitor (taken from “Op Amps for Everyone”)

Capacitor type Max Frequency
Aluminum Electrolytic 100 KHz
Tantalum Electrolytic 1 MHz
Mica 500 MHz
Ceramic 1 Ghz

 

The table on the right summeries the typical capacitor value available commercially. Standard Commercial Capacitor Value:
pF pF pF nF nF nF uF uF uF uF uF
1 10 100 1 10 100 1 10 100 1,000 10,000
1.1 11 110 1.1              
1.2 12 120 1.2              
1.3 13 130 1.3              
1.5 15 150 1.5 15 150 1.5 15 150    
1.6 16 160 1.6              
1.8 18 180 1.8              
2.0 20 200 2.0              
2.2 22 220 2.2 22 220 2.2 22 220 2,200  
2.4 24 240 2.4              
2.7 27 270 2.7              
3.0 30 300 3.0              
3.3 33   3.3 33 330 3.3 33 330 3,300  
3.6 36 360 3.6              
3.9 39 390 3.9              
4.3 43 430 4.3              
4.7 47 470 4.7 47 470 4.7 47 470 4,700  
5.1 51 510 5.1              
5.6 56 560 5.6              
6.2 62 620 6.2              
6.8 68 680 6.8 68 680 6.8 68 680 6,800  
7.5 75 750 7.5              
8.2 82 820 8.2              
9.1 91 910 9.1              
                     
                     
                     

Active filter with op-amp

For flat frequency response, use Butterworth filter

For a sharp cutoff frequency, use Chebyshev filter

For linear phase, use Bessel filter.

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

Singapore Customized, custom made Electronics Circuits & Kits

 

 

Transistor Switching  
 

I didn’t realised that transistor switching speed can be so important until I had encountered a problem using it for SPI communication. The data communication gets corrupted. Go through all the codes, and eventually found that the transistor switching speed was slow. The current batch of transistor is different from my previous batch; and I always thought that all BC817 npn transistor is the same. I am wrong, it is not. The problem might have been due to my design as well, unable to discharge the base signal in time, to turn off the transistor.

Ch1(yellow) shows the signal input through a 1kohm resistor to the base of the npn transistor. Ch2(blue) is the output at the transitor’s collector terminal, with a pull up resistor of 560ohm. The is

The following present the various BC817 transistor’s switching digital speed.

Switching speed of my original transistor.

delay of about 0.7us.

using npn BC846

delay of about 2us.

using npn BC817

delay of about 2.5us.

BC817-16LT1G

delay 2us

MMBT4401LT1G

delay 4.5us

MMBTA05LT1G

delay 0.25us

   
Effect of the signal switching without a resistor across the Vbe terminal of a npn transistor BC817.

Effect of the signal switching without a 10kΩ resistor across the Vbe terminal of a npn transistor BC817.

There is a slight improvement in delay, but not very noticable.

Effect of the signal switching without a 10kΩ resistor across the Vbe terminal of a npn transistor BC817.

More than 100% improvement shortening the delay, of the inverted signal by about 1us.

 

 

 

 

 

 

Keyword: op-amp, buffer, inverter, amplifier

 

SMD Soldering

Your reference guide to soldering with surface mount devices

Edited by Lim Siong Boon, last dated 06-May-09.

 

Short cut to your reference guides and charts

  1. Introduction to SMD soldering

  2. SMD soldering (prototyping board)

  3. SMD soldering (prototyping PCB socket 2.54mm pitch)

     

 

1. Introduction to SMD soldering  
SMD IC stands for surface mount device integrated circuit, or commonly known as SMT surface mount technology. Why go into SMD? Small in size, light in weight. This is the advantage of smd. Being small, engineer is able to design small electronics gadget that people can carry around. It is quite obvious that people prefer small mobile phone.

The ultimate advantage will be lower cost to consumer. Being small in size, the printed circuit board (pcb) can be small, meaning low cost. Transportation cost can be reduce because it is now lighter and more products can be packed into the same box. Space required is less, meaning cost saving on the warehouse storage. PCB board is easy to route without the through hole. Better signal integrity. Easily assembled by machine. There is too much advantages. Going SMT is certainly the way forward.

Technology evolution, from big to small.

A phone small enough to carry around.

 

 

Smaller mobile phone

Even smaller phone

 

Mobile phone as thin as biscuit.

 

 

I used to build circuits using dual in-line package (DIP or DIL) IC only. I hardly thought of using surface mount device/component (SMD) because I have great doubt that I can solder the fine legs of the IC chip. The pitch for the older DIP IC package are 2.54mm. Pitch is the distance between adjacent pins as illustrated in the picture. Most IC comes with a variety of packages. The IC that I know of, offer both the SMD and DIP packages. I thought that I will never ever need to use smd packages until one day, I have no more choice. I managed to pick up new circuit designs, and discover more and more new IC chips. Most new IC chips design do not have DIP packages. You can hardly find one. I realised that in order to implement better circuits, I need to learn to use new IC chip. In order to use the new chip, I have to find ways to solder smd components. That’s where I venture into the world of smd.

Nowadays people prefer to use smd, because they are small in size, which turns out to be cost efficient fabricating small PCB. With smaller PCB, space & weight is saved, resulting in lower cost for the transportation/distribution and storage.

Research and research, I got to know from other electronics guru that smd is in fact easier to work with than through hole. I try it out and from that day onwards, I am in love with smd components. Small to solder, but it save me the effort to cut the lead for through hole component. I managed to store my component using minimum box and space. There are many many advantage to work with smd.

Many people might think that you need special tools like a rework station or fine tip iron to solder the small smd components with small pitches. With the correct technique, you can use your soldering iron to do the soldering. In fact my 60W goot TQ-95 soldering iron has quite blunt tip. So thick that most people think that it is not possible to solder smd IC with fine pitches. Fine tip iron is easy to reach the fine lead, but I find that it is not as hot as the same iron with blunt tip. If you prefer fine tip, I will recommend hotter soldering iron or those which can allow you to adjust the temperature, they can be hot. I managed to solder smd package TQFP, SSOP QSOP with pitch as small as 0.5mm. Width of the lead of about 0.3mm.

Dealing with SMD components do not necessary requires you to fabricate a professional pcb board. You can also mount smd components on low cost prototyping board. To start off implementing smd components, you might like to try using the soic package. Quite common at this point in time, but may just phase out as what has happened to the dip packaging. SOIC has a pitch of 1.27mm, which is exactly half of DIP packages. This size is great because I can solder the IC to the same old 2.54mm pitch prototyping donut padded board. What I usually do is to cut the donut pad into half. Soldered onto each pad is two pins 1.27mm apart.

You can refer to the following article, for further illustration.

SMD soldering (prototyping board)

Through hole packages

DIP – 8 pins

resistor

capacitor

inductor

diode

 

SMD packages

SOIC – 8 pins

TQFP – 44 pins

resistor

capacitor

inductor

diode

 

With so much advantage there is indeed a disavantage. SMD IC comes with many type of packages with different pitches. Unlike DIP IC, the pitch is typical 2.54mm. I can easy purchase a prototype board with 2.54mm, and almost all the DIP will fit to the board. SOIC package can still be mounted onto the 2.54mm prototype board. The rest of the SMD IC chip has quite a wide range of completely different packaging. This make them difficult to start with, without having to fabricate a PCB.

There are actually solution to this. Most IC company usually introduce their IC chip together with a prototype board for the IC.

Another solution will be to use a pre-fabricated prototyping board that allows mounting of various smd footprint. You can search for the various names such as

– prototype adaptor

– chip adaptor

– smd prototyping board

– smd to dip adaptor

– smd socket

– smd adaptor

– smd to 2.54mm converter

– SMD to DIP converter

– chip carrier

You can refer to the following article, for further illustration.

SMD soldering (prototyping PCB socket 2.54mm pitch)

 

Various distributor for the prototyping adaptor

 

In prototyping with DIL IC, pcb mount IC socket is usually used, so that the IC can be removed easily if damaged. Some sockets are designed for programming used where the chip can be inserted and remove easily for programming purpose. To remove the component, you need not have to do de-soldering. Like DIL package, smd also comes with their own IC socket. There are many variety of smd packaging, and getting the socket for your smd components is not going to come cheap & easy compare to DIL. Therefore I usually built prototype without any sockets for smd design. After numerous attempts designing and building of circuits, you will definitely attain a certain level of confident on your design without considering IC socket. Without the socket, cost and space are saved significantly.

SMD IC sockets:

 

DIL IC sockets/ holder.

Turn pins designs is of better quality.

 

 

 

 

 

 

 

 

Various distributor for SMD socket

 

 

 

The headache will come when you really need to removed the smd IC. How do you remove the IC from the PCB? For de-soldering of smd component more than 3 leads, you can add in more solder to connect up the IC pins heat pins on all the sides of the IC and eventually pull out the component. It is easier to use the rework station or IR heater to de-solder smd components. The rework station uses hot sir to melt down the solder on the board. You will need to aim the hot air at the solder joint.

Rework Station

If you do not have the lurxy of getting the rework station, another possible method might be to use a special solder that has lower melting point. LowMelt® DeSolder Wire. A lower melting point means that the solder will takes a longer time to cool down to a solid. This allows you more time to remove the IC after heating up the solder. The solder is flooded onto the pins of the IC. The pins are heated up together using a soldering iron and the smd IC can then be removed easily with a tweezer.

Low melt solder wire

 

 

 


Various type of smd packaging
* SOT, SC
* SOIC, ExposedPad™
* SSOP, ExposedPad™
* TQFP, ExposedPad™
* TSOP
* TSSOP, ExposedPad™
* PLCC 
* LQFP, ExposedPad™
  * LGA
* PBGA
* PSOP
* Dual Row MicroLeadFrame®
* LQFP PowerQuad®
* MicroLeadFrame® (MLF®)
 * MQFP PowerQuad®
* PSvfBGA
* SuperBGA®
* TapeArray® BGA
* tsCSP
* Ultra CSP™
* CABGA, CTBGA, CVBGA

 

 

 

www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

Singapore Customized, custom made Electronics Circuits & Kits

 

 

2. SMD soldering (prototyping board)

 
   

The prototype board above has pad with 2.54mm pitch and is designed for DIL and through hole components. The board is easily available from local store. Dealing with smd components on this 2.54mm pitch board is not difficult as well. I have been using this board to solder quite a number of surface mount components.

– SOIC

– DPAK

– SOT23-6, SOT-3

– TO-263

– PSOP

 

High pin count component with pitch less than 1.27mm will not be suitable to mount onto this board. For passive smd component like resistor, capacitor or inductor which only have 2 pin, mounting is simpler. Size is not an issue soldering onto the board.

 

Align the SMD IC to the position on the pad. Mark out the pad for the cutting to be done.

Use a penknife to cut the donut pad into half. Ensure that the half pad does not short circuit using your multi-meter. Sometimes the cut may not be deep enough or conductive reside between the gap resulting in a short circuit. Remember to ensure that each is proper cut before you start to solder.

Align the smd with your finger or tweezer and begin soldering one of the pin. Check if the IC is still properly align after soldering the first pin. If not, heat up the soldered pin and realign again. After the ICis align, solder all the rest of the pin. If the solder bridge across to the adjacent pin, use a soldering sucker to remove the excess solder.

The cut between the pad usually make the solder harder to bridge across the adjacent pin. Bridging is still possible, and it is quite easy to have it removed.

SMD ribbon cable connector being soldered onto the 2.54mm pitch prototype board.

Example of building the circuit using surface mount component on the prototyping board with 2.54mm pitch pads. As shown above, the pins are being wired by fine wire wrapping wire. The single core wire is very flexible and comes in a variety of color, making it easy to identify the type of signal being carried by the wire.

 

 

 

 

 

3. SMD soldering (prototyping PCB socket 2.54mm pitch)

 

What you need…

 

List of items:

– Surface IC chip (TQFP package)

– Surface mount IC adaptor or converter

– Soldering Iron

– Tweezer or Pincer

– Solder with flux core

– Soldering Flux

– Stick for coating flux

– Wiping paper

– Tinner

 

PIC-200 smd to 2.54mm pitch adaptor

from .

Holding onto the side view of the

QFN package IC.

 

INTRODUCTION

In this setup, I am going to solder a surface mount microcontroller (TQFP 44 pins) onto a smd adaptor. The adaptor will then be used on the commonly available prototyping board, so that I can try out my new design for circuit control.

TQFP, QFN and SOIC are quite some common footprint for prototyping smd microcontroller from 18 to 64pins. This prototyping adaptor pic-200 (on the left) that I have is an ideal adaptor for my microcontroller. Converting the smd device into 2.54mm,  I can easily mount the smd unit onto my 2.54mm pitch prototyping board. It is available locally.

   Prototyping board with 2.54mm pitch donut pads.

The pic-200 smd adaptor originate from PIC-CONTROL and is well documented. Commonly used smd footprint can be found on either the top or bottom side of the pcb adaptor. These are some of the smd packages that can be mounted onto pic-200 adaptor.

IC Front Back
TQFP-44
QFN-44
SOIC-28
SOT-3

 

 

With a wide range of smd components that can be mounted, it is easier to stock up this pcb adaptor for future prototyping use.

The following article is about getting my smd microcontroller PIC24FJ64G004 soldered onto this board. After which I will be on my way to do prototyping for my new control circuit.

This smd adaptor origined from PIC-CONTROL. For other type of adaptors, you can also refer to other manufacturer as mention above.

 

 

<Step 1>

Before soldering, ensure that the soldering pad on the PCB is free of oxidation. PCB is usually tinned to protect the copper surface from oxidation. In cases where the surface is oxidized, you can try cleaning the surface with a contact cleaner. Apply the solution with tissue paper or toothbrush to clean up the contact. This solution make the PCB board rather oily, which I don’t quite appreciate.

Contact cleaner.  

Let us start our smd soldering here. Soldering surface mount component. The first important thing to introduce would be the solder.

There are many type of solder. Choosing the correct solder takes a bit of some knowledge too. Leaded or lead free solder? The industries is moving towards Pb free components & PCB, calling for unleaded product. Lead is toxin and not environmental friendly. I would advise ou to wash your hand after soldering or handling pcb board. A soldering fume extractor to vacuum the smoky fume would be quite comfortable for your soldering. The smoke is quite choking and a health hazard if you breath that in.

soldering fume extractor.

Solder also comes with a variety of metal alloy combination. Nowadays it is common in solder core to contain flux. If the solder do not have the flux in the core, the flux have to be manually applied onto the metal surface before the soldering beginning. The flux cleans up the soldering surface, and also make the solder flow rather smooth like liquid. One of the important ingredient to make a good solder joint lays in the soldering flux.

Solder wire also comes in a wide range of diameter to choose from. Generally I use 0.8mm soldering wire roll with flux at the core. Smaller diameter solder wire allows you a better control of the amount of solder to apply. For soldering larger pins or connector component thicker diameter wire will be preferred. Wire too thin  is rather troublesome, because you need to feed in a longer length of solder in order to solder the large surface/lead. For general purpose PCB board soldering 0.8mm wire fits somewhere in the middle. Not too thick nor too thin. For smd components, diameter smaller than 0.8mm is preferred. Using 0.8mm for smd soldering is not of any issue.

Solder wire 2mm

1.2mm

1.0mm

0.8mm

0.5mm

 

<Step 2>

One of the pad being tinned.

 

Align smd IC to the respective pad.

 

IC being fixed in position

 

Checking if alignment is correct.

 

Flooding the pins with the rest of the solder.

 

Pins flooded with solder

My microcontroller TQFP package has 44pins around the square package. To secure the package to the adaptor, I will need to solder one of the pin to the board first. It is important to solder only one pin. In case of mis-alignment, we can correct it easily. If more pins are soldered, it will be more difficult to correct any alignment.

Pin 1 of the adaptor pad is  first tinned with a layer of solder. A tweezer is then used to align the IC chip on the pad. The IC is secure to the board with a slight touch from my soldering iron, soldering the IC pin to the pad.

The important factor to consider would be the heat generated by the iron. I prefer to use a 60W iron, which still works well in air-con room. A lower wattage or fine tip iron will not heat up that well in colder environment.

 

         Goot TQ95 60W

If you prefer a fine tip, perhaps the soldering station will be more suitable. The iron temperature can be adjusted to a higher or precise temperature for the component that you want to solder. Component with thick metal contact like connector, heat sink, for thick cables should be solder with a higher temperature. The iron should be held on longer, in order to have the component fully heated up before any solder is applied.

Solder Station

For soldering the IC pin to the pad, you can start off by heating up the pad. Then while heating up the pad, touch the IC pin and apply the solder wire directly to the pad or IC pin, allowing the solder to flow like liquid. The IC pin is heated last to minimize the chance of over heating the pin. If it doesn’t flow very well, you can manually some flux to the joint. The solder wire should not touch the iron directly, because this will vaporize the flux, and solder flow will be restricted.

Heat up the lead and pad longer allows the solder to flow and form a good joint. Not for too long as it can also damaged your IC. You should be able to see the solder flow eventually onto the lead & pad. With a bit of practice, you will see the difference between a quick solder touch and another one with lead & pad heat up a little bit longer. It takes a number of practice to get a good joint with minimum amount of heating time.

The soldering iron that I use has rather thick tip, but that does not matter when I do soldering for the smd microcontroller. All we do is to flood the pins with solder. They can be be suck up later.

There is a technology  known as ultrasonic soldering. The soldering iron tip has this micro vibration which helps the solder to flow more easy without much use of flux. It can also solderthose difficult to solder material. The following is one article that I found that describe about it. – Soldering the unsolderable.

 

<Step 3>

I have applied more flux at this stage. It should have been applied before flooding the pin, but it doesn’t matter too much. The flux will make the solder rather liquid so that it is easier to suck up the excess solder.

solder flux paste

Baker Soldering Fluid

<Step 4>

The flooded solder is being heated up, and the excess solder are being sucked up.
<Step 5>

Each pins is being touch up, ensuring that the pin is solder to pad and that they are not bridged across to the adjacent pins.

Now we have got our smd component soldered onto the board.

<Step 6>

 

The flux helps a lot in doing a good solder but it often leaves the board with tiny dots of transparent strain, a bit sticky, also known as grease or flux residue. The board looks untidy with these tiny bits of grease.

These are the various recommended cleaning solution for pcb.

– 50% Alcohol + 50% Water

– Thinner

– Flux remover

– Multicore Prozone MCF800

– Solvent-> Bromopropane; propane, 1-bromo-; propyl bromide (Chemical Formula: C3H7Br)

 

Alcohol MSDS (Material Safety Data Sheet)

Thinner MSDS (Material Safety Data Sheet)

Electrolube, FLU Fluxclene Cleaning Solvent, pdf file

MG Chemicals 413B Heavy Duty Flux RemoverBrush for the crush

Flux Remover

Multicore Prozone MCF800

 

Besides using chemical, or after using chemical, there may still be some white blur stain. Those are flux spread dry up on the surface. Using a hot air blower, or heater on the surface can melt the dry up flux, and recover the smooth shiny PCB board surface again. Clean away the melt flux immediate after the heat.


Using alcohol is strongly recommended. Thinner is not suitable for certain plastic/material. Care is required when using thinner for cleaner. Using thinner on the PCB, copper pads and soldering joint isn’t a problem. When use on plastic, you are advise to do a trial to ensure that the material is able to with stand thinner solution. Flux remover is commercially ready mixed solution. From what I learn in the manufacturer website, they are non-flammable chemical solution.

 

Alcohol & thinner has a lower flash point, and catch fire easily. You have to be extremely in handling and storing these flammable chemical. Do not store or work on the chemical near electrical appliances, hot area or things that can cause spark. Keep your windows open to allow air to circulate while working with these chemical. They may cause headache, dizziness and uncomfortable when inhaled.

 

 

Chemical comes in different level of grade. A slight different in the chemical concentration or purity can results in a large difference in cost. Alcohol can be  expensive. For pcb cleaning purpose, request for technical grade alcohol. Higher grade alcohol is typically used for consumption or lab experiment purpose. Since we are using it for cleaning, there is not much advantage in using high quality chemical which is expensive. Dickson chemical is specialized in high graded chemical for laboratory use. They do sell lower cost technical grade alcohol. They are not suitable for consumption but is ok for cleaning application.

   Dickson Chemical selling Technical grade alcohol

You can easily buy thinner from your local hardware. Typically used for cleaning your brushes after all the wall painting works.

   Non-flammable Flux remover

 

 

 

 

These are other recommendation in the web. After researching further, I would advise not use them. These chemical are of health hazard.  Exposure will have severe adverse health effects.

– 50% isopropanol + 50% water

– Trichloroethylene

– Carbon tetrachloride

 

Isopropanol (true chemical name) is also known as Isopropyl alcohol or 2-propanol. 2- is refer as Iso. Other chemical may starts with 1- refer as N. These are some jargon used in the chemical industrial. I managed to learn a few of the terms from the vendor.

Trichloroethylene (true chemical name) is typically used for degreasing the metal. It is an extraction solvent for oil. Another name for Trichloroethylene is Trielin. Based on some read up, they can cause cancer.  

http://www.answers.com/topic/trichloroethylene

 

Carbon tetrachloride can harm our environment, producing CFC which deplete the earth’s ozone layer. http://en.wikipedia.org/wiki/Carbon_tetrachloride

 

Initially I tried using contact cleaner to clean the stain off. I use cloth or tissue but the fabric is often tear by the component sharp edges. Most corners are not easy to reach. Later on I tried using a toothbrush, the result is better.

For mass cleaning job, you can try using the ultrasonic pcb cleaner. It is a deep metal container for the solution, using micro vibration to shake off the dirt. I have never tried on it before, and I believe it is the same machine people used for cleaning their jewelry. Basically, you will need to dip the pcb board into the solution, and the ultrasonic will be activated to do it’s job. The solution used is the same as manual cleaning, requiring 3-5 minutes of cleaning.

   Ultrasonic cleaner

Ultrasonic jewelry cleaner

 

 

 

There is also a flux that does not leave residue on the PCB. I found it on the internet, and have not try it before.

INTERFLUX, IF 2005M No-Residue™ flux, pdf file

 

Article relating to removing flux residue:

pcb cleaning – Aqueous Cleaning Process.pdf
pcb cleaning – Flux Removal, nuxx.pdf
pcb cleaning – pcb cleaning article.pdf
pcb cleaning – PCB Cleaning, Printed Circ.pdf
pcb cleaning – pcb washing chemical composite.txt
pcb cleaning – remove solder flux.pdf
pcb cleaning – Solvent washing PCB boards.pdf
pcb cleaning – washing the board using alcohol.pdf
pcb cleaning – PCB cleaning article Inventec_S24_03.pdf

 
 

<Step 7>

A close up view of the clean and neatly soldered surface mount IC on the prototyping adaptor. Soldering smd components is simple and fast with a bit of practice. Small and easy to clean up. There are too many advantage in working with surface mount, compared to through hole components.

This is the end of the short demonstration on smd soldering. I hope these article can provide you some insight and confident to start experimenting circuits using surface mount components.

 

Video available. Please click here,

smd soldering.mpg (25MB)

smd cleaning pcb.mpg (5.5MB)

 

Article on smd soldering.

2010-07 How to Solder Surface-Mount Devices.pdf

 

 

 

 

www.pic-control.com, Singapore Circuit Design & PCB fabrication

Singapore Customized, custom made Electronics Circuits & Kits

 

Various Chemical Reference:

Alcohol 70% + Distill Water 30%
MDX4-4159
7MHFE-71DE
Cyclohexanone
Methylethylketone
ethylacetate,
Silicon Wacker
Wacker M4503, General purpose mould making silicon (Using Two Part Silicon Mold Putty to Make Molds)
http://www.kirkside.com.au/, Mould Material Specialist

Propanol, used to clean PCB. (close to white electric oil)
Acetone, remove away ink printed on PVC stickers
n-Hexane (white electric oil)

smd glue for surface mount component mounting / soldering use
Seal-glo NE series, NE3000S, NE8800T, more Seal-glo

 

 

Keyword: surface mount soldering, smd adaptor, smd to 2.54mm convertor

 

DIY Home PCB Fabrication

DIY — Fabricate your own PCB board at home

Written by Lim Siong Boon, last dated 08-Dec-09.


 

PCB is the abbreviation for Printed Circuit Board. Some may refer it as PWB which stands for Printed Wiring Board. The board consist of copper tracks connection printed on the surface of a non-conducting material. Your designed circuit connection will be contained within this board. This method of fabrication is an efficient method for reproducing a circuit. The circuit quality can be more consistent and the reproduction can be faster. This makes it suitable for manufacturing large quantities of electronic circuits.

Are you thinking of building your own PCB board at home? Do you have an electronics project in mind? Then you have come to the right site. This is a step-by-step guide to building your own PCB boards, complete with photos and video illustrations.

 

Home DIY PCB board finished product

PCB Fabrication Overview
  1. PCB board design
  2. Printing Artwork
  3. Exposure
  4. Developing
  5. Etching
  6. Cuting and Drilling
  7. Tinning and Masking
  8. Other method of PCB making

 

The following project will introduce you to the basic steps in fabricating a circuit board at home. For low quantity fabrication, this method can save you some time and help you stay within your budget.

For a simple prototype circuits, I would recommend point-to-point wire solder. While this process is tedious and takes time, your project cycle will be shorter than making a PCB which is more or less permanent. Individual wire connection are soldered directly onto the component leads or pins. The wiring makes modification quick and easy.

This photo is an example of a point-to-point wire wrap circuit. The leads are soldered into place. The colored wiring helps keep things organized, but the back side of the project still looks like “spaghetti”. Constructing a board in this manner requires proper planning of your component positioning for minimum wiring work. You may be constantly flipping the board over from front to back to double-check the connections. It can be quite fast if you are used to visionlizing the components from the back side.

 

Come, join in, as we walk through the process of PCB fabrication. We will proceed step-by-step. It’s as easy as ABC and you will soon be the proud owner of your own custom printed circuit board.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

At this time, you might be aware of an alternative. It is possible to have your designs produced by professional companies that specialize in PCB board fabrication.

Professional PCB board fabrication

PCB fabricating machine is more efficiency for mass production. For professional looking PCB board, you may outsource the task to a PCB design house or manufacturer. Well established PCB manufacturer normally ask for higher fabrication volume. There are manufacturer that can do PCB fabrication in lower volume for your prototype. Some accept a few pieces, and even provide you with software for drawing your PCB design. Lead-time is typically a week or 2, while some manufacturer may offer express PCB fabrication service. If you are looking into high volume professional PCB board, China can offer a more competitive price. More reference to these manufacturer and PCB fabricating machines is available on this website.

Various professional PCB manufacturer.

San Francisco Circuits San Francisco Circuits

                      

       

                

prototype pcb – The PCBs from Seeed Studio Fusion is short delivery time, competitive price and high quality.”

In order to have your PCB boards professionally fabricated, the factory will need your design in a format called a “gerber” file. These gerber files are a list of mechanical instructions for fabricating the PCB. See the DIY steps in the section that follows to learn how to generate your own gerber files. The factory will usually charge a setup fee for each fabrication job. The cost per piece is usually low.

Most of the time you may only have the circuit designed on a piece of paper. You can also engage a professional to draft and generate the manufacturing gerber files. Be sure that your circuit is a working design and you have the connection drawn correctly before submitting to them for drafting. I don’t think they verify your design. You also need to prepare the component datasheets or sample, so that they can draw out the component’s soldering pad or footprint that your circuit is using. If the footprint is wrong, you will not be able to solder your component onto the board probably. Any requirement, example- the placement of the component, you should also indicate them clearly.

The design should also indicate the type of connector you want to use. I usually forgot to draw out the connector component. You can seek for their recommendation on those connector or other components that may not be critical to your design.

The computer drafted schematic and pcb layout will be sent for your final verification. Once you acknowledge the design, they will then generate the gerber files for your pcb fabrication submission.

Various Schematic Capture & PCB Layout Vendor

            http://www.shinmark.com

  

Of course, if you do not have the complete circuit designed, you will have to engage a circuit designer to design a circuit for you. Designing services can be quite expensive.

 

If you want to fabricate the professional looking green board for a smaller quantity, you can try PIC-CONTROL. The gerber files are submitted to them for pcb fabrication at a reasonable price. However the delivery lead time is slower. About 2 times longer as compare to the typical manufacturer who can deliver the fabricated board in 1-2 weeks times.

They also do electronic circuit design, custom made controller kit, drafting, programming, engineering and reverse engineering stuff, mainly in the area of electronics.

 

A computer aided design for the schematic capture and pcb gerber file is usually a major cost. I usually DIY, drafting out the design on my own. It save me quite a lot by generating my own gerber files. I can understand why the charge for the design drafting is usually high. There is quite a lot of work in drafting out the design file. It is a time consuming task.

   

 

 

www.pic-control.com, Singapore Circuit Design & PCB fabrication

Singapore Customized, custom made Electronics Circuits & Kits

 

 

1.   PCB board design

Material and Equipment

  • electronics schematic design

  • computer

  • Protel DXP or PCB design software

        

 

 

software for

drawing PCB board.

 

 

 

 

  

Protel DXP software enviroment.

 

component layout & traces diagram.

 

new Protel DXP version (2005).

1.1 PCB design introduction

 

Before any PCB fabrication can be done, we need to design PCB electrical pads for component placing and trace for component connectivity. It can be draw by hand but if your design is very complex, the PCB software will be very helpful. The software have ready to use components footprint, and modification can be easy done, saving you a lot of time and effort as compare to manual drawing.

There are various brand of software for designing and drawing PCB, and most of them can generate gerber file (*.gbr) which is a common file format used for PCB fabrication in the local industries.

Professional PCB software such as CADSTAR and PROTEL can easy cost above thousand of dollars. Simple and basic PCB software such as Eagle or Easy-PC is slightly lower in cost, in the range of about $500 to $1200. They are cheaper in cost, but features can be limited. Limitation can be in the form of limited board size, number of board layer or the number of component’s pin allowed in the design. Professional PCB software has a lot more sophisticated features to make the PCB design process more efficient. Software trials are available from most of these PCB vendors, for user to evaluate.

 

Various electronics schematic & PCB design tools.

Easy-PC from Number One Systems

 

CADSTAR from Zuken

Eagle from Cadsoft

 

 

 

 

 

 

Alternative you can engage professional help for the PCB design work, to relieve yourself from the extensive software training. With the experience and expertise from a PCB design specialist like Quantum CAD, you can be sure that your project can be in time and well taken care of. Demanding layout design for analog or any high frequency circuitry, would seems like a breeze in your development work.

 

 

 

 

In this fabrication trial, Protel DXP is used to aid schematic design and PCB layout. It is quite user friendly and technical support is strong in terms of user group and tutorial documentation.

Gerber file is not used in this home fabrication, instead a pictorial format save in *.pdf file. *.gbr gerber file is normally use in local fabrication house. The component layout and traces generated are save onto the *.pdf file.

The PCB artwork is now in *.pdf format and is ready for printing.

For more information on Protel DXP, you may refer to the following website, http://www.altium.com/

 

 

A good electronics design is not stop at the schematics. You may have a very good circuit schematic but it can still create problems for you if the components & traces are not place properly. This is especially important for analog circuits. Understand how to place components and route the power/signal pcb trace is also very important. Understanding radio frequency and high frequency theory will help a lot. I have a delicate page specially for PCB trace.

 

I have also started a website to document some common surface mount component footprint for references.

     

More PCB footprint references here. Footprint

 

 

 

Here is a reference on PCB design guideline that I got it from a website. Quite a useful information to guide you into design a proper PCB board.

Board Design Guidelines 2003 Rev-A.pdf

 

Also another good reference from Texas Instruments about PCB layout recommendation is available in the section Analog Electronics.

op amps for everyone (Texas Instrument).pdf

 

The following are some of the advance topics that you may like to research further into, if you are interested to find out more about PCB design. http://www.ipc.org

 

– IPC Designer and Advanced Designer Certification,

– IPC-T-50 Terms and Definitions for Interconnecting
and Packing Electronics Circuits,

– IPC 2222, Sectional Design Standard for Rigid Organic
Printed Boards

– IPC 2221, Generic Standard on Printed Board Design

– IPC-D-325 A, Documentation Requirements for Printed
Boards, Assemblies and Support Drawings

 

Layout

– Characteristics of Grid Systems

– Purpose of Tooling Holes

– Feature Formed in Copper

– Through-Hole Land & Tolerance Requirements

– Design Differences for SMT vs. Through-Hole

– Interrelated Considerations for Design

– Printed Boards & Assemblies Viewing Principles

 

Electrical considerations

– Schematics/Logic Transformation for Component Arrangement

– Schematic and Logic Symbols

– Functional Electrical Characteristics

 

Materials

– Copper Clad Laminates

 

Component requirements

– DIP & SIP Components

– Clinched & Unclinched Leads

– Point-to-Point Wires

– Axial & Radial Lead Mounting Differences

– DIP & Chip Carrier Sockets

– Edge-Board Connectors

– Characteristics of a bus bar

– Jumper Wires

– Purpose of Stiffeners

– Purpose of eyelets

– Differences between Automatic & Manual Placement

– Non-standard Parts Information

 

 

 

 

 

Assembly requirements

– Differences Between Manual & Pick-and-Place SMT Placement

– Considerations for Component Mounting

– Legend & Polarity Markings

 

Board fabrication

– Board & Assembly Panelization

– Hole Types & their tolerances

– Coating & Markings Used on Printed Boards

 

Physical board characteristics

– Thermal Management for Assemblies

– Thermal Management for Boards

 

Documentation

– Tolerancing Methods

– Datum Features & Location Principles

– True Positioning Dimension Techniques

– Conductive Pattern Location to Datum References

– Plated-Through-Hole Dimensions & Grid Location

– Tooling Hole Location Documentation

– Datum Symbols and Hole Description

– Documenting Fastening Hardware

– Minimum Drawing Requirements

– Master Drawing Hole & Conductor Description

– Minimum Requirements for Master Drawing

– Artwork Acceptance Criteria Inspection and test

– Testing & Techniques & Procedures

 

Reliability

– Reliability Terms & Design Issues

 

High Speed Design

 

RF Design

 

Design for EMC


(updated on 2016-07-28)
After your PCB layout design is completed, and gerber file is generated, you may like to check the generated gerber if the PCB layer is generated correctly. Mistake can be found through visual inspection of your gerber layers.

The following is a free online gerber viewer that you can use,
http://www.gerber-viewer.com/

For free off-line gerber viewer, you can download the gerber viewer software from,
Viewmate (http://www.pentalogix.com/viewmate.php)
gerbv (is a free open source gerber viewer. Some presentation error detection, so use with care. Look out for the improved version if any)
GraphiCode GC-Prevue (free gerber viewer for a limited period of time)
 

www.pic-control.com, Singapore Circuit Design & PCB fabrication

Singapore Customized, custom made Electronics Circuits & Kits

 

 


 

 


2.   Printing Artwork

 

Material and Equipment

  • PCB artwork

  • paper

  • printer

  • transparency

  • laser printer or photo copier

material for the making of the transparency film.

 

a closer view of a printed PCB pad and traces photocopied onto a transparency.

 

2.1 Artwork introduction

 

The PCB layout can be printed from a normal home printer onto a white piece of paper. The printing will be photocopied to a transparency. The transparency will be use for photo-resist PCB board exposure in the next stage.

A laser printer is prefer for sharper trace, especially if the traces are very close to each other. The laser printer can also print directly to transparency.

The transparency is cut to PCB size 15x10cm. Five PCB artwork are squeeze and arranged to maximize board usage.

 

There is also another popular DIY call the tone transfer method. Basically, it is using a laser printer to print your art work on a piece of paper. The toner print out is then iron onto a piece of copper plated board. This forms the etch resist layer on top of the board which can be send to the etching process.

The following link provide further information on this method. http://www.fullnet.com/~tomg/gooteepc.htm

The advantage of tone transfer is that it is simple, fast and does not require special positive acting presensitized (photo sensitive) PCB board.

 

The following step presents the traditional photo exposure method. The etch resistance layer can be formed on the photo sensitive board after the exposure.

 

 

 


 

 


3.   Exposure

 

Material and Equipment

  • ultra violet lamp

  • a box

  • Positive Acting Presensitized PCB board

  • transparency with PCB artwork printed

  • scotch tape

ultra-violet lamp (left) to expose the photo-resist coated Kinsten PCB board (right).

3.1 Exposure introduction

 

A typical Ultra Violet UV lamp for exposure on a Positive Acting Presensitized Kinsten PCB board.

 

   Where to buy them locally???

The ultra violet UV lamp is available in most lightings shop. I brought it at a electrical shop along kelantan lane (near Sim Lim Tower). The Kinsten PCB board, I brought in from Bell System, #03-12, Sim Lim Tower. It is also available in another shop Sunlight.

 

peeling off the protective film from the PCB board.

 

3.2 Preparing PCB board for exposure

 

Tear off the white/black protective film on the photo-resist board. Place the transparency artwork on top of the PCB board. Secure the artwork position with scotch tape.

 

laying film on PCB.avi (3.2MB)

 

Alternative you can buy a bare copper board and spray on the photo resist chemical which will be similar to the ready product photo-resist board that I have brought.

3.3 Exposure setup

 

If you have a piece of glass, place it on top, to make a good contact between the artwork and the PCB board. Close proximity should be maintain to make sure that trace are not expose to the UV light. I actually make this box out of a shoes box to prevent over UV exposure to the PCB board.

 

PCB setup in the exposure box.avi (1.5MB)

ultra-violet exposure

 

3.4 PCB exposure

 

Turn on and expose the PCB board for 90 seconds for ultra violet lamp, or 6-10 minutes for normal fluorescent lamp.

The above reference is base on the guideline of the lamp of about 5cm distance away from the artwork PCB. If the distance is far from the typical one, the exposure time should increase proportionally.

 

exposure to ultra violet light.avi (0.9MB)

 

 

A quick reference guide to the typical type of PCB material/substrates

There following introduce you to the various PCB substrate that you might consider before fabricating your PCB board. For typical applications, FR2 or FR4 board will be more than sufficient for your project. For delicated projects, you may consider the reference for the type of PCB material suitable for your appliation.

Various type of PCB materials

 

CEM-1 (Composite Epoxy Material):

CEM-1 specification

 

FR-1 Paper/phenolic (Flame Resistance-1): Room temperature punchable, poor moisture resistance

FR-1 specification

 

FR-2 Paper/phenolic (Flame Resistance-2): low cost pcb material usually found in high volume consumer products. Suitable for single sided PCB consumer equipment, good moisture resistance.

94VO material

 

FR-3 Paper/epoxy (Flame Resistance-3): Good of mechanical and electrical properties.

 

FR-4 Fibreglass (Flame Resistance-4, Glass cloth/epoxy): Excellent mechanical and electrical properties. Fibreglass pcb material offers a strong substrate than FR-2. The specification for a typical FR-4 board would be of thinkness 1.6mm, 1oz copper track, green solder mask, white silkscreen, double sided, etc…

FR-4 specification

tg135-tg170 material

 

FR-5 Fibreglass (Flame Resistance-5, Glass cloth/epoxy): High strength at elevated temperatures, self-extinguishing.

 

G10 Fibreglass (Glass cloth/epoxy): High insulation resistance, highest bond strength of glass laminates, high humidity resistance.

 

G11 Fibreglass (Glass cloth/epoxy): High flexural strength retention at high temperatures, extreme resistance to solvents.

 

Flexible PCB: thin and flexible pcb, typically design with movable component.

 

Ceramic/Metal/Aluminium substrates/base: provides better heat dissipation. Often used component that dissipate a lot of heat. Example: high power LED component, power transistors, etc…

 

Radio Frequency, Rogers PCB: low dielectric plastics suitable for high frequency applications.

Other PCB laminate materials name,
– CEM-3
– CEM-5
– BT-Epoxy
– Cyanate Ester
– Polyimide
– PTFE, Polytetrafluoroethylene (Teflon)

References:

http://www.trianglecircuits.com/substrates.html

 

 

 

 


 

 


4.   Developing

 

Material and Equipment

  • Sodium Hydroxide or Developer solution

  • distill or plain water

  • gloove

  • glass, plastic, wooden rod or old chopstick

  • container slightly bigger than the PCB board

  • exposed PCB board

  • container with water for washing

Sodium Hydroxide NaOH, and a pair of Gloves.

4.1 Developer introduction

 

Sodium Hydroxide is used as a developer. Correct proportion is necessary as too much will destroy the photo-resist coating instantly, while too little will have no effect in developing the PCB.

Commercial developer solution (pre-mixed with distill water) might work better since mixture is in the correct ratio for PCB developing.

Silicate Based Product make a better developer as less likely to be over-developed. Higher concentration will increase the developing speed.

I have seen on other website that the chemical NaOH is used as the drain pipe cleaner.

 

   Where to buy them locally???

You can buy alternately pcb developing solution from Bell System, #03-12, Sim Lim Tower. Or visit the local chemical store in Singapore

 

 Visit Dickson Chemicals,

the local chemical store in Singapore

Dickson Chemicals

www.dicksonchemical.com.sg

Tel: 6280 0468

Fax: 6281 1082

30 Shaw Road #05-05,

Singapore 367957

 

 

 

 

mixing solution, NaOH chemical with water.

4.2 Developer mixture

 

I have used a old ice-cream container to mix the solvent. The solvent composite for making the developer consist ratio of about

 

1unit of Sodium Hydroxide is to

 

20 unit of Water.

 

The solution must be of uniform concentration. Stir the mixture until NaOH is fully dissolved in the water. If the chemical is not fully dissolved, the region with concentrated NaOH can destroy the photo-resist coating instantly.

Use a glass rod when working with chemical if possible. Glass material is less reactive with most chemical.

 

mixing NaOH developer solution.avi (3.4MB)

 

When mixing NaOH to water, heat will be produce. Stir the water solution constantly while adding in NaOH slowly.

 

 

Various Developing Chemical

 
Sodium Metasilicate

(msds)

Sodium Hydroxide NaOH

(msds)

PCB developing. washing away photo-resist coating that are expose to the ultra-violet in the earlier stage.

4.3 Developing PCB board

 

Developing PCB board by dipping into the chemical solution. For this setup, I am also using ice-container.

During the developing process, the chemical board should be agitate constantly until the board is developed.

 

developing PCB board.avi (3.6MB)

 

The board is fully developed when the PCB traces appear green in color. This green layer is the photo resist layer which protect the copper surface underneath during the etching process. The region to be etched away later will be expose and is brown in color. The brown color is the actual color of the copper. There is no photo-resist coating to protect the surface.

Rinse the developed PCB board with running water after developing.

 

picture of a developed PCB board.

4.4 Over and under developed board

 

The left portion of the board is developed fairly. Notice that there are still some unwanted fade green coating on the copper surface. The board has been soaking in the developer solution for quite some time but the green photo-resist coating is still not remove. This is probably due to inadequate UV exposure time. The UV exposure for this board is exactly 60 seconds. The UV exposure should be 90 seconds instead. It is better to over exposed during the UV lighting process.

There is no attempt to dip the board for a longer period or using stronger solution to remove the fade green coating. It may just cause the dark green pattern to be washed away as well.

The photo-resist layer on the right portion of the board is being washed away. The board is dipped into the solution, without dissolving the NaOH chemical completely. The strong concentration of the chemical have wash away the coating instantly. This example serve as a reminder to stir and dissolve the mixture well before any attempt to develop the PCB board.

mending the circuit trace that are over developed.

This is the marker use in the demonstration. A fine tip oil base black marker from “ZEBRA NAME PEN” made in Japan.

4.5 Repairing over developed board

 

Sometimes, thin traces on the board may be over-developed. The required trace is not protected by the photo-resist coating after soaking for too long in the developer. The trace has to be protected or it will be etch away in the etching process. These broken or missing circuit trace pattern can be corrected and repaired by drawing over the copper surface with a Etch resist marker. The marker ink will cover up the copper region and acts as etch resistance during the etching process.

There are commercial etch resist marker available, however a general purpose oil base marker will be just as good for use as a etch resist coating. It is a commonly available permanent marker, meant for general use.

 

 

   Where to buy them locally???

I am fortunate to test out my zebra name pen marker can actually work as an etch resist shield. You can easy get this type of marker in our local stationary shop. For example, Popular Book shop. If you are looking for a professional etch resist marker, you can buy them from Farnell. They should have it. The tray is actually also a old ice-cream box.

 

 

 Visit Dickson Chemicals,

the local chemical store in Singapore

 

Dickson Chemicals

www.dicksonchemical.com.sg

Tel: 6280 0468

Fax: 6281 1082

30 Shaw Road #05-05,

Singapore 367957

 

over developed PCB board, with all traces wiped away. The NaOH mixture is too strong. The photo-resist layer got wipe out instantly.

4.6 Over developed board

 

The photos show the results of a over developed board. Too much chemical was mix in the solution, resulting in a very strong developer solution. The green photo-resist coating on the board was wiped away instantly. The clear and sharp printed pattern appear immediately when the board is dipped into the solution. When the board is lifted up, the whole photo-resist layer is being wash down from the surface of the solution. Leaving away nothing but bare copper on the board surface.

When PCB trace appear instanly when it is dip into the developer, it can indicate that the solution is too strong. Start off with low NaOH concentration, and increase a bit at a time. Experiment and obtain the correct mixture for the developer. Remember to dissolve the chemical fully when adding more chemical, before dipping the board into the solution.

 

 

 


 

 


5.   Etching

 

Material and Equipment

  • Ferric Chloride powder

  • distill or plain water

  • gloove

  • glass, plastic, wooden rod or old chopstick

  • long container for the etchant

  • a boarder container for boiling hot water below

  • 3 litre of boiling water

  • drilling machine

  • plastic string

  • developed PCB board

  • container with water for washing

  • detergent

Ferric Chloride FeCl3,

SENO 3200 (hexahydrate type)

 

Translated Instruction from German Language found on SENO 3200 iron iii-Chloride.

Long-proven etching agent for printed circuits, copper and high-grade steel, which already corrodes at ambient temperature and is almost for an unlimited period storable also in used condition. In the temperature range of 20-40 it is characterised by a good etching rate and a small under etching. With increase temperature increases both. Copper admission on the average 40-50g/Litre, etching rate 40-3µ/min

Caution: Injurious to health when swallowing. Far of children and food store. Rinse off immediately during contact with the eyes thoroughly with much water and physician consult. Marks with difficulty removable.

 

Content: 230g per pack for 0.5 to 1 Litre of etchant.

 

mixing FeCl3 with water

5.1 Etching introduction

 

Ferric Chloride is use to etch away copper surface on the PCB board. It is a very toxin chemical and is harmful to the environment. Please handle and dispose the chemical waste with care. It is dark yellowish in color and can stain your clothing.

Remember to wear protective gloves while handling FeCl3. Chemical is toxin and will cause skin irritation Wash skin with running water immediately when in contact with skin.

Stronger FeCl3 solution enables etching process to be faster.

When design PCB board, it may be a good idea to fill up with regions of copper. This is to minimise the area of copper surface to be etched away. With less copper to etched, it will also means that the solution can be effectively use to etch more PCB board.

 

 

   Where to buy them locally???

You can buy Ferric Chloride from Bell System, #03-12, Sim Lim Tower. Please do take care of our environment when disposing this chemical. The etching tray is again an old ice-cream box.

 

 Visit Dickson Chemicals,

the local chemical store in Singapore

 

Dickson Chemicals

www.dicksonchemical.com.sg

Tel: 6280 0468

Fax: 6281 1082

30 Shaw Road #05-05,

Singapore 367957

 

 

 

 

 

5.2 Etchant mixture

 

The solvent composite for making the etchant consist of

 

about 1 unit of Ferric Chloride FeCl3 is to

 

3 unit of water.

 

 

or about 1 unit of Ammonium Persulphate is to

 

5 unit of water.

 

Stir the mixture until FeCl3 is fully dissolved with the water.

 

mixing FeCl3 etching solution.avi (3.4MB)

Various Etching chemical

 
Ferric Chloride FeCl3

(msds)

– Ammonium Persulphate

(msds)

– Sodium Persulphate

(msds)

– Peroxy Sulfuric (recyclable chemical)  
– Ammonium Persulfate

(msds)

warming up the FeCl3 solution

5.3 Warming up etchant

 

Warm up the FeCl3 solution on a tray (blue) filled with hot water. Temperature range from about 50°C to 60°C will be suitable to speed up etching process.

 

warming up the etchant solution.avi (3.6MB)

secure PCB board with string

 

or use scotch tape to secure string to the PCB board.

5.4 Board preparation for etching

 

Drill a small hole on the PCB board so that a string can be secure to the board. The string is use to position or pull out the PCB in the toxin solution.

 

or

 

A scotch tape can be used to secure the string to the PCB board.

PCB board etching until the unwanted copper is remove completely by the chemical.

5.5 Etching PCB

 

Immerse the PCB board slowly into the FeCl3 solution. Agitate the PCB by tilting the container to and fro gently, until the unwanted copper layer are properly etched away, leaving only the required region on the PCB. The process may take 15 – 60 minutes to complete. Process duration will depends on the concentration, temperature of the etchant solution.

 

 A video clip is available to help you visualise the process.

 

etching process 1.avi (2.8MB)

etching process 2.avi (2.7MB)

etching process 3.avi (2.9MB)

 

 

Etching method also plays a part in the etching speed. If you leave the board without any agitation, the process may takes hours. There are other method of agitation, for example by using bubble or spraying onto the copper surface. A good agitation equipment helps to speed up the process to merely a few minutes.

The etching effectiveness will be reduce if the solution is re-used for a number of times. Strong FeCl3 concentration and high temperature can increase the etching speed.

testing of different ways to resist copper from being etched by the chemical.

5.6 Testing various etch resist material

 

The photos simulate a developed PCB board masked with some scotch tape, masking tape, and text using oil based marker. The board is over-developed and is used for testing various etch resist materials.

The experiment shows that adhesive tapes and oil base marker can be implemented to perform as a mask to resist from the etchant.







Notes:

For commercial PCB fabrication it is important to leave a minimum spacing between the copper track depending on the PCB copper thickness. This is needed so that it have enough space for the etching to take place.

http://www.pcbuniverse.com/pcbu-tech-tips.php?a=4



Cu Weight         Min Recommended Space between copper features

1oz                     3.5mil (0.089mm)

2oz                     8.0mil (0.203mm)

3oz                     10mil (0.254mm)

4oz                     14mil (0.355mm)

washing PCB with detergent after etching.

5.7 Washing board condemned with FeCl3

 

Prepare a container of detergent solution to wash the PCB board condemned with chemical FeCl3. Detergent contain Sodium Carbonate or Sodium Hydroxide, which can neutralize FeCl3.

removing away the photo-resist green coating.

photo-resist coating removed, however the black marker writing is still on the board

 

 

contact cleaner is apply to tissue paper wiping away the marking.

 

washing chemical content on the board with running water.

 

PCB etching completed

5.8 Removing photo-resist coating and other stain

 

Photo-resist mask or marking of the traces can be removed using the NaOH developer. It is the same developer used during the developing process. Stronger solution can be use this time round as the etching is already completed. The protective coating is no more in use.

A cloth soak with the solution can be use to wipe on the PCB board surface to remove the coating.

For the marker stain, it can be remove using commercial available contact cleaner, alcohol, or thinner solution.

Rinse with water, clean and dry the PCB board.

 

wiping marker ink away from the copper.avi (2.8MB)

 

soaking FeCl3 in detergent before attempting to dispose this chemical waste.

 

 

 

5.9 Disposing toxin chemical

 

Ferric Chloride FeCl3 is a toxin chemical. Please consult your local authority for proper dispose of chemical waste product.

As recommended, detergent (or other baking soda) can be mixed to the FeCl3 solution. The mixture solution can easily produce bubble foam which can grow 10 times in volume. Lay waste paper under the container to prevent toxin overflowing out of the container onto the floor. Leave it to dry before disposing the waste.

 

Sodium carbonate (washing soda) or sodium hydroxide can be added to neutralize Ferric Chloride before proper disposal.

For information on the disposal of Ferric Chloride. Follow this link,

http://www.mgchemicals.com/techsupport/ferric_faq.html

one month after neutralizing FeCl3

semi-dry residue at the wall of the container.

This is the result, one month after neutralizing FeCl3 with detergent. Just taking some pictures of this experiment for the fun of it. The solution smells and strong toxic gas can be felt. There are still little bubbles popping at that time during photo taking. The test copper board has been etched naked after soaking for so long. The wooden stick that I dump into the chemical has become totally black in color. The tissue paper throw in, still looks the same. Plastic rope is still there. To dispose this pool of chemical, they should be left to dry. The dry residues is easier dispose off. Less harmful to the as compare to when FeCl3 is in its liquid form.

 

 


 

 


 

6.   Cutting and Drilling

 

Material and Equipment

  • dot punch or sharp tool

  • drilling machine or hand drill

  • 1mm, 1.5mm drill bits

  • coping saw

  • hand files

  • penknife

  • steel ruler

  • bench clamp or support

Complete fabrication of smaller individual PCB board

6.1 Introduction to cutting and drilling

 

The etching is completed. The original artwork is arrange to maximise the use of the PCB board. 5 small PCB can be fabricated on the 15cm x 10cm board. 3 of the PCB pattern is not formed properly during the developing process, therefore only 2 PCB board can be extracted.

Hole is necessary to mount component (example: resistor, capacitor, inductor, board mount switch, DIP integrated circuit IC etc). Before drilling, a dot punch is used to mark the hole position. This serves as a shallow guide for the drill bit to align easily while drilling. Any other sharp pointed tool can be use to do the marking.

The drill is fitted with a 1mm drill bit. A typical hole size large enough for most components. A 1mm drill bit is thin and can break easily. Hold the drill steady and drill in straight slowly. The hole will be drilled with little force applied.

After the drilling is completed, the board outline is then marked with a steel ruler and a pen knife. Coping saw is used to cut the board out. The board will leave sharp bur edges after sawing the board. Use the hand file to de-bur the sharp edge.

The PCB board making is completed and is ready for use.

 

drilling holes for components.avi (2.8MB)

 

There is a market trend of shifting all electronics to surface mount type. Components are more compact and therefore reduces the overall size. Eventually it contributes to the reduce in cost in almost every aspect of the project. Cost reduce in component, PCB board, transportation, etc… . Although it is fairly difficult to solder, the convenience of making PCB board without the hazard of drilling holes make it very attractive to the home PCB fabrication. Soldering surface mount device (SMD) component is possible and requires some practices.

Talking about soldering SMD component, there is this interesting question I have once raised. Have you ever notice the perfect soldering in the industrial PCB? It took me quite an imaginary journey searching for machine to do a perfect soldered PCB board. In the PCB manufacturing industrial, they are using a grey solder paste/cream instead of the solder wire roll. Similar to a toothpaste it is actually a lot of tiny solid solder balls mixed with flux. The paste is spread onto the PCB soldering pad, where the leads or SMD component will be later place on. The paste should  keep cool when not in use; no refrigiration needed, with an expiry period of about a year.

The whole PCB board is then taken on a conveyer belt ride through the hot oven to melt the solder paste and flowing solder will occur. After melting the paste on the PCB, it is then cool, and the solder harden which results in a perfect soldered PCB board. This re-melting process is know as reflow.

Reflow soldering is very fast, a method suitable for mass production. Unlike using a soldering iron, there is no need to aim on the soldering pad, typical heating through gases. SMD component will align automatic themselves during the reflow. You may be interested in getting a reflow station, or reflow machine for high volume production. For a cheaper reflow solution at home, you can click down to this highly recommended website,

 http://www.sparkfun.com/tutorial/ReflowToaster/reflow-hotplate.htm. They have demonstrated how surface mount component are soldered to PCB using industrial standard. It is a very interesting and educational website. Hope that you will enjoy.

The wave soldering process, is another method used for mass soldering of the circuit. Quite interesting.

http://www.ami.ac.uk/courses/topics/0225_wave/index.html

 

More article on Wave and reflow soldering.

http://www.ibselectronics.com/pdf/pa/walsin/smt_notes.pdf

www.zianet.com/erg/SMT_Soldering.html

mounting of surface mount component.pdf

Reference for smd equipment for soldering production.

smt equip,emt reference.pdf

http://www.faze.co.za/Products.html

 

 

 


 

 


7.   Tinning and Masking

 

Material and Equipment

  • solder flux

  • soldering iron (flat tip is available)

  • soldering stand with wetted sponge

  • solder sucker

 

 

tinned PCB board.

 

 

finish PCB product

 

DTMF decoder circuit using MT8870DE

 

LM2576 dc-dc converter circuit

 

7.1 Tinning the copper surface

 

Copper will oxidize when expose to oxygen environment. Oxidization should be avoided as soldering is difficult on oxidization surface.

A thin layer of solder is coated on the copper surface to prevent oxidization. Apply solder to the copper surface with hot soldering iron and spread the liquified solder across the surface. Covering the copper surface with solder helps protect the copper from oxidization.

 

tinning PCB copper area.avi (3.0MB)

 

 

There are various type of commercial surface finish options for PCB board.

– HASL -Hot Air Solder Leveled (Low$)

– Immersion Tin (RoHS, Low$)

– Lead Free HASL -Hot Air Solder Leveled (RoHS, Mid$)

– ENIG -Electrodless Nickel Immersion Gold (RoHS, Mid$)

– Electroplated Gold (RoHS, Mid$)

– Immersion Silver (RoHS, Mid$)

 

Reference link:

http://www.nciproto.com/info/Surface_finish.htm

 

 

 

7.2 Masking PCB board

Masking can be applied to non-soldering area to protect the board from potential short circuit, oxidization and overflow of solder during soldering. The soldering would also be easier and nicer

It is not really necessary in home PCB fabrication, however if you want to give your board the professional touch, there is masking spray available in the market to lacquer the PCB board.

 

Click here for a short clip on “Apply a solder-resist mask to PCB“.

 

 

 

 

 

 


 

 


7.   Other Method of PCB making

 

<This is an OLD ARTICLE>

Laser printing, iron transfer artwork

Use Etch-resist pen

PCB patter transfer film

Milling PCB

Using etching machines for mass production.

 

If you are interested to know a brief idea of how a professional PCB fabrication process is, please follow this link, http://www.jlc.net/~preid/pcbpro/indexpcb.htm

 

bubble etching equipment

 

bubble Tank accessories for PCB board fabrication.

container to hold the Etching chemical.

A flat plastic container is used for developing the photo-resist PCB. Glass rod should be used to stir and mixed the chemical in distill water, because glass material does not have chemical reaction with most chemical.

air pump to sort of stir the liquid to quicken the etching process.

long stone rod to disperse air bubble

water tank or fish tank heater to warm up the water during etching process.

 

 

 

photo-resist PCB board 15cm x 10cm from Kinsten

 

Old Article:

Written by Lim Siong Boon, dated 03 Dec 2005.

The fabrication process was a failure. Photos was taken on the fabrication process. Unfortunately the photos were lost in the borrowed digital camera. Damn it, the pictures are lost for no reason. Should have retrieve the photos immediately after the photo taking.

The first fabrication was done in a friend’s company, selling and dealing with chemical stuff. He is Chee Keong, my good friend from Singapore Polytechnic. He is my very supportive of my project, and invited me to his company on a fine Saturday evening (Sep 2005) for my board fabrication. The place is great because he have all the chemical, tools and facilities I need to fabricate the PCB.

Sodium Hydroxide NaOH was used to developing the photo-resist board, and Sodium Persulphate was used to etch away the metal. Ferric Chloride is a more common chemical used for etching the board, it is a very toxin chemical and disposal needs careful attention. The chemical is a controlled item in Singapore and requires license to use the chemical. It is this reason that I insist to try something safer, like sodium persulphate. However after the trial, sodium persulphate doesn’t seems to perform. I have not yet figure out the reason, but would like to try out Ferric Chloride for my next trial. It is a dangerous chemical, so some knowledge research or revision is recommended before any attempt to use the chemical.

There are other alternative chemical used in PCB fabrication after some research on the internet.

Bubble etching concept

Trying to heat up the solution with the heater. It is slow and very troublesome. The air pump has to be glue to the bottom as it will tends to float and is unable to keep still. Cleaning is very troublesome because a lot of equipment is required for the etching.

After trying for 2 times, a simpler idea pops out of my mind. Shortcuts are for lazy people like me.

New IDEA

A new and simple etching setup that pops up on my mind.

Hair Dryer will provide the heat and agitation to speed up the etching process.

The flat lying plastic tray will provide minimum amount of chemical to be mixed for etching the PCB board, through means less wastage.

In the end, I ended up using an even easier method by placing the container of etchant solution on a tray of boiling water.

It works and have less minimum setup. Etching quality is just as nice.

   
   

Other PCB making references:

This is a very interesting video that I have found, showing the detail process of making a professional PCB board using manual method.
A very primitive method of fabricating a PCB board.
http://www.youtube.com/watch?v=8-WGaAmpfOU&feature=related

 

www.pic-control.com, Singapore Research & Development R&D

Singapore Customized, custom made Electronics Circuits & Kits

 

 

  Home PCB Fabrication Cost

 

 

Bill Of Materials, estimate to be S$60.00

S/N Tools Cost
1 Container+cover take from home
2 Air pump S$4.00 (2nd hand)
3 Air tubing S$1.00
4 Stone rod S$2.00
5 Photo-resist PCB 15cm x 10cm S$3.00
6 Heater rod S$3.00 (2nd hand)
7 Ultra-violet lamp tube+ballast casing S$14.00
8 A plastic basin S$2.00
9 Etching Chemical S$10.00
10 Gloves S$1.00
11 Water or Distilled water S$1.00
12 Ferric Chloride FeCl3 S$9.00
13 Transparency S$0.50
14 Scotch tape S$0.50
15 Sodium Hydroxide or Developer solution S$9.00
16 Distill or plain water S1.00
17 Gloove S$1.00
18 Chopstick or rod S$0.50
19 Plastic/Nylon String S$0.10
20 Detergent S$2.00

 

 

 


 

 

Keyword: DIY Printed Circuit Board PCB fabrication home, printed wiring board, step by step instruction process PCB making, photos video illustration, Sodium Hydroxide, Ferric Chloride, chemical

 

Reverse Engineering of Electronics Circuit Board. Your Hacking Resources.

Resource to assist reverse engineering of circuit board and IC .


Edited by Lim Siong Boon, last dated 10-Aug-2014.

Topic Discussion Overview

  1. Introduction to reverse engineering of electronic circuit board
  2. Recognizing Components
  3. Mapping out the Traces
  4. Looking at IC chip marking


1. Introduction to Reverse Engineering of electronic circuit board



Reverse engineering circuit board is definitely not a simply one day training lesson. It is not as simple as knowing it all simply from a search engine on the internet. It is a process which harness the years of experience accumulated in electronic design and studying of how other engineers design their circuits. While as tough as I may have describe, it does not means that there is no way to learn this skill.

There are many reason why we need to reverse engineer a circuit board. One reason that I enjoy doing, is to learn something from the board. In the early days of my engineering career, as a fresh graduate who have background about electronics but practically don’t even dare to design a circuit for commercial use. There was just not enough confident in myself to design something for the industries to use. It was also a time when I started to become curious of how a circuit works. As a fresh new hardware engineer in a R&D department, basically I start create circuit solution by copying. Copying design that I find from books, from electronic kits purchase from stores, from internet where many people uploaded for their projects. I was also fortunate to have a colleague who had had retired and was working for this small company that I was working in, who makes me felt like he is nagging, trying his very best to share his knowledge about electronics with me. Standing there listening to him teaching from the very basic, starting from the name of a component. Topic like, how to classify the type of switch SPST DPST DPDT,can seems boring. It can be quite an annoying thing, when he speaks about simple things (which I thought they were). The truth is those simple thing that I thought they were, are actually fundamentally important, I had realized. Over time I started to earn some insight which I didn’t really catch then during my polytechnic and university school days. The topic “Switch” that I wrote in another webpage is one of the simplest and most important topic that I think all electronic hardware engineer needs to know by hard.

Reverse engineering can be like looking at a piece of blank at first. The more newbie you are, the more you do not know where to start understanding the circuit. In this section, I will briefly go through the process of how a circuit board can be reverse engineered in a sequential process.

Circuits can looks like an art where almost every circuit seems so different. The truth is that many circuits are very similar in nature. There is a pattern that you can find in every circuit. Recognizing these pattern is important. The more pattern you know, the faster you are about to decode the circuit. Electronic is physics and physic is the same across the world we are now living in. People use the same knowledge, copy the same knowledge, ends up with circuits that are quite standardize across the design that we can find. First important concept that we can start with, is to know that there is a standard circuits in many of the design. Just like a rubber stamp, people tends not to reinvent the wheel. We design a circuit that works, and keep on using that same circuit pattern. Whenever we trace out the component connection, we will try to match these patterns that we are able to recognizing. As you might have realized by now, the prerequisite to master the skill of reverse engineering, is the skill of designing electronic circuits. Like wise the opposite is also true. Both reverse engineering and circuit design are skills that need to progress hand in hand.

Why Reverse Engineering?
– to learn how things work.
– to do something new or unique.
– test hardware’s specification, security and weaknesses.
– better control of the system.
– identify design failure, weak components due to current, voltage or heat.
– identify how product can be improved.

Method of hacking and doing reverse engineering
– information gathering
– trace hardware components and connection
– firmware reverse engineering
– external interface analysis
– silicon die analysis (reverse engineering at microscopic level)
– communication monitoring, protocol decoding, Serial, USB, Ethernet, I2C, SPI, CAN using oscilloscope, logic analyzer, sniffers, software tools, etc.

reference:
https://media.blackhat.com/bh-dc-11/Grand/BlackHat_DC_2011_Grand-Workshop.pdf
or BlackHat_DC_2011_Grand-Workshop.pdf

Removing Epoxy Encapsulation.
– hot air soften epoxy
– Chemical, MG Chemicals’ 8310 Conformal Coating Stripper (www.mgchemicals.com)



2. Recognizing Components


Recognizing all the components on the circuit board.

The most basic thing you need to recognize is the electronic components that you see on the circuit board. As a new engineer, you may find yourself floated with odd components that you have not seen before. Many newbie may recognize those component symbol that we read from the schematic, but may not be able to recognize them in the actual physical form in a real physical circuit.
The resistor component alone can comes with many sizes, shapes, and color. It is important to recognize them, and understand their differences in characteristic. In school, we usually take resistor as only a ohm value, and don’t bother about the precision of the resistor,  tolerance, and even wattage is often ignored. In a practical circuit design, there are reason why some resistor are bigger or why some are more precision. First thing first, ensure you can recognize each and every component on the circuit. Knowing their names and how they are classified can helps you speed up the time needed to identify them. It is also a reason why through out my other webpages, I try to use photo, and put down the possible names that can be use to identify the components. Identify as much components as you can. Resistor, Capacitor, Inductor, IC chips, fuse, diode, transistors, connectors, PCB board, etc…

Nowadays, modern circuit board uses more IC chips than passive components. All IC chip looks the same black encapsulation with various shape and size. The important thing is to examine the number that is printed on the chip itself. Without it, you will need more brain power and experience to decode the board. It is also a main reason why some manufacturers will find ways to erase the lettering on the IC chips. It is a means to increase the barrier for reverse engineering, which can reduce the probability of their circuit design being copied.

With the lettering on the IC chip, you can search for their datasheet on the internet. If you cannot find them in the search engine, you may like to try again, leaving out some lettering in the front or back in order to increase the probability to get a search hit. The latter section “looking out for the IC chip marking” delicate a section to improve your chance to discover the IC marking and the search for its datasheet.

Most modern circuits are design using surface mount components. They can be small and traditional color band scheme for a component like resistor cannot be use. For these SMD resistors, they are number coded. For bigger SMD resistor, they are number coded, similar to the color band scheme where the first few digit represent the actual digit, while the last digit represent the number of zeros. Smaller SMD resistor which has a smaller printed area print their value using a standard coded system. This standard coding system is known as EIA marking code. There is no way to determine the resistor value easily from the code. Fortunately, we do not have to remember it by hard. With a search through the internet, we just need to extract its value base on the code. There is also this free android apps call “ElectroDroid” which can allow you to key in the EIA code, and return you with the resistance value. The apps also contains many other features which can assist you in your reverse engineering process. For more information about resistors and capacitors classification, click on the respective links.

Recognizing the components is only the first step. Identifying component itself already requires a lot of experience and effort. Even after nearly two decades of working with electronics, I still do find components which I find it difficult to identify. Inductor and transformer is a component which I am still not able to overcome easily. Newer modern components being used in circuits, often curious me. It is a never ending learning process.

STEP 1:

Take a photo of the circuit board (top and bottom), and start to assign a reference designator (label numbering) for each of the components.
pcb-front.jpg  pcb-back.jpg

Use OpenOffice Impress to help you do the component part labelling on the photo of the circuit board (PCB).
pcb-labelled.jpg

For example, all resistor can have prefix R1, R2, R3, R… R46, capacitors C1, C2, C3, C… C56.

Document these parts on a OpenOffice Calc spread sheet with the following columns,

(S/N or component prefix label, Component type, Package, Marking, Part no., Manufacturers)

Try to fill up the columns with information as much as you can.

You can download a template example here.
Component reference designator labelling (*.odp)
BOM list (*.ods)

Check out

STEP 3:

Copy another PCB bottom and extract only the trace or copper area.
pcb-back-trace.jpg
Flip the PCB bottom, and size it to be the same size as the top.
The PCB bottom trace adjust the Red & Blue by 50%, so that the trace color can be differentiated from the top pcb trace.
Overlay the PCB top over the PCB bottom. Adjust the transparency of the PCB top to 60%.
pcb-overlay.jpg
This overlay can help you trace the connection without flipping the circuit board physically.

STEP 3:

Build a schematic, laying out the component parts base on those on the BOM list.

STEP 4:

Trace out the connection on the circuit board onto the schematic that you are building.

STEP 5:

This step requires your experience from the circuits that you have seen. It is sort like a jigsaw puzzle, using your brain pattern recognition skills, matching component’s connection forming the typical circuits layout that was used.
Arrange the connected components in their typical function configuration layout.
For example the connection may represent a typical
– transistor switch configuration
– input switch and pull-up resistor
– voltage regulator
– amplifier
– output
– etc…






reverse engineering electronic circuit board solution




3. Mapping out the Traces


Mapping all the traces, the connection on the circuit board.

This is the most tedious part of the reverse engineer process. It is to map out how the components that you have identified earlier are connected. Component by component, we map out all the connection (known as traces).

Before starting the tracing process, it is important to recognize the PCB board type. I classify them as single layer, double layer and multilayer board.

The simplest board is the single sided PCB where one side of the board is consist of only the PCB trace routing, while the other side is the electronic components. Typically consist of mostly through holes components. Fairly simple to trace out the connection.

The second type is a double layered PCB board where traces can be found at both side of the board. Most of the time, through hole components are found on one side of the board while the surface mount component is found on the other side. Very often, traces are routed below through hole components and IC chip. This makes it impossible to trace out the connection using only our vision. Multi-meter’s function “continuity” is required to aid us to identify a connection (sometimes also known as the continuity tester). Basically is will buzz when the probes touch two points which is connected by a trace. You can also use a ohm meter function which reads a 0ohm when a connection is probed. I prefer the buzz, because while I focus my attention tracing the circuit, I do not have to look up in the multimeter screen to check for a connection. The buzz sound is much more convenient. Although it is a productive feature to use to trace connection, it is important to note how the “continuity” feature works. Depending on the multimeter, the buzz is set to sound at a certain ohm threshold. This means that a 10ohm resistor between two point, can cause a buzz from the multimeter, which may mislead you into thinking that the two point is shorted. Do keep this in mind during the probing process. Using visual and the continuity features together should help minimize mistake. Components that you typically need to take note is, sense resistor (usually bigger in size than the rest of the resistor), inductors, transformer, coil and any external connection or wiring to the board. Another common mistake is to probe the circuit without switching off the power supply. Ensure that all connection to the board are disconnected before tracing for connection.

The most difficult board to trace will be the multilayer boards. Typically for a 4 layer boards, most designer likes to allocate the middle layer for power traces like VCC and GND. It is not a definite, but just a high possibility base on the experience of looking at other circuit boards and also some common circuit theory. Doing reverse engineering requires you to think a lot as if you are the designer designing the board that you are hacking. For a multilayer board, it is normally near to impossible to trace the board using visual. Matching of component pins connection is normally done for the whole of the circuit board. Matching one pin to the rest of the pin, one at a time. Sometimes with the understanding of the component, and some experience as a designer, you might be able to shorten the process. There will be zones that you will instinctively that there is no need to try.

Draw out the components position, and how they are connected. Taking a picture of the circuit helps you to trace easier. Sometimes I will superimpose the routed trace with the components in order to see the connection better. Label all the components, and name the trace once you are able to identify its function.

Power supply traces are the simplest to start with. This is because we usually knows where the power line is connected to the circuit. From there we can trace out where the power line goes to. From the power line, we will be able to trace out the next stage which is typically the voltage regulators. For a AC power line, usually a rectifier can be located a before it reaches the voltage regulator. These suggestion assumes typical design, it will be up to you to recognize it yourself because there are just too many variation of circuits designed.

Studying the datasheet of the IC chip on board can also help you to recognize connection. Arrange the component symbol into the standard stamp circuit configuration that you can recognize. Common standard circuit like input circuit, pull up, driver circuit using transistor, relay circuits, voltage regulator, etc… can easily be recognize. Draw them out in a format that helps you to recognize the circuit module functionality.

The process is complex, and it is a never ending topics on reverse engineering. The more you reverse engineer the more you will learn and improve your techniques, finding new ways to decode and learn how other circuits are designed.




www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller




Looking at IC chip marking

Looking out for the IC chip marking

IC chip is getting smaller and smaller. Many small chip can only be coded with only 3-4 letterings only. This is the IC marking which represent a part number from the manufacturer.


References for searching base on the letter/number marking on the IC,
– Database search, http://www.ecadata.de/searchnew/
– smd codes catalog 2012, SMD-codes Active SMD semiconductor components marking codes
– smd marking, http://www.satcure-focus.com/design/page2.htm
http://www.dl7avf.info/charts/smdcode/c3.html
http://www.sos.sk/pdf/SMD_Catalog.pdf

Marking code search from manufacturer’s website
Texas Instruments, http://www.ti.com/general/docs/partmarking/partmarkinghome.jsp
Cross competitor search: http://focus.ti.com/general/docs/searchhome.tsp

Fairchild, http://www.fairchildsemi.com/topmark/

Analog Device, http://search.analog.com/search/default.aspx

NXP, http://www.nxp.com/packages/

Cross Reference next to the search box, type the part number and search: http://www.st.com/web/en/ordering/buy_from_distributors.html?s_searchtype=keyword
Product selector: http://www.st.com/stonline/stappl/productcatalog/app?page=productSelector

Microchip, http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1924&dDocName=en544123
Product selector or Cross competitor search: http://www.microchip.com/maps/search2.aspx

Looking out for the logo on the IC chip.

Analog Devices
Atmel
BI Technologies
Burr Brown
Cirrus Logic
Cypress Semiconductors
Dallas Semiconductor
Diotec
Fairchild Semiconductor
Holtek Microelectronics
Intersil
International Rectifier
Maxim
Microchip
Motorola
NEC
National Semiconductor
NXP
Semtech
STMicroelectronics
Texas Instruments

References for IC manufacturer logos,
http://www.elnec.com/support/ic-logos/
http://www.classiccmp.org/rtellason/logos/semiconductorlogos.html
http://www.advanced-tech.com/ic_logos/ic_logos.htm or pdf
http://web.archive.org/web/20040401171928/http://www.elektronikforum.de/ic-id/

 

 

 

















www.pic-control.com, Singapore Network Ethernet WiFi RS232 RS485 USB I/O Controller

 

 

   

 

 

 

 

reverse engineering electronic circuit board solution

 





Keyword: reverse engineering, IC marking code, marking database lookup, footprint, datasheet, Singapore