In this article, I would like discuss about using
LPC82x MCU with MCUXpresso IDE.
I will use
LPCXpresso824-MAX Board as a hardware platform.
Showing posts with label Communication. Show all posts
Showing posts with label Communication. Show all posts
Wednesday, March 2, 2022
Wednesday, July 7, 2021
K82 USB CDC Virtual Comm
In this article, we will discuss about using K82 as a USB CDC virtual com device.
Setting up environment for K82 development is discussed in previous article at the following link.
http://cool-emerald.blogspot.com/2020/01/getting-started-with-frdm-k82f.html
http://cool-emerald.blogspot.com/2020/01/getting-started-with-frdm-k82f.html
Monday, July 5, 2021
Software timers and Ring Buffered UART Com for Kinetis K82 MCU
In this article, I would like discuss about using
Kinetis K82 MCU with MCUXpresso IDE.
I will use
FRDM-K82F development board as a hardware platform.
Setting up environment for K82 development is discussed in previous article at the following link.
http://cool-emerald.blogspot.com/2020/01/getting-started-with-frdm-k82f.html
http://cool-emerald.blogspot.com/2020/01/getting-started-with-frdm-k82f.html
Tuesday, April 12, 2016
Using 3rd party CC2530 modules
I would like to talk about 3rd party CC2530 modules - ( a first one and a second one ) that I bought from Aliexpress. In a previous article, I talked about CC2530DK from TI. In this post, using SmartRF05EB to debug 3rd party module is discussed.
Figure. A small CC2530 module whose size is 13 mm x 18 mm.
Figure. A small CC2530 module whose size is 13 mm x 18 mm.
Friday, January 1, 2016
Mesh Bee - JN5168
Mesh Bee is a 2.4GHz wireless transceiver mady by seeed studio. It uses JN516x wireless chip from NXP. It is open hardware, open source. The IDE and tools from NXP are also free.
Labels:
Communication,
Electronics,
Embedded System,
firmware,
IEEE 802.15.4,
Interface,
JN5168,
Mechatronics,
Mesh Bee,
Microcontroller,
Open source,
Programming,
RS232,
Serial,
Transceiver,
Wireless,
Zigbee
Wednesday, November 25, 2015
CC2531 Zigbee USB Dongle
In this article, we discuss about using CC2531 USB Evaluation Module Kit for wireless communication. At first, a zip file - CC USB Firmware Library and Examples, was downloaded from TI's website. After that, USB RF Modem Example in CC USB Software Examples User’s Guide was tested.
Labels:
2.4 GHz,
8051,
C,
C++,
CC2530,
Circuit,
Communication,
Electronics,
firmware,
Free Software,
Hardware,
IAR,
IEEE 802.15.4,
Microcontroller,
Robotics,
TI,
USB,
Wireless,
Zigbee
Tuesday, November 24, 2015
Wireless Communication using CC2530 Zigbee Wireless MCU
CC2530 is an system-on-chip (SoC) solution for IEEE 802.15.4 and Zigbee that combines RF transceiver and 8051 MCU. To develop a wireless module using it, we had bought a CC2530DK devolopment kit that consists of 2 CC2530EM Evaluation Modules, 2 SmartRF05EB Evaluation Boards, and a CC2531 USB Dongle. It cost about USD 400. At first, we installed SmartRF Studio which was available for free at TI's website.
Labels:
2.4 GHz,
8051,
C,
C++,
CC2530,
Circuit,
Communication,
Electronics,
firmware,
Free Software,
Hardware,
IAR,
IEEE 802.15.4,
Microcontroller,
Robotics,
TI,
Wireless,
Zigbee
Tuesday, August 4, 2015
Bluetooth Module to be Used with Microcontroller
HC-05 Master/Slave Bluetooth Module is a cheap (~SGD 16) and easy to use Bluetooth module with UART interface. Interfacing and using HC-05 with Arduino Uno microcontroller to control an LED light as commanded by a hand phone via Bluetooth communication is discussed in this post. In fact, any microcontroller with UART interface can be used with it.
HC-05 uses 3.3V for its digital logic pins while the voltage level for Arduino Uno is 5V. A bi-directional logic level converter can be used to interface them. But, here, we just use simple voltage dividers using readily available components in our labs to interface them as shown in the following diagram.
To communicate this Bluetooth module from an Android phone, we can search and use any 'Bluetooth SPP' app in the Play store. We have used 'Bluetooh spp tools pro' by Jerry.Li. After opening the app and scanning for Bluetooth devices, you can connect HC-05 using '1234' as the pairing pin. Thereafter, characters sent to RX pin of HC-05 UART will be received by the phone and the characters sent by phone will be output from TX pin of UART of HC-05. If you connect the Bluetooth module using computer instead of the phone, a serial port will appear in your computer which can be used as a normal comm port sending and receiving data to and from the Bluetooth module.
This Arduino program forwards the characters sent by phone to the serial monitor and vice versa. It turns on or off the LED which is connected to the pin 13 of Arduino Uno microcontroller board when 1 or 0 is sent from the phone. The push button on HC-05 Bluetooth module needs to be pressed to send AT commands and to configure it.
Another Bluetooth module called Bluetooth Shield is also tested. That module is designed for Arduino Uno and can be directly fixed on the Arduino Uno board. Therefore, no additional interfacing or connection is needed to make it work. But you need to make sure that the jumper settings are correct. As shown in the following figure, the jumper for HBT_TX is connected to D2 pin of the Arduino Uno board and HBT_RX is connected to D3. Therefore, D2 needs to be configured as RX pin and D3 as TX pin respectively in the demo program which is available at Bluetooth Shield Wiki page. You can define Bluetooth device name and pairing pin in that example program.
HC-05 uses 3.3V for its digital logic pins while the voltage level for Arduino Uno is 5V. A bi-directional logic level converter can be used to interface them. But, here, we just use simple voltage dividers using readily available components in our labs to interface them as shown in the following diagram.
To communicate this Bluetooth module from an Android phone, we can search and use any 'Bluetooth SPP' app in the Play store. We have used 'Bluetooh spp tools pro' by Jerry.Li. After opening the app and scanning for Bluetooth devices, you can connect HC-05 using '1234' as the pairing pin. Thereafter, characters sent to RX pin of HC-05 UART will be received by the phone and the characters sent by phone will be output from TX pin of UART of HC-05. If you connect the Bluetooth module using computer instead of the phone, a serial port will appear in your computer which can be used as a normal comm port sending and receiving data to and from the Bluetooth module.
#include <SoftwareSerial.h> #define RxD 2 #define TxD 3 char recvChar; SoftwareSerial blueToothSerial(RxD,TxD); void setup() { Serial.begin(9600); pinMode(RxD, INPUT); pinMode(TxD, OUTPUT); blueToothSerial.begin(9600); pinMode(13, OUTPUT); } void loop() { if(blueToothSerial.available()) { recvChar = blueToothSerial.read(); Serial.print(recvChar); if(recvChar == '1') digitalWrite(13, HIGH); else if(recvChar == '0') digitalWrite(13, LOW); } if(Serial.available()) { recvChar = Serial.read(); blueToothSerial.print(recvChar); } }
This Arduino program forwards the characters sent by phone to the serial monitor and vice versa. It turns on or off the LED which is connected to the pin 13 of Arduino Uno microcontroller board when 1 or 0 is sent from the phone. The push button on HC-05 Bluetooth module needs to be pressed to send AT commands and to configure it.
Another Bluetooth module called Bluetooth Shield is also tested. That module is designed for Arduino Uno and can be directly fixed on the Arduino Uno board. Therefore, no additional interfacing or connection is needed to make it work. But you need to make sure that the jumper settings are correct. As shown in the following figure, the jumper for HBT_TX is connected to D2 pin of the Arduino Uno board and HBT_RX is connected to D3. Therefore, D2 needs to be configured as RX pin and D3 as TX pin respectively in the demo program which is available at Bluetooth Shield Wiki page. You can define Bluetooth device name and pairing pin in that example program.
Monday, July 8, 2013
CAN bus
CAN bus (controller area network) is a vehicle bus standard designed to allow microcontrollers and devices to communicate with each other. CAN bus is a message-based protocol, designed specifically for automotive applications but now also used in other areas such as aerospace, industrial automation and medical equipment.
The advantages of CAN bus compared to RS232 communication are as follows.
Tuesday, May 3, 2011
Byte Stuffing
I occasionally need to write programs to send and receive data bytes from one device to another. That is why I arbitrarily choose a simple variant of byte stuffing methods to build frames to send and receive data. To delimit the frame, control characters - 0x02 and 0x03- are defined as start of text (STX) and end of text (ETX) respectively. For error detection, exclusive-or of data bytes is appended after the ETX as a checksum. If you need better error detection, CRC as described at
CRC Calculation in VB and C
can also be used.
For example, if we want to send two bytes of data -
Byte Stuffing on GitHub
The following is the C++ code to build, send and receive a frame.
CRC Calculation in VB and C
can also be used.
For example, if we want to send two bytes of data -
0x30 0x31,the resulting frame will be
0x02 0x30 0x31 0x03 0x01,where 0x02 at the start is added as STX, followed by data bytes and the byte before the last one, 0x03, is added as ETX. Since the exclusive-or of data bytes, 0x02^0x03, is 0x01, it is appended at the end as checksum. How can we send data that contains 0x02 or 0x03 which were already used as control characters? We need to define another control character 0x10 as Data Link Escape (DLE) to mark data that are not control characters. As an another example, let us build a frame for five data bytes -
0x30 0x02 0x65 0x10 0x03.We will do byte stuffing by putting DLE in front of every data byte that conflicts with STX, ETX, or DLE. And
0x02 0x30 0x10 0x02 0x65 0x10 0x10 0x10 0x03 0x03 0x44will be the resulting frame. I have developed a few programs in C and LabVIEW. Example programs can be downloaded at the following links.
Byte Stuffing on GitHub
The following is the C++ code to build, send and receive a frame.
// Byte stuffing- sending and receiving frames // Author: Yan Naing Aye #ifndef FRAME_H #define FRAME_H #include#define STX 0x02 #define ETX 0x03 #define DLE 0x10 #define TX_BUF_SIZE 128 #define RX_BUF_SIZE 128 enum RX_STATE { IGNORE,RECEIVING,ESCAPE,RXCRC1,RXCRC2 }; //----------------------------------------------------------------------------- class Frame { RX_STATE rState; protected: int TxN;//number of transmitting bytes int RxN;//number of receiving bytes char tb[TX_BUF_SIZE];//transmit buffer char rb[RX_BUF_SIZE];//receiving data public: Frame(); int setTxFrame(char* d,int n); unsigned int CRC16CCITT_Calculate(char* s,unsigned char len,unsigned int crc); int getTxN(); int getRxN(); int receiveRxFrame(char c);//get receiving frame from received char char* getTxBuf(); char* getRxBuf(); }; //----------------------------------------------------------------------------- Frame::Frame():TxN(0),RxN(0),rState(IGNORE){} //----------------------------------------------------------------------------- char* Frame::getTxBuf(){ return tb; } //----------------------------------------------------------------------------- char* Frame::getRxBuf(){ return rb; } //----------------------------------------------------------------------------- //Prepare transmitting frame int Frame::setTxFrame(char* d,int n) { unsigned int txcrc=0xFFFF;//initialize crc char c; int i=0,j=0; tb[i++]=STX;//start of frame for(j=0;j < n;j++) { c=d[j]; if((c==STX)||(c==ETX)||(c==DLE)) tb[i++]=(DLE); tb[i++]=c; } tb[i++]=(ETX);//end of frame txcrc=CRC16CCITT_Calculate(d,n,txcrc);//calculate crc tb[i++]=txcrc & 0xFF; tb[i++]=(txcrc >> 8) & 0xFF; TxN=i; return TxN; } //----------------------------------------------------------------------------- //Inputs //s : pointer to input char string //len: string len (maximum 255) //crc: initial CRC value //Output //Returns calculated CRC unsigned int Frame::CRC16CCITT_Calculate(char* s,unsigned char len,unsigned int crc) { //CRC Order: 16 //CCITT(recommendation) : F(x)= x16 + x12 + x5 + 1 //CRC Poly: 0x1021 //Operational initial value: 0xFFFF //Final xor value: 0 unsigned char i,j; for(i=0;i < len;i++,s++) { crc^=((unsigned int)(*s) & 0xFF) << 8; for(j=0;j<8;j++) { if(crc & 0x8000) crc=(crc << 1)^0x1021; else crc <<=1; } } return (crc & 0xFFFF);//truncate last 16 bit } //----------------------------------------------------------------------------- //get number of transmitting bytes int Frame::getTxN() { return TxN; } //----------------------------------------------------------------------------- //get number of transmitting bytes int Frame::getRxN() { return RxN; } //----------------------------------------------------------------------------- //process receiving char int Frame::receiveRxFrame(char c) { static char b; unsigned int crc; unsigned int rxcrc=0xFFFF;//initialize CRC switch(rState){ case IGNORE: if(c==STX) { rState=RECEIVING;RxN=0;} break; case RECEIVING: if(c==STX) { rState=RECEIVING;RxN=0;} else if(c==ETX){rState=RXCRC1;} else if(c==DLE){ rState=ESCAPE; } else { rb[RxN++]=c; } break; case ESCAPE: rb[RxN++]=c; rState=RECEIVING; break; case RXCRC1: b=c; rState=RXCRC2; break; case RXCRC2: rState=IGNORE; crc=( (int)c << 8 | ((int)b & 0xFF) ) & 0xFFFF;//get received crc rxcrc=CRC16CCITT_Calculate(rb,RxN,rxcrc);//calculate crc //printf("crc: %x rxcrc:%x \n",crc,rxcrc); if(rxcrc==crc){return RxN;}//if crc is correct else {RxN=0;}//discard the frame break; } return 0; } //----------------------------------------------------------------------------- //############################################################################# class Frame2:public Frame { char Dt[20];//transmitting data public: Frame2(); void printTxFrame(); void printRxFrame(); void printRxData(); void setTxData(float x,float y,float z,float b,float t); }; //----------------------------------------------------------------------------- Frame2::Frame2():Frame(),Dt(""){} //----------------------------------------------------------------------------- //Print out frame content void Frame2::printTxFrame() { printf("Tx frame buffer: "); for(int j=0;j < TxN;j++) printf("%02X ",(unsigned char)tb[j]); printf("\n"); } //----------------------------------------------------------------------------- //Print out frame content void Frame2::printRxFrame() { printf("Rx data buffer: "); for(int j=0;j < RxN;j++) printf("%02X ",(unsigned char)rb[j]); printf("\n"); } //----------------------------------------------------------------------------- //Set transmitting data void Frame2::setTxData(float x,float y,float z,float b,float t) { *(float*)(Dt)=x; *(float*)(Dt+4)=y; *(float*)(Dt+8)=z; *(float*)(Dt+12)=b; *(float*)(Dt+16)=t; Frame::setTxFrame(Dt,20); } //----------------------------------------------------------------------------- //Print out received data void Frame2::printRxData() { float x,y,z,b,t; x=*(float*)(Dt); y=*(float*)(Dt+4); z=*(float*)(Dt+8); b=*(float*)(Dt+12); t=*(float*)(Dt+16); printf("Rx data: %f %f %f %f %f \n",x,y,z,b,t); } //----------------------------------------------------------------------------- #endif // FRAME_H
Thursday, June 10, 2010
Circular Buffered UART Com Module for 8051 Microcontroller
A lot of embedded systems uses UART communication. That is why, I would like to share a circular buffered UART comm module here. I have developed the module for 8051 microcontroller but it can easily be modified for other microcontrollers as well.
UART-Timer-8051 on GitHub
Using Circular Buffered UART Com Module
You need to put the header files in the module you want to use them. In my example, I put all my header files into 'headers.h' file and I just need to include that file. Transmit and receive buffer sizes need to be defined in ComConfig.h file. And then, define a function to call on receive event. In the main function, poll the ComChkRx() function to retrieve the received data from the buffer. The source code for the example can be seen atUART-Timer-8051 on GitHub
Saturday, October 10, 2009
Multidrop network for RS232
I got a requirement to communicate one master device and eight slave devices. I intended to use RS485 half-duplex communication for this system but all devices happened to have only RS232 interfaces.
RS232 communication is a sort of communication that is to be used for one-to-one system. There is no problem if only the master device transmits and all slaves are receiving. The problem is that transmit lines of the slaves cannot be disabled and so that they cannot connect to the same line.
After analyzing the voltage signals, I have got an alternative solution to this problem. By adding a diode to the transmit line of each slave, I can use the system just like RS485 half-duplex communication. See the following figure for the hardware connection.
Updated: 2017 Sep 02
Thanks for all your comments. I have added more configurations according to your comments.
Updated: 2017 Sep 02
Thanks for all your comments. I have added more configurations according to your comments.
RS232 network with multiple masters and multiple slaves
UART/TTL-Serial network with single master and multiple slaves
If you are not using RS232 transceivers to change the physical signal voltages, the outputs of UARTs are still TTL level signals. In this case, you can connect multiple UARTs to a single master as follow.UART/TTL-Serial network with multiple masters and multiple slaves
Friday, September 25, 2009
CRC Calculation in VB and C
Just to share a few software modules that were written in Visual Basic 2005 and C for the calculation of CRC -Cyclic Redundancy Check.
CRC Calculation - GitHub
An example usage for calculation of CRC16 CCITT is shown below.
Initial value for CRC16 CCITT is 0xFFFF. The following example calculate CRC for Str1 and use that CRC value as initial value to calculate Str2.
CRC Calculation - GitHub
An example usage for calculation of CRC16 CCITT is shown below.
Online checksum calculator such as the following one may be useful to debug the code.
Online Checksum Calculator
CRC Calculation in VB2005
The followings are the source code for various CRC calculations in VB2005. To make the calculation faster, they use CRC tables.CRC Calculation - GitHub
An example usage for calculation of CRC16 CCITT is shown below.
Dim StrIn as String= "String to calculate CRC" Dim CRCVal16 As UInt16 = 0 Dim crc As String CRCVal16 = CRC16_CCITT.Calculate(StrIn) crc = CRC16_CCITT.ToString(CRCVal16)
Initial value for CRC16 CCITT is 0xFFFF. The following example calculate CRC for Str1 and use that CRC value as initial value to calculate Str2.
CRCVal16 = CRC16_CCITT.Calculate(Str1) CRCVal16 = CRC16_CCITT.Calculate(Str2, CRCVal16) crc = CRC16_CCITT.ToString(CRCVal16)
CRC Calculation in C
The followings are the source code for various CRC calculations in C. To save storage, they do not use CRC tables .CRC Calculation - GitHub
An example usage for calculation of CRC16 CCITT is shown below.
#define STRLEN 4 char str[STRLEN]={0x01,0x01,0x00,0x0B}; unsigned char c[2]; unsigned int crc; //Calculate CRC16 CCITT crc=CRC16CCITT_InitialValue(); crc=CRC16CCITT_Calculate(str,STRLEN,crc); CRC16CCITT_ToString(crc,c); printf("CRC16 CCITT = %02X %02X \n",c[0],c[1]);
Online checksum calculator such as the following one may be useful to debug the code.
Online Checksum Calculator
Sunday, May 4, 2008
RS232-RS485 Converter
When you need to convert your serial communication from RS232 to RS422/RS485 or when you need to communicate to an RS485 device from a computer that uses RS232, you can use RS485 converter.
This kind of converters are easily available. As an example, IC-485SN bidirectional converter is shown in the following figures.
As shown in the first figure, this RS485 converter can be configured by using two switches.
The first switch is used to select device mode. If the RS232 side (where DB25 Female connector is located) is connected to a Computer or a Data Terminal Equipment, it must switch to DTE. If that side is connected to a modem or a device (data communication equipment), it must switch to DCE.
The second switch is used to select transmitting and receiving mode.
TxON, RxON is used for point to point operations. Transmit driver is always enabled and it is also always receiving. We can say, it is converting from RS232 to RS422. In RS232 side, RTS and CTS, DTR and DSR are loopback connected.
RS485 side connections are as follow:
TxRTS, RxON is used for multidrop operations. Although it is always receiving, transmit driver is enabled only when RTS is high. For a DCE, CTS must be used instead of RTS. It can be used as four wire RS485 full duplex communication. In RS232 side, RTS and CTS, DTR and DSR are loopback connected.
RS485 side connections are as follow:
TxDTR/RTS, RxDSR/ON is used for RS485 half duplex communication. For a DTE, transmit drivers for data lines and busy lines are enabled only when RTS is true. When DTR is true, busy signal will be transmitted. On the receiving side, DSR will be true when a busy signal is received. For a DCE, CTS must be used instead of RTS. And DTR and DSR are inverse. In RS232 side, only RTS and CTS are loopback connected.
RS485 side connections are as follow:
The connections for DB 9 female and DB25 male Cable are as follow
As shown in the first figure, this RS485 converter can be configured by using two switches.
The first switch is used to select device mode. If the RS232 side (where DB25 Female connector is located) is connected to a Computer or a Data Terminal Equipment, it must switch to DTE. If that side is connected to a modem or a device (data communication equipment), it must switch to DCE.
The second switch is used to select transmitting and receiving mode.
1. TxON, RxON Mode
TxON, RxON is used for point to point operations. Transmit driver is always enabled and it is also always receiving. We can say, it is converting from RS232 to RS422. In RS232 side, RTS and CTS, DTR and DSR are loopback connected.
RS485 side connections are as follow:
Pin 1 = Tx+
Pin 2 = Tx-
Pin 3 = Rx-
Pin 4 = Rx+
2. TxRTS, RxON Mode
TxRTS, RxON is used for multidrop operations. Although it is always receiving, transmit driver is enabled only when RTS is high. For a DCE, CTS must be used instead of RTS. It can be used as four wire RS485 full duplex communication. In RS232 side, RTS and CTS, DTR and DSR are loopback connected.
RS485 side connections are as follow:
Pin 1 = Tx+
Pin 2 = Tx-
Pin 3 = Rx-
Pin 4 = Rx+
3. TxDTR/RTS, RxDSR/ON Mode
TxDTR/RTS, RxDSR/ON is used for RS485 half duplex communication. For a DTE, transmit drivers for data lines and busy lines are enabled only when RTS is true. When DTR is true, busy signal will be transmitted. On the receiving side, DSR will be true when a busy signal is received. For a DCE, CTS must be used instead of RTS. And DTR and DSR are inverse. In RS232 side, only RTS and CTS are loopback connected.
RS485 side connections are as follow:
Pin 1 = Data+
Pin 2 = Data-
Pin 3 = Busy-
Pin 4 = Busy+
The connections for DB 9 female and DB25 male Cable are as follow
Female DB9 -------------- Male DB25
pin 1 ---------------------- pin 8 .......... Black
pin 2 ---------------------- pin 3 .......... Brown
pin 3 ---------------------- pin 2 .......... Red
pin 4 ---------------------- pin 20 ........ Orange
pin 5 ---------------------- pin 7 .......... Yellow
pin 6 ---------------------- pin 6 .......... Green
pin 7 ---------------------- pin 4 .......... Blue
pin 8 ---------------------- pin 5 .......... Magenta
pin 9 ---------------------- pin 22 ........ Gray
Wednesday, April 23, 2008
Using PC Serial Port
Controlling and using PC serial port using Visual Basic programming is discussed. Many computers have a serial port. If your computer does not have one, you can buy a USB to RS232 converter.
There are three topics to be discussed here.
1. Using VB6
2. Using VB2005 (VB.NET2)
3. Serial Port as IO
After OK has clicked, there will be MSComm control with a telephone icon in the Toolbox. Double click on this control to add it onto the Form. Its name will be "MSComm1" as shown below and you can change its settings in the Properties box near the bottom right corner.
In this example, its settings will not be changed in its properties box. But they will be changed in "Form_Load()" event. Double click on any blank space on the form to write in Form_Load() event as shown in the following code.
The setting "9600,N,8,1" means that we will use Baud rate 9600, No parity, 8 data bit and 1 stop bit. RThreshold defines number of bytes in receive buffer to trigger receive event. In this example, Receive Event will be triggered even if there is only one byte in receive buffer. Comm port 1 of PC is used and opened here. A textbox is used to display the receive data. Another textbox and a Command button are added to the form to send data. Caption property of the Command button is changed to 'Send'.
Double click on that button and write the following code in its click event function.
Everytime the button is clicked, the data "ABCD" will be sent from the serial port. You can replace ABCD with any data you want to send. To receive data, OnComm event of MSComm control is used. Double click on MSComm control and write the following code in its event function. If OnComm Event is a data received event -comEvReceive, the Textbox will be updated with received data.
After that, program will be as shown in the following figure.
Try to run the program. Data will be sent when the Send button is clicked.
In VB2005, using Serial port is easier because SerialPort control is already in the toolbox. Create a Windows Application from File Menu -> New Project command. Double click on SerialPort Control in the Toolbox to add it onto the form.
Select the control and change its properties in the properties box. In the example, Name will be SerialPort1, BaudRates will be 9600, Databits will be 8, Parity will be None and StopBits will be One. ReceivedBytesThreshold defines number of bytes in receive buffer to trigger receive event. In this example, Receive Event will be triggered even if there is only one byte in receive buffer. Therefore ReceivedBytesThreshold will be 1. Comm port 1 of PC is used and PortName will be set to COM1.
Double click on the Form and write the following code in the Form Load Event.
By doing so, the comm port will be opened at the program start. Normal Encoding of serial port control is ASCII. You can also change Encoding at the Form Load Event as follow.
Add a Button to send data and a TextBox to display received data. Change Text property of the Button to Send. Double click on the Button and write the following code in its click event.
Everytime, the button is clicked, the data "ABCD" will be sent. You can replace ABCD with any data you want to send. To receive data, write the following code in the DataReceived event of SerialPort1.
If you want to read the received data byte by byte, the following code can also be used.
After that, the program will be as follow.
Then, you can try the program to send and receive data.
Sending Binary Data
The example above is for character data. For binary data whose ASCII code number greater than 127 can be manipulated as follow.
ReadChar cannot be used to receive binary data. ReadByte can be used instead as in the following example.
Getting Port List in Your PC
To list the all ports in your PC in a Combo box and to select the port number that had been saved in user setting, you can used the following code.
Related post:
There are three topics to be discussed here.
1. Using VB6
2. Using VB2005 (VB.NET2)
3. Serial Port as IO
Using VB6
MSComm ActiveX contorl can be used in VB6 to communicate through a serial port. Create a New project by selecting Standard Exe. Go to Project Menu and select Components command. Add Microsoft Comm Control 6.0 from Components dialog.
After OK has clicked, there will be MSComm control with a telephone icon in the Toolbox. Double click on this control to add it onto the Form. Its name will be "MSComm1" as shown below and you can change its settings in the Properties box near the bottom right corner.

In this example, its settings will not be changed in its properties box. But they will be changed in "Form_Load()" event. Double click on any blank space on the form to write in Form_Load() event as shown in the following code.
Private Sub Form_Load()
MSComm1.Settings = "9600,N,8,1"
MSComm1.RThreshold = 1
MSComm1.CommPort = 1
MSComm1.PortOpen = True
Text1.Text = ""
End Sub
The setting "9600,N,8,1" means that we will use Baud rate 9600, No parity, 8 data bit and 1 stop bit. RThreshold defines number of bytes in receive buffer to trigger receive event. In this example, Receive Event will be triggered even if there is only one byte in receive buffer. Comm port 1 of PC is used and opened here. A textbox is used to display the receive data. Another textbox and a Command button are added to the form to send data. Caption property of the Command button is changed to 'Send'.

Double click on that button and write the following code in its click event function.
Private Sub Command1_Click()
MSComm1.Output = "ABCD"
End Sub
Everytime the button is clicked, the data "ABCD" will be sent from the serial port. You can replace ABCD with any data you want to send. To receive data, OnComm event of MSComm control is used. Double click on MSComm control and write the following code in its event function. If OnComm Event is a data received event -comEvReceive, the Textbox will be updated with received data.
Private Sub MSComm1_OnComm()
If MSComm1.CommEvent = comEvReceive Then
Text1.Text = Text1.Text & MSComm1.Input
End If
End Sub
After that, program will be as shown in the following figure.

Try to run the program. Data will be sent when the Send button is clicked.

Using VB2005
In VB2005, using Serial port is easier because SerialPort control is already in the toolbox. Create a Windows Application from File Menu -> New Project command. Double click on SerialPort Control in the Toolbox to add it onto the form.

Select the control and change its properties in the properties box. In the example, Name will be SerialPort1, BaudRates will be 9600, Databits will be 8, Parity will be None and StopBits will be One. ReceivedBytesThreshold defines number of bytes in receive buffer to trigger receive event. In this example, Receive Event will be triggered even if there is only one byte in receive buffer. Therefore ReceivedBytesThreshold will be 1. Comm port 1 of PC is used and PortName will be set to COM1.

Double click on the Form and write the following code in the Form Load Event.
CheckForIllegalCrossThreadCalls = False
SerialPort1.Open()
By doing so, the comm port will be opened at the program start. Normal Encoding of serial port control is ASCII. You can also change Encoding at the Form Load Event as follow.
SerialPort1.Encoding = System.Text.Encoding.Default
Add a Button to send data and a TextBox to display received data. Change Text property of the Button to Send. Double click on the Button and write the following code in its click event.
SerialPort1.Write("ABCD")
Everytime, the button is clicked, the data "ABCD" will be sent. You can replace ABCD with any data you want to send. To receive data, write the following code in the DataReceived event of SerialPort1.
TextBox1.Text &= SerialPort1.ReadExisting()
If you want to read the received data byte by byte, the following code can also be used.
Dim n As Int32
Dim i As Int32
Dim cmd As String
Dim c As String
n = SerialPort1.BytesToRead
For i = 1 To n
c = Chr(SerialPort1.ReadChar())
cmd &= c
Next
TextBox1.Text &= cmd
After that, the program will be as follow.

Then, you can try the program to send and receive data.

The example above is for character data. For binary data whose ASCII code number greater than 127 can be manipulated as follow.
Dim a(3) As Byte
a(0) = &H41
a(1) = &H31
a(2) = &HFF
a(3) = &H80
SerialPort1.Write(a, 0, 4)
ReadChar cannot be used to receive binary data. ReadByte can be used instead as in the following example.
Dim n As Int32
Dim i As Int32
Dim cmd As String = ""
Dim c As String
n = SerialPort1.BytesToRead
For i = 1 To n
c = Chr(SerialPort1.ReadByte())
cmd &= c
Next
TextBox1.Text &= cmd
Getting Port List in Your PC
To list the all ports in your PC in a Combo box and to select the port number that had been saved in user setting, you can used the following code.
Dim ports As String() = SerialPort.GetPortNames()
Dim port As String
Array.Sort(ports)
cmbSerial.Items.Clear()
For Each port In ports
cmbSerial.Items.Add(port)
Next port
Dim index As Integer
index = cmbSerial.FindString(My.Settings.MCOM)
cmbSerial.SelectedIndex = index
Using Serial Port as IO
Besides Tx and Rx to send and receive data, there are two control outputs and four status inputs in a serial. RTS and DTR can be used as outputs. CTS, DSR, CD and RI can be used as inputs. If you don't need a lot of I/O in an application, serial port is a good choice for IO interface.Related post:
Saturday, April 19, 2008
Asynchronous Serial Communication- RS232, RS422 and RS485
In serial communication, data bytes are sent bit by bit. Its advantage is that data can be sent using only one wire instead of using many parallel wires. But it needs a UART to convert data byte to serial bit stream.
UART not only converts data into serial bit stream, but it also format the bit stream into Asynchronous Serial Communication Protocol by inserting start bit, parity bit, stop bits, etc.
In idle state, a UART normally puts its output in 1. The receiving UART needs to differentiate whether the 1 is data to receive or idle state to ignore. Start bit is used to solve this problem. Normally, a UART ignore 1 as idle. After it received the first 0 as start bit, it accepts the following bits as data for predefined number of bits.
The rate of sending data unit is called Baud rate. For example, if the baud rate is 1 kHz, time period to send each data bit is 1/(1kHz)= 1 ms. A popular baud rate is 9600.
The number of data bits for sending UART and receiving UART must be the same. It can be from 5 bit data to 8 bit data. For example, ASCII data are normally sent with 7 bits. LSB is sent first. A popular number of data bits is 8.
Parity bit is used to check the integrity of the data. In even parity, the number of 1 in data bits and the parity bit itself is even. In odd parity, it is odd. Typically, parity bit is not used.
Stop bit is used to separate the consecutive data bytes. The number of stop bit can be 1,2, etc. 1 is used as a stop bit. Stop bits are sent after sending data bits and parity bits. A popular number of stop bit is 1.
The following example send the data byte 0x41 using 9600, 8N1. That means
Baud rate = 9600
Data bit = 8 bits
Parity = No parity (N= No parity, E= Even parity, O= Odd parity)
Stop bit= 1 stop bit
Since it is no parity, stop bit will come immediately after data bit without any parity bit.
A UART can be in many different forms. The first one is in the form of a discrete IC. A popular IC is 16550. For CMOS, it will become 16C550, and so on. It has its own buffer and interrupt mechanisms. Therefore, it is easy to use. Serial data comes out from sout pin. Its basic configuration is as shown in the following diagram.
Another form of UART is built-in UART within a microcontroller. The last form of UART is software UART that uses IO pins to emulate it.
A UART uses 5V output to represent 1 and uses 0V output to represent 0. To connect to external devices, these output voltages are normally converted into suitable signaling levels by using a transceiver. A popular signaling standard is RS232. A RS232 transceiver outputs or inputs -10V for 1 and +10V for 0. Valid voltage range is from +/- 3V to +/-25V. A popular transceiver IC is MAX232. Its configuration is shown in the following diagram.
If you want to use smaller capacitor (0.1uF) and smaller IC, you can use MAX202. To use MAX202 with 16C550, connect sout pin of UART which produces 0V and 5V to its pin 11. Then Tx will come out from pin 14 as +10V and -10V. Similarly, +10V and -10V received from Rx line that is connected to pin 13 will come out as 0V and 5V from pin 12 which connects to sin of UART.
The following figure shows typical connection for RS232.
You can use a multimeter to differentiate Tx and Rx of opened RS232 lines. Typically, the voltage between Tx and Ground is -10V and there is no voltage between Rx and Ground. RS232 is said unbalanced lines.
In RS232 communication, besides data transmit line (Tx) and data receive line (Rx), there are also control and status lines for handshaking. Among Primary Communication lines, Tx and RTS are outputs and Rx and CTS are inputs. Among Status and Control lines, DTR is output while DSR and CD are inputs. They will be discussed further. When we talk about RS232 devices, DTE ( Data Terminal Equipment) refers to computer and DCE (Data Circuit-Terminating Equipment) refers to Modem or device.
RTS- Request To Send signal is requested by DTE to DCE. It is normally logic 1 (negative voltage) and when requested it becomes logic 0 (positive voltage).
CTS- Clear To Send signal is used by DCE to infrom DTE that it is ready to receive. It is normally logic 1 (negative voltage) and it becomes logic 0 (positive voltage) when asserted.
DSR- DCE Ready (Data Set Ready) is used by DCE (device) to inform DTE that it has turned on and is ready. It is normally logic 1 (negative voltage) and it becomes logic 0 (positive voltage) when asserted.
DTR- DTE Ready is asserted by DTE to inform DCE that it want to communicate. It is normally logic 1 (negative voltage) and it becomes logic 0 (positive voltage) when asserted.
CD- Carrier Detect (Received Line Signal Detector) is used when DCE is a modem. When this modem receives the answer tone of a modem at the other side of the telephone line, it asserts the computer with logic 0.
RI- Ring Indicator is asserted when a modem receives ring signal. It outputs logic 0 to the computer. It is positive only when there is ring signal. It is negative between ring signals and when there is no ring signal.
Let us continue to discuss about RS232 wire connectors.
As shown in the following figure, a computer (DTE) has Male DB9 connector for RS232 and a device (DCE) has Female DB9 connector. Pin connection for a male connector is shown.
Pin connection of a female connector is also shown below.
RS422 and RS485 function using the difference voltage between two wires. Transmit voltage is between +12V and -12V and they can receive even if the voltage difference is about 0.4V. The voltage between +Tx and -Tx is output voltage and the voltage between +Rx and -Rx is input voltage. They are called balance line because they don't use the voltage between ground and transmit line. They have more resistance to common mode noise. Therefore, they can communicate faster and can communicate over longer distance.
Note:
-200mV to +200mV = 0.4 V
-6V to +6V = 12V
Both RS232 and RS422 can have many receivers on a single bus line but they can have only one transmitter on a bus line. In RS485, transmit driver circuit can be enabled and disabled by using data enable line. As a result, it can have many receivers and transmitters on a bus line. Normally, RS422 uses two wires (+Tx, -Tx) for transmitting and another two wires (+Rx, -Rx) for receiving. Therefore, RS422 uses total of four wires. RS485 can communicate using only two wires for both transmitting and receiving in half duplex mode. RS485 can also be used in Full duplex mode using four wires. The following figure shows a typical connection for RS485 using MAX481 transceiver IC. It has only two wires to use in half duplex mode.
An example using MAX491 to connect RS485 in full duplex mode is shown below. If you connect +Tx and +Rx and at the same time -Tx and -Rx, it can be used in half duplex mode.
Actually, full duplex RS485 with four wires whose transmit driver circuit always enabled is same as RS422. RS422 is normally used to extend distance of RS232 communication. When the distance is too far to use RS232, RS422 converter can be used in transmitting side and receiving side can convert the signal back to RS232.
In case, you want to use RS422/RS485 input device with RS232 output device without converter, you can directly connect RS232 Tx output to RS422/RS485 -Rx and RS232 GND to +Rx line. I tried it once before and it was OK. RS422, RS485 half duplex and RS485 full duplex connections are shown below. The first one is RS422 which can be used for only one to one connection. There can be many receivers, but there can only be one transmitter in a bus line. We cannot control transmit driver.
Note that RS485 half duplex has driver enable and receiver enable. Typically, there can be up to 32 node in a bus line.
RS485 full duplex.
UART not only converts data into serial bit stream, but it also format the bit stream into Asynchronous Serial Communication Protocol by inserting start bit, parity bit, stop bits, etc.
In idle state, a UART normally puts its output in 1. The receiving UART needs to differentiate whether the 1 is data to receive or idle state to ignore. Start bit is used to solve this problem. Normally, a UART ignore 1 as idle. After it received the first 0 as start bit, it accepts the following bits as data for predefined number of bits.
The rate of sending data unit is called Baud rate. For example, if the baud rate is 1 kHz, time period to send each data bit is 1/(1kHz)= 1 ms. A popular baud rate is 9600.
The number of data bits for sending UART and receiving UART must be the same. It can be from 5 bit data to 8 bit data. For example, ASCII data are normally sent with 7 bits. LSB is sent first. A popular number of data bits is 8.
Parity bit is used to check the integrity of the data. In even parity, the number of 1 in data bits and the parity bit itself is even. In odd parity, it is odd. Typically, parity bit is not used.
Stop bit is used to separate the consecutive data bytes. The number of stop bit can be 1,2, etc. 1 is used as a stop bit. Stop bits are sent after sending data bits and parity bits. A popular number of stop bit is 1.
The following example send the data byte 0x41 using 9600, 8N1. That means
Baud rate = 9600
Data bit = 8 bits
Parity = No parity (N= No parity, E= Even parity, O= Odd parity)
Stop bit= 1 stop bit
Since it is no parity, stop bit will come immediately after data bit without any parity bit.

Forms of UART
A UART can be in many different forms. The first one is in the form of a discrete IC. A popular IC is 16550. For CMOS, it will become 16C550, and so on. It has its own buffer and interrupt mechanisms. Therefore, it is easy to use. Serial data comes out from sout pin. Its basic configuration is as shown in the following diagram.

Another form of UART is built-in UART within a microcontroller. The last form of UART is software UART that uses IO pins to emulate it.
RS232
A UART uses 5V output to represent 1 and uses 0V output to represent 0. To connect to external devices, these output voltages are normally converted into suitable signaling levels by using a transceiver. A popular signaling standard is RS232. A RS232 transceiver outputs or inputs -10V for 1 and +10V for 0. Valid voltage range is from +/- 3V to +/-25V. A popular transceiver IC is MAX232. Its configuration is shown in the following diagram.

If you want to use smaller capacitor (0.1uF) and smaller IC, you can use MAX202. To use MAX202 with 16C550, connect sout pin of UART which produces 0V and 5V to its pin 11. Then Tx will come out from pin 14 as +10V and -10V. Similarly, +10V and -10V received from Rx line that is connected to pin 13 will come out as 0V and 5V from pin 12 which connects to sin of UART.
The following figure shows typical connection for RS232.

You can use a multimeter to differentiate Tx and Rx of opened RS232 lines. Typically, the voltage between Tx and Ground is -10V and there is no voltage between Rx and Ground. RS232 is said unbalanced lines.

In RS232 communication, besides data transmit line (Tx) and data receive line (Rx), there are also control and status lines for handshaking. Among Primary Communication lines, Tx and RTS are outputs and Rx and CTS are inputs. Among Status and Control lines, DTR is output while DSR and CD are inputs. They will be discussed further. When we talk about RS232 devices, DTE ( Data Terminal Equipment) refers to computer and DCE (Data Circuit-Terminating Equipment) refers to Modem or device.
RTS- Request To Send signal is requested by DTE to DCE. It is normally logic 1 (negative voltage) and when requested it becomes logic 0 (positive voltage).
CTS- Clear To Send signal is used by DCE to infrom DTE that it is ready to receive. It is normally logic 1 (negative voltage) and it becomes logic 0 (positive voltage) when asserted.
DSR- DCE Ready (Data Set Ready) is used by DCE (device) to inform DTE that it has turned on and is ready. It is normally logic 1 (negative voltage) and it becomes logic 0 (positive voltage) when asserted.
DTR- DTE Ready is asserted by DTE to inform DCE that it want to communicate. It is normally logic 1 (negative voltage) and it becomes logic 0 (positive voltage) when asserted.
CD- Carrier Detect (Received Line Signal Detector) is used when DCE is a modem. When this modem receives the answer tone of a modem at the other side of the telephone line, it asserts the computer with logic 0.
RI- Ring Indicator is asserted when a modem receives ring signal. It outputs logic 0 to the computer. It is positive only when there is ring signal. It is negative between ring signals and when there is no ring signal.
Let us continue to discuss about RS232 wire connectors.

As shown in the following figure, a computer (DTE) has Male DB9 connector for RS232 and a device (DCE) has Female DB9 connector. Pin connection for a male connector is shown.

pin 1 = CD- Carrier Detect (input)
pin 2 = Rx- Receive Data (input)
pin 3 = Tx- Transmit Data (output)
pin 4 = DTR- Data Terminal Ready (output)
pin 5 = GND- System Ground
pin 6 = DSR- Data Set Ready (input)
pin 7 = RTS- Request To Send (output)
pin 8 = CTS- Clear To Send (input)
pin 9 = RI - Ring Indicator (input)
Pin connection of a female connector is also shown below.

pin 1 = CD- Carrier Detect (output)
pin 2 = Tx- Transmit Data (output)
pin 3 = Rx- Receive Data (input)
pin 4 = DTR- Data Terminal Ready (input)
pin 5 = GND- System Ground
pin 6 = DSR- Data Set Ready (output)
pin 7 = CTS- Clear To Send (input)
pin 8 = RTS- Request To Send (output)
pin 9 = RI - Ring Indicator (output
RS422 and RS485
RS422 and RS485 function using the difference voltage between two wires. Transmit voltage is between +12V and -12V and they can receive even if the voltage difference is about 0.4V. The voltage between +Tx and -Tx is output voltage and the voltage between +Rx and -Rx is input voltage. They are called balance line because they don't use the voltage between ground and transmit line. They have more resistance to common mode noise. Therefore, they can communicate faster and can communicate over longer distance.

Note:
-200mV to +200mV = 0.4 V
-6V to +6V = 12V
Both RS232 and RS422 can have many receivers on a single bus line but they can have only one transmitter on a bus line. In RS485, transmit driver circuit can be enabled and disabled by using data enable line. As a result, it can have many receivers and transmitters on a bus line. Normally, RS422 uses two wires (+Tx, -Tx) for transmitting and another two wires (+Rx, -Rx) for receiving. Therefore, RS422 uses total of four wires. RS485 can communicate using only two wires for both transmitting and receiving in half duplex mode. RS485 can also be used in Full duplex mode using four wires. The following figure shows a typical connection for RS485 using MAX481 transceiver IC. It has only two wires to use in half duplex mode.

An example using MAX491 to connect RS485 in full duplex mode is shown below. If you connect +Tx and +Rx and at the same time -Tx and -Rx, it can be used in half duplex mode.

Actually, full duplex RS485 with four wires whose transmit driver circuit always enabled is same as RS422. RS422 is normally used to extend distance of RS232 communication. When the distance is too far to use RS232, RS422 converter can be used in transmitting side and receiving side can convert the signal back to RS232.
In case, you want to use RS422/RS485 input device with RS232 output device without converter, you can directly connect RS232 Tx output to RS422/RS485 -Rx and RS232 GND to +Rx line. I tried it once before and it was OK. RS422, RS485 half duplex and RS485 full duplex connections are shown below. The first one is RS422 which can be used for only one to one connection. There can be many receivers, but there can only be one transmitter in a bus line. We cannot control transmit driver.

Note that RS485 half duplex has driver enable and receiver enable. Typically, there can be up to 32 node in a bus line.

RS485 full duplex.

Subscribe to:
Posts (Atom)