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

Energy Audit with a portable power meter

How to save energy at home? Check out this page for my home appliance’s electricity consumption.

Let us begin energy/environment conservation for our planet by first understanding how and where we have wasted our energy.

Edited by Lim Siong Boon, last dated 12-Dec-2011.

Topic Discussion Overview

  1. How much is the electricity tariff rate costing us?
  2. Power Meter
  3. Home Appliances Power Consumption
  4. Lightings

 


   

1. How much is the electricity tariff rate costing us?

The Singapore electricity tariff rate has been rising steadily 18.03¢ (as of Apr 2009) to 27.28¢ (as of Jul 2011) ; A wopping 151% increase in tariff rate. How does this tariff rate relates to the electrical appliances that we are using at home?

The following example show you how to compute the cost of our electricity cost.

 

Assuming a device consuming 10W 24hr per day for one whole month.

Total energy consumption in a single day = 10W x 24hr = 240 Whr

Total energy consumption in a month = 240Whr x 31days = 7440 Whr = 7.44kWh

The bill for 7.44kWh of electricity consumption will be = 7.44kWh x $0.2728/kWh = $2.029632

 

This means that the appliance consuming 10W will cost me $2/mth.

Appliance consuming 20W will cost me $4/mth.

Appliance consuming 100W will cost me $20/mth.

If the tariff rate go up, the cost of electricity per watt will relatively increase as well.

 

What can I do to reduce my electricity bills, at the same time conserve our global energy resource?

First I have to understand my energy consumption in my own house, by doing a simple energy audit.

Being energy conscious will be the very first step to start save energy.

The energy audit of my home shown on this page will be based on the latest tariff rate of 27.28¢ (as of Jul 2011).

 

 

 

Our electricity tariff in Singapore since 2009.

Energy cost: S$0.1803/kWh as on 1st Apr 2009

Energy cost: S$0.1928/kWh as on 1st Oct 2009

Energy cost: S$0.2169/kWh as on 1st Oct 2009

Energy cost: S$0.2287/kWh as on 1st Jan 2010

Energy cost: S$0.2356/kWh as on 1st Apr 2010

Energy cost: S$0.2413/kWh as on 1st Jul 2010

Energy cost: S$0.2334/kWh as on 1st Oct 2010

Energy cost: S$0.2410/kWh as on 1st Jan 2011

Energy cost: S$0.2558/kWh as on 1st Apr 2011

Energy cost: S$0.2728/kWh as on 1st July 2011

Energy cost: S$0.2698/kWh as on 1st Oct 2011

Energy cost: S$0.2759/kWh as on 1st Jan 2012

 

 

References:

http://www.energysave.sg/

http://www.spservices.com.sg/

http://www.ema.gov.sg/Electricity/new/ (more tips to save energy)

Singapore electricity tariff rate Jun 2011

Singapore electricity tariff rate Jan 2012

 

   

Calculator for computing Appliance’s Electricity Cost

 

 

 

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

 


2. Power Meter

The beginning of this page starts with my handy portable power meter. It will be the most important instrument to help me measure the power consumption of the everyday appliances in my house. It was a coincidence that I brought my power meter. I had always like to have such a power meter to measure power consumption for fun and knowledge; the cost of such a gadget was rather expensive to be purchase just for fun. I got myself this power meter which is inexpensive. I like the huge display; the numbers are easy to read. It is very simple to use; just plug in the appliances that you want to measure and switched on the power. The function button can be pressed to cycle through the list of measurement parameters as follows.

1) Wattage, display the power consumption of the appliance

2) Display the energy consumption in terms of dollar cost

3) kWh (kilo Watt Hour), accumulated energy since operation.

4) Number of days, hours since measurement begins. (This helps to check against the kWh energy consumed and the accumulated cost run since measurement starts)

5) Voltage (Vrms measurement usually range from 220 – 240Vac)

6) Frequency (always 50Hz for measurement in Singapore)

7) Current (High current device usually requires thicker cable guage. High current flowing through thin cables can generate heat which leads to energy loss, and may result in fire.)

8) Power factor (PF range from 0.0 – 1.0. PF near to 1.0 indicates that the appliance has a better current to power efficiency, consuming all the power that was drawn) http://en.wikipedia.org/wiki/Power_factor

9) Highest/lowest wattage detected. (The meter when monitoring the appliance over a long period of duration, is able to show the highest/lowest wattage detected)

10) Key in the latest electricity tariff rate..

11) Reset button to reset the measurements.

The features on the power meter are more than enough to measure household appliances. There is a current limit of about 13A which the meter can handle; the meter will give off a warning beep sound and cut of the power if it is overloaded. I just love this power meter, cheap and good enough for my energy audit.

It was when I started measuring my household appliance, that I started to learn the appliances that are energy consuming. It is difficult to judge base on the device, even though I am a trained engineer in electronics circuit design. I was shocked to find that many appliances are poorly design in terms of energy conservation. This is also the reason why I started this page. I would like to find out the power consumption of the appliance in a typical home. The step to start saving our earth starts by being aware of our energy consumption; this is also known as our carbon footprint.

Besides measuring power consumption, this power meter is also very useful in my area of engineering works.

This portable power meter helps to verify my electrical installation works. There are also times where 110Vac is used in our 230Vac electrical system in Singapore. This meter helps to check if the voltage step-down transformer installation is correct, before we plug in any expensive 110Vac equipment from oiverseas. It can also be used to check the wattage of your equipment so that the accessories with the correct wattage can be purchased and installed.

Power factor (range 0.0 to 1.0) indicates the efficiency of the current drawn from the power station. Poor power factor is cause by your inductive equipment (eg. Fridge, Fan, Motor etc..) at home or factory. A power factor of 1.0 is the best, indicating the lowest possible current drawn. A reading of 0.6PF or below indicates a poor power factor, and you will expect the current drawn to be higher. The good news is, it can be improve by installing a capacitor across the power line.

This meter measures the power factor which allows me to add in the correct amount of capacitance to correct the power factor close to 1.0. Power factor of 1.0 means that the current drawn by my equipment will be minimum. The meter will also show the drop in the current drawn, before and after the capacitance installation. For more technical information on correcting power factor, I have another delicated page explaining all the details.

http://www.siongboon.com/projects/2012-01-24_power_saver/index.html

In the course of designing products for the industries, this meter also helps me to verify my design in terms of the energy consumption. It helps me to improve the design, allowing the product to consume less energy.

With this measuring instrument, we will have a better idea of how we can improve our energy consumption.

 

   “If you can not measure it, you can not improve it.”
                                                                     Lord Kelvin (1824-1907)

 

I hope this page can provide the awareness to get you conscious about your carbon footprint. It will also serve as a platform to compare the consumption with the available energy saving products. The journey shall starts with my power meter. Let’s get started.

References:

www.saveone.com.sg

 

 


 

 

My portable power meter packed with many features (description details on the left). Measure power from the plug.

1) Wattage

2) Accumulated electricity expense

 

saveOne power meter

3) kWh

4) Records of the number of Days & Hours since measurement starts

5) Voltage

6) Frequency

7) Current

8) Power factor

9) Highest/Lowest wattage detected
10) Entering the electricity tariff rate costing.

 

This power meter is purchased from saveOne logo.

Acknowledgement: some of the pictures on this page were taken from saveOne website. saveOne is a local company in Singapore, specialising in energy saving products and consultation services. They are also selling their various patented energy saving lightings products to promote green building to the industrial, hence reducing our carbon footprint in Singapore.

Website: www.saveone.com.sg , Email: sales@saveone.com.sg

Address: 63 Hillview Avenue, #08-01, Lam Soon Industrial Building, Singapore 669569.
Tel: +65 6764 3333, Fax: +65 6862 6277

 

 

Other brand of power meter available in Sim Lim Tower (Sim Lim Tower, 10 Jalan Besar 208787)

 

 

 

 

 

 

 

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



3. Home Appliances

Power Consumption

 

 

Note: the indicated elecrical costing is using the triff rate of $0.30/kWh

 

This is my electrical bill for my HDB house for the month of March 2012 from SP Services. The power consumption is estimated to be 363kWh which accounts to a bill of S$100.15. This is an estimation base on our electricity consumption for the pass few months. The tariff rate is 0.2759 for this quarter Jan-Mar 2012.

I am trying to measure all my appliances to see if I can estimate near to the indicated consumption of 363kWh per month. The list of contribution would propably comes from the following devices.

– Fridge
– Aircon
– Fan
– Computer
– TV and entertainment system
– Washing machine
– Lights
– Radio

It is time to find out the main culprit.

   

 

 

 

 

Home Lightings

Energy saving LED and Fluorescent lamp

 

 

Check out the various energy saving lamps here.

http://www.siongboon.com/projects/2011-04-17%20lamp%20bulb/index.html

 

 

Hot/Warm Water Dispenser

Model: Bio Pure (KEN2)

 

water dispenserwater dispenser

reading reading measurement
Typical standby power consumption is 6.8W When dispensing water, the wattage shoot up to 21W Total energy consumption for 63 days + 1 hour operation totals up to about 60.91kwh costing S$17.15

Standby power: 3.5W

Typical: 6.9W (wattage), 0.077A (current), 0.36PF (power factor)

Highest Wattage detected: 2256W

Low Wattage detected: 3.5W

 

AC indicator lamp

 

 

AC lamps

Hardly any wattage and current detected from the AC indicator lamp found on the multi socket adaptor..

 

Wireless Door Bell

Model: Sonik

 

wireless door bell Standby power is 1.2W

Even if the loud door bell ring is activated, the consumption still remains at 1.2W.

The door bell transmitter outside the door is using a battery.

 

Electric Fan

Model: Aerogaz 16″ stand fan AZ-163SF (60W)

 

Standby power: 0W

Speed 1 energy consumption: 34.2W, 0.159A, 0.95PF

Speed 2 energy consumption: 40.6W, 0.177A, 1.00PF

Speed 3 energy consumption: 45.3W, 0.190A, 1.00PF

Lab Bench Power Supply

Model: Kikusui variable DC power supply PAD 35-10L 0~35V 10A

 

14.3W consumption with no load to the lab bench power supply. Open DC voltage of about 0Vdc.

 

15.1W consumption with no load to the lab bench power supply. Open DC voltage of about 3Vdc.

 

Open DC voltage was tuned up to about 30Vdc. AC power consumption increases to 20.3W.

 

The current limits is purposely set very low to 0A. Consumption is now at 14.5W.

 

5Vdc open load. Wattage consumption is 15.2W.

 

5Vdc shorted load of 1A. This would have been a 5W load. Consumption is 27.9W. A 12.7W increased from the open load consumption.

 

Din rail MCB (Miniature circuit breaker), ELCB/RCD (Earth leakage circuit breaker)

Model: MOELLER PLS6-B6/2-AS (MCB ‘B’ 2Pole 6A 6kA), MOELLER PFIM-40/2/003-A (ELCB 40A 2Pole 30mA)

 

The circuit breaker and ELCB or RCD device uses very little energy. No power consumption was detected.

 

Charger for mobile phone (5V, 0.89A)

Model: Nokia C3

 

Not much power consumption when the charger is not plugged onto the mobile phone. Measured consumption is 0W. When the charger is plugged in, the consumption is about 1.3W.

Charger for bluetooth earpiece (5V , 0.55A)

Model: Sony Ericsson MW600

 

The bluetooth charger is similar to the mobile phone charger experiment. When the charger is plugged in, the consumption is about 0.7W.

Power Adaptor for laptop (19Vdc, 3.42A)

Model: Asus X23F 10″ laptop

 

For this Asus laptop’s adaptor, the consumption is more. When the adaptor is not plugged onto the laptop, the consumptionm measured is 0.3W, 0.014A.

When the adaptor is plugged onto the laptop, the consumption increases to 45.2W, 0.314A, 0.59PF

Then the laptop was switched on, the power consumption increases to 72.1W, 0.519A, 0.57PF.

The laptop was shutdown, and the power consumption drop back to 0.328A, 0.69PF. Should be about 45W.

 

Hair Dryer

Model: Rowenta (1500W)

 

This hair consumes a standby power of about 0.1W, 0.015A.

 

The hair dryer was switched to no.1, and the consumption is measured to be 755W, 3.26A, 0.98PF

 

Switching to no.2, the consumption now is measured to be 1460W, 6.3A, 1.00PF

 

Power Adaptor for Mini PC

Model: Giada Slim-N10 Intel dual-core Atom N330 1.6GHz, NVIDIA 9400M Graphics processor, 5x USB, 250Gb HDD, 2Gb DDR2 RAM, 802.11b/g WiFi, HDMI, Card reader

 

This Mini PC with power adaptor unplugged consumes about 0.5W. When it is plugged to the mini PC, the wattage increases to 3.6W, 0.053A, 0.25PF..

 

When the mini PC is switched on, the power consumption is about 28-30W, 0.21A, 0.55PF

 

Power consumption during standby with mini PC switched off.

 

Food Streamer

Model: Tefal, serie S07 (760W-900W)

 

When the streamer is off, power consumption is measured to be 0W. Turning on the “Keep Warm” features consumes about 835W, 3.55A, 0.98PF. The streamer will switch the streamer off when it reaches certain temperature threshold. This will keep the food warm while trying to keep the power coonsumption low.

With the streamer fully switched on, the reading is similar rto the power consumption of the “Keep Warm” feature.

 

LCD monitor

Model: 24″ Philips 240B MWB1240I (230Vac 1.2A)

 

This monitor has a standby power of 0.6W.

When it is switched on, it consumed about 27W and can reach as high as 43W.

 

Measurement taken 26.7W, 0.19A, 0.56PF.

 

Personnal Desktop Computer

Model: Shutter PC, Intel Core 2 Duo CPU E7500 2.93GHz, 4Gb RAM, 250Gb HDD, DVD drive

 

The computer CPU system has a standby of 0.7W when it is plugged onto a socket but not switched on. Typical about 60W, and the highest reading meansured is >70W. Current is 0.361A, Power Factor of 0.82PF. When the computer is put into sleep mode, the power consumption drop down to 3.6W 0.067A 0.21PF..

 

 

Color Laser Printer

Model: Fuji Xerox CP205W

 

Printer on standby 11.5W to 750W

Printer reaching its peak 776.1W.

The laser printer standby power is about 11.4W and reaches to 750W every 10 to 20sec in a pulsing manner (0.139A, 0.33PF). Perhaps it is using the energy to warm itself every now and then. Current 0.139A, Power Factor 0.33PF. Measurement taken during the printing process is about 50W to 750W.

 

A4 paper scanner

Model: Fujitsu Scansnap S510 (16V 1.5A), Power adaptor (230Vac to 16Vdc 2.5A)

 

Scanner power adaptor consume 0.5W when it is not plugged onto the scanner. When it is plugged to the scanner, the standby power is about 0.8W.

 

The scanner reaches to about 17.7W (0.131A, 0.54PF) when it is turned on. During the scanning process, the consumption is about 26.4W.

 

TV tuner box

Model: MyGica (5Vdc 0.6A), Power adaptor (230Vac to 5Vdc 1A)

 

This TV tuner box is surprisingly using not much energy. The consumption is measured at 0W when the adaptor is not plugged onto the device, and reads 1.5W when it is plugged in. Turning on the TV tuner consume only 3.3W.

Water Kettle

Model: Tefal VITESSE BF21 (2000-2400W)

 

The water is a simple heating element device. The load is resistive in nature. When not activated, the kettle consume 0W.

During the water heating process, the power consumption measured was 2140W (9.28A,0.98PF)

 

Battery Charger AA/AAA

Model: GP Power Bank GPPB50GS (230Vac 0.175mA, or 12Vdc 0.75A)

 

The battery charges has a standby power of 0.7W (0.008A) when no battery is under charging. The charging is a pulsing process. The wattage taken pulse between 3.1W & 0.7W when one AAA size battery was inserted for charging. The wattage goes up as more batteries (1x AAA and 2x AA) were inserted. The pulse is between 6.9W & 0.7W (0.055A, 0.5PF)

 

40″ LCD TV

Model: Sony KDL-40EX400 (155W)

 

 

See in this short video clip how the wattage increase as the TV starts to turn on. MVI_8968, sony lcd tv power consumption.AVI

 

 

The standby power for this Sony TV is quite high. 10.1W (0.095A, 0.42PF) was measured. It is equivalent to a lamp turning on.

The TV was switched on with the TV show running. The power consumption at this point in time was about 114W (0.546A, 0.89PF) .

There is this video footage capture for your reference. In the video, you can see on the power consumption rises as the TV was switched on.

MVI_8968, sony lcd tv power consumption.AVI

 

DVD player

Model: Pioneer DV-595K (7W)

 

Standby power 0.7W measured is the same as specified in the user manual. Thie meter seems quite accurate for our energy audit.

 

The standby power for this DVD player is 0.7W (0.008A).

When the player starts to playback video on the CD, the measurement taken was 6.5W (0.057A, 0.51PF). Energy consumption is quite reasonable for a player.

It increases slightly at time to 7.2W (0.6A, 0.49PF)

 

Induction cooker

Model: TAIYO TH-ID19 (1900W)

 

 

 

 

See in this video clip how a induction cooker consume the energy. MVI_8983, induction cooker.AVI

 

The standby power is about 4W (0.25A, 0.1PF) . When it is switched on without any pot, the reading was 10.8W (0.141A, 0.29PF). The induction cokker is quite intelligence. No power will be activated when the cooking pot is not on the stove.

A stainless steel pot fillled with water was placed on the cooker stove. The induction cooker detects the load and starts to consume a lot of nergy to boil the water. The power consumption was 1974W (8.691A, 0.99PF). The induction cooker power factor is surprising good. The load may not be inductive in nature, or perhaps capacitors are added to the cooker to correct the power factor. By correcting the power factor of your appliances to a value close to 1.00, the current it draws will be at its minimum. This helps to reduce losses, reduce of cable size, prolong lifespan of your cable, generate less heat, etc…. many benefits. The benefits will not be significant but it is better to have it optimised than a design that isn’t.

The following footage shows how the power consumption changes on this induction cooker.

MVI_8983, induction cooker.AVI

 

NAS Network Attached Storage

Model: Netgear ReadyNAS Duo, Power adaptor (230Vac to 12Vdc 5A)

 

The power adaptor was not plugged onto the NAS, gives a reading of 0.4W. This means that the power adaptor doing nothing is actually wasting the electricity when connected with the mains socket switched on. When plugged onto the NAS device, the standby power is 0.8W.

When the NAS was switched on, the power reading was 23W (0.17A, 0.53PF).

 

Home Wireless Router

Model: Dlink DIR-655 (12Vdc, 2A)

 

Wireless router’s power consumption seems ok. Measured power during operation was 6.1W (0.051A, 0.51PF).

 

AV Wireless Transceiver

Model: AV@AirPro

 

This wireless AV transceiver consume about 2W. Quite little energy.

 

Cable TV setup box

Model: STARhub Hubstatio DC162SHB

 

The STARhub setup box has a significantly high standby power required. The measured power during standby was 20-25.6W (0.184A, 0.59PF).

The setup box reaches 27W (0.187A, 0.6PF) during start up, and consume 26.5W (0.19A, 0.59PF) during the cable TV show. The increase in power from standby is relatively low. This device has the most energy wasted during standby. Turning the machine off to a standby mode will only save you 1 to 2W, but actually wasting about 25W.

 

The little multimedia Zen10 box consume much less energy compared to the STARhub setup box. Zen10 consume only about 0.4W during standby, and 6.2W (0.052A, 0.42PF). If the power adaptor is not plugged onto Zen10, the wasted power on the adaptor is measured at 0.2W.

Fridge

Model: MITSUBISHI

 

The fridge consumption seems rather stable. Different from what I have expected. I thought it should be like a pulsing type of power consumption pattern. Switching on and off the compressor when neccesary to cool the fridge. Typical wattage consumption was about 209.1W and can reach as high as 388.7W.

The meter was put on the fridge for another period of 32 days. The following reading was taken which was more accurate.

Wattage at the point in time: 204W

Current at the point in time: 1.126A

Power factor at the point in time: 0.78

Lowest wattage detected: 17.3W

Highest wattage detected: 440.5W

Voltage range: 228.9 to 230Vac (50Hz)

Total measurement period: 31days and 23 hours

Total energy consumed: 149.1kWh

Total electrical bill amount: $44.73 (base on electricity tariff rate $0.30/kWh)

 

I was shopping around to take a look at the latest energy efficient fridge. The consumption for these fridge as displayed was about 500-700kWh per annual. The efficient is much better. I am assuming the measurement was took without considering the typical scenario of opening of the fridge door. Opening the door increases the temperature inside, which means that more energy is required to cool it down.

 

Washing Machine

Model: National NA-FSSY6T

 

Washing machine standby power is 1.3W – 1.8W (0.006A, 0.42PF)

Filling up the washer with water consume 8W (0.038A, 1.00PF)

Washing process rotate the motor clockwise and anti-clockwise. The consumption is pulsing between 100W and 340W (0.7A and 1.4A 0.19PF). The power factor becomes lower when the motor starts to be activate. Motor is an inductive load causing the power factor to becomes lower.

After the washing process, the washing machine drained the water. This activity consume only 4.8W (0.021A 0.85PF).

The washing machine starts to spin to squeeze out the water. The machine controls the spin. I can see the wattage moving slowing from about 230W to 260W as the spin starts to pick up. When the spin reaches its momentum, the wattage starts to drop gradually to 200W. At top spin the wattage is about 200W. The initial start up requires more torque to spin the load, therefore more power was required. When the spin reaches it top speed, the torque required was less, therefore less power was required. This activity consume an average of about 230W for 2 min.

 

The whole washing process takes about 45min to 60min. Total wattage consume is about 0.352kWh for two wash (medium load). This comes up to about 0.176kWh of energy consume for each washing.

Oven

Model: TEFAL Turbo Delice 26L

 

oven baking tart oven baking tart

My mother was baking the pineapple tarts for Chinese New Year, when I took this measurement. I wanted to find out how much electricity is used to bake the tarts.

The tarts were baked at about 180°C for about 20 minutes. A total of 7 trays (36 pineapple tarts per tray) were baked in 4 batch. The cost of electricity is $0.42. This means that the electricity cost for each batch of baking cost about $0.105, each tray cost $0.0525, or each pineapple tart cost about $0.0015. The bill seems quite affordable.

Wattage at the point in time: 2900W

Current at the point in time: 12A

Power factor at the point in time: —

Lowest wattage detected: —

Highest wattage detected: —

Total measurement period: 1 hour 20 minutes

Total energy consumed: 1.431kWh

Total electrical bill amount: $0.42 (base on electricity tariff rate $0.30/kWh)

 

Soldering Iron

Model: GOOT TQ-95 Quick Heat Soldering Iron 200W/20W

 

 

When the soldering iron is first switched on, the wattage measured is 60W.

As the iron gets heated up, the temperature starts to drop to a constant wattage of 25W (0.1A, 1.0PF)

There is this quick heat button to heat up the iron faster (can only press for no longer than 10sec).

When this button is pressed, the wattage shoot up to about 128W (0.523A, 0.98PF).

The soldering iron is a resistive load, which is why the power factor is always quite close to 1.0PF.

 

Cost of running the soldering iron for 1 hour = 25W/1000 x 1hour x 0.30kWhr = $0.0075 (about 1 cent every hour)

 

   

Conclussion:

– Top energy consuming devices

– Many switching AC-DC power adaptor do consume energy when it is left switched on. The power factor from all these advance switching adaptor seems quite poor.

 

 

 

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

 

 




Keyword:
Power meter, energy consumption measurement, energy audit, energy saving, save energy, ECO friendly


Cable, Wiring and Connector Guide

Your reference guide for PCB (trace resistivity, footprint) wire (gaage chart), mil/ inch/mm, hole (drill, tap chart), fastener

Edited by Lim Siong Boon, last dated 02-Oct-09.


 

Shortcut to your reference guides and charts

  1. PCB Trace reference
  2. Wire and Cable gauge
  3. Advance conductor
  4. PCB Footprint reference
  5. Tap drilling guide (mm chart)
  6. Common Connector Pin Out
  7. Name of Connectors/Plugs
  8. Name of Cable/Wire

 

I always have to refer to these dimension references frequently,

and decide to put them up once and for all on this website.

Hope they are useful to you too.

 

 

 

1. PCB Trace reference

 

 

 

 

Trace resistance guide based on

PCB board 1oz copper at temperature 100˚C. (worst case)

 

Name Trace width Trace Length ResistanceCurrent
Power Normal 1.27mm 1000mm 0.49Ω1.75A
Power Min 0.64mm 1000mm 0.98Ω1.20A
Signal Normal 0.38mm 1000mm 1.65Ω0.80A
Signal Min 0.25mm 1000mm 2.51Ω0.50A

Conversion calculator might not work on some web browser.

 

Unit conversion table & calculator between inch, mil, mm, oz.

inch mil mm oz
1 1000 25.4  
0.1 100 2.54  
0.001 1 0.0254  
0.03937 39.37 1  
  1.38 0.035 1oz

Conversion calculator might not work on some web browser.

 

 

also Download the wire gauge calculator from UltraCAD Design, Inc

 

 

The IC chips, active and passive components are all connected by traces or wire. The traces on the PCB are assume to be of short circuit, which is 0Ω. This assumption is reasonable if it conduct a very small amount of current. When the conductor starts to carry larger amount of current, the voltage drop across the trace could be significant, causing intermediate hardware problem.

If you are expecting a large current flowing through the traces, you have to keep in mind to provide a wider trace to increase the conductivity of the cable. Larger trace width means lower resistance.

For my PCB route software, the defined trace width for power is 1.27mm and signal is 0.38mm. Sometimes there is a need to route the trace through narrow space. In this situation, I would have to use the recommended trace width for power min, and signal min. Usually I will keep this narrow trace as short as possible to avoid higher resistance.

Seldom do I need to worry about traces carrying signal information. I am more worried about the conductor distributing the dc supply to individual circuit zone. Whenever possible, I would provide a wider traces for my 5V and ground supply.

When designing the PCB routing for my power supply, I would use the star topologies. This will ensure a evenly spread for the current distribution, hence lowering the burden of individual traces. I have actually experience such technical issue during my final year school project. The noise problem is somehow reduce after the attempt to improve on the trace routing. Another experience involve power up a remote system about 10m away. The distance is quite near and the power cable is rather thick to me. The voltage at the remote end is found to be too low to power the remote system. We have to double the cable conductor in order to resolved the problem. Our equipment conduct high current of about 20A if I remember correctly. The problem might not be obvious because the high current being drawn might happen during certain hard to determine event. For example, when your system trigger the lightings or motor which draws very high current for a short period of time. The voltage drop cause by the sudden high current draw might cause your system to fail. Therefore the design should always cater for the worst case. Always find out the maximum possible current drawn. Over design the system to ensure that the system will not fail in the worst case scenario. Just to make a note, that I have been referring to dc voltage supply.

For high voltage AC supply, I guess it is a different way of looking at it. My understanding in high voltage system is quite weak.

On the left is the reference table to estimate the resistance of the trace for my PCB routing. I have assume the worst case at temperature 100˚C with the copper layer of 1oz thick. Seldom do you need to refer to this table, unless you have encounter space restriction for your high current carrying traces. It is my usual practise to double the current carrying capacity. 2 times the maximum current I will be expecting. If you have the space, make it wider.

Electrical Resistance Equations:

Resistance = Resistivity x Length/Area

 

 

Question 1:

1oz copper PCB, Trace width 0.25mm, Trace length 0.1m, Operating temperature 25˚C

 

Solution 1:

Copper resistivity at  25˚C is 1.68×10-8Ω.m

Resistance = 1.7×10-8Ω.m  x  0.1m  /  (1oz x 0.25mm)

                 = 1.7×10-8Ω.m  x  0.1m  /  (35um x 0.25mm)

                 = 1.7×10-8Ω.m  x  0.1m  /  (8.75nm2)

                 = 1.7×10-8Ω.m  x  0.0114×109m-1

                 = 0.19Ω

 

Question 2:

1oz copper PCB, Trace width 0.25mm, Trace length 0.1m, Operating temperature 100˚C

 

Solution 2:

Copper resistivity at  100˚C is 2.17×10-8Ω.m,

Resistance = 2.2×10-8Ω.m  x  0.1m  /  (1oz x 0.25mm)

                 = 2.2×10-8Ω.m  x  0.0114×109m-1

                 = 0.25Ω

 

I have also provide the computation for copper resistance for your reference. Taking this opportunity to do further read up in order to explain in a simplified form.

Area is the cross sectional area of the conductor. Just like a water pipe, the larger the cross sectional area, the easier the current is able to flow through.

Resistivity defines the resistance of the material for a unit of length at a certain temperature. The resistivity for the material copper at 25˚C is found to be 1.7×10-8Ω.m

The resistivity changes with temperature. The resistance will increase as the temperature increase. The term for this changing resistivity with temperature is known as the thermal resistivity of that particular material.

The material resistivity would therefore look like a graph curve. They are obtained through test and experiment. For some material, the graph curve could be approximated in the form of equation. This complicated formula describe the resistance behavior of the material under different temperature condition. For copper material, it can be represented from the following equation,

Copper resistivity = ρ0(1+α(Temperature-T0))

= 1.7×10-8Ω.m  x  (1 + 3.9×10-3Ω/˚C  x  (100˚C-25˚C))

= 2.2×10-8Ω.m at a temperature of 100˚C

0 is the material resistivity at T0 temperature>

As you can see from the calculation on the left, the increase in temperature from 25˚C to 100˚C has increase the 0.1m copper trace by 0.06Ω. This is about 30% increase in the resistance.

To keep the topic simple, we will not go into the details of varying temperature. There can be other factor that can affect the resistance of the material.

Here is a quick and simple graph showing the change in temperature in relation with the trace width and the current flowing through it. (taken from the magazine elektor 2010-02). The graph assume the pcb copper trace thickness to be 35um (1oz) & that it is place in a open air environment (not enclosed inside a box/casing). For example, given the trace width of 0.6mm, and a 1.5A current flowing through it, we can expect the copper area to rise by another 10°C.

pcb trace width, current, temperature

 

 

Some article reference:

PCB trace – HwB, trace vs current graph.pdf

 

Recommended digital and analog circuit layout on a PCB board.

recommended circuit layout

 

Recommended trace corner layout.

trace corners

 

Recommended plane placement.

plane placement

Reference taken from “Op Amps for Everyone“.

More PCB layout recommendation can be found in the book “Op Amps for Everyone” from Texas Instruments.

 

 

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

 

 

2. Wire and Cable gauge

I have put up this wire gauge guide for my own reference. Very often there is a need to return to this reference to choose an appropriate cable for use. I have also written an article some time back. Myth about how the cable relate to their resistance. It is taken out from the main webpage but I have place a link here, for anyone who are interested to understand more.

NOTE: The following guideline is a brief guideline for copper ampacity (current rating or current-carrying capacity) of the cable used for power supplying purpose. The ampacity is defined as the maximum current the cable can withstand. Any current higher than that will generate enough heat to burn away  the cable. There are many factor affecting the current capacity of the cable, and it should be compensated accordingly. I would advise to select the cable, with at least double the current-carrying capacity for the intended equipment. Never operate near the cable current-capacity limits. You will never know when, the current overruns. Some of the factors that will affect the current-carrying capacity of a cable are:

– Conductive wire cross section area.

– Wire material. The temperature the material can withstand without melting out.

– Temperature. If the wire/insulator jacket can withstand higher temperature, the cable is able to carry more current.

     – place of installation or the surrounding temperature.

     – material of insulation jacket/skin/cover.

     – how much the cable can dissipate heat

– Stranded or solid wire type. Stranded wire can carry more current than a solid wire for AC type of signal/power. This is due to a phenomenon known as skin effect.

 

Reference:

ayenbee AWG Wire Current Rating guide.pdf

Wire Chart for 12Volt 24Volt.pdf

A Guide to Wire and Cable Construction.pdf

230v Cable Size Selector- http://www.electacourse.com/cableselector.html

 

The factors involve are quite complex. The table is a simplified reference for myself to select the cables. Always allow a larger safety margin of minimum x2 when you chose your cable. Do take careful note of what you deploy.? There are many other factor, eg screw connections, plug contact which will affects the results. If the cable has the slightest warm, it is quite clear that the cable will be hitting it’s limit any time soon.

 

Wire Cable Description Diameter (mm) Area (mm2) Copper Resistance 20˚C.Ω/km Nearest SWG gauge (mm) Nearest AWG gauge (mm)
  11.68 107.2 0000
  10.4 85.03 000
  9.266 67.43 00
  8.252 53.48 0
  7.348 42.41 1
  6.543 33.63 2
  5.827 26.27 3
  5.189 21.15 4

230Vac power cable 16mm2 (absolute maximum 69A)

eg. Sub Mains

4.620 16.77 5
  4.115 13.30 6

230Vac power cable 10mm2 (absolute maximum 52A)

eg. high power showers, cookers & other very high power devices

3.665 10.55 7
  3.264 8.366 8

230Vac power cable 6mm2 (absolute maximum 38A)

eg. showers, cookers & other high power devices

2.906 6.634 9
  2.588 5.261 10

230Vac power cable 4mm2 (absolute maximum 30A, 6.9kW)

eg. low power electric shower

2.305 4.172 11
  2.00 3.10 5.47 14 (2.05) 12 (2.05)
  1.90 2.80 6.05    

230Vac power cable 2.5mm2 (absolute maximum 23A)

 

1.80 2.60 6.76 15 (1.83) 13 (1.83)
  1.70 2.30 7.57    

Wire copper enameled, Pro-Power ECW1.5. current rating 2.74A

eg. power speaker, transformer, motor

 
1.60 2.00 8.54 16 (1.63) 14 (1.63)
  1.50 1.80 9.7    

230Vac power cable 1.5mm2 (absolute maximum 16A, 3.6kW)

 

 
1.40 1.50 11.2 17 (1.42) 15 (1.45)
  1.30 1.30 13.0   16 (1.29)

230Vac power cable 1mm2 (absolute maximum 13A, 2.99kW)

eg. for light circuit

 
1.20 1.10 15.2 18 (1.22)  
  1.10 0.95 18.1   17 (1.15)

Audio cable (shielded), Belden 8760

eg. power speaker drive

1.00 0.78 21.1 19 (1.02) 18 (1.02)
  0.95 0.71 24.3    
  0.90 0.64 26.9 20 (0.91) 19 (0.91)
  0.85 0.57 30.2    
  0.80 0.50 34.1 21 (0.81) 20 (0.81)
  0.75 0.44 38.9    
  0.70 0.69 44.6 22 (0.71) 21 (0.72)
  0.65 0.33 51.7   22 (0.64)
  0.60 0.28 60.7 23 (0.61)  
  0.55 0.24 72.3 24 (0.56) 23 (0.57)
Wire Cable Description Diameter (mm) Area (mm2) Copper Resistance 20˚C.Ω/km Nearest SWG gauge (mm) Nearest AWG gauge (mm)
Category 5E network cable, 8060-OZZ7FNL from Alcatel

16 strand Ø0.2mm/strand

Multipurpose 10core shielded. (RS232 communication, data signal), Belden 9540, Belden 9536 (6 core), Belden 9534 (4 core)

0.50 0.20 87.5 25 (0.51) 24 (0.51)
Category 5E network cable

 

0.45 0.16 108 26 (0.46) 25 (0.45)
Telephone line cable, GC5040 from Pro Power 0.40 0.13 137   26 (0.40)
  0.35 0.096 178 29 (0.35) 27 (0.36)
Ribbon cable, 1.27mm pitch         28
  0.30 0.071 243 31 (0.29) 29 (0.28)
Wire wrapping wire, Ok Industries 0.25 0.049 351 33 (0.25) 30 (0.25)

Wire copper enameled

eg. small magnetic coil, speaker, solenoid, inductor, metal detector coil, small motor.

0.20 0.031 547
32 (0.20)
  0.19 0.028 605 36 (0.19)  
  0.18 0.026 676   33 (0.18)
  0.17 0.023 757 37 (0.17)  
  0.16 0.020 844   34 (0.16)
  0.15 0.018 970 38 (0.15)  
  0.14 0.015 1120   35 (0.14)
  0.13 0.013 1300 39 (0.13) 36 (0.13)
  0.12 0.011 1520 40 (0.12)  
  0.11 0.0095 1810 41 (0.11) 37 (0.11)
  0.10 0.0078 2190 42 (0.10) 38 (0.10)
  0.09 0.0064 2700 43 (0.09) 39 (0.09)
  0.08 0.0050 3420 44 (0.08) 40 (0.08)
  0.07 0.0039 4460 45 (0.07) 41 (0.07)
  0.06 0.0025 6070 46 (0.06) 42 (0.06)

Wire copper enameled (very fine)

eg. transformer coupler for audio/signal, wire for earphone

0.05 0.0020 8750 47 (0.05) 43 (0.05)
Wire Cable Description Diameter (mm) Area (mm2) Copper Resistance 20˚C.Ω/km Nearest SWG gauge (mm) Nearest AWG gauge (mm)
           

 

Cable Guide (typical cable type and name)          Click the chart for enlarge view.

Chart and images taken from Farnell, RS components and other websites.

 

      also Download the wire gauge calculator from UltraCAD Design, Inc

Other reference,

http://www.wiki.diyfaq.org.uk/index.php?title=Cables#Cable_Sizes

 

Refer to the most current National Electrical Code for further information on the electrical cable standards.

 

 

 

 

 

3. Advance conductor

 

Special material for conductivity connection. Some references for non-traditional or advance conductor materials.

 

I happen to see some special wire product that I think I should put them in this website for reference.

The follow shows a rubber strip (a black layer sandwich in between the two white layer). It is call the elastomer connector. It is typically used to connect a flat LCD display panel to the pcb board without any soldering. It is quite cool when it was being shown to me for the first time. The LCD and pcb is connected with this elastomer connector sandwich in between.

   

Elastomer connector

(soft rubber strip that can conduct like a wire)

 

 

Conductive fabric or cloth

this pic is tken from other website

The conductive fabric actually can feels like a typical cotton cloth material. Some other feels like a nylon fabric, a bit like plastic. This is great for RF shielding, which we used it to test the performance of RF transmission through various material.

 

Glocom Marketing Pte Ltd

 

Conductive glass

reference: conductive glass

 

Singapore Safety Glass

Conductive paint

 

 

Conductive tapes

 

 

 

 

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

 

 

4. PCB Footprint reference

 

 

Click here to access to footprint page.

 

5. Tap drill guide (metric chart)

Commonly used screw size in Singapore, Metric (fine pitch)

Screw Standard

Screw

diameter ‘O’

Drill size

diameter ‘I’

Pitch (fine)

M 1 1.0mm 0.75mm  
M 1.1 1.1mm 0.85mm  
M 1.2 1.2mm 0.95mm  
M 1.4 1.4mm 1.10mm  
M 1.6 1.6mm 1.25mm  
M 1.8 1.8mm 1.45mm  
M 2 2.0mm 1.60mm  
M 2.2 2.2mm 1.75mm  
M 2.5 2.5mm 2.05mm  
M 3 3.0mm 2.50mm 0.35mm
M 3.5 3.5mm 2.90mm  
M 4 4.0mm 3.20mm 0.5mm
M 4.5 4.5mm 3.70mm  
M 5 5.0mm 4.20mm 0.5mm
M 6 6.0mm 5.00mm 0.75mm
M 7 7.0mm 6.00mm 0.75mm
M 8 8.0mm 6.70mm 1.0mm
M 9 9.0mm 7.80mm  
M 10 10.0mm 8.50mm 1.25mm
M 11 11.0mm 9.50mm  
M 12 12.0mm 10.20mm 1.5mm
M 14 14.0mm 12.00mm  
M 16 16.0mm 14.00mm 1.5mm
M 18 18.0mm 15.50mm  
M 20 20.0mm 17.50mm  
M 22 22.0mm 19.50mm  
M 24 24.0mm 21.00mm 2.0mm
M 27 27.0mm 24.00mm 2.0mm






1/4″-36 6.5mm 6.0mm Thread for SMA RF connector thread

1/4″-36 6.5mm 6.0mm Toggle switch thread

 

 

 

 

 

Image of a machine cap screw

Enlarge image of the screw thread

  

diameter ‘I’

Diameter of the screw core

(Hole size to drill, for tapping the thread )

 

diameter ‘O’ Diameter of the screw thread

->

 

 

 

 

 

 

 

  Fastener Manufacturer:

References: http://www.aboveboardelectronics.com/catalogsmain.htm

Fasterner selection guide
http://www.aboveboardelectronics.com/abe_prodmain.htm
http://www.boltdepot.com/fastener-information/Type-Chart.aspx

 

 

Plastic fastener, Cable accessories

Enclosure bumper/rubber padding

Slide

 

 

 

 

Self-Clinching Nut, Standoff Guide  

Self Clinching Standoff

Installation Guide

 

 

Self Clinching Nut

Installation Guide

Silicone Moldmaking Techniques & Materials Silicon Moldmaking techniques & material guide.pdf

 




www.pic-control.com, Singapore Network WiFi Ethernet Solution

 

 

6. Common Connector Pin Out

This is a connector pin out reference.

 

3.5mm 4pins

Commonly use for:
– Earphone + Microphone

 

Earphone + Microphone:
Pin 1- Left Speaker
Pin 2- Right Speaker
Pin 3- Mic+
Pin 4- Ground

iPhone Mobile Phone Earpiece:
Samsung Galaxy
Samsung Nexus S
Pin 1- Left Speaker
Pin 2- Right Speaker
Pin 3- Ground, Push Switch
Pin 4- Mic+, Push Switch

Nokia Mobile Phone Earpiece:
Pin 1- Left Speaker
Pin 2- Right Speaker
Pin 3- Mic+, Push Switch
Pin 4- Ground, Push Switch

3.5mm 3pins

Commonly use for:
– Earphone
– Speaker

 

Earphone/Speaker pin out:
Pin 1- Left Speaker
Pin 2- Right Speaker
Pin 3- Ground

Notes: Speaker’s load is inductive. Measuring the resistivity from the pins will usually yield very low resistance (near to short circuit). Measurement by probing the pin in reverse will yield the same result.

Microphone pin out:
Pin 1- Mic+
Pin 2- Mic Power
Pin 3- Ground

Earphone/Microphone pin out:
Pin 1- Spk+
Pin 2- Mic+
Pin 3- Ground

3.5mm 2pins

 

Commonly use for:
– Microphone

 

Microphone pin out:
Pin 1- Mic+
Pin 2- Ground

Notes: Commonly available electret microphone contains active components. The positive terminal of a microphone can be detected using a ohm meter. Measure Mic+ (+ve Probe), Mic- (-ve Probe) will yield a higher resistivity than probing the reverse way Mic- (+ve Probe), Mic+ (-ve Probe).

Electret microphone equivalent circuit

Other type of microphone:
– The Carbon Granule Microphone
– The Piezoelectric Microphone
– The Condenser Microphone
– The Dynamic Microphone
– The Ribbon Microphone
– The Hot-Wire Microphone

reference:
http://mysite.du.edu/~jcalvert/tech/microph.htm

 

3.5mm 3pins, 2.5mm 3pins

 

Known to be use for:
– Walkie talkie

3.5mm 3pins, 2.5mm 2pins

Known to be use for:
– Walkie talkie

3.5mm 2pins, 2.5mm 3pins

Known to be use for:
– Walkie talkie

3.5mm 2pins, 2.5mm 2pins

Known to be use for:
– Walkie talkie

Mini DIN socket 6 pins (female receptacle)

 

 

Known to be use for:
– Walkie talkie

 

Walkie Talkie pin out:
Pin 1- Mic- / PTT Switch common
Pin 2- Mic+
Pin 3- PTT Switch
Pin 4- Speaker+ (left)
Pin 5- —unused— (right)
Pin 6- Speaker-

Mini DIN plug 6 pins (male pins)

 

Known to be use for:
– Walkie talkie

 

Walkie Talkie pin out:

Pin 1- Mic- / PTT Switch common
Pin 2- Mic+
Pin 3- PTT Switch
Pin 4- Speaker+ (left)
Pin 5- —unused— (right)
Pin 6- Speaker-

Pin 1 Mic- / PTT Switch common Re
Pin 2 Mic+ Bk
Pin 3 PTT Switch Wh
Pin 4 Speaker+ (left) Ye
Pin 5 —unused— or Speaker+ (right) Bl
Pin 6 Speaker- Gr

 

Mini DIN plug 4 pins (male pins)

Commonly use for:
– S-Video
– Walkie talkie PTT switch connector

 

Walkie Talkie pin out:
Pin 1- —unused—
Pin 2- —unused—
Pin 3- PTT Switch
Pin 4- PTT Switch

Mini DIN plug 4 pins (female pins)

 

DIN 5 pins

 

 

Known to be use for:
– Bike’s audio connector

 

Bike Audio pin out:
Pin 1- —unused—
Pin 2- —unused—
Pin 3- PTT Switch
Pin 4- PTT Switch

DIN 7 pins

 


Known to be use for:
– Bike’s audio connector

 

Bike Audio pin out:
Pin 7- PTT Switch (White)
Pin 3- Speaker L
Pin 5- Speaker R
Pin 2- Speaker Gnd
Pin 4- Mic-
Pin 1- Mic+
Pin 6- Mic shield

DIN 8 pins

 
GX16 Aviation plug and socket connectors (16mm)



GX16-2%20aviation-plug%2016mm.jpgGX16-8%20aviation-plug%2016mm.jpg

GX16-4%20aviation-socket%2016mm.jpgGX16-4%20aviation-plug%2016mm.jpg

GX16-5%20aviation-socket%2016mm.jpgGX16-5%20aviation-plug%2016mm.jpg



GX16-3%20dimension1.jpg
GX16-2%20dimension2.jpg
GX16%20connector%20selection.jpg
FD-M16 16mm Connectors FD-M16%20connector%20selection.jpg
Nanaboshi Connectors
(panel mount)

NJC series (general metallic connectors/socket)
NR series (twist lock connector, one-touch lock mechanism)
NJW series (waterproof panel mount connectors
/socket)
connector/Nanaboshi%20Connectors%20NJC%20NR%20Series.pdf
connector/nanaboshi%20njc%20panel%20mount%20connector.pdf
connector/nanaboshi%20connectors.pdf

Amphenol Connectors
(panel mount)

connector/amphenol%20connectors.pdf

XLR Plug 3 pins

 

Commonly use for:
– Studio Microphone

 

Studio Microphone pin out:
Pin 1- Shield
Pin 2- Positive Balance Signal
Pin 3- Negative Balance Signal

DC barrel jack/socket

DC barrel jack (OD=5.5mm, ID=2.1mm, length=11 to 12mm)

 

DC barrel socket

 

 

SMA RF connector (socket for WiFi Antenna)


sma rf cablesma rf cablesma rf cable
Toggle switch dimension, drill hole dimension and thread size 1/4-40 UNS-2A
sma connector dimension

 

 

 

7. Name of Connectors/Plugs

 

 

UK 3 pins Plug

EU 2 pins Plug

IEC 3 pins Socket


Male Plug -> IEC C14 (picture shown above)

Female socket -> IEC C13

Male Plug (with groove) -> IEC C16

Female socket (with groove) -> IEC C15

Check out here for more,

https://en.wikipedia.org/wiki/IEC_60320

 IEC socket dimension 230Vac 3 pin

Molex SPOX 5267 series connector header THT 2.5mm 4 way

Molex 5263 housing crimp receptacle 2.5mm 4 way

2.54mm pitch

General  
Product Family Crimp Terminals
Series 5263
   
Product Name SPOX™
UPC 800753534919
   
Physical  
Gender Female
Material – Metal Phosphor Bronze
Material – Plating Mating Tin
Material – Plating Termination Tin
Net Weight 43.200/mg
   
Plating min – Mating 0.889μm
Plating min – Termination 0.914μm
   
Termination Interface: Style Crimp or Compression
   
Wire Insulation Diameter 1.90mm max.
   
Wire Size AWG 22, 24, 26, 28
   
Wire Size mm² NA
   
   
Old Part Number 5263PBTL


molex KK 6410 series

molex KK 6471 crimp receptacle

2.54mm pitch

General  
Product Family Crimp Terminals
Series 4809
   
Product Name KK®
UPC 800753746022
   
Physical  
Gender Female
Material – Metal Brass
Material – Plating Gold
Material – Plating Gold
Net Weight 0.066/g
   
Plating min – Mating 0.381μm
Plating min – Termination 0.381μm
   
Termination Interface: Style Crimp or Compression
   
Wire Insulation Diameter 1.57mm max.
   
Wire Size AWG 22, 24, 26, 28, 30
   
Wire Size mm² NA
   
   
Old Part Number 4809555L

TJC8 connector (header and housing/receptacle pins)

Another name for housing is receptacle.

Pin Header PCB Crimp Style Cable Connector

TJC8 series(2.54mm pitch)Wire to Board Crimp style cable P.C.B connector housing terminal pin header

1. Pole: 1-40
2. Housing pins for wire size AWG28# – 22#
3. Header pins for PC board thickness: 1.6mm, 2.54mm pitch
4. Temperature range: -25C~85C
5: Voltage rating: 250V. AC/DC
6. Current rating: 3A
7. Contact resistance: 0.02
8. Insulation resistance: 800M
9. Withstand Voltage: 1000V. AC/1Min
10. Material:
Housing: PA66
Wafer: PBT
Terminal: Phos. Bronze Tin plated

Crimping tool, die sets size = ???

JST ZH connectors

B3B-ZR(LF)(SN)

S3B-ZR(LF)(SN)

ZHR-3

SZH-002T-P0.5

SZH-002T-P0.5 (0.08-0.13mm2, AWG28# – 26#, OD 0.8-1.1mm)
SZH-003T-P0.5 (0.032-0.08mm2, AWG32# – 28#, OD 0.5-0.9mm)

 
JST EL-2P (2 Way) Multipole Connectors With Wire

JST EL-2P multipole connectors




Connectors > Crimp Terminals / Solder Terminals & Splices > Quick Disconnect Crimp Terminals
Crimp terminal,
Blade,
Pin,
Push-on
Insulated push-on,
Butt,
Fork,
Ring,
Piggyback,
Male tab (6.35mm or 1/4 inch tab connector),
Male bullet,
Female bullet


Red Insulation   0.5-1.5mm2 / 22-16 AWG
Blue Insulation  1.5-2.5mm2 / 16-14 AWG
Yellow Insulation   4.0-6.0mm2 / 12-10 AWG


Good terminal is made of copper (tinned), not aluminium.





Wire size for various ferrule size (color determine the size)

Ferrule

 

 

 

8. Name of Cable/Wire

 

 

Ribbon Cable & IDE connectors

 IDC connector pin rating is 1A.

Flat Flexible Cable (FFC)

 

Flex Jumper

 
   

 




9. Others

 

 

RJ45 (Panel Mount), Ethernet network socket, 8P8C plug to socket
panel%20mount%20RJ45.png

USB Socket (Panel Mount)
panel%20mount%20USB%20socket.jpg



   



 

 

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

 

 

 

 

Keyword: mm inch mil thou, tap drill size, reference guide, PCB trace resistivity computation calculator, Foot print reference, Cable wire gauge resistance, cable wire selection, fastener