Project Report DAS
Transcript of Project Report DAS
1
1. INTRODUCTION:
This project implements a high speed data acquisition, Logging and Controlling system
using ATMega16, ATMega8 microcontrollers and RS-485. Our main focus for this project was
to take analog or digital data from sensors which are distributed across very large area.
Maintaining the records of the data is important task when analyzing manually the status of
system; this is done with help of database record. Displaying every instant value to the operator
is being done with the help of visual basic user interface. Controlling an event when some
physical quantity has reached above its maximum limit or below its minimum limit is being done
with the help of control feature for every sensor.
Every sensor is connected to Atmega8 controller’s ADC through its signal conditioning circuit.
We have taken three Atmega8 modules which are connected to a main controller module which
is having Atmega16 controller. When any sensor give data to the Atmega8 it is converted to its
digital equivalent and transferred to the main controller which is connected to PC through RS-
485 interfacing. It is important to use RS-485 interface as it reduces the noise interference which
is very common in industries. The data coming from sensors is regularly being displayed on the
computer through the visual basic 6.0 software. There is also an option of controlling a particular
physical quantity which is being sensed regularly. This is with the help of control option being
provided in the software.
We have used RS-485 and RS-232 protocols to transfer data from slave to computer. Between
the slave and master controller there is RS-485 interface while between main controller and the
computer we have used RS-232 interface. Line drivers IC’s are used for this conversion.
The major design challenge we have encountered is with integration of all slave controllers with
master controller. As the master controller must know from which slave controller the data is
coming, this is done by making a data frame of 6bytes.this data frame contains address of the
slave, data from the slave, start and end reorganization of the frame. After this it becomes easy to
recognize the frame and give that frame to appropriate field in the user interface.
Our original proposal was to do this work in wireless medium but due budget constraints we
have to take simple RS-485 interface to complete the task. Project every part is built in such a
manner that we can extend the slave controllers as well its data frame width with some simple
modifications.
2. HIGH LEVEL DESIGN :
i. Rationale:
Original idea was to build some set of data acquisition and signal conversion system for aircrafts.
It was prepared to do with the wireless medium but due to budget constraint we have to switch to
wire medium. Even after that also the project can be used in any environment where there is the
2
requirement of data sensing from the physical quantity and taking the appropriate control action
according to that data.
ii. Logical structure:
Block diagram for DAQ
MASTER DEVICE
ATMEGA 16
PC
USB
PORT
USB TO
UART
CONVER
TER
SLAVE
DEVICE
ATMEGA 8
SLAVE
DEVICE
ATMEGA 8
SLAVE
DEVICE
ATMEGA 8
RESISTOR
SENSOR
LIGHT
SENSOR
TEMPERATURE
SENSOR
3
iii. Hardware/software tradeoffs:
As the software (VB6.0) is getting the data from USART buffer which is 16 times faster than the
hardware, there no much trade-off requirement for communication. At the run time hardware is
providing the data at sufficient speed which is being taken from the software easily accurately.
iv. Standards:
We have used two standards for data communication. That are RS-485 between the slave
controllers and the main controller and RS-232 between the main controller and pc. Protocols
study:
a) RS-232 protocol
Communication as defined in the RS232 standard is an asynchronous serial
communication method. The word serial means, that the information is sent one bit at a time.
Asynchronous tells us that the information is not sent in predefined time slots. Data transfer can
start at any given time and it is the task of the receiver to detect when a message starts and ends.
Asynchronous communication has some advantages and disadvantages, which are both discussed
in the next paragraph.
Devices, which use serial cables for their communication, are split into two categories.
These are DCE (Data Communications Equipment) and DTE (Data Terminal Equipment.) Data
Communications Equipments are devices such as modem, TA adapter, plotter etc while Data
Terminal Equipment are Computer or Terminal.
The electrical specification of the serial port is contained in the EIA (Electronics Industry
Association) RS232C standard. It states many parameters such as -
1. A "Space" (logic 0) will be between +3 and +25 Volts.
2. A "Mark" (Logic 1) will be between -3 and -25 Volts.
3. The region between +3 and -3 volts is undefined.
4. An open circuit voltage should never exceed 25 volts. (In Reference to GND)
5. A short circuit current should not exceed 500mA. The driver should be able to handle this
without damage. (Take note of this one!)
Serial Ports come in two "sizes". There are the D-Type 25 pin connector and the D-Type
9 pin connector both of which are male on the back of the PC, thus you will require a female
connector on your device. Below is a table of pin connections for the 9 pin and 25 pin D-Type
connectors.
Table various serial port pins
D-Type-
9 pin no.
D-Type-
25 pin no.
Pin outs Function
3 2 RD Receive Data (Serial data input)
2 3 RD Transmit Data (Serial data output)
4
7 4 RTS Request to send (acknowledge to modem that UART
is ready to exchange data
8 5 CTS Clear to send (i.e.; modem is ready to exchange data)
6 6 DSR Data ready state (UART establishes a link)
5 7 SG Signal ground
1 8 DCD Data Carrier detect (This line is active when modem
detects a carrier
4 20 DTR Data Terminal Ready.
9 22 RI Ring Indicator (Becomes active when modem detects
ringing signal from PSTN
Null Modems
A Null Modem is used to connect two DTE's together. This is commonly used as a cheap way to
network games or to transfer files between computers using Zmodem Protocol, Xmodem
Protocol etc. This can also be used with many Microprocessor Development Systems.
Above is preferred method of wiring a Null Modem. It only requires 3 wires (TD, RD &
SG) to be wired straight through thus is more cost effective to use with long cable runs. The
theory of operation is reasonably easy. The aim is to make to computer think it is talking to a
modem rather than another computer. Any data transmitted from the first computer must be
received by the second thus TD is connected to RD. The second computer must have the same
set-up thus RD is connected to TD. Signal Ground (SG) must also be connected so both grounds
are common to each computer.
The Data Terminal Ready is looped back to Data Set Ready and Carrier Detect on both
computers. When the Data Terminal Ready is asserted active, then the Data Set Ready and
Carrier Detect immediately become active. At this point the computer thinks the Virtual Modem
to which it is connected is ready and has detected the carrier of the other modem.
5
All left to worry about now is the Request to send and Clear To Send. As both computers
communicate together at the same speed, flow control is not needed thus these two lines are also
linked together on each computer. When the computer wishes to send data, it asserts the Request
to send high and as it's hooked together with the Clear to Send, It immediately gets a reply that it
is ok to send and does so.
Notice that the ring indicator is not connected to anything of each end. This line is only
used to tell the computer that there is a ringing signal on the phone line. As we don't have a
modem connected to the phone line this is left disconnected.
RS232 bit streams
The RS232 standard describes a communication method where information is sent bit by
bit on a physical channel. The information must be broken up in data words. The length of a data
word is variable. On PC's a length between 5 and 8 bits can be selected. This length is the
information length of each word. For proper transfer additional bits are added for
synchronization and error checking purposes. It is important, that the transmitter and receiver use
the same number of bits. Otherwise, the data word may be misinterpreted, or not recognized at
all.
With synchronous communication, a clock or trigger signal must be present which
indicates the beginning of each transfer. The absence of a clock signal makes an asynchronous
communication channel cheaper to operate. Less line is necessary in the cable. A disadvantage is
that the receiver can start at the wrong moment receiving the information. Re-synchronization is
then needed which costs time. All data received in the resynchronization period is lost. Another
disadvantage is that extra bits are needed in the data stream to indicate the start and end of useful
information. These extra bits take up bandwidth.
Data bits are sent with a predefined frequency, the baud rate. Both the transmitter and
receiver must be programmed to use the same bit frequency. After the first bit is received, the
receiver calculates at which moments the other data bits will be received. It will check the line
voltage levels at those moments.
With RS232, the line voltage level can have two states. The on state is also known as
mark, the off state as space. No other line states are possible. When the line is idle, it is kept in
the mark state.
Start bit
RS232 defines an asynchronous type of communication. This means, that sending of a
data word can start on each moment. If starting at each moment is possible, this can pose some
problems for the receiver to know which the first bit to receive is. To overcome this problem,
each data word is started with an attention bit. The space line level always identifies this
attention bit, also known as the start bit. Because the line is in mark state when idle, the receiver
easily recognizes the start bit.
Data bits
6
Directly following the start bit, the data bits are sent. A bit value 1 causes the line to go in mark
state; the bit value 0 is represented by a space. The least significant bit is always the first bit sent.
Parity bit
For error detecting purposes, it is possible to add an extra bit to the data word automatically. The
transmitter calculates the value of the bit depending on the information sent. The receiver
performs the same calculation and checks if the actual parity bit value corresponds to the
calculated value.
Stop bits
Framing means, that all the data bits and parity bit are contained in a frame of start and stop bits.
The period of time lying between the start and stop bits are a constant defined by the baud rate
and number of data and parity bits. The start bit has always space value, the stop bit always mark
value. If the receiver detects a value other than mark when the stop bit should be present on the
line, it knows that there is a synchronization failure. This causes a framing error condition in the
receiving UART.
The stop bit identifying the end of a data frame can have different lengths. Actually, it is not a
real bit but a minimum period of time the line must be idle (mark state) at the end of each word.
On PC's this period can have three lengths: the time equal to 1, 1.5 or 2 bits. 1.5 bits is only used
with data words of 5 bits length and 2 only for longer words. A stop bit length of 1 bit is possible
for all data word sizes.
b) RS485 Protocol:
RS485 is the most versatile communication standard in the standard series defined by the EIA, as
it performs well on all four points. That is why RS485 is currently a widely used communication
interface in data acquisition and control applications where multiple nodes communicate with
each other.
Differential signals withRS485
Longer distances and higher bit rates
One of the main problems with RS232 is the lack of immunity for noise on the signal
lines. The transmitter and receiver compare the voltages of the data- and handshake lines with
one common zero line. Shifts in the ground level can have disastrous effects. Therefore the
trigger level of the RS232 interface is set relatively high at ±3 Volt. Noise is easily picked up
and limits both the maximum distance and communication speed. With RS485 on the contrary
there is no such thing as a common zero as a signal reference. Several volts difference in the
ground level of the RS485 transmitter and receiver does not cause any problems. The RS485
signals are floating and each signal is transmitted over a Sig+ line and a Sig- line. The RS485
receiver compares the voltage difference between both lines, instead of the absolute voltage level
on a signal line. This works well and prevents the existence of ground loops, a common source
7
of communication problems. The best results are achieved if the Sig+ and Sig- lines are twisted.
The image below explains why.
In the picture above, noise is generated by magnetic fields from the environment. The
picture shows the magnetic field lines and the noise current in the RS485 data lines that is the
result of that magnetic field. In the straight cable, all noise current is flowing in the same
direction, practically generating a looping current just like in an ordinary transformer. When the
cable is twisted, we see that in some parts of the signal lines the direction of the noise current is
the opposite from the current in other parts of the cable. Because of this, the resulting noise
current is many factors lower than with an ordinary straight cable. Shielding—which is a
common method to prevent noise in RS232 lines—tries to keep hostile magnetic fields away
from the signal lines. Twisted pairs in RS485 communication however adds immunity which is a
much better way to fight noise. Differential signals and twisting allows RS485 to communicate
over much longer communication distances than achievable with RS232. With RS485
communication distances of 1200 m are possible.
Differential signal lines also allow higher bit rates than possible with non-differential
connections. Therefore RS485 can overcome the practical communication speed limit of RS232.
Currently RS485 drivers are produced that can achieve a bit rate of 35 mbps.
Table Characteristics of RS485 compared to RS232
RS232 RS485
Differential No Yes
Max no. Of drivers Max
no. Of receivers
1 1 32 32
Half duplex
Full duplex
Half duplex Full
duplex
Network Topology Point-to-point Multi point
8
Max speed at 12m Max
speed at 1200 m
20kbps (1kbps) 35Mbps
100kbps
Receiver input resistance 3-7kohm 12kohm
Driver load impedance 3-7kohm 54ohm
Receiver input range ±15 V –7-12 V
Max driver output voltage ±25 V –7-12 V
Max distance 15m 1200m
We see that the speed of the differential interface RS485 is far superior to the single ended
version of RS232. To avoid reflections on longer cables it is necessary to use appropriate
termination resistors.
RS485 can be used in situations with a severe ground level shift of several volts, where at
the same time high bit rates are possible because the transition between logical 0 and logical 1 is
only a few hundred-mill volts.
Network topology with RS485:
Network topology is probably the reason why RS485 is now the favourite in data acquisition and
control applications. RS485 is the only of the interfaces capable of internetworking multiple
transmitters and receivers in the same network. When using the default RS485 receivers with an
input resistance of 12 kΩ it is possible to connect 32 devices to the network. Currently available
high-resistance RS485 inputs allow this number to be expanded to 256. RS485 repeaters are also
available which make it possible to increase the number of nodes to several thousands, spanning
multiple kilometres. It is the reason why RS485 is so popular with computers, PLCs, micro
controllers and intelligent sensors in scientific and technical applications.
In the picture above, the general network topology of RS485 is shown. N nodes are connected in
a multipoint RS485 network. For higher speeds and longer lines, the termination resistances are
necessary on both ends of the line to eliminate reflections. The RS485 network must be designed
as one line with multiple drops, not as a star. Although total cable length maybe shorter in a star
9
configuration, adequate termination is not possible anymore and signal quality may degrade
significantly.
RS485 COMMUNICATION
RS485 functionality
All the senders on the RS485 bus are in tri-state with high impedance. In most high-level
protocols, one of the nodes is defined as a master, which sends queries or commands over the
RS485 bus. All other nodes receive these data. Depending of the information in the sent data,
zero or more nodes on the line respond to the master. In this situation, bandwidth can be used for
almost 100%. There are other implementations of RS485 networks where every node can start a
data session on its own. This is comparable with the way Ethernet networks function. Because
there is a chance of data collision with this implementation, theory tells us that in this case only
37% of the bandwidth will be effectively used. With such an implementation of a RS485
network it is necessary that there is error detection implemented in the higher-level protocol to
detect the data corruption and resend the information at a later time.
There is no need for the senders to explicitly turn the RS485 driver on or off. RS485
drivers automatically return to their high impedance tri-state within a few microseconds after the
data has been sent. Therefore it is not needed to have delays between the data packets on the
RS485 bus.
RS485 is used as the electrical layer for many well-known interface standards for
Modbus. Therefore RS485 will be in use for many years in the future.
10
v. Packet structure:
We have made a protocol for the data frame in which there is 6 bytes field is there. First
byte is start of bit, second is address byte, third is control byte, fourth and fifth is for data bytes
and sixth byte is of end of frame.
STX ADDRESS CONTROL
DATA
DATA DATA ETX
Description:
• STX is start of header it act as starting mark for packet.
• ADDRESS is the address for the slave from which communication is to be done.
• CONTROL DATA contains control signal which is to be from PC to slaves in order to
control certain devices.
• Next two bytes carries data from slaves to PC.
• ETX act as end point of packet.
3. CIRCUIT DESCRIPTION:
1. Schematic diagram and PCB layout for the slave controllers is as shown below. The
project layout is made with the help of EAGLE 5.5.0 (PCB layout making software).
11
Slave controller schematic.
12
Slave controller track side layout.
Description:
1. Atmega8 is the controller used.
2. USART RxD and TxD pins are connected to data in and data out of 75176B (line driver IC)
which converts RS-232 signals into RS-485.
3. 5v constant power supply is used.
4. Separate headers for ISP and ports are provided.isp header is used for burning the controller.
5. Crystal oscillator and the Reset circuitry is connected to the appropriate controller pins.
2. Schematic diagram for main controller is as shown below. This is also made with
EAGLE 5.5.0 (PCB layout making software).
13
Master controller schematic.
14
Master controller track side layout.
Description:
1. Atmega16 is used as the main controller.
2. Multiplexer 74155N and De -multiplexer 74LS153N IC’s are used to switch between rs-232
and rs-485 communication interfaces.
3.75176b is used to convert rs-232 signals into rs-485 protocol communication.
4.5v power supply is used.
5. Various headers are taken to take the port output and input.isp header is provided for burning
process.
6. Crystal oscillator and the Reset circuitry is connected to the appropriate controller pins.
USB to serial converter:
15
We designed the system to be connected to pc via USB port, for this purpose we
developed USB to UART (AVR-CDC) converter module. AVR-CDC is a USB-RS232C
interface using the CDC (Communication Device Class) protocol. Although the bulk endpoint
required for CDC is not allowed within the low-speed USB standard, it works fine on major
platforms.
Features:
• No dedicated driver necessary. OS loads a built-in driver ("usbser.sys" on Windows).
• Very low cost. This is the cheapest solution for the USB-RS232C interface.
On Windows, an INF file is required to load the pre-installed driver when the device is
connected for the first time. The virtual COM port appears after the connection established.
The Vcc should be lower than 3.6V to meet the USB standard. Use a quartz crystal instead of
a ceramic resonator for stable connection. ATmega8/48/88 can achieve the higher transfer rate
(e.g. 38400bps) using the internal USART.
All information about AVR-CDC USB-RS232C interface is obtained from link
http://www.recursion.jp/avrcdc/index.html.
USB to Serial converter Schematic
16
USB to Serial Converter track side layout
Description :
1. There is a header SL 1 which connects RxD and TxD pins to the serial cable.
2. Output from the PC is given to COM port which is connected to the USB port of the USB
to Serial Converter.
3. Crystal oscillator is connected to the appropriate controller pin.
4. HARDWARE DESIGN:
i. Data aquisition system:
All the modules connected in the proper manner is shown below. Total setup is working
accurately according to the requirement.
17
Data Acquisition system set-up
ii. Slave controller:
The diagram shown below is of slave controller board. All the IC’s and headers used are
shown in the diagram. ADC header is used to connect the sensor output to the slave
controller. ISP header is used to programmed the slave controller with the help of USB
programmer. 75176B is the line driver IC used to convert RS-485 protocol into RS-232
protocol and vice-versa.
18
Slave controller board
iii. Main controller:
The diagram shown below is of main controller board. All the IC’s and headers used are
shown in the diagram. ISP header is used to program the main controller with the help of
USB programmer. 75176B is the line driver IC used to convert RS-485 protocol into RS-
232 protocol and vice-versa. 75LS153N is the multiplexer IC used to multiplex the
signals from serial port and RS-485 and the vice versa. 75LS155 is the demultiplexer IC
used to demultiplex the signals from serial port and RS-485 and vice versa.
19
Master controller board
iv. Sensor assembly:
We have used three sensors in our project. They are, light intensity sensor, temperature
sensor and trim pot. They are giving their data to the respective ADC of the slave
controller.
a) LDR (Light Dependent Resistors):
The resistance of the Light Dependent Resistor (LDR) varies according to the amount of
light that falls on it. The relationship between the resistance RL and light intensity Lux for a
typical LDR is
RL = 500 / Lux Kohm
20
With the LDR connected to 5V through a 3.3K resistor, the output voltage of the LDR is
Vo = 5*RL / (RL+R)
Reworking the equation, we obtain the light intensity
Lux = (2500/Vo - 500)/R
For a low cost LDR, at the same light intensity, the part to part variation in resistance can be as
high as 50%.
Lux is a derived unit based on lumen, and lumen is a derived unit based on candela.
One lux is equal to one lumen per square metre, where 4π lumens is the total luminous flux of a
light source of one candela of luminous intensity:
1 lx = 1 lm·m-2 = 1 cd·sr·m–2.
21
As with other SI units, SI prefixes can be used, for example a kilolux (klx) is 1,000 lux.
Luminance.
TABLE FOR TYPICAL VALUES OF LUX METER
Typical
value(LUX)
Area & conditions
10-5 lux Light from Sirius, the brightest star in the night sky
10-4 lux Total starlight, overcast sky
50 lux Family living room
80 lux Hallway/toilet
100 lux Very dark overcast day
320 lux Recommended office lighting (Australia)
400 lux Sunrise or sunset on a clear day. Well-lit office area
500 lux
Lighting level for an office according to the European law UNI
EN 12464
1,000 lux Overcast day]; typical TV studio lighting
10,000–
25,000 lux
Full daylight (not direct sun)[
32,000–
130,000 lux
Direct sunlight
b) Temperature Sensor - The LM35:
The LM35 is an integrated circuit sensor that can be used to measure temperature with an
electrical output proportional to the temperature (in ºC)
Features
• You can measure temperature more accurately than a using a thermistor.
• The sensor circuitry is sealed and not subject to oxidation, etc.
22
• The LM35 generates a higher output voltage than thermocouples and may not require that
the output voltage be amplified.
• It has an output voltage that is proportional to the Celsius temperature. The scale factor is
.01V/ ºC
• The LM35 does not require any external calibration or trimming and maintains an
accuracy of +/-0.4 ºC at room temperature and +/- 0.8 ºC over a range of 0 ºC to +100 ºC.
• Another important characteristic of the LM35DZ is that it draws only 60 micro amps
from its supply and possesses a low self-heating capability. The sensor self-heating
causes less than 0.1 º C temperatures rise in still air.
LM35 Temperature IC
The LM35 comes in many different packages, including the following.
• TO-92 plastic transistor-like package,
• T0-46 metal can transistor-like package
• 8-lead surface mount SO-8 small outline package
• TO-202 package. (Shown in the picture above).
Connections for LM35DZ
Typical circuit is shown below
In this circuit, parameter values commonly used are:
23
• Vc = 4 to 30v
• 5v or 12 v are typical values used.
• Ra = Vc *1000000Ω
• Actually, it can range from 80 KΩ to 600 KΩ, but most just use 80 KΩ.
Temperature measurement
• We need to use a voltmeter to sense Vout.
• The output voltage is converted to temperature by a simple conversion factor.
• The sensor has a sensitivity of 10mV / ºC.
• Use a conversion factor that is the reciprocal that is 100 ºC/V.
• The general equation used to convert output voltage to temperature is:
• Temperature ( ºC) = Vout * (100 ºC/V)
• So if Vout is 1V , then, Temperature = 100 ºC
• The output voltage varies linearly with temperature.
c) Resistance sensor:
Potentiometers are passive transducers. It has three legs; moving nut provides variance in
resistance.
Trim pot
24
From the circuit the resistance RL given by
RL = ( Vout / Vcc ) * R
So we need only to measure Vout to measure resistance.
Rl
R
25
Sensor elements board
v. USB to serial converter:
We designed the system to be connected to pc via USB port for this purpose we
developed USB to UART (AVR-CDC) converter module. AVR-CDC is a USB-RS232C
interface using the CDC (Communication Device Class) protocol. Although the bulk endpoint
required for CDC is not allowed within the low-speed USB standard, it works fine on major
platforms.
Features:
• No dedicated driver necessary. OS loads a built-in driver ("usbser.sys" on Windows).
• Very low cost. This is the cheapest solution for the USB-RS232C interface.
On Windows, an INF file is required to load the pre-installed driver when the device is
connected for the first time. The virtual COM port appears after the connection established.
The Vcc should be lower than 3.6V to meet the USB standard. Use a quartz crystal instead of
a ceramic resonator for stable connection. ATmega8/48/88 can achieve the higher transfer rate
(e.g. 38400bps) using the internal USART.
26
All information about AVR-CDC USB-RS232C interface is obtained from
http://www.recursion.jp/avrcdc/index.html.
USB to Serial converter
vi. AVR DOPER USB PROGRAMMER:
For programming the microcontroller we have developed AVR-Doper USB programmer.
Circuits and PCB layout can be obtained from site
http://rototron.info/default.aspx?Page=USBAVR/USBAVR.aspx.
AVR-Doper is an STK500 compatible In-System Programmer (ISP) and High Voltage
Serial Programmer (HVSP).It simply consists of an ATMega48 or an ATMega8 and a couple of
passive components. The programmer uses a firmware-only USB driver; no special USB
controller is needed. All firmware and USB drivers and can be downloaded from
http://www.obdev.at/products/vusb/avrdoper.html
27
USB ISP Programmer
USB ISP programmer pin out
Atmega 8
ISP connector
74HC126 IC USB connector
Power supply forward jumper
28
Features:
• HVSP allows using RESET pin for I/O, which is especially beneficial on 8 and 14 pin
devices.
• Simple hardware which can be built on a single sided PCB. No special USB chips are
needed.
• Compatible to Atmel's STK500 with built-in USB to Serial converter.
• Adjustable ISP clock allows flashing of devices clocked at very low rate, e.g. 32 kHz.
• ISP clock can be lowered with a jumper (if the programmer software does not support
setting the ISP clock).
• Second USB to Serial converter for processing debug output from the target.
• Uses USB power supply, no external supply required.
• Open Source (including firmware and schematics).
5. SOFTWARE DESIGN:
i. Visual basic 6.0
Visual Basic 6 is Microsoft’s one of the greatest version of the Visual Basic
programming language. Although writing programs can be a tedious chore at times,
Visual Basic reduces the effort required on your part and makes programming enjoyable.
Visual Basic makes many aspects of programming as simple as dragging graphic objects
onto the screen with your mouse.
Much of creating a Visual Basic program requires placing graphic objects on the screen
and setting attributes for those objects that determine how the objects are to look and
behave. Visual Basic is truly the only programming language today that beginning
programmers can learn easily. In addition, Visual Basic allows advanced programmers to
create powerful Windows applications.
Visual Basic is an enjoyable language due to its visual environment. Much of building a
Windows program in Visual Basic requires dragging and dropping graphic objects onto
the screen from a toolbox which houses those objects. Your
Windows program appears before your eyes as you add the objects. Visual Basic is one
of the first programming languages to incorporate a true WYSIWYG (What You See Is
What You Get) environment. The program that you build looks like the program users
see when they run the program from Windows.
Visual Basic is based on a language named BASIC. Visual Basic is visual and uses a
simple BASIC-like programming language, yet Visual Basic enables you to create
powerful Windows programs.
29
Visual Basic’s visual nature is more important than its programming language in many
ways. The visual interface provides your program’s character and interacts with the user.
The programming language works behind the scenes to connect the visual elements.
ii. AVR studio as IDE
AVR Studio is an Integrated Development Environment (IDE) for writing and debugging AVR
applications in Windows 9x/ME/NT/2000/XP/VISTA environments. AVR Studio provides a
project management tool, source file editor, simulator, assembler and front-end for C/C++,
programming, emulation and on-chip debugging.AVR Studio supports the complete range of
ATMEL AVR tools and each release will always contain the latest updates for both the tools and
support of new AVR devices.
AVR Studio 4 has a modular architecture which allows even more interaction with 3rd party
software vendors. GUI plug-ins and other modules can be written and hooked to the system.
Please contact us if you are interested in more information about this.
30
6. DATA FLOW DIAGRAM:
FLOW CHART FOR VB PORGRAM
N Y
Create packets for slave
device’s address at regular
intervals and send them to
master device.
Wait to receive packets from
master device.
According to address of packet
obtained data bytes and
calculate sensor output and
display them on screen.
Put control signal on control
bytes in packet and send packet
to desired slave through master.
Receive packet from master and
discard it.
If user generates
control signal from
screen
Initialize COM port in VB program
31
FLOW CHART FOR MASTER DEVICE
N
Y
Initialize UART with baud rate
57600
Enable RS232 port & receive
packets from computer
Enable RS 485 as Tx &
broadcast packets to all slaves.
Enable RS485 port as rx &Wait
until reply from slaves.
Receive packet from slave.
Enable RS 232 port & transmit
packet to computer.
Discard packet
If packet address
matches with
connected
slaves.
32
FLOW CHART FOR SLAVE DEVICE
ADC complete ISR
Initialize UART with baud rate 57600 &
RX complete interrupt also initialize ADC
with ADC complete interrupt.
Enable RS 485 as Rx
Do nothing and call ADC &
UART RX complete ISR when
ADIF & RXC flags are set.
ADC complete ISR
Return
Copy REGISTER ADCL &
ADCH to tempH& tempL
33
N
Y
RXC complete ISR
RXC complete ISR
Receive packet from slave.
Copy ADC data to data byte of
packet.
If address
matches
Enable RS 485 port as tx and
transmit whole packet.
Enable RS 485 port as Rx
Return
34
7. PROGRAMMING LOGIC:
i. Program for slave controllers:
#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h> //Including header files
#define STX 0x02
#define ETX 0x04
#define pack_length 0x06
void USART_Init(unsigned long int); //function to initialise USART.
void ADC_Init(void); //initialise ADC in free running mode.
void RS485_Tx_en(void); //function to enable RS-485 as tx
void RS485_Rx_en(void); //function to enable RS-485 as Rx
unsigned char USART_Receive(void); //function to rx single character
void USART_Transmit( unsigned char); //function to tx single character
void PACKET_RX(void); //0 for rs-232 & 1 for rs485
void PACKET_TX(void); //0 for rs-232 & 1 for rs485
unsigned char Address_Check(void); //function to check for right address
void read_control_sig(void); //function to read control signal from packet.
//Globle variable delaration.
unsigned char data_packet[6],data_counter=0,temp_dataH=0,temp_dataL=0;
const unsigned char Device_Address = 0x36; //for temperature sensor.
char i=0,j=0,k=0;
short isEndTwo=0;
ISR(ADC_vect) //ISR to handle ADC complete
interrupt.
temp_dataL = ADCL; //copy ADCL to temp_dataL
temp_dataH = ADCH; //copy ADCH to temp_dataH
ISR(USART_RXC_vect) //ISR to handle RXC complete
interrupt.
PACKET_RX(); //receive packet from master
data_packet[3] = temp_dataH; //copy ADC data to packet.
data_packet[4] = temp_dataL;
//_delay_ms(500);
35
if(Address_Check() && isEndTwo)
read_control_sig(); //if address matches then read control signal
PACKET_TX(); //tx packet to master.
RS485_Rx_en(); //enable RS-485 as rx
int main (void)
DDRB=0x3F; //make portB outport.
DDRC=0x00; //make portC inport for ADC.
DDRD=0xFF; //make portD outport for controls.
USART_Init(57600); //set baud rate
RS485_Rx_en(); //enable RS-485 as rx
ADC_Init(); //init. & start ADC
sei(); //enable globle interrupt flags.
while(1) //wait until interrupted.
return 0;
/////////////////////////////*FUNCTION DECLARATION*/////////////////////////
void USART_Init( unsigned long int baud)
baud = (((12000000l / (baud * 16UL))) - 1); //calculate vulue for UBRR register
UBRRH = (unsigned char)(baud>>8); // Set baud rate
UBRRL = (unsigned char)baud;
UCSRB |= (1<<RXEN)|(1<<TXEN)|(1<<RXCIE); // Enable receiver and transmitter
UCSRC |= (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1); //Set frame format: 8 data, 1 stop
bit & asynchronous comm.
void ADC_Init(void)
ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // Set ADC prescalar to 128 -
125KHz sample rate @ 16MHz
ADMUX |= (1 << REFS0); // Set ADC reference to AVCC
36
ADMUX |= (0 << REFS1); // Set ADC reference to AVCC
ADMUX |= (0 << ADLAR); // Right adjust ADC result to allow easy 8 bit
reading
// No MUX values needed to be changed to use ADC0
ADCSRA |= (1 << ADFR); // Set ADC to Free-Running Mode
ADCSRA |= (1 << ADEN); // Enable ADC
ADCSRA |= (1 << ADIE); //Enable ADC interrupt
ADCSRA |= (1 << ADSC); // 1 to Start A2D Conversions
void PACKET_RX(void)
j=0;
data_counter = 0;
for(k=0;k<=5;k++)
data_packet[k]= 0; //flush data_packet.
while(j<=5) //condition to take care of correct data
reception
i = USART_Receive(); //receive first
if(i == STX) //start of packet.
do
data_packet[data_counter++] = i;
i = USART_Receive(); //receive until whole packet rxd
while(!(data_counter == (pack_length-1)));
if(i==ETX)
data_packet[data_counter] = i; //
isEndTwo=1;
else
isEndTwo=0;
break;
j++;
37
void PACKET_TX(void)
RS485_Tx_en() ;
data_counter = 0;
do
USART_Transmit( data_packet[data_counter++] ); //code to tx data packet.
//_delay_ms(500);
while(!(data_counter == (pack_length-1)));
USART_Transmit( data_packet[data_counter] );
unsigned char Address_Check(void)
if(data_packet[1]==Device_Address) //if packet address matches with device add.
return 1 else 0
return 1;
else
return 0;
void read_control_sig(void) //reads control signal & latches control to portD
if(data_packet[2]=='1')
PORTD = 0x04;
if(data_packet[2]=='2')
PORTD = 0x00;
unsigned char USART_Receive( void )
while ( !(UCSRA & (1<<RXC)) ); // Wait for data to be received
return UDR; // Get and return received data from buffer
void USART_Transmit( unsigned char data )
UDR = data; // Put data into buffer, sends the data
38
while(!(UCSRA & (1<<TXC)));
UCSRA &= 0xfd; // Wait for empty transmit buffer
void RS485_Tx_en(void)
PORTB =0x03; //write portB to select RS485 as tx
void RS485_Rx_en(void)
PORTB =0x00; //write portB to select RS485 as rx
ii. Program for main controller:
#include <stdlib.h>
#include<string.h>
#include <avr/io.h>
#include<util/delay.h> //Including header files
#define STX 0x02
#define ETX 0x04
#define pack_length 0x06
void USART_Init(unsigned long int); //To initialise USART.
unsigned char USART_Receive(void); //To receive char from USART
void USART_Transmit( unsigned char); //To receive char from USART
void PACKET_RX(unsigned char); //0 for rs-232 & 1 for rs485
void PACKET_TX(unsigned char); //0 for rs-232 & 1 for rs485
//Globle variable delaration.
unsigned char data_packet[6],data_counter=0,i=0,j=0 ;
int main (void)
DDRA=0xFF; ////make portd outport to select RS-485.
USART_Init(57600);
while(1)
39
while(1)
PACKET_RX(0); //rx from computer.
if(data_packet[1]=='6' | data_packet[1]=='7' | data_packet[1]=='8')
break; //if packet address does not matches with connected
slaves then break
PACKET_TX(1); //tx to slaves.
PACKET_RX(1); //rx from slaves
PACKET_TX(0); //tx to computer.
return 0;
/////////////////////////////*FUNCTION DECLARATION*/////////////////////////
void USART_Init( unsigned long int baud)
baud = (((12000000l / (baud * 16UL))) - 1);
UBRRH = (unsigned char)(baud>>8); // Set baud rate
UBRRL = (unsigned char)baud;
UCSRB |= (1<<RXEN)|(1<<TXEN); // Enable receiver and transmitter
UCSRC |= (1 << URSEL) | (1 << UCSZ0) | (1 << UCSZ1); //Set frame format: 8 data, 1 stop
bit
void PACKET_RX(unsigned char port)
unsigned char i=0,j=0;
data_counter = 0;
if(port==0) //check & select rs232 port.
PORTA =0x00;
else if(port == 1) //check & select rs485 port
PORTA =0x0c;
while(j<=5)
i = USART_Receive();
if(i == STX) //start of packet.
do
data_packet[data_counter++] = i;
40
i = USART_Receive();
while(!(data_counter == (pack_length-1)));
data_packet[data_counter] = i; //end of packet
break;
j++;
void PACKET_TX(unsigned char port1)
data_counter = 0;
if(port1==0) //check & select rs232 port.
PORTA =0x00;
else if(port1 == 1) //check &select rs232 port
PORTA =0xcc;
do
USART_Transmit( data_packet[data_counter++] );
while(!(data_counter == (pack_length-1)));
USART_Transmit( data_packet[data_counter] );
unsigned char USART_Receive( void )
while ( !(UCSRA & (1<<RXC)) ); // Wait for data to be received
return UDR; // Get and return received data from buffer
void USART_Transmit( unsigned char data )
UDR = data; // Put data into buffer, sends the data
while(!(UCSRA & (1<<TXC)));
UCSRA &= 0xfd; // Wait for empty transmit buffer
iii. Visual basic programming:
a) Programming for taking the data from sensors and storing in database:
41
'Global variable declarations
Public db As Database
Public rs As Recordset
Dim k As Integer
Public sno As Integer
Dim curx As Single
Public num_sensors As Byte
Dim numFrameReceived As Byte
Dim first_Address As Byte
Dim ch As Byte
Dim interval As Byte
Dim cury() As Single
Dim xRange(1) As Integer
Dim yRange(1) As Integer
Dim yscale As Integer
Dim xscale As Integer
Dim isFanOn As Boolean
Dim isControlOn As Boolean
Dim temp As Integer
***********Procedure of command button named
cmdshow*********************************
Private Sub cmdshow_Click()
If (rs.RecordCount) Then
Form2.Show
Else
MsgBox "There is no record in the database", vbExclamation, "Warning"
End If
End Sub
***********Procedure of command button named
controlcmd********************************
Private Sub controlcmd_Click()
If ((Val(Text1(2).Text) >= Val(Text1(0).Text)) And (Val(Text1(2).Text) <=
Val(Text1(1).Text))) Then
If (MSComm1.PortOpen) Then
sendFrame (49)
isControlOn = True
Else
MsgBox "Port is not open. Communication can't take place", vbExclamation, "DAQ"
End If
Else
MsgBox "Value of Set point must be between low limit and high limit", vbExclamation,
"DAQ"
42
End If
End Sub
***********Procedure of sendframe
function***************************************************
Private Sub sendFrame(controlData As Integer)
Dim ctr As Byte, f As Variant
Dim frame(5) As Byte
frame(0) = 49
frame(1) = 54
frame(2) = controlData
frame(3) = 0
frame(4) = 0
frame(5) = 50
For ctr = 0 To 5
f = Chr(frame(ctr))
MSComm1.Output = f
Next ctr
If (controlData = 49) Then
isFanOn = True
ImgFan.Visible = True
Else
isFanOn = False
ImgFan.Visible = False
End If
End Sub
***********Procedure of command button
deleterecord***************************************
Private Sub delreccmd_Click()
Dim Msg, Style, Title, Response, MyString
Dim i As Integer
Msg = "You will lose all previous records..Do you want to continue?"
Style = vbYesNo + vbExclamation + vbDefaultButton2
Title = "Confirmation Box"
Response = MsgBox(Msg, Style, Title)
If Response = vbYes Then
Call delRec
For i = 0 To 2
lblsensor(i).Caption = 0
Next
End If
End Sub
***********Procedure of delRec
function*******************************************************
Private Sub delRec()
db.Execute ("Delete from sensors_data")
rs.Close
43
Set rs = db.OpenRecordset("sensors_data", dbOpenDynaset)
Me.sno = 1
Call drawgrid
For ctr = 0 To length
cury(ctr) = yRange(1)
Next ctr
curx = xRange(0)
End Sub
***********Procedure of command button exit
************************************************
Private Sub exitcmd_Click()
rs.Close
db.Close
End
End Sub
***********Procedure of Form_Load
function**************************************************
Private Sub Form_Load()
Dim length As Byte, ctr As Byte
'Set number of sensors
num_sensors = 3
'Set address for first sensors
first_Address = 54
ch = first_Address
interval = 1
xRange(0) = 260
xRange(1) = 860
yRange(0) = 350
yRange(1) = 610
yscale = (yRange(1) - yRange(0)) / 10 'set no. of pixels for one Y part of 10
xscale = 40 'set no. of pixels for one X part of 10
temp = yscale
length = num_sensors - 1
ReDim cury(length) 'Dynamic allocation
Set db = OpenDatabase(App.Path & "\daq.mdb")
Set rs = db.OpenRecordset("sensors_data", dbOpenDynaset)
If (rs.AbsolutePosition = -1) Then
Me.sno = 1
For ctr = 0 To length
cury(ctr) = yRange(1)
Next ctr
Else
rs.MoveLast
For ctr = 0 To length
If (ctr = 1) Then
yscale = yscale / 5
44
End If
cury(ctr) = yRange(1) - rs.Fields(ctr + 2).value * (yscale / 10)
yscale = temp
Next ctr
Me.sno = rs.Fields("Sr No").value + 1
End If
curx = xRange(0)
VScroll1(0).value = Text1(0).Text
VScroll1(1).value = Text1(1).Text
End Sub
***********Procedure of drawgraph
function**************************************************
Private Sub drawgraph()
Dim x As Single
Dim y As Single
Dim ctr As Byte
x = curx + (xscale / 5)
If (x > xRange(1)) Then
Me.Cls
Call drawgrid
curx = xRange(0)
x = curx + (xscale / 5)
End If
rs.MoveLast
For ctr = 2 To (num_sensors + 1)
If (ctr = 3) Then
yscale = yscale / 5
End If
y = yRange(1) - (rs.Fields(ctr).value * (yscale / 10))
Line (curx, cury(ctr - 2))-(x, y), QBColor(9 + ctr)
cury(ctr - 2) = y
yscale = temp
Next ctr
curx = x
End Sub
***********Procedure of drawgrid
function**************************************************
Private Sub drawgrid()
Dim i As Integer
i = 0
Me.Line (xRange(0), yRange(0))-(xRange(1), yRange(1)), QBColor(0), BF
For x = xRange(0) To xRange(1) Step xscale
Line (x, yRange(0))-(x, yRange(1) + 5), QBColor(2)
CurrentX = CurrentX - (xscale \ 5)
CurrentY = CurrentY + 3
Me.Print i
45
i = i + 5
Next
i = 10
For y = (yRange(1) - temp) To yRange(0) Step -temp
Line (xRange(0) - 5, y)-(xRange(1), y), QBColor(2)
If (i = 100) Then
CurrentX = xRange(0) - 35
Else
CurrentX = xRange(0) - 30
End If
CurrentY = CurrentY - 3
Me.Print i
i = i + 10
Next
End Sub
***********Procedure of form_Paint
function**************************************************
Private Sub form_Paint()
'Variable Declarations
Dim x As Single
Dim i As Single
Dim j As Single
Dim value As Single
Dim c As Integer
Dim y() As Single
ReDim y(num_sensors - 1)
Call drawgrid 'Draws grid for graph
x = curx
For c = 0 To (num_sensors - 1)
y(c) = cury(c)
Next
If (x > xRange(0)) Then
For c = 2 To (num_sensors + 1)
CurrentX = x
CurrentY = y(c - 2)
rs.MoveLast
If (c = 3) Then
yscale = yscale / 5
End If
For i = x - (xscale \ 5) To (xRange(0) + 8) Step -(xscale \ 5)
rs.MovePrevious
value = Me.rs.Fields(c).value
46
j = yRange(1) - (value * (yscale / 10))
Line -(i, j), QBColor(9 + c)
Next
rs.MovePrevious
If (rs.BOF) Then
j = yRange(1)
Else
value = Me.rs.Fields(c).value
j = yRange(1) - (value * (yscale / 10))
End If
Line -(i, j), QBColor(9 + c)
yscale = temp
Next
End If
End Sub
***********Procedure of testSensor1Data
function********************************************
Private Sub testSensor1Data()
If (Val(lblsensor(0).Caption) >= VScroll1(0).value And Val(lblsensor(0).Caption) <=
VScroll1(1).value) Then
Shape1.FillColor = RGB(0, 255, 0)
If (isFanOn And (Val(lblsensor(0).Caption) <= Val(VScroll1(2).value))) Then
sendFrame (50) 'off the fan
End If
controlcmd.Enabled = False
ElseIf (lblsensor(0).Caption < VScroll1(0).value) Then
Shape1.FillColor = RGB(0, 0, 255)
controlcmd.Enabled = True
Else
Shape1.FillColor = RGB(255, 0, 0)
controlcmd.Enabled = True
End If
If (isFanOn And (Val(lblsensor(0).Caption) <= Val(VScroll1(2).value))) Then
sendFrame (50) 'off the fan
End If
End Sub
***********Procedure of testSensor2Data
function********************************************
Private Sub testSensor2Data()
Dim value As Single
value = CSng(lblsensor(1).Caption)
If (value >= 0 And value <= 20) Then
DarkShape.FillColor = RGB(0, 255, 0)
OptimumShape.FillColor = RGB(255, 255, 255)
BrightShape.FillColor = RGB(255, 255, 255)
ElseIf (value >= 21 And value <= 70) Then
47
DarkShape.FillColor = RGB(255, 255, 255)
OptimumShape.FillColor = RGB(0, 255, 0)
BrightShape.FillColor = RGB(255, 255, 255)
Else
DarkShape.FillColor = RGB(255, 255, 255)
OptimumShape.FillColor = RGB(255, 255, 255)
BrightShape.FillColor = RGB(0, 255, 0)
End If
End Sub
***********Procedure of testSensor3Data
function********************************************
Private Sub testSensor3Data()
Dim value As Single
value = CSng(lblsensor(2).Caption)
If (value >= 0 And value <= 30) Then
RngShape1.FillColor = RGB(0, 255, 0)
RngShape2.FillColor = RGB(255, 255, 255)
RngShape3.FillColor = RGB(255, 255, 255)
ElseIf (value >= 31 And value <= 60) Then
RngShape1.FillColor = RGB(255, 255, 255)
RngShape2.FillColor = RGB(0, 255, 0)
RngShape3.FillColor = RGB(255, 255, 255)
Else
RngShape1.FillColor = RGB(255, 255, 255)
RngShape2.FillColor = RGB(255, 255, 255)
RngShape3.FillColor = RGB(0, 255, 0)
End If
End Sub
***********Procedure of getbyte
function********************************************
Private Function getbyte() As Byte
Dim a As Byte
'wait as long as receive buffer is empty
While MSComm1.InBufferCount < 1
Wend
'get first 8-bits in variable a
a = Asc(MSComm1.Input)
getbyte = a
End Function
***********Procedure of lblsensor_Change
function******************************************
Private Sub lblsensor_Change(Index As Integer)
48
If (Index = 0) Then
Call testSensor1Data
ElseIf (Index = 1) Then
Call testSensor2Data
Else
Call testSensor3Data
End If
End Sub
***********Procedure of Timer_Timer
function******************************************
Private Sub Timer_Timer()
Dim ctr As Byte, f As Variant
Dim overflow As Integer
Dim frame(5) As Byte
If (interval = 1) Then
frame(0) = 49
frame(1) = ch
frame(2) = 0
frame(3) = 0
frame(4) = 0
frame(5) = 50
While (MSComm1.InBufferCount)
a = getbyte()
Wend
For ctr = 0 To 5
f = Chr(frame(ctr))
MSComm1.Output = f
Next ctr
ch = ch + 1
While (MSComm1.InBufferCount = 0)
overflow = overflow + 1
If (overflow = 2000) Then
MsgBox "Data is not being received", vbCritical, "Error"
Call stop_comm 'Stop communication
Exit Sub
End If
Wend
Timer.interval = 1
Call mscomm1_OnComm
Else
interval = interval - 1
End If
End Sub
***********Procedure of mscomm1_OnComm
function***************************************
49
Private Sub mscomm1_OnComm()
'Variable Declarations
Dim data As Long
Dim sensors_data As Single
Dim ctr As Byte, Index As Byte, a As Byte, c As Byte
Dim frame(5) As Byte
Dim v As Single
'Check whether data is received or not
If (MSComm1.CommEvent = comEvReceive) Then
a = getbyte()
If a = 49 Then
'Building frame
frame(0) = a
frame(1) = getbyte()
frame(2) = getbyte()
frame(4) = getbyte()
frame(3) = getbyte()
frame(5) = getbyte()
'concatnate frame(3) and frame(4) to get 16-bit data
data = 0
data = data + frame(3)
For ctr = 1 To 8
data = 2 * data
Next
data = data + frame(4)
'Now right shift 16-bit data to 6 places to get 10-bit data
For ctr = 1 To 6
data = data \ 2
Next
'set value of index based on the sensor's address ( i.e. frame(1))
Index = frame(1) - first_Address
If (Index = 0) Then
'convert 10-bit sensor-1 data into actual data using conversion formula
sensors_data = (data * 100) / 1024 'Temperature conversion formula
ElseIf (Index = 1) Then
'convert 10-bit sensor-2 data into actual data using conversion formula
50
v = 5 / 1024 * data
If (v < 0.5) Then
v = 0.5
End If
sensors_data = (250 / v) - 50 'Light Intensity conversion formula
Else
'convert 10-bit sensor-3 data into actual data using conversion formula
sensors_data = (data * 100) / 1024 'Resistance conversion formula
End If
'Display Data into appropriate field
lblsensor(Index).Caption = sensors_data
Else
MsgBox "There is some data loss in communication", vbCritical, "Error"
Call stop_comm 'Stop communication
Exit Sub
End If
numFrameReceived = numFrameReceived + 1
If (numFrameReceived = num_sensors) Then
'when data has been received from all the sensors, insert all sensor's data
'into database
rs.AddNew
rs.Fields("Sr No").value = Me.sno
rs.Fields("Time And Date").value = Now
For ctr = 2 To Form1.num_sensors + 1
rs.Fields(ctr).value = CSng(lblsensor(ctr - 2).Caption)
Next ctr
rs.Update
Me.sno = Me.sno + 1
' insertion completed
'Draw values on graph
Call drawgraph
'now reset values of variables, because recordings of this time has been completed
numFrameReceived = 0
ch = first_Address
Timer.Enabled = False
Timer.interval = 1000
Timer.Enabled = True
51
'Set Time delay in seconds between two recordings
interval = 1
End If
End If
End Sub
***********Procedure of command button start
************************************************
Private Sub startcmd_Click()
On Error GoTo ErrorHandler
MSComm1.CommPort = VScroll7.value
MSComm1.Settings = "57600,N,8,1"
MSComm1.InputLen = 1
MSComm1.PortOpen = True
startcmd.Enabled = False
stopcmd.Enabled = True
VScroll7.Enabled = False
controlcmd.Enabled = True
Timer.Enabled = True
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbExclamation, "Warning"
End Sub
***********Procedure of command button stop
************************************************
Private Sub stopcmd_Click()
Call stop_comm
End Sub
***********Procedure of stop_comm
function************************************************
Private Sub stop_comm()
VScroll7.Enabled = True
stopcmd.Enabled = False
startcmd.Enabled = True
MSComm1.PortOpen = False
controlcmd.Enabled = False
Timer.Enabled = False
End Sub
***********Procedure of txtchange
function************************************************
Private Sub txtchange(Index As Integer)
If (Val(Text1(Index).Text) Or Text1(Index).Text = "0") Then
If (Val(Text1(Index).Text) >= 0 And Val(Text1(Index).Text) <= 100) Then
VScroll1(Index).value = Val(Text1(Index).Text)
52
Else
MsgBox ("Value is out of range")
Text1(Index).Text = 0
End If
Else
If (Text1(Index).Text <> "") Then
MsgBox ("Invalid Value")
Text1(Index).Text = 0
End If
End If
End Sub
***********Procedure of Text1_Change
function**********************************************
Private Sub Text1_Change(Index As Integer)
Call txtchange(Index)
End Sub
***********Procedure of VScroll1_Change
function*******************************************
Private Sub VScroll1_Change(Index As Integer)
Text1(Index).Text = VScroll1(Index).value
If (Val(Text1(0).Text) > Val(Text1(1).Text)) Then
MsgBox "Low limit can't exceed High limit", vbExclamation, "Warning"
Text1(0).Text = Val(Text1(1).Text)
Else
If (lblsensor(0).Caption <> "") Then
Call testSensor1Data
End If
End If
End Sub
Private Sub VScroll7_Change()
Text7.Text = VScroll7.value
End Sub
b) Programming for making the database:
***********Procedure of setFlex function*******************************************
Public Sub setFlex()
Dim ctr As Byte
fg.TextMatrix(0, 0) = "Sr No"
fg.TextMatrix(0, 1) = "Time And Date"
53
fg.ColWidth(0) = 700
fg.ColWidth(1) = 2000
For ctr = 2 To Form1.num_sensors + 1
fg.TextMatrix(0, ctr) = "Sensor" + CStr(ctr - 1)
fg.ColWidth(ctr) = 1500
Next
For ctr = 0 To (Form1.num_sensors + 1)
fg.Row = 0
fg.Col = ctr
fg.CellFontBold = True
fg.ColAlignment(ctr) = 3
Next ctr
End Sub
Sub fillGrid()
Dim T As Integer, ctr As Integer
Form1.rs.MoveFirst
Do While Not Form1.rs.EOF
T = T + 1
For ctr = 0 To (Form1.num_sensors + 1)
fg.TextMatrix(T, ctr) = Form1.rs.Fields(ctr)
Next ctr
totalrec.Caption = "Total Records: " + CStr(fg.Rows - 1)
Form1.rs.MoveNext
fg.Rows = fg.Rows + 1
Loop
Form1.rs.MoveFirst
End Sub
***********Procedure of fg_Click
function*******************************************
Private Sub fg_Click()
End Sub
Private Sub Form_Load()
fg.Cols = Form1.num_sensors + 2
Call setFlex
Call fillGrid
End Sub
54
8. Results of design:
i. Accuracy:
All the sensors are providing the output according to the formula provided in their datasheet. As
the network is RS-485 there is less interference of noise or radiations on the data. All the data
from the sensors is represented graphically and numerically in very user friendly manner with the
help of visual basic. Therefore results are shown accurately with only ±1% deviation from
original value.
ii. Speed of execution:
We have transmitted and receive the data at 9600baud to 57600baud. Our system works better at
the higher baud value than at the low values. Perfect execution occurs at 57600 baud.
iii. Graphical representation of data:
All the sensors output are shown graphically in the visual basic software. It gives the
comparative values for 75sec. which gives perfect sensing of low and high output values for a
particular sensor. It also gives the knowledge of values of different sensor output in a particular
span of time.
55
There is also separate text representation of sensors output which give their values in figure. This
shows the exact output value for every sensor at particular time in its respective text box.
iv. Database:
All the output values from all sensors are being stored in a database file named “daq.mdb”. There
is a separate column for the sr. no., date and time, sensor1, sensor2, sensor3 which shows the
sensors output value at a particular date and time. This record is very useful when we are
interested in knowing the value of any physical quantity at a particular date and time.
v. Usability:
This Data acquisition, logging and control system can be used in areas where there is
requirement of knowing the values of particular physical quantity. At present we are only
measuring the temperature, light intensity and trim pot resistance values but it can be extended to
every analog or digital sensors output value.
The system can be used especially in noisy industrial environment as the network is of RS-485
type which less interfere with the noise or radiation. The system is also capable of controlling
physical quantity which is being measured. This is shown in temperature sensor control in the
form 1 of visual basic. We are activating a fan when the temperature exceeds or go below a
particular value. Therefore we can control a physical quantity when required manually. It can
also extend to automatic control of physical quantity by some programming.
A database file is there to store the output value of sensors. A good user interface is provided for
seeing and controlling the sensors output values. This all makes this system to acquire, log as
well as control the sensors output value. This system can be used in all the industries where there
is requirement to sense and control a physical quantity.
56
9. CONCLUSION:
Our main aim of this project is to take the sensors data and forward to the pc accurately with the
help of RS-485 network accurately. This is being fulfilled wholly and correctly.
We have taken simple sensor assembly as that of temperature sensor, light sensor and trim pot
which are giving values of respective physical quantity accurately. Temperature sensor is
converting the surrounding temperature into the voltage according the formula provided in the
data sheet. Light sensor is sensing the surrounding light intensity accurately and converting that
value into its respective voltage with the help of some biasing circuitry. Trim pot is giving its
resistance into voltage which is sensed accurately.
All the sensors are giving their data to the particular slave controller board which converts this
analog value into digital with help of their A/D converters. The 10 bit value corresponding to the
voltage is representing true physical quantity. That 10 bit value is taken into fourth and fifth byte
of 6byte data frame. All the slave controllers have their unique address from which they are
being recognized in the network.
As every data frame contains the address of respective slave controller therefore it is being
recognized easily at the main controller that from which slave controller data has came. The RS
485 network is taken for the common junction between main and slave controllers. Working of
this network is tested and it is working perfectly according to the requirement. The values of the
respective sensors is represented graphically and numerically on the form made in visual basic.
All the conversion and the representation of the quantity is working in the best manner which is
required.
The system is built in such a manner that the extension and the modifications can be done easily.
If there is requirement of any slave controller then it can be done by simply adding one more
address in our programming. if there is requirement of adding more sensors on any existing slave
controller then it can be done by simply adding two more bytes in the 6bytes frame in the data
area and modify the code accordingly.
57
10. ERRORS & PRECAUTIONS:
The following errors are encountered from very beginning of our project development:
1. Baud rate is also one problem that at 9600baud the system is not responding accurately
while at 57600baud system is performing at its peak.
2. At first we have make the RS -485 junctions (where all the RS -485 lines from the slave
controllers come) open with no bias. Due to this there is reflection from that end and the
result at the hyper terminal is not the required one. Solution of this problem was the
introduction of one 120ohm resistor at the open end. This allows no reflected waves to
introduce again in the circuit. After this the results are accurate.
3. We have made all the power supplies to the slave, sensor assembly and the main
controller at one point. At first we think that it is enough to give the voltage of 8-9 v from
the adapter but when the system becomes hang again and again and giving the “data is
not being received” this makes to think more. After that by thinking that it is the loading
problem we have increased the power supply from the adapter to 11-12v and then this
makes the system to work properly.
4. While burning special attention should be paid on the fuse bits and lock bits settings. In
fuse bit settings if external clock frequency is set at 8 Mhz and you are using 12mhz
crystal oscillator then there will be wrong results. We should also see whether RC
oscillator is selected or not. If yes then it will make the onboard crystal oscillator
ineffective. Therefore first check the fuse bits and then make the burning procedure to go.
There must no lock bits should be selected.
58
11. ESTIMATED COST:
Sr. No. Component Value Quantity Cost
1. Atmega8 5 80 * 5 = 400
2. Atmega16 1 160
3. 75176B 4 40* 4 =160
4. 74153N 1 50
5. 74LS155 1 45
6. 7805 4 40
7. Headers 130 130
8. LDR 1 10
9. Temperature
sensor
1 70
10. Trim Pot 1 10
11. Crystal
Oscillator
5 5 * 10 = 50
12. Resistors 15 15 * 1 = 15
13. Capacitors 30 30 * 1 = 30
14. Switches 8 8 * 2 =16
15. Connectors 30 30 * 2 = 60
16. USB cable &
connectors
30
17. Copper plate 1*1 feet*feet 80
18. Total 1356
59
BIBLIOGRAPHY:
http://www.google.co.in
http://www.recursion.jp/avrcdc/index.html.
http://rototron.info/default.aspx?Page=USBAVR/USBAVR.aspx.
http://www.obdev.at/products/vusb/avrdoper.html
http://www.avrfreaks.com
http://www.atmel.com
http://www.alldatasheets.com
http://www.edutalks.org