Docsity

RS232 Communication Class in VB.Net - Prof. Erik Goodman, Lab Reports of Principles of Theater Design

Partial preview of the text

Download RS232 Communication Class in VB.Net - Prof. Erik Goodman and more Lab Reports Principles of Theater Design in PDF only on Docsity!

How to Build a Basic Digital Thermometer with Serial

Interface

Developed By Kevin Scheel

ECE 480 Spring 07’

Executive Summary:

Many consumers use digital thermometers every day and due to their usefulness they

have become cheap and readily available. Most users only need to know if they have a

temperature or are running a fever and so a one time use and read system is preferable. In this

case outputting the result to an LCD is easier and gives the user immediate results. However,

what if the user wants to keep track of their results digitally? In a situation such as this you

would want to be able to store temperatures in a file on a computer. This presents a problem

as most digital thermometers available today are meant for independent use. That is, they are

not designed to transmit their data anywhere outside the device itself. In this Application note

we will design a basic digital thermometer that can transmit the temperature data it receives to

a computer via the RS232 protocol.

This data can then be displayed by a computer program able to communicate with the

device over serial, via a graphical or command line based program. Optionally, this data could

even be written to a database for permanent storage or simply a file for safe keeping.

Key Terms:

ADC – Analog to digital converter

(For more info see http://en.wikipedia.org/wiki/Analog-to-digital_converter)

MCU/PIC – Microcontroller in our case this will be a PIC microcontroller used to manipulate

input analog signals to perform functions, it can be programmed using C to perform various

functions with a given input(s).

(for more info see http://en.wikipedia.org/wiki/PIC_microcontroller)

RS232 – The protocol governing serial communications between electronic devices devices

(For more information on RS232 please see http://en.wikipedia.org/wiki/RS232)

GUI – Graphical User Interface, a computer program utilizing a graphical method of

displaying and manipulating data via a keyboard, mouse, touch screen, stylus, etc.

(For more information on GUI’s please see http://en.wikipedia.org/wiki/GUI)

Op-Amp – short for operational amplifier, this common electrical component that serves as

DC voltage amplifier. The amplification can be adjusted with the placement of varying

resistor values between the +/- inputs and the output pin.

(For more information on op-amps please see http://en.wikipedia.org/wiki/Op-amp)

Thermistor – a kind of resistor for which the resistance value changes based on the

temperature surrounding it.

For more information on thermistors please see http://en.wikipedia.org/wiki/Thermistor)

Components list:

Qty Part Number Description

1 PIC18F4520 Programmable microcontroller w/ ADC

1 MX045HS 40Mhz Crystal clock

1 MAX232 RS232 Line Driver/Reciever

1 Winford RJ-11 Standard 6 pin RJ-11 port for PIC programming

1 Winford DB-9 Standard DB-9 serial connector

1 LM324N Low power Op-Amp (quad)

of hardware that we need since we can convert the ADC output to a temperature within our

GUI program itself.

Figure 2: Op-Amps and Gain equations (from lab 3C40-e5)

Above is an example of a traditional non-inverting amplifier making use of an op-amp

to amplify Vin. In our case we can simply use Rb, to restrict the flow of a standard 5v Vin

based on our temperature. This will provide us with an analog voltage value that we can work

with. To find the relationship between this signal and temperature we will have to do some

more testing which we will get to later on in this document.

For now we are concerned with what will be done once we have an analog signal. As

figure 1 demonstrates, this value will be converted into a digital signal and we need to get that

value over to our GUI.. To do this we will use our PIC and our MAX232 chips. The

advantage to the PIC18F4520 is that it has a built in 10-bit ADC and can make use of

software handshaking to transmit and receive serial signals with the help of the MAX232. For

a good tutorial on how to construct this part of the circuit we can use a pair of ECE480 labs

from Michigan State University available at

http://www.egr.msu.edu/classes/ece480/goodman/ForMiniprojects/Lab4.pdf and

http://www.egr.msu.edu/classes/ece480/goodman/ForMiniprojects/Lab3.pdf. These lab

explain how to construct a few PIC based circuits including a circuit capable of transmitting a

converted analog voltage signal to a GUI. From these two labs I have designed a circuit

schematic for the circuit that we will need to use. Please see the schematic below and

construct it on a proto-board.

Figure 3 : Thermometer Schematic (See Appendix A for full-sized schematic Pg. 14)

Section B: Programming your PIC Microprocessor

Now that we have built our circuit we are ready to program the PIC microcontroller to

handle our data and output the correct digital voltage value to our MAX232 Chip. Below is

the code from the .c file we will be using to program the PIC. We will use MPLAB to

program our PIC along with a Microchip MPLAB ICD 2 PIC programmer. (More

information can be found on this product here

http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1406&dDoc

Name=en010046)

For instruction on programming you PIC please use the MSU LAB 3 pdf file, linked

to here http://www.egr.msu.edu/classes/ece480/goodman/ForMiniprojects/Lab3.pdf.

information on programming the PIC18F4520 can be found in the first section. Please use the

code below. (Simply copy and paste)

#include <p18cxxx.h>

#include <usart.h>

#include <ADC.h>

#pragma config LVP=OFF

#pragma config WDT=OFF

void rx_handler (void); //Declare the ISR function

unsigned char data;

char data2[6] = {'S', 'c', 'h', 'e', 'e', 'l'};

long int count;

int dloop, dloop2, altflash, adc_result;

void main()

OpenUSART (USART_TX_INT_OFF & USART_RX_INT_ON &

USART_ASYNCH_MODE & USART_EIGHT_BIT &

USART_CONT_RX & USART_BRGH_LOW, 63);

RCONbits.IPEN = 1; /* Enable interrupt priority */

IPR1bits.RCIP = 1; /* Make receive interrupt high priority */

INTCONbits.GIEH = 1; /* Enable all high priority interrupts */

OpenADC(ADC_FOSC_32 & ADC_RIGHT_JUST & ADC_12_TAD,

ADC_CH0 & ADC_INT_OFF, 0); //open adc port for reading

SetChanADC(ADC_CH1); //Set ADC to Pin 3

ADCON1 =0x00; //set VREF+ to VDD and VREF- to GND (VSS)

TRISD = 0x04;

PORTDbits.RD0 = 0;

PORTDbits.RD3 = 0;

PORTDbits.RD1 = 0;

altflash = 1;

dloop = 0;

dloop2 = 0;

while(1)

Section C: Building Your GUI

To view the the data on our computer we will need to design a simple graphical user

interface for a user to manipulate. For simplicity we will be using Visual Basic.NET, however

you can use which ever programming language you wish. You will however need a class of

some sort to handle communications over RS232. A Sample class for visual basic can be

found in Appendix C. The code for our form can found below and should be added to a form

called Form1.vb. This form should appear under your solution explorer pane in Visual

Studio.NET as seen in figure 5 below. Note that CRs232.vb is our RS232 driver located in

Appendix B (Pg. 15) of this tutorial.

Figure 5 : Solution Explorer Pane in Visual Studio with project information

If you need additional guidance please consult MSU Lab 4 found here

http://www.egr.msu.edu/classes/ece480/goodman/ForMiniprojects/Lab4.pdf. Please also use

the help function within Visual Studio to answer questions on how to create a new VB

project.

After you have your file structure setup please proceed to add the following code to your

Form1.vb file to create a GUI we can use.

Public Class Form Inherits System.Windows.Forms.Form Dim setRs232 As New Rs Dim serial_in As String Dim x As Integer Dim sf As String Dim sr As String Dim sleepf As Integer Dim sample As Integer Declare Sub Sleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long) #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents Button1 As System.Windows.Forms.Button Friend WithEvents TextBox1 As System.Windows.Forms.TextBox 'Friend WithEvents Chart1 As Dundas.Charting.WinControl.Chart Friend WithEvents Button7 As System.Windows.Forms.Button <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.TextBox1 = New System.Windows.Forms.TextBox Me.Button7 = New System.Windows.Forms.Button Me.SuspendLayout() ' 'TextBox ' Me.TextBox1.Location = New System.Drawing.Point(120, 32) Me.TextBox1.Name = "TextBox1"

Section D: Calibrating Your Thermistor

After you have built your circuit you are ready to find the formula necessary for

converting your voltage value into a temperature value. This part of the process is quite

simple and straight forward. The simplest way to find your relationship is through testing.

You will need the following items to run your test.

Equipment:

1 - Cup filled with ice

1- Cup filled with hot water

1- Thermometer or temperature probe

1 - 5V power supply

Your finished and operational circuit

To measure the relationship between voltage and temperature follow the following steps.

1) Connect up your circuit with 5V from your power supply.

2) Connect your Circuit to MP Lab via the RJ-11 port, build your code, program your

PIC, and finally run the program (Please see MSU labs for information on

programming in MP lab).

3) Open Visual Studio and run your GUI

4) Place the thermometer and your thermistor probe in warm water (*Warning, be careful

in dealing with water around your circuit and make sure that your thermistor is housed

properly*) It is recommended that you use the case from a store bought thermometer

to ensure that you will not have any water leakage, also the thermistor from this

product.

5) After the commercial thermometer has reached it’s final temperature record the

temperature and click “get temperature” in your GUI and record the voltage value that

appears in the text box to the right.

6) Repeat steps 4-6 at least 20 times, waiting a few minutes between each test to allow

for a significant temperature change in the water.

7) After you have 20 or more data points enter your data either in Microsoft Excel or

MATLAB. Your table should look something like the one in figure 6 below.

temperature in F vdc 104.4 4. 97.3 3. 97.4 3. 96.1 3. 95 3. 92.9 3. 91.1 3. 91.5 3. 96.5 3. 97 3. 97.7 3. 98.2 3.

Figure 6: Example Table of recorded Data

*Note: This data will vary from experiment to experiment depending on what resistance value

your thermistor operates at and the temperature of the water you are using/time between

measurements.

With this data you can graph the relationship and find a curve using the tools within

the given program. For more information on graphing in MS Excel please use the following

link(http://chemed.chem.purdue.edu/genchem/lab/datareports/excel/plotting.html) After the

data has been plotted goto chart->add trend line and select exponential. This should give you

a formula for the best fit line of your data.

Change in Voltage vs.

Temperature

y = 3.125e0.0045x

4

Temperature in degrees Fahrenheit )Voltage ) VDC Series Expon. (Series1)

Figure 7: Graph of Voltage vs. Temperature

From figure 7 we can see that our general formula is y = 3.125.0045x^ with y equaling the

voltage and x equaling the temperature in degrees Fahrenheit. From this we can derive the

following equation to determine the temperature based on a given voltage value in decimal

form (which is what we get in from our circuit). The resulting equation is

Temperature = ln(voltage/3.125)/-0.0045. Lucky for us the natural log function can be used

in Visual Basic. Net with the command Math.Log(). Your GUI code should be modified to

display your new temperature result. By changing the following lines of code in Form1.vb.

Conclusion:

Through this note we have designed and built a digital thermometer that can be used

with a windows computer. The applications for such a device are wide ranging including, but

not limited to, medical thermometers and temperature sensors for a detection system. We have

designed this thermometer to be accurate to within 0.1 degree F, which should work for even

medical applications. Your results will vary depending on the resistance value of your

thermistor and the sensitivity/tolerance of the thermistor itself. This may vary from

commercial product to commercial product. Other possible changes to this device include

programming the GUI in a language such as Qt for cross platform support, however this will

require a RS232 support class. Such classes can be found on the Internet, an example of one

such class can be found at http://qextserialport.sourceforge.net/. One might also use an API to

save the recorded data to a database file for future reference and comparison. This can also be

accomplished in Qt. This product is meant as a starting point for work with digital

thermometers and hopefully you have gained some insight into how such products function.

Appendix A: Circuit Schematic

' Rev.4 (24/05/2002) ' Fixed problem with ASCII Encoding truncating 8th bit ' ' Rev.5 (27/05/2002) ' Added IDisposable / Finalize implementation ' ' Rev.6 (14/03/2003) ' Fixed problem on DCB fields Initialization ' ' Rev.7 (26/03/2003) ' Added XON/XOFF support ' ' Rev.8 (12/07/2003) ' Added support to COM port number greater than 4 ' ' Rev.9 (15/07/2003) ' Added CommEvent to detect incoming chars/events ' Updated both Tx/Rx method from Non-Ovelapped to Overlapped mode ' Removed unused Async methods and other stuff. ' ' Rev.10 (21/07/2003) ' Fixed incorrect character handling when using EnableEvents() ' ' Rev.11 (12/08/2003) ' Fixed some bugs signaled by users ' ' Rev.12 (01/09/2003) ' Removed AutoReset of internal buffers and added PurgeBuffer() method ' ' Rev.13 (02/09/2003) ' Removed GetLastErrorUse in favour of Win32Exception() ' ' Rev.14 (14/09/2003) ' Added IsPortAvailable() function ' Revised some API declaration ' Fixed problem with Win98/Me OS ' ' Rev.15 (24/09/2003) ' Fixed bug introduced on Rev. ' ' Rev.16 (12/10/2003) ' Added SetBreak/ClearBreak() methods ' ' Rev.17 (02/11/2003) ' Fixed field on COMMCONFIG ' ' Rev.18 (03/03/2004) ' Fixed bug: Testing mhRS for <>0 is not correct ' ' Rev.19 (08/04/2004) ' Fixed bug: Fixed bug on DTR property ' ' Rev.20 (12/07/2004) ' CommEvent is no more raised on a secondary thread ' pEventsWatcher now uses a background thread '

' Rev.21 (24/10/2004) ' EscapeCommFunction declaration fixed ' Pariti enum fixed to Parity ' ' Rev. 22 (05/03/2005) ' Fixed memory leak problem causing program closing ' without any message on some systems. ' Thanks to Ralf Gedrat for testing this scenario ' ' Rev.23 (05/04/2005) ' Fixed bug DisableEvents not working bug ' ' Rev.24 (20/04/2005) ' Fixed memory leak on Read method ' Added InBufferCount property ' IsPortAvailable method is now shared ' Thanks to Jean-Pierre ZANIER for the feedback '=================================================== '// Class Members Private mhRS As IntPtr = New IntPtr(0) '// Handle to Com Port Private miPort As Integer = 1 '// Default is COM Private miTimeout As Int32 = 70 '// Timeout in ms Private miBaudRate As Int32 = 9600 Private meParity As DataParity = 0 Private meStopBit As DataStopBit = 0 Private miDataBit As Int32 = 8 Private miBufferSize As Int32 = 512 '// Buffers size default to 512 bytes Private mabtRxBuf As Byte() '// Receive buffer Private meMode As Mode '// Class working mode Private moThreadTx As Thread Private moThreadRx As Thread Private moEvents As Thread Private miTmpBytes2Read As Int Private meMask As EventMasks Private mbDisposed As Boolean Private mbUseXonXoff As Boolean Private mbEnableEvents As Boolean Private miBufThreshold As Int32 = 1 Private muOvlE As OVERLAPPED Private muOvlW As OVERLAPPED Private muOvlR As OVERLAPPED Private mHE As GCHandle Private mHR As GCHandle Private mHW As GCHandle '--------------------------------------------------------------------


#Region "Enums" '// Parity Data Public Enum DataParity Parity_None = 0 Parity_Odd Parity_Even

Public Parity As Byte Public StopBits As Byte Public XonChar As Char Public XoffChar As Char Public ErrorChar As Char Public EofChar As Char Public EvtChar As Char Public wReserved2 As Int End Structure <StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure COMMTIMEOUTS Public ReadIntervalTimeout As Int Public ReadTotalTimeoutMultiplier As Int Public ReadTotalTimeoutConstant As Int Public WriteTotalTimeoutMultiplier As Int Public WriteTotalTimeoutConstant As Int End Structure <StructLayout(LayoutKind.Sequential, Pack:=8)> Private Structure COMMCONFIG Public dwSize As Int Public wVersion As Int Public wReserved As Int Public dcbx As DCB Public dwProviderSubType As Int Public dwProviderOffset As Int Public dwProviderSize As Int Public wcProviderData As Int End Structure <StructLayout(LayoutKind.Sequential, Pack:=1)> Public Structure OVERLAPPED Public Internal As Int Public InternalHigh As Int Public Offset As Int Public OffsetHigh As Int Public hEvent As IntPtr End Structure <StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure COMSTAT Dim fBitFields As Int Dim cbInQue As Int Dim cbOutQue As Int End Structure #End Region #Region "Constants" Private Const PURGE_RXABORT As Integer = &H Private Const PURGE_RXCLEAR As Integer = &H Private Const PURGE_TXABORT As Integer = &H Private Const PURGE_TXCLEAR As Integer = &H Private Const GENERIC_READ As Integer = &H Private Const GENERIC_WRITE As Integer = &H Private Const OPEN_EXISTING As Integer = 3 Private Const INVALID_HANDLE_VALUE As Integer = - Private Const IO_BUFFER_SIZE As Integer = 1024 Private Const FILE_FLAG_OVERLAPPED As Int32 = &H Private Const ERROR_IO_PENDING As Int32 = 997 Private Const WAIT_OBJECT_0 As Int32 = 0

Private Const ERROR_IO_INCOMPLETE As Int32 = 996 Private Const WAIT_TIMEOUT As Int32 = &H102& Private Const INFINITE As Int32 = &HFFFFFFFF #End Region #Region "Win32API" '// Win32 API <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetCommState(ByVal hCommDev As IntPtr, ByRef lpDCB As DCB) As Int End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function GetCommState(ByVal hCommDev As IntPtr, ByRef lpDCB As DCB) As Int End Function <DllImport("kernel32.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function BuildCommDCB(ByVal lpDef As String, ByRef lpDCB As DCB) As Int End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetupComm(ByVal hFile As IntPtr, ByVal dwInQueue As Int32, ByVal dwOutQueue As Int32) As Int End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetCommTimeouts(ByVal hFile As IntPtr, ByRef lpCommTimeouts As COMMTIMEOUTS) As Int End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function GetCommTimeouts(ByVal hFile As IntPtr, ByRef lpCommTimeouts As COMMTIMEOUTS) As Int End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function ClearCommError(ByVal hFile As IntPtr, ByRef lpErrors As Int32, ByRef lpComStat As COMSTAT) As Int End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function PurgeComm(ByVal hFile As IntPtr, ByVal dwFlags As Int32) As Int End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function EscapeCommFunction(ByVal hFile As IntPtr, ByVal ifunc As Int32) As Boolean End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function WaitCommEvent(ByVal hFile As IntPtr, ByRef Mask As EventMasks, ByRef lpOverlap As OVERLAPPED) As Int End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function WriteFile(ByVal hFile As IntPtr, ByVal Buffer As Byte(), ByVal nNumberOfBytesToWrite As Integer, ByRef lpNumberOfBytesWritten As Integer, ByRef lpOverlapped As OVERLAPPED) As Integer End Function <DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function ReadFile(ByVal hFile As IntPtr, <Out()> ByVal Buffer As Byte(), ByVal nNumberOfBytesToRead As Integer, ByRef lpNumberOfBytesRead As Integer, ByRef lpOverlapped As OVERLAPPED) As Integer End Function <DllImport("kernel32.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As Integer, ByVal dwShareMode As Integer, ByVal