User Interface for a Hardware Model of a Biological
Document Sample


Senior Design Project 2007
DSRC Accident Warning System at
Intersection
Final Report
Team Pishro-Nik and Ni
Members:
Richa Prasad . Raza Kanjee . Hui Zhu . Thai Nguyen
Professor Pishro-Nik Professor Ni
Advisor, ECE Advisor, CEE
May 24, 2007
Contents
1 PROBLEM STATEMENT
1.1 Background........................................................................................................ 1
1.2 The Design ........................................................................................................ 1
1.3 Deliverables...................................................................................................... 3
2 REQUIREMENT SPECIFICATIONS
2.1 Principle of Operation & System Block Diagram............................................... 6
2.2 Input................................................................................................................ 7
2.3 Output............................................................................................................. 7
2.4 Acceptability Test............................................................................................. 8
2.5 Product Cost .................................................................................................... 8
3 TECHNOLOGY SURVEY
3.1 Global Positioning System ................................................................................ 9
3.2 Transceiver ..................................................................................................... 18
3.3 Current State-of-Art Practice .......................................................................... 22
3.4 Project Specifications...................................................................................... 26
4 SYSTEM COMPONENTS
4.1 Latency Calculations ....................................................................................... 27
4.2 Traffic Light.................................................................................................... 34
4.3 Transceiver Communication .......................................................................... 36
4.4 GPS-Laptop Communication.......................................................................... 39
4.5 GPS Data Reception by RSE ........................................................................... 43
4.6 RSE Algorithm................................................................................................ 44
4.7 Testing & Debugging...................................................................................... 49
5 STATISTICAL ANALYSIS
5.1 Confidence of False Alarm.............................................................................. 54
5.2 Frequency of Alarm with Distance ................................................................. 54
5.3 GPS Inaccuracy............................................................................................... 56
5.4 Confidence of Transceiver Connection Range ............................................... 57
6 SUMMARY
6.1 Conclusion ..................................................................................................... 58
6.2 Future Work .................................................................................................. 58
7 BIBLIOGRAPHY ................................................................................................. 59
8 APPENDIX
8.1 Roadside Equipment Code ............................................................................. 60
8.2 OnBoard Equipment Code ............................................................................ 89
1 PROBLEM STATEMENT
1.1 Background
Vehicle collisions at intersections account for a large percentage of overall traffic
accidents. Figure 1 shows three of the most common ways for collisions at intersections.
Figure 1: Common reasons for collisions at intersections
The situations illustrated in Figure 1 account for 65% of injury accidents and 70% of fatal
accidents [1]. It is also true that for the past thirty years, the annual fatality rate due to
traffic accidents in the United States has been over 40,000.
We can prevent a large number of these accidents from occurring if we could provide
drivers with warnings about potential collisions. For example, if a system could warn a
car sitting at an intersection that another car is about to run the light, the driver waiting at
the intersection would then not immediately start driving the minute the light turns green
for him since he would be aware that there could be a potential collision with a car
running the light.
Our project concentrates on using technology to provide warnings to drivers about
potential accidents and collisions at intersections.
1.2 The Design
Vehicle Infrastructure Integration
The Accident Warning System we plan on creating falls under a broader system called the
Vehicle Infrastructure Integration (VII). This system enables real-time wireless
communication between cars and between cars and static intelligent stations or units to
help create an efficient and safe transportation system. VII is a massive system whose
various applications and technologies are under research and testing in various parts of
the world – especially in the United States and Europe. Figure 2 illustrates the many
varied applications of VII.
1
Figure 2: Applications of VII
• Safety
Other than accident warning systems at intersections, the other ways to provide
safety to drivers is to also provide them with path and speed suggestions.
Pedestrian warning could be implemented alongside warnings of potential car
collisions. Furthermore, on a straight road, when a car is attempting to overtake
another car, then the VII system could help in completing the maneuver
successfully and safely.
• Entertainment
There would no longer be a need to carry iPods or wait on popular radio stations
for a particular favorite song. The driver could simply request a song to be played
and the VII system would play that song. This could further be expanded if the
driver wanted to play verbal trivia or some other games while driving.
• Tutor
The VII system could act as a tutor to amateur drivers in training to earn their
license. The trainees could be provided suggestions and evaluations on how they
are driving and what they could do to improve their driving.
• Traffic Management
This ties up with the safety aspect of VII. Data on the traffic situations at various
parts of a highway or region of a state could be transmitted to a remote traffic
station from where traffic management at a large scale could occur.
• Routing
This is an aspect of VII which is already in use currently. Planning routes to
destinations will continue to be part of the VII experience.
• Weather
Each car will be equipped with weather sensing technology. Detailed information
such as humidity, cloud cover, temperature, etc would be read by a car and
transmitted to a weather station. This would allow weather stations to have real-
time accurate data on weather conditions in even remote areas, thus providing
weather stations with the capability of more accurate weather prediction.
These are only some of the applications of VII.
2
Dedicated Short Range Communication
Dedicated Short Range Communication (DSRC) is a wireless communication protocol in
the 5.9 GHz frequency band with a bandwidth of 75 MHz [2]. It refers to short to
medium range wireless communications that offers data transfer in a vehicular ad-hoc
network. The IEEE Standard for it is 802.11p. This standard is exclusively for
transportation communication systems.
1.3 Deliverables
Our project exclusively focuses on the Safety aspect of VII using DSRC. The goal of our
project is illustrated by Figure 3.
Figure 3: Accident Warning System at Intersections
There are two types of messages that can be sent from the OnBoard Equipment to the
Roadside Equipment. They contain information on the speed and location of the car in
which the transmitting OnBoard Equipment is located.
1. Status Messages
The Roadside Equipment receives these and simply logs them. No action is taken
on these messages.
2. Event Messages
The Roadside Equipment needs to take action on the basis of these messages.
From Figure 3, we notice two main components of the accident warning system:
1. Roadside Equipment (RSE)
This is a component of the system which acts as the central unit. It is in constant
contact with the traffic light in order to determine when the light will turn red.
Once it realizes that the light will turn red, it starts treating all messages from the
OnBoard Equipment as Event Messages. Hence, it uses the speed and location
information being transmitted to determine whether the car transmitting the
message will run the red light, and if it will, then it needs to warn the other cars of
this possibility.
3
2. OnBoard Equipment (OBE)
This is a component of the system located within a car. It constantly calculates the
speed and location of the car, and transmits this information to the Roadside
Equipment. It also receives the warning signal from the Roadside Equipment
telling it to activate the alarm system in order to warn the driver of whether a car
will run the light.
We have further narrowed our goal by placing the following restrictions on our project:
1. Range of DSRC communication
The transceiver range is limited to about 250 meters. We have chosen 250 meters
because of the following concerns:
a. Closely located intersections
If there are closely located intersections, then we do not want the data
and warnings being communicated to overlap. Hence, in order to prevent
such a fiasco, we have chosen 250 meters of communication range since it
limits the system of communication to one intersection.
b. Irrelevancy of warnings to cars far away from the intersection
If a car is far away from an intersection, then even though it receives the
warning of another car running the light, that information is irrelevant to it
since it is not in any danger of colliding with the speeding car.
Figure 4 illustrates how the Roadside Equipment and OnBoard Equipment are
only aware of the traffic around a certain limited range around them.
Figure 4: Range of awareness of OBE and RSE
2. System of Communication
There will be no communication between cars. All communication will occur
between the Roadside Equipment and the OnBoard Equipment. This aspect of the
project is shown in Figure 5.
4
Figure 5: Only RSE-OBE Communication
Thus to summarize, the following are the goals of our project:
1. Accident Warning System of only whether a car will run the red light
This means that there will be no path and speed suggestion provided to the
driver. There will also be no warning for pedestrians crossing the road. The
project only deals with warning a driver if another car is about to run the red
light.
2. Limitation to only one speeding car
Unlike a real-life scenario, there will only be one car approaching the intersection,
and one other car receiving a warning of whether the approaching car will run the
red light.
3. Real-Life demonstration
We hope to accomplish a real-life demonstration of the working project.
4. Technical Documentation
A comprehensive documentation will be completed and delivered to the advisors
of this project.
5
2 REQUIREMENT SPECIFICATIONS
2.1 Principle of Operation & System Block Diagram
The principle of operation is illustrated by the System Block Diagram depicted in Figure 6.
Figure 6: System Block Diagram
6
Speeding Car
OnBoard Equipment consists of a GPS which constantly determines the location and
speed of the car in which the unit is located. This information is logged by a laptop
and sent to the transceiver, which sends it to the Roadside Equipment.
Roadside Equipment
The Roadside Equipment transceiver receives the speed and location information from
the OnBoard Equipment. It verifies if the light is turning red anytime soon, and if it is
then it calculates whether the speeding car will run the red light. If it will run the red
light, then a warning signal is sent to the transceivers of all OnBoard Equipments.
Traffic Light
We are simulating the traffic light on a microcontroller. The microcontroller has an
external clock which helps it keep track of the period of time the light should remain
a certain color. It is directly connected to the Roadside Equipment laptop, to which it
sends a control signal defining the point after which the Roadside Equipment needs to
consider all messages from the OnBoard Equipment as Event Messages.
Warning Signal
If the speeding car will run the red light, then a warning message is sent from the
Roadside Equipment transceiver to the transceivers on the OnBoard Equipments of
the speeding car as well as the waiting car.
2.2 Input
There are two inputs to the Accident Warning System.
1. GPS
This input contains information on the speed and location of the car in which the
GPS is located. It is constantly sent to the Roadside Equipment.
2. Traffic Light
This input allows the Roadside Equipment to judge when to regard the speed and
location information from the OnBoard Equipment as Event Messages.
2.3 Output
There are two kinds of output from the Accident Warning System.
1. Warning Signal
A warning signal is sent from the Roadside Equipment transceiver to the OnBoard
Equipment transceiver of the speeding and waiting cars in order to warn both cars
that the speeding car is about to run the red light.
2. No Action
If the speeding car will not run the red light, then no action is taken by the
Roadside Equipment and hence no warning signals are received by the OnBoard
Equipments.
7
2.4 Acceptability Test
The acceptability test is to ensure the successful execution of the real-life demonstration of
an accident warning system involving a single speeding car. If the car is about to run the
red light, then a warning should flash on the laptops of the speeding and waiting car. If it
is not going to run the red light, then no action should be taken.
2.5 Product Cost
8
3 TECHNOLOGY SURVEY
3.1 Global Positional System
Overview
The Global Positioning System, or GPS, can show you your exact position on Earth any
time, anywhere, in any weather. The system consists of a constellation of 24 satellites that
orbit 11,000 nautical miles above Earth’s surface and continuously send signals to ground
stations that monitor and control GPS operations.
GPS satellite signals can be detected by GPS receivers, which calculate their locations
anywhere on Earth within a meter by determining distances from at least three GPS
satellites. No other navigation system has ever been so global or so accurate.
GPS, formally known as the Navstar Global Positioning System, was initiated in 1973 to
reduce the proliferation of navigation aids. By creating a system that overcame the
limitations of many existing navigation systems, GPS became attractive to a broad
spectrum of users worldwide. GPS has been successful in virtually all navigation
applications, and because its capabilities are accessible using small, inexpensive equipment,
GPS is being utilized in a wide variety of applications across the globe.
Figure 7: Constellation of Satellites
The principle behind GPS is the measurement of distance (or “range”) between the
satellites and the receiver. The satellites tell us exactly where they are in their orbits by
broadcasting data the receiver uses to compute their positions. It works something like
this: If we know our exact distance from a satellite in space, we know we are somewhere
on the surface of an imaginary sphere with a radius equal to the distance to the satellite
radius. If we know our exact distance from two satellites, we know that we are located
somewhere on the line where the two spheres intersect. And, if we take a third and a
fourth measurement from two more satellites, we can find our location. The GPS receiver
processes the satellite range measurements and produces its position.
GPS uses a system of coordinates called WGS 84, which stands for World Geodetic System
1984. Likewise, GPS uses time from the United States Naval Observatory in Washington,
D.C., to synchronize all the timing elements of the GPS system.
9
Figure 8: GPS Principles of Working
Figure 9: GPS Working Stepwise
The basic GPS service provides users with approximately 100-meter accuracy, 95% of the
time, anywhere on or near the surface of the earth. To accomplish this, each of the 24
satellites emits signals to receivers that determine their location by computing the
difference between the time that a signal is sent and the time it is received. GPS satellites
carry atomic clocks that provide extremely accurate time. The time information is placed
in the codes broadcast by the satellite so that a receiver can continuously determine the
time the signal was broadcast. The signal contains data that a receiver uses to compute the
locations of the satellites and to make other adjustments needed for accurate positioning.
The receiver uses the time difference between the time of signal reception and the
broadcast time to compute the distance, or range, from the receiver to the satellite. The
receiver must account for propagation delays, or decreases in the signal's speed caused by
the ionosphere and the troposphere. With information about the ranges to three satellites
and the location of the satellite when the signal was sent, the receiver can compute its
own three-dimensional position. An atomic clock synchronized to GPS is required in
order to compute ranges from these three signals. However, by taking a measurement
from a fourth satellite, the receiver avoids the need for an atomic clock. Thus, the receiver
uses four satellites to compute latitude, longitude, altitude, and time.
10
Working Principles of GPS
The GPS works in five logical steps:
• Trilateration
• Measuring Distance
• Precise Timing
• Satellite Positioning
• Error Correction
• Position is calculated from distance
measurements (ranges) to satellites.
• Mathematically four satellite ranges are
needed to obtain exact position.
Figure 10: Step 1 – Trilateration of Three Satellites
• Distance to a satellite is determined by measuring how
long a radio signal takes to reach us from that satellite.
• To make the measurement we assume that both the
satellite and our receiver are generating the same
pseudo-random codes at exactly the same time.
• By comparing how late the satellite's pseudo-random
code appears compared to our receiver's code, we
determine how long it took to reach us.
• Multiply that travel time by the speed of light and
you've got distance.
Figure 11: Step 2 – Measuring Distance
11
• Accurate timing is the key to measuring
distance to satellites.
• Satellites are accurate because they have
atomic clocks on board.
• Receiver clocks don't have to be too accurate
because an extra satellite range measurement
can remove errors.
Figure 12: Step 3 – Precise Timing
• To use the satellites as references for range
measurements we need to know exactly where they are.
• GPS satellites are so high up their orbits are very
predictable.
• Minor variations in their orbits are measured by the
Department of Defense.
• The error information is sent to the satellites, to be
transmitted along with the timing signals.
Figure 13: Satellite Location
12
Figure 14: Error Correction
In the real world there are lots of things that can happen to a GPS signal that will make its life less
than mathematically perfect. Some of the prominent sources and solutions to errors are:
• As a GPS signal passes through the charged particles of the ionosphere and then through the
water vapor in the troposphere it gets slowed down a bit. A way to get a handle on these
atmosphere-induced errors is to compare the relative speeds of two different signals. This
"dual frequency" measurement is very sophisticated and is only possible with advanced
receivers.
• Trouble for the GPS signal doesn't end when it gets down to the ground. The signal may
bounce off various local obstructions before it gets to our receiver. This is called multipath
error and good receivers use sophisticated signal rejection techniques to minimize this
problem.
• The atomic clocks they use are very, very precise but they're not perfect. Minute
discrepancies can occur, and these translate into travel time measurement errors.
• The policy called "Selective Availability" or "SA" and the idea behind it was to make sure that
no hostile force or terrorist group can use GPS to make accurate weapons. Basically the DoD
introduced some "noise" into the satellite's clock data which, in turn, added noise (or
inaccuracy) into position calculations. The DoD may have also been sending slightly
erroneous orbital data to the satellites which they transmitted back to receivers on the
ground as part of a status message. On May 1, 2000 the White House under President
Clinton’s administration signed a Presidential Order to discontinue the intentional
degradation of the GPS signals to the public beginning at midnight.
13
Civilian Accuracy Technology
Prior to 1 May 2000 Global Positioning Systems accurate up to 100 meters (300 feet) due
to “Selective Availability” feature enabled by he Department of Defense to prevent
terrorist and rouge nations from using GPS as a targeting mechanism. The U.S. military
was able to quickly develop and test their ability to selectively block accurate GPS
transmissions in areas of conflict or where U.S. security was at risk. When the U.S. Air
Force Space Command turned off SA last night, GPS became incredibly accurate for the
entire planet. After President Clinton signed the Executive Order removing. This allowed
GPS receivers to be accurate up to 10 meters (60 feet). Accuracy up to 10 meters is not
enough for various civilian applications such as GIS, mapping, construction, mining and
vehicle tracking. Hence, to overcome this inaccuracy in tracking, a couple of other
techniques were used to bypass the limitations put fourth by the Department of Defense
to make bring the accuracy up to 5 centimeters (2 inches). The following three
technologies have been implemented by the Federal Aviation Administration,
Department of Transportation and various other groups to improve the accuracy of GPS
signals.
• Wide Area Augmentation System (WAAS)
The Federal Aviation Administration (FAA) has designed a Satellite Based
Augmentation Systems (SBAS) to improve the accuracy, integrity and availability
of the Global Positioning System (GPS) required by civilian throughout the United
States. The SBAS designed by the FAA is called the Wide Area Augmentation
System (WAAS). Since a GPS unit already consists of a satellite receiver, correction
signals were sent out on these frequencies than to use an entirely separate system
and thereby double the probability of failure. Existing GPS satellites did not have
any additional channels that could be used for this feature, so instead it was
planned to add broadcasters to existing communications satellites. In addition to
lowering implementation costs by "piggybacking" on a planned launch, this also
allowed the signal to be broadcast from geostationary orbit, which meant a small
number of satellites could cover all of North America. WAAS has twenty-five
Wide-area Reference Stations positioned throughout the United States which
compare the GPS signal with known (surveyed) coordinates. With WAAS
implementation accuracy of the GPS increases to 3 meters (10 feet). Figure 15
shows how the accuracy of the GPS varies and its coverage throughout the United
States.
Figure 15: WAAS Accuracy and Coverage
14
• Differential Global Positioning System (DGPS)
Differential Global Positioning System or "DGPS" can yield measurements good to
a sub meter level in moving applications and even better in stationary situations.
Differential GPS involves the cooperation of two receivers, one that's stationary
and another that's roaming around making position measurements. DGPS
improves GPS accuracy by using a high-performance GPS receiver (reference
station) at a known location. Since the reference station receiver or beacon knows
its exact location, it can determine errors in the satellite signals. The error data for
each tracked satellite is formatted into a correction message and transmitted to
GPS users. These differential corrections are then applied to the GPS calculations,
removing most of the satellite signal error and improving accuracy.
Figure 16: DGPS Working
Product Overview
Market overview of the different types of GPS provided us with various options available
to us. A brief overview of the products considered for the project and why were they
rejected is provided in the table below.
Table 1: GPS Product Comparison
Product Cost USD Accuracy (WAAS) Accuracy (DGPS) Reason Rejected
GlobalSat BU-353 79.00 5 meters NA Not Accurate
Magellan AC12 Board 160.00 1 meter 0.8 meter Accepted
Magellan DG14 Board 1500.00 1 meter 40 – 70 cm Expensive
Trimble BD950 Board 2000.00 5 meters 1 meter Expensive
We chose the Magellan AC12 Board for our project because it was accurate enough for
our project requirements and also within budget. Apart from being accurate the Magellan
AC12 also had two bidirectional serial RS232 ports for communication with other
peripheral devices.
15
United States Coast Guard Beacon Coverage
NAVCEN operates the Coast Guard Maritime Differential GPS (DGPS) Service and the
developing Nationwide DGPS Service, consisting of two control centers and over 60
remote broadcast sites. The Service broadcasts correction signals on marine radio beacon
frequencies to improve the accuracy of and integrity to GPS-derived positions.
The Magellan AC12 board can use the radio frequencies from the beacons to provide
accuracies up to sub meter level. Coverage in the Amherst, MA area is provided by two
beacons. One is located in Acushnet, MA and the other is located in Hudson Falls, NY.
Figure 17 shows the coverage of the United States Coast Guard beacon signals in
Massachusetts.
Figure 17: United States Coast Guard Coverage in Massachusetts
16
Figure 18: Position of Beacon Station Relative to Amherst MA
17
3.2 Transceiver
Wireless Network IEEE Standard
The IEEE 802.11 standard denotes a set of Wireless LAN standards. The 802.11 family
includes six over-the-air modulation techniques that use all the same protocol. A brief
summary of some of the standards and their characteristics is provided in Table 2 [3].
Protocol Release Date Operational Frequency Data Rate (Typical) Data Rate (Maximum) Indoor
Range
802.11a 1999 5 GHz 25 Mbit/s 54 Mbit/s 30 m
802.11b 1999 2.4 GHz 6.5 Mbit/s 11 Mbit/s 50 m
802.11g 2003 2.4 GHz 25 Mbit/s 54 Mbit/s 30 m
802.11n 2007 2.4 GHz or 5 GHz 200 Mbit/s 540 Mbit/s 50 m
802.11p 2008 5.9 GHz 27 Mbit/s 54 Mbit/s ?
Table 2: Summary of 802.11 family
The most popular standard is the 802.11b. 802.11a and 802.11g are the second most
popular standards. The 802.11p and 802.11n standards are still under research and
standardization process. The 802.11p is specifically for DSRC VII systems.
IEEE 802.11p Standard
Bandwidth
75 MHz (5.850 – 5.925 GHz)
Channels
There are 7 non-overlapping 10 MHz channels. 2 of the channels can be combined to
make one 20 MHz channel. This is illustrated in Figure 19 [2].
Figure 19: DSRC Channel scheme in United States
It is important that all safety messages are transmitted on one designated channel in
order to ensure that all vehicles listen to the proper one for such messages.
18
Reserved Channel
This is also called the “guard channel”. 5 MHz at the lower end of the spectrum
are reserved for it.
Service Channels
Channels 172 and 184 are reserved for safety related applications. However, these
two are not meant to be an option for regular safety communication. The
remaining six channels (174, 175, 176, 180, 181 and 182) can be used for non-
safety communication.
Control Channel
This channel is strictly for safety related communication and non-safety related
communication is strictly limited in terms of transmission line and interval. This is
illustrated in Table 3.
RSE Vehicle
Maximum Data Transmission Duration 750 μs 580 μs
Minimum Interval Between Data Transmissions 100 ms 750 ms
Table 3: Control Channel usage limits for non-safety transmission in USA
Power
Usually less than 2 W but up to 30 W for qualified public safety applications on the
Control Channel.
Product Overview
There are no commercially available 802.11p transceivers. The first are scheduled to
appear in the market around 2012, according to Mr. Gary Pruitt from Arinc. Table 4
illustrates our technology survey for the Transceiver [4] [5] [6] [7].
Transceiver Company Characteristics Price Decision
OTTO on Board MarkIV Range: 300 m Not for Purchase Cannot be
802.11p Bought
Data Rate: 27 Mbps
RS232 Serial Port
Q-Free RSE and OBE Q-Free Range: 20 m - Too short
802.11p Range
RS232 Interface
USB Interface
Tsunami QuickBridge Proxim Range: 100 m $2500.00 Too
802.11a/b/g Expensive
10/100Base-TXEthernet
54 Mbps (Max)
Airbornedirect Serial Bridge Quatech Range: 100 m $236.00 Bought
802.11b/g
RS232 Interface
Wireless AP
Table 4: Overview of Transceiver Product Survey
19
Our key goals in the search of a transceiver were the following:
1. Range
The Accident Warning System is to work across a radius of 200 m around the
‘traffic light’. Hence, we need a transceiver which transmits and receives data over
a range of about 250 m.
2. Interface
We are using laptops to act as the system which logs GPS data, calculates whether
a car will run red light, and also as the system which receives the warning signal of
a car running the red light and alerts the driver. The easiest and most convenient
interface is the serial port. Hence, we looked for the RS232 port interface to be
available in the transceiver.
We began our transceiver technology survey with the assumption that a commercially
available 802.11p transceiver is available in the market. Upon researching and contacting
the companies, MarkIV and Q-Free, we realized that our assumption was incorrect.
Hence, we switched to finding an 802.11b transceiver which could work in lieu of the
802.11p transceiver. Once an 802.11p transceiver is available, then the 802.11b transceiver
could simply be replaced.
Our search for a suitable 802.11b transceiver brought us to the Proxim Tsunami
QuickBridge. This product was perfect for a transceiver except for the fact that it was too
expensive. The Quatech Airbornedirect Serial Bridge on the other hand, is as suitable as
the Proxim Tsunami QuickBridge and is also within price range. Hence, we purchased the
Airbornedirect Serial Bridge Development Kit.
The Development Kit comes with the following components [4]:
1. AirborneTM Embedded Wireless Device Server
2. Evaluation Board (6” x 9”)
3. Access Point Router
4. Quick Start Guide
5. Power Supply
6. Serial Port Cable - DB9F to DB9M
7. ISP Cable - DB25M to DB25M
8. External Antenna
9. 9 Volt Battery
10. Software CD includes:
a. Evaluation utilities
b. Kit user’s guide
c. Module firmware
d. Release notes
20
Figure 20: Airbornedirect Serial Bridge Development Kit
3.3 Current State-of-Art Practice
Global Positioning System
Currently commercial GPS receivers are capable of receiving Wide Area Augmentation
Signals (WAAS) which gives these receivers an accuracy of around 3 meters depending on
signal reception and environmental conditions. For some applications this is not an
acceptable measure of accuracy. To overcome this obstacle the civilian sector has come up
with the use of Differential Global Positioning System (DGPS) which was explained in
detail earlier. There exist two different methods of DGPS implementation that vary on
cost and accuracy.
The first implementation uses the correctional signals from the beacons placed by the
United States Coast guard, which can be accessed freely by any DGPS receiver. The only
draw back in using this implementation is being in the area that has this coverage. This
increases the accuracy of the GPS system to about 0.8 – 1 meter. A standalone GPS
receiver is not enough to implement this solution as they are not equipped to receive the
radio waves from the beacons. Two different hardware solutions are commercially
available to implement a DGPS system.
• Magellan DG14 Board is equipped with both a GPS and a DGPS receiver, in
other words, it can receive signals from both the GPS satellites and also from
the United States Coast Guard beacons and provide correction ability. This
board cost 1500 USD, which is a fairly expensive solution.
• Magellan AC12 Board can be attached to a DGPS Beacon receiver enabling it to
receive both GPS satellite signals and the Coast Guard correction beacon signals.
The AC12 Board cost 160 USD. A compatible and commercially available DGPS
receiver is provided by NAVTEQ, the SBX-3 Board, which cost 425 USD with
the DGPS antenna. This solution is relatively cheaper than the DG14 Board.
21
The second implementation makes use of local beacon stations installed and maintained
by individuals. This implementation increases accuracy to a few centimeters. The AC12
Board can be used as a GPS receiver attached to transceiver can be used, along with a
base station that has to be setup. The Magellan DG14 Board can be configured to act as a
base station, but the correctional signals from the DG14 have to be transmitted to the
receivers in the area. Two different types of transceiver solutions can be implemented that
vary in cost and signal strength.
• Freeware provides low cost spread spectrum UHF receivers that can transmit
correctional signals from the base station to the receivers. Using Freeware
transceivers does not require a FCC license but they can only be used in direct
line of sight setting due to signal characteristics. Hence, this implementation is
not possible in urban settings.
• Pacific Crest is the other type of transceiver that can be used in setting with
line of sight is not possible. This requires an FCC license and each transceiver
costs 1200 USD. One transceiver will have to be installed on the base station
and the other transceiver on the GPS receiver such as the AC12 Board.
Accident Warning System
The state-of-the-art practice is currently being done by the PReVENT organization. This is
a European project being conducted by a consortium of organizations ranging from car
companies to electronics companies to universities.
PReVENT is a much broader project than our accident warning system project. It deals
with the following fields [1]:
Safe Speed and Safe Following
• Co-operate seamlessly with the driver through the most suitable HMI channels,
and suggest the proper velocity and headway for the given driving conditions.
• Automatic detection, locating and relevance check of hazards through traffic and
weather based on onboard sensors and a positioning system such as GPS.
• Testing a local, self-organized car-to-car communication system for establishing a
decentralized communication network with both oncoming and following cars.
Lateral support and driver monitoring
• Examining a next generation adaptive lane-keeping support system, especially for
use in situations where lane markings are missing, ambiguous or when the visibility
is restricted.
• Studying a lateral and rear area monitoring application that enhances the driver’s
perception of collision risk in the lateral and rear area of the vehicle - especially
when detection is very difficult due to limited visibility or critical overload on the
driver’s attention.
22
• Testing a stand-alone lane-change assistance system with integrated blind spot
detection that assists the driver in lane-change maneuvers while driving on
multilane roads.
Intersection safety
• Speed recommendation to driver
• Predicting the trajectories of the driver’s car and other nearby vehicles
• Testing a driving simulator allowing the development of active safety applications
with state-of-the-art and future technology.
• Investigation of an intersection infrastructure able to communicate bi-directionally
with all vehicles passing the intersection. The traffic light is able to communicate
the delay for the color change, and the vehicle is able to communicate an
estimation of the friction coefficient in order to forward this information to other
vehicles arriving at the intersection.
Function field vulnerable road users and collision mitigation
• Versatile 3D sensor technology for urban collision mitigation and protection (for
pre-crash or blind spot surveillance applications),
• High performance sensor systems - including real-time object classification, capable
of reliably classifying pedestrians, bikes, motorcycles, cars and trucks
• Collision mitigation through the intervention of active structural components such
as controllable bumpers, crash boxes, motor hoods, and safety belt pre-tensioners.
• Collision mitigation through autonomous or semi-autonomous braking, which
significantly reduces kinetic impact energy by mutual adaptation and suitable
combination of sensors and actuators to achieve integrated, actuator-powered
collision mitigation systems
• Collision mitigation in terms of pre-fire and pre-set applications, aiming to
improve the efficiency of reversible (belt-pre-tensioning) and non-reversible
(airbags) restraint systems by providing additional set-up information to them
• Collision mitigation by prevention of truck acceleration from stationary, when
pedestrians or other VRUs are present in the blind spot area, in particular in front
of the truck
We are of-course only concerned with the Intersection Safety aspect. As we mentioned
earlier, the PReVENT Intersection Safety Project deals not only with an accident warning
system but also with providing speed suggestions to drivers as well as path suggestions on
the basis of trajectories calculated of other vehicles at the intersection. Traffic
management also comes into play by traffic information at the intersection being
analyzed and decisions being made upon them. Pedestrian warning is another aspect
which is not present in our project.
23
We are using only a GPS to track a car’s speed and location. The PReVENT organization
on the other hand uses a variety of technologies to accomplish the task of keeping
intersection traffic information.
Laser Sensor and Video Camera
These are within the vehicle and sense the road around for obstructions and moving
vehicles. They also guide the vehicle in which they are located in terms of speed and
path to be taken as the vehicle approaches the intersection. This is done by detecting
lane markings and the white arrows indicating turning lanes. Figure 21 shows the area
detected by the sensors.
Figure 21: Area of detection of on-board vehicle sensors
Figure 22 shows where the sensors are located in a vehicle.
Figure 22: Location of sensors in a vehicle
24
The sensors are also used to build a dynamic high-accuracy map of the intersection
using static objects. This provides an accurate position of the vehicle on the
intersection.
GPS
This provides the location of the host vehicle on the map. However, as a GPS is not
very accurate in localizing exactly where the vehicle is located on the intersection, it is
used alongside the on-board laser sensor and video camera in order to provide an
accurate position of the vehicle.
Transceiver
There are not any commercially available 802.11p transceivers in the market. Since OTTO
on Board is the only 802.11p transceiver whose data sheet is available on the web – it is
easily the state-of-art practice.
The OTTO on Board has been developed by a consortium of companies including Arinc,
MarkIV, Highway Electronics and Transcore to name a few. It is currently under test by
the US Department of Transportation. A brief summary of the important features of the
OTTO on Board are:
1. Range: 300 m
2. Data Rate: 27 Mbps
3. Interface: Serial Port
Figure 23 shows the OTTO on Board transceiver logo.
Figure 23: OTTO on Board
25
3.4 Project Specification
To summarize the Technology Survey section, our project specifications are shown in
Table 5.
Transceiver GPS
Company: Quatech Company: Garmin
IEEE Standard: 802.11b/g Accuracy: 5 m
Range: 100 m
Table 5: Project Specification
26
4 SYSTEM COMPONENTS
Hardware Components:
• DPAC Airbornedirect Serial Bridge
This is the OBE transceiver or the OnBoard Unit (OBU).
• Access Point/Router
We used a Linksys 802.11b/g router, but this can be replaced by any other
router. The Linksys router had a range of up to 100 meters and acts as the RSU
• Laptop
As our project is to be built upon, laptops were used for software
development. We used Dell Inspirion 6400 laptop for the OBE and an IBM
ThinkPad for the RSE.
• Garmin GPS
Inaccuracy of 5 meters and updates itself every second. It is directly connected
to the OBE laptop
Operating System:
• Windows 2000/XP
Software Components:
• Visual Studio 2005
Road Calculations, GPS data parsing, reception and transfer were all carried
out by C++ programs written in VS 2005. Installed on RSE and OBE laptops
• DPAC Airbornedirect Utility
This utility is installed on the RSE laptop. It allows us to fix the wireless settings
such as the baud rate, etc of Airbornedirect Serial Bridge.
• DPAC Virtual Configuration Utility
This utility is installed on the RSE laptop. It allows us to specify to the router
which wireless device it should connect to.
• Garmin GPS Spanner
GPS Spanner is a program which sets the virtual serial ports to receive data
from the GPS as well as formally starts the GPS. This is installed on the OBE
laptop.
4.1 Latency Calculations
The scenario we are considering for an accident at an intersection is called Signalized
Intersection, Straight Crossing Path. This means that the intersection consists of a traffic
27
light and we assume that the vehicle approaching the intersection plans on traveling
straight; i.e. does not plan on making a turn.
Background on SI/SCP Accidents
For the purpose of a complete study on SI/SCP accidents, we performed a background
literature search on the factors resulting in SI/SCP accidents [11]. Figure 24 provides
background on the conditions under which SI/SCP crashes occur.
SI/SCP Crash Occurrence due SI/SCP Crash Occurrence due SI/SCP Crash Occurrence due
to Pavement Condition to Ambient Weather Condition to Ambient Light Condition
Snowy or Icy Rain Dark, Dawn/Dusk
Snow/Sleet
2% 12% Unlighted 3%
12%
3%
Dark,
Dry 79% Lighted
No Adverse Daylight
22%
Wet Pavement Weather 72%
19% 66%
Figure 24: Conditions under which SI/SCP Crashes occur
As we see from these charts, most of the accidents occur during normal conditions: dry
pavement, no adverse weather conditions and daylight. Our system works for both
normal and adverse conditions. Figure 25 shows the speed at which vehicles are traveling
when the crash occurs.
18%
16%
14%
12%
10%
8%
6%
4%
2%
0%
0-5 6-10 11-15 16-20 21-25 26-30 31-35 36-40 41-45 46-50 51-55 56+
Travel Velocity (mph)
Figure 25: Travel Velocity of vehicle at time to crash
Most of SI/SCP accidents seem to occur at velocities 35 mph or lower. This might be
because of last minute rapid braking. Our system is very sensitive to rapid braking and
issues alarms prior to when the braking occurs and if after braking it detects the vehicle is
safe, the alarm stops. Figure 26 shows the most common reasons for the incidence of
accidents.
28
Vision Obstructed 4.3%
Vehicle Defect 1.9%
Other 5.9% Driver Inattention
36.4%
Driver Intoxication
12.9%
Failed to Obey Signal
23.2%
Tried to beat Signal 16.2%
Figure 26: Reasons for SI/SCP Crashes
Since the aim of our system is to alarm the driver on offense and the vehicles in the
vicinity of the intersection of a possible collision, we directly address the issues of driver
inattention, trying to beat the signal, and vision obstruction. These factors contribute to
57% of the accidents.
Road Calculations
There are four main to consider when judging whether a vehicle will run the red light.
1. Travel Speed
2. Time left before light turns red or remains red
3. Acceleration rate
4. Driver and machine reaction time delays
In order to address these factors, we need to consider some terminologies. Figure 27
shows the schematic of an intersection.
Figure 27: Intersection Schematic
• Clearance Zone (Dcz)
Clearance Zone is the distance from the stop line within which if a vehicle is
present, it can easily and safely cross the intersection prior to the light turning red.
This is an important first check in our system as it provides an initial status on the
29
vehicle and prevents us from performing several other checks before concluding
that the vehicle is safe. This improves the efficiency of our program.
When we say that a vehicle has safely crossed the intersection, we mean that it has
crossed the entire intersection as well as all of its length is completely after the
stop line of the road to which the vehicle was crossing the intersection and
moving towards. This distance has been shaded in Figure 27.
We need the distance prior to the stop line in which a car needs to be present in
order to be in clearance zone.
Clearance Zone = Distance traveled in time before light turns red – Length of Car
– Width of Intersection
Distance traveled in time before light turns red = Speed of vehicle x Time left for
light to turn red
If: vSV : speed of subject vehicle (SV)
tA : time left for light to change state
L : length of vehicle
W: width of intersection
Dcz = Clearance Zone
Dcz = vSVtA – L – W
Figure 28 shows the clearance zone at different speeds with different lengths of
time left for the light to turn red.
300
250
200
Dcz (m)
150
100
50
0
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
Speed (kph)
Dcz30 Dcz25 Dcz20 Dcz15 Dcz10 Dcz5
Figure 28: Clearance zone at different speeds and different tA
‘Dcz30’ means there are 30 seconds left for the light to turn red. Similarly, ‘Dcz25’
means there are 25 seconds for the light to turn red, and so on. For example, if
we take the speed of the car to be 55 kph and 5 seconds for the light to turn red,
then we see from the graph that the vehicle needs to be within 60 meters of the
stop line to be in the clearance zone.
30
If the light is currently green, then we want the vehicle to be close to the stop line
and within the clearance zone in order for it to cross the intersection safely. If the
light is currently red, we want the vehicle to be away from the stop line so
hopefully by time it reaches the stop line, the light will have turned green. Thus, in
this case, we want the vehicle to be outside the clearance zone.
• Dilemma Zone
Dilemma Zone is the region in which if a car is present, then it cannot stop in time
and neither can it cross the intersection safely before the light turns red. This
region is present right before the clearance zone. One of the aims of traffic light
design is to reduce the dilemma zone.
• Distance to Stop (Dstop)
Dstop is the distance required for the vehicle to come to a complete stop at its
present deceleration rate. This distance is independent of the vehicle’s actual
distance from the stop line.
Distance to Stop = Distance for car to stop + Extra distance traveled due to
Human + Machine Delay
In order to calculate the distance for to stop, we use the fourth equation of
motion:
v2 = u2 + 2as
In our case: v = 0
Distance for car to stop = -v2SV/2a
Since the car is decelerating, a is negative. Thus:
Distance for car to stop = v2SV/2a
We assume:
Human Delay + Machine Delay = 2.0s
Thus:
Dstop = v2SV/2a + 2vSV
If a vehicle is decelerating, Dstop in comparison with the vehicle’s actual distance
from the stop line is an important check for whether a car will be able to stop in
time.
We use these terms in judging whether a vehicle will run the red light. Before we
introduce the system flowchart for the road calculation, there are some other terms we
need to address:
• ts: time for subject vehicle to cross the stop line
• tg: time left for light to turn green or remain green
31
• Dloc: actual distance of the vehicle from the stop line
Now, let us assume that the light is green. Figure 29 shows the system flowchart.
Figure 29: System flowchart when light is currently green
We see that despite the vehicle being in the clearance zone or the time for the vehicle to
reach the stop line being after the light turns green, we keep checking if it remains in the
clearance zone and if the time needed for the vehicle to reach the stop line remains
greater than the time needed for the light to turn green. This is because drivers are
unpredictable and we cannot guarantee that the vehicle will continue traveling at the
same speed and acceleration rate.
Figure 30 shows the system flowchart when the light is currently red.
32
Figure 30: System Flowchart for when light is currently red
Upon comparison of figures 29 and 30, we notice that two checks have changed: 1)
clearance zone. We rewrite the explanation for this here:
If the light is currently green, then we want the vehicle to be close to the stop line and
within the clearance zone in order for it to cross the intersection safely. If the light is
currently red, we want the vehicle to be away from the stop line so hopefully by time it
reaches the stop line, the light will have turned green. Thus, in this case, we want the
vehicle to be outside the clearance zone.
The second check which has changed is the comparison between time left for vehicle to
reach the stop line versus the time left for the light to turn/remain green. Since the light is
currently red in Figure 30, we want the vehicle to reach the stop line after the time left
for the light to change state. While in Figure 29, when the light is currently green, we
wanted the vehicle to reach the stop line prior to the time left for the light to change
state.
System Latencies
The delay in transfer of data between each equipment is also of concern since all road
calculations are performed real-time and any major delay would cause the failure of our
system.
33
The transfer of data between all components physically wired together (RSE: RSE Laptop,
RSU. OBE: GPS, OBE Laptop, OBU) suffers from no delay. The only delay possible is in
the transmission of data wirelessly.
Baud Rate of our Wireless Connection = 2400 = 19200 bps
Size of Data being transmitted = 47 bytes = 376 bits
GPS update = every 1.0 second
Size sent = 376 bits per second
Ratio of Available bandwidth VS Used = 51:1
Since the size of data being sent is so relatively small to the available connection rate, we
can safely assume that there is negligible delay between the transfer of GPS data from the
OBE to the RSE.
4.2 Traffic Light
The traffic light is virtually simulated through C++ on the RSE Laptop. The main
components to consider when designing the traffic light were:
1. Length of One Cycle
Traditionally, the length of one cycle is less than 200 seconds. We chose the
length to be 180 seconds.
2. Length of Amber Light
When a light is about to turn red, there is a region before the stop line in
which if a vehicle is present, then it cannot stop before the light turns red and
neither can it cross the intersection safely. We used an analysis done by Gazis
et. al, which can be seen in Figure 31.
34
Figure 31: Design amber times associated with various vehicle travel velocities
The formula associated with the graph is the following:
Vsv W + L
t DesignAmber = t DesignDelay + +
2a vsv
We took the average speed limit of 40 mph and chose 5 seconds for amber
light length.
Figure 32 shows the timeline for one cycle of the traffic light.
85 s 5s 90 s
90 s
Figure 32: Traffic Light Timeline for One Cycle
In the context of the system, the traffic light is virtually simulated on the RSE laptop. It
needs to provide a constant countdown to update the traffic light information on how
many seconds are left for the light to change state. Figure 33 shows the virtual
implementation of the traffic light.
35
C++ Data Array 5 6
…………………………GPS Data……………………… Traffic Light State Traffic Light Time
5 cells To: G 2
G 1
R 90
Figure 33: C++ Data Array consisting of GPS data in first 4 cells and traffic light data in last 2 cells
The GPS is updated every second, and the RSE Laptop receives this information every
second. Thus, all we need to set is the length of the countdown (90 seconds per state in
our case) and which state to begin with. The traffic light state is represented in numbers.
‘1’ means that the light is currently green, while ‘2’ means the light is currently red. For
example, if we want to start the traffic light countdown from 90 seconds to green, Figure
34 explains the system.
Cell 2: Time Cell 5 Cell 6
1 …………………………GPS Data……………………… 2 90
Yes No
Cell 6 = 1? Cell 5 = 2?
No
Cell 2 Yes Cell 5 Cell 6
+1 …………………………GPS Data……………………… 1 90
Cell 2 Cell 5 Cell 6
+1 …………………………GPS Data……………………… 1 -1
Cell 2 Cell 5 Cell 6
+1 …………………………GPS Data……………………… 2 -1
Figure 34: Traffic Light Flowchart
Cell 2 is the time data received from the GPS. It is the last two digits of the time – the
seconds of the time. Thus, it starts at 00 and increments till 59 after which it reverts to 00
and continues looping.
4.3 Transceiver Communication
We are using the Airbornedirect Serial Bridge as the OBU. As established earlier, the
bridge has RS232 Serial Communication and is 802.11b/g compliant. Figure 35 shows the
Airbornedirect Serial Bridge.
36
Figure 35: Airbornedirect Serial Bridge
Figure 36 shows the wireless connectivity arrangement for the system.
Bridge
12 VDC 5 VDC
802.11g
Ethernet
Serial
Access Point
RSE OBE
Figure 36: Wireless Connectivity Set-up of System
The RSU – Access Point (AP) – is set-up by the following steps:
1. AP is accessed by entering its given IP Address in an Internet Browser. For the
Linksys router we used, the IP Address was 192.168.1.1
2. Click on Wireless tab, then Wireless MAC Filter
3. Enable MAC Filter temporarily to view MAC Filter List
4. Search for Airbornedirect IP Address in AP’s Wireless Client MAC List (Figure 37)
Figure 37: RSU’s Wireless MAC List
5. DO NOT leave the MAC Filter enabled
6. Set COM 7 as Virtual Communication Port (Comport) in Virtual Configuration
Utility (VCOM)
7. Enter Airbornedirect IP Address in VCOM Comport 7 NMS Settings (Figure 38)
37
Figure 38: VCOM Comport 7 Set-Up
These steps are required because we need to specify which remote wireless device the
RSU should connect to among all the wireless devices it is detecting.
The OBE is set-up in the following steps:
1. Open Airbornedirect Utility program (AEU)
2. Under Network tab, select DHCP
3. Under Serial tab, change “TCP Session Inactivity Timeout” to 0
4. Under Serial tab, set Bit Rate, Data Bits, Parity and Flow Control
Dynamic Host Configuration Protocol (DHCP) allows for the device to automatically be
assigned an IP Address upon network connection. This is contrary to the concept of Static
IP Address where every time a device is booted, it has the same IP Address. DHCP is also
enabled in the AP/router.
We select TCP Session Inactivity Timeout to be 0 because we do not want the bridge to
disconnect if it is not receiving any data. It should be connected or searching for
connection continuously.
The SSID needs to be the same in the AP as well as the AEU. Both are named DSRC
currently.
The current Baud Settings are:
• Bit Rate: 2400
• Data Bits: 8
• Parity: None
• Flow Control: None
38
Figure 39: Current Baud Settings in AEU
These settings are used in the RSU and OBU C++ program for transferring data. If any
changes are made to these settings, ensure that the C++ code is also changed accordingly.
The settings specify the rate and type of control on the data being transmitted wirelessly.
It is important that both the RSU and OBU have the same settings.
4.4 GPS-Laptop Communication
GPS Spanner
This program needs to be installed on the OBE laptop [12]. We set a virtual comport (up
to the user) as the serial communication port receiving GPS data. We use this set comport
in HyperTerminal to receive GPS data. Once the comport has been set, we need to
always connect the GPS to the same USB port otherwise the spanner will not recognize
the GPS.
HyperTerminal
HyperTerminal is a Windows session which allows remote devices to communicate with
each other. In this case, let us assume that we set comport 1 as the serial port to receive
GPS data. The following are the steps to view the GPS data on HyperTerminal:
1. Start :: Run :: Type hypertrm
2. Type GPS under Name. Click OK
3. Connect Using: COM1. Click OK
4. Bits per second: 2400
5. Data bits: 8
6. Parity: None
7. Stop bits: 1
8. Flow control: None. Click OK
We now see a string of GPS data on the HyperTerminal screen. The raw GPS data consists
of a lot of pieces of information that are of no relevance to us. Figure 40 shows an
extract of the raw GPS string.
39
Figure 40: Raw GPS String
The only line we are interested in is the line starting with $GPRMC. In Figure 40, that line
provides us with the following pieces of information:
• 200753 – Greenwich Meridian Time at the time when GPS was run
• V – GPS is not connected to satellite. ‘A’ means connected to satellite
• 4223.1073 – Latitude of current location in hours, minutes, seconds
• N – direction of latitude
• 07231.8678 – Longitude of current location in hours, minutes, seconds
• W – direction of longitude
• , - when speed is 0, ‘,’ is shown. This is the second comma after W
Thus, in order to extract only the relevant data, we wrote a GPS Parser C++ program.
When we wrote the C++ program to directly extract GPS data from the serial port and
parse it, either Visual Studio or the GPS software created a virtual buffer which caused
delays in transfer of data. However, when we viewed the GPS data through
HyperTerminal, there was no delay. Thus, we used HyperTerminal to capture all the
output from the GPS into a text file named GPS_Read.txt. The text file was then
opened using C++ to parse and transfer to the Airbornedirect Bridge (OBU), which then
sent out the GPS data wirelessly to the AP (RSU).
We instructed HyperTerminal to capture the GPS data onto a text file by:
1. Transfer menu :: Capture Text…
2. We specified the location to save the file in the folder consisting of the GPS Parser
VC++ Project, called GPS_Read
Figure 41 shows the location of the GPS_Read.vcproj on my computer.
40
Figure 40: Location of GPS_Read VC++ Project
Thus, after Capture Text… I will put down the location as:
C:\Documents and Settings\Richa\My Documents\Visual Studio
2005\Projects\GPS_Read_Copy\GPS_Read\GPS_Read.txt
Note that I specifically put down GPS_Read.txt as the text file name. This is because the
C++ program is set to use a text file with that name to read the GPS data.
GPS_Read Program
GPS_Read VC++ Project consists of 4 C++ source files and 1 header file. To execute the
code:
1. Build menu :: Build Solution (F7)
2. Debug menu :: Start without Debugging (Ctrl+F5)
If an error occurs:
1. Project menu :: Properties
2. Configuration: All Configurations
3. Character Set: Use Multi-Byte Character Set
41
Figure 41: Set to Multi-Byte Character
If the error persists, make a new VC++ Empty Project and add all the source and header
files into your newly created project.
Once the code is executed, a DOS menu is seen as shown in Figure 42.
Figure 42: DOS OBU Menu
1. Open/Configure Airbornedirect Serial Port (OBU)
This is always the first selection made in this menu. It opens the serial port to
the OBU. Select the serial port to which the OBU is connected to on the OBE
Laptop. (This can be discovered by looking through the Device Manager)
42
2. Start Transmitter
Once the comport to the OBU is open, we select this option which then starts
the transmitter. We also see a copy of what is being transmitted on our screen.
The information is garbled but rest assured, the data transmitted to the RSU is
only the relevant GPS information.
There are three text files located in the GPS_Read folder containing the VC++ Project.
1. GPS_Read.txt
Contains the GPS data from HyperTerminal. File read by GPS_Read.vcproj
2. tester.txt
Contains position location of read cursor and character read from
GPS_read.txt. This file is from debugging purposes
3. output.txt
Contains parsed GPS data which is also being sent to RSU and displayed on
DOS screen through VC++
Perform the Capture Text… in HyperTerminal after you have run the GPS_Read program
and set the serial port. This is because the three text files are deleted upon executing the
program, and if HyperTerminal starts using the GPS_Read.txt then it would not get
deleted which means that old data would be transmitted. In summary:
1. Start HyperTerminal to receive GPS data
2. Run GPS_Read.vcproj
3. Menu Item 1: Set Serial Port to Bridge
4. Capture Text… on HyperTerminal
5. Menu Item 2: Start transmitting GPS data
4.5 GPS Data Reception by RSE
Build and Run the Road Side Unit.vcproj in the same manner as explained how to
build and run GPS_Read.vcproj. If there are errors while running the program, then
follow the same steps as explained in section 4.4.
Upon executing the program, a DOS Menu appears as shown in Figure 43.
43
Figure 43: RSE Menu
Note that the menu starts from number 2.
2. Open/Configure Router Virtual Serial Port
If we had set the Router to serial port 7 in VCOM, then set to comport 7
3. Test GPS Data Transmission
Displays wirelessly received GPS data without any road calculations performed
4. Start Road Side Calculation
Begins road calculations and displays the calculations as performed real-time
The details of serial port programming in C++ can be found in reference [13].
4.6 RSE Algorithm
The Road Calculation or RSE Algorithm is contained in the LatencyCalculation.cpp file.
The algorithm is the implementation of the system flowcharts we saw in figures 29 and
30. An explanation of each function in LatencyCalculation.cpp:
• GPSRetrieve()
Receives GPS data in a 5 cell array from DataAcquisitionTest.cpp. We want to
have an array with two rows – one row consisting of latest data and the other
row consisting of one second old data. This is for the purpose of calculating
acceleration, which requires two sets of data. Figure 44 shows the 5 cell GPS
array received at the start of the function.
Cell 1 Cell 2 Cell 3 Cell 4 Cell 5
Connection Time Latitude Longitude Speed …Traffic Light data…
Figure 44: GPS Array – each row 2 Cells
44
Cell 1 contains information on whether the data being received is when the
GPS is connected to the satellite. A connection means the value in Cell 1 is 1,
otherwise it is 0.
After creating the 2 x 7 GPS array with old and new GPS data, we tack on the
last cells in each row consisting of traffic light information. The traffic light
data is appended to the array in the manner explained in Section 4.2
As explained earlier in Section 4.2, the range for the time data is 00 to 59 after
which it loops back to 00 and starts over. Thus, in cases where the new time is
00 and the old time was 59, and we are calculating the time difference
between the two sets of data, we write a small code to compensate for this.
• CalcDloc()
This function calculates the distance in meters between two longitude and
latitude coordinates given in degrees. For an explanation of the method, see
[14].
• CalcDcz()
We set the length of the car to be 4.8 meters and the width of the intersection
as 14.63 meters. These numbers are relevant to the testing site and vehicle
used for our project. As explained in Section 4.1, we use the following formula
for calculating the clearance zone:
Dcz = vSVtA – L – W
The velocity and time left for light to change state is retrieved from the GPS
array.
• CheckAcc()
Acceleration = (Current velocity – Old velocity)/(Current time – Old time)
This forms the check in our flowcharts in figure 29 and 30 to check if the
vehicle is accelerating/cruising or decelerating.
• AccLess0()
If CheckAcc() shows that we are decelerating, we enter this function where we
compare the distance required to stop at the vehicle’s current speed and
deceleration rate (Dstop) versus the vehicle’s actual distance from the stop line
(Dloc). The equation for calculating Dstop is restated here:
Dstop = v2SV/2a + 2vSV
The Dstop versus Dloc is a check of whether the system flow control should
branch towards the final check prior to alarming the drivers in the vicinity of
the intersection.
45
• Acc0OrMore()
If CheckAcc() shows that we are accelerating/cruising, we enter this function
where we calculate the deceleration rate that would be required at the
vehicle’s present speed and distance from the stop line for it to come to a
complete stop at the stop line. We use the fourth equation of motion:
v2 = u2 + 2as
In this case: v = 0
Predicted Deceleration = aPRED = -v2SV/2Dloc
The comfortable ranges vary depending on the distance of the vehicle from
the stop line. For example, if a vehicle is very far away, say, at a distance
greater than 30 meters, then the comfortable deceleration range would be 0
to 1.5 m/s2. If the vehicle is very close to the stop line, say within 20 meters,
then any movement on the part of the vehicle would cause it to cross the stop
line. Thus, there is no range for vehicles within the 20 meter distance of the
stop line – the system simply alarms if it detects any movement of a vehicle in
that distance range. The distance between 30 and 20 meters is tricky as a
vehicle might be moving along very slowly but may require a deceleration
rate greater than 1.5 m/s2, which is accomplished by sudden braking. Thus, for
this distance, we put in a comfortable deceleration range of between 0 and
0.3 m/s2.
There numbers are based on trial and error methods in the testing field.
• TimeGreen()
This function compares the time for the vehicle to reach the stop line at its
current speed and accelerate rate versus the time left for the light to change to
green or remain green. This function is only accessed if: a) vehicle is
decelerating and Dstop > Dloc, or b) vehicle is accelerating/cruising, and
predicted deceleration rate is outside of comfortable range.
Using fourth equation of motion:
v2 = v2SV + 2aDloc
v = (v2SV + 2aDloc)0.5
… v: velocity of vehicle when it has reached the stop line
vSV: current velocity of subject vehicle
a: acceleration rate calculated in CheckAcc()
Dloc: distance from stop line calculated in CalcDloc()
If we notice that v2 is negative, then we can conclude that the vehicle is
probably decelerating currently, and it will be able to stop at a distance prior
to Dloc: safe. If v2 is zero, then the vehicle is not moving.
If the vehicle is accelerating, we use the first equation of motion:
46
v = u + at
…v = calculated from fourth equation of motion
u = vSV
t = tG = time to reach the stop line
a = acceleration determined in CheckAcc()
tG = (v – vSV)/(a – 0.5)
If the vehicle is cruising, we use the second equation of motion, as a = 0 in
this case:
s = 0.5(v + u)t
…s = Dloc
v = calculated from fourth equation of motion
u = vSV
t = tG = time to reach the stop line
tG = (2Dloc)/(v + vSV)
This function performs the last check of whether the system should alarm. If it
determines that the time for the vehicle to reach the stop line is earlier than
the time left for the light to turn green or the time to reach the stop line is
after the time left for the light to remain green, the system alarms.
• Alarm()
This function starts the alarm on the RSE and OBE. The alarm is not
continuous in that it does not keep getting triggered if it is triggered once.
Every time the full set of calculations is made and the system flow control
reaches this function, the alarm is set. This is because our system does not
compensate for sudden braking. It always assumes that the driver will brake
smoothly. Thus, it might generate a premature alarm, and after the driver
brakes rapidly, the alarm is not generated again.
• RSUlonglat()
This function sets the RSE longitude-latitude. Since, these pieces of data are
fixed due to the RSE being fixed at the traffic light of the intersection, we can
put in actual numbers (not variables) and set the longitude-latitude.
• latencyflowcontrol()
This function controls the branching shown in flowcharts in figures 29 and 30.
A point of note is that if the vehicle is decelerating and Dstop > Dloc, the
function only allows the system to alarm (enter Alarm()) when Dloc < 40
meters. This is to prevent any premature alarming.
Another point to note is that all calculated and GPS array data is being saved
in an excel file called output.xls. This file is for debugging purposes, and is
found in the folder containing Road Side Unit.vcproj.
47
A final point of note is that when we retrieve GPS data by calling the
GPSRetrieve() function, we have this call set in a while loop where the system
keeps asking for new GPS data if it sees the connectivity to satellite is 0 (not
connected)
• latencyflow()
This function starts the latency calculations by setting the traffic countdown
length per state and the traffic light state to start from. This gives us control in
testing situations where we want the light to be a particular state when the
vehicle reaches the stop line. If we set the traffic countdown length to be 40
seconds and starting state as red, then the total traffic light time would be 80
seconds: 40 seconds red, 40 seconds green, then it loops again.
We also retrieve the first set of GPS data until we see the connectivity to
satellite flag is 1, before passing the flow control to latencyflowcontrol().
4.8 Testing & Debugging
Location
Our testing site was the football stadium at the University of Massachusetts Amherst
campus near University Drive. Figure 45 shows a satellite image of the site.
Figure 45: Satellite image of testing site at football stadium
48
Setup
We chose a long stretch of road bordering the stadium (encircled in red in Figure 45), and
placed the RSE at a three-way junction, while choosing the crosswalk at that junction as
our stop line. Figure 46 shows the setup at the testing site.
RSE
RSE Laptop
GPS
Router (RSU)
OBE
OBE Laptop
Airbornedirect Serial Bride
System (OBU)
Figure 46: System Setup at Test Site
This set-up restricted us to the 100 meter range of the router as the connectivity when we
approached from out-of-range to in-range was not very quick. This is due to our using an
802.11b/g transceiver which is not built for use in time-valued systems like these. Thus, as
the RSE longitude and latitude can be fed into the road calculation code as a ‘hard
number’; i.e. constant, we can have the RSE along with the OBE within the vehicle, since
according to the road calculations, the system would always detect the RSE to be at the
intersection. Thus, we could test the system from distances as large as we needed.
49
Tests
1. Clearance Zone Test
This test was to check if the system correctly detected whether a vehicle is in
the clearance zone. Thus, the part of the flowchart we tested is shown in
Figure 47 (shows for light currently green).
Figure 47: Clearance Zone Check in Flowchart
As explained earlier, if the light is currently green, we want the vehicle to be
inside the clearance zone; otherwise if the light is red, the vehicle should be
outside the clearance zone.
Table 6 shows one of the field test data for this test.
Speed (m/s) Traffic Light (s) To… Distance (m) Clearance Zone Distance (m) Alarm
13.5528 45 R 118.992 591.08 0
15.497 43 R 89.761 647.529 0
17.062 41 R 57.571 680.93 0
18.574 39 R 24.42 705.57 0
19.546 37 R 14.44 704.386 0
Table 6: Field Test Data for Clearance Test
We have replaced the To… data from 1 (to red. currently green) and 2 (to
green. currently red) to R and G for easier understanding. As the light is
currently green, we want the vehicle to be within the clearance zone, which it
is throughout the test, thus no alarm was generated.
2. Acceleration Test
This test was for a vehicle accelerating towards the intersection. Thus, if the
light is red when the vehicle crosses the intersection, the alarm should be set-
off. The portion of the flowchart under test is shown in Figure 48 (shows for
light currently green).
Yes
No Yes
a = + or 0? Calculate deceleration for Comfortable
Start In Dcz?
v =0 at stop line range?
No
Yes
Warning ts < tg Time to reach stop line
No
Figure 48: Acceleration Test in Flowchart
50
Table 7 shows one of the field test data for this test.
Speed (m/s) Traffic Light (s) To Distance (m) Clearance (m) Predict acc (m/s2) Time Stop (s) Alarm
15.335 2 R 190.554 11.839 -0.617 0
17.062 25 G 158.786 407.735 -0.916 0
18.0885 23 G 124.882 397.206 -1.31 0
18.790 21 G 89.304 375.770 -1.97 0
19.222 19 G 53.327 346.396 -3.464 2.883 1
19.384 17 G 16.587 310.705 -11.327 0.863 1
19.546 15 G 20.547 274.366 -9.296 1.062 1
Table 7: Field Test Data for Acceleration Test
We see from the data that we are always outside the clearance zone during
green light and inside the clearance zone during red light, which is unwanted
and branches the flow of control to check the acceleration rate of the vehicle.
The predicted deceleration rate is within comfortable range till the speed
reaches 19.222 m/s. At that point, the predicted deceleration range becomes -
3.464 m/s2, which is greater than 1.5 m/s2. We then check the time for the
vehicle to reach the stop line – 2.883 seconds, while the time left for the light
to turn green 19 seconds. Thus, the alarm is set off. The predicted deceleration
rate continues to be outside of comfortable range and the time to reach the
stop line reduces at a rate faster than the countdown of the traffic light,
therefore the alarm keeps being triggered.
3. Deceleration Test
The deceleration test is where a vehicle decelerates until it comes to a
complete stop at the stop line. Figure 49 shows the portion of the system
flowchart being tested (shows for light currently green).
Figure 49: Deceleration Test Flowchart
Table 8 shows one of the field test data for this test.
51
Speed (m/s) Traffic Light (s) To Distance (m) Clearance (m) Predict acc (m/s2) Time Stop (s) Alarm
17.8185 35 G 107.641 604.8186 -1.475 0
16.766 33 G 75.030 528.199 6.137 1
14.146 31 G 46.65 419.722 4.512 1
11.4471 29 G 23.342 313.135 2.602 1
8.96326 27 G 8.936 223.178 0.613 1
Table 8: Field Test Data for Deceleration Test
We are always inside the clearance zone during a green light, thus sending the
flow of control to check the vehicle’s acceleration rate. The first set of data
seems to indicate the vehicle accelerated because the predicted deceleration
column is filled. The distance of the vehicle at that point is greater than 30
meters so the comfortable deceleration range is 0 to 1.5 m/s2. Since the
predicted deceleration rate is within the range, no alarm is set off. In the
second set of data, we see that the vehicle has decelerated, and Dstop > Dloc
as time to reach stop line (time stop) has been calculated. This time is 6.137
seconds while the time left for the traffic light to turn green is 33 seconds.
Thus, the alarm is set-off. The vehicle continues to seen to break the red light,
and thus, the alarm is set off repeatedly.
4. System Test
This test begins at the vehicle a long distance away from the intersection. The
vehicle accelerates, then decelerates until it comes to a stop at the intersection.
Then it slowly creeps up and crosses the intersection. The test takes place
under red light, and thus the alarm should finally be triggered. This test
validates the entire system shown in Figure 30.
Table 9 shows the field test data.
52
Table 9: Field Test Data for System Test
We see that the vehicle is at rest at the beginning. Once it starts moving, the
light is currently red, and it is outside the clearance zone which means it is safe.
However, at the speed of 11.0691 m/s, it moves within the clearance zone,
thus branching the flow of control to check the acceleration rate of the
vehicle. We see that the car is accelerating until its speed reaches 16.1987 and
during the entire time its predicted deceleration rate is within the comfortable
range, thus not triggering the alarm. Once it starts decelerating, we see that
the alarm is not triggered despite Dstop > Dloc because in order to prevent
premature alarms, we have set the system to only alarm in the case of a
decelerating vehicle, when it is within 40 meters of the stop line. When the
vehicle enters the 40 meter range, we see that v2 (from Section 4.6) is
negative, which means that the vehicle can stop before the stop line at its
present deceleration rate. The vehicle comes to a complete stop with no alarm
having been triggered off so far. But the vehicle starts accelerating again to
cross the intersection during a red light and this time when detected that the
vehicle is inside the clearance zone, and is moving, the alarm is triggered.
53
5 STATISTICAL ANALYSIS
Our system always gives an alarm when it should.
5.1 Confidence of False Alarm
The purpose of this test was to determine with 95% confidence the probability of a false
alarm – an alarm when there should be none. We conducted 40 tests.
No. of tests = N = 40
Mean = 0.025
Standard Deviation = 0.156
Z* = 1.96
-0.0234 ≤ Sample Mean ≤ 0.0734
We usually take the tail ends of a normal distribution curve to be percentage leftover
from confidence interval divided by 2; i.e. 2.5% on both ends for our 95% confidence
case. Since the probability cannot be less than 0, we can ignore the left tail end.
Thus, with 97.5% confidence, the probability of a premature/false alarm is less than
7.34%. Figure 50 shows the normal distribution with the shaded region being the
confidence interval.
2.5% 2.5%
0 0.025 0.0734
Figure 50: Normal Distribution of False Alarm
The probability of false alarm is minute thus validating our system as very reliable.
5.2 Frequency of Alarm with Distance
Figure 51 shows the histogram representing the frequency of alarm generated by the
system with respect to the vehicle’s distance from the stop line.
54
350
300
250
Frequency of Alarm
200
150
100
50
0
0 10 20 30 40 50 60 70 80 90
Acceleration Cruising Deceleration (0-1 m/s2) Distance
Deceleration (1-2 m/s2) Deceleration (2-3 m/s2)
Figure 51: Histogram of Alarm with Distance from Stop Line
Acceleration and Cruising Behavior
The system starts alarming in the cases of acceleration and cruising tests the farthest from
the stop line. We see the frequency increasing as the vehicle approaches the intersection
because the system grows more confident that the vehicle will break the red light.
Decelerating Behavior
The alarm for decelerating behavior is only seen after 40 meters because we have set in
the code to only trigger after 40 meters for this behavior. This is to avoid any premature
alarms.
When the vehicle is 40 meters away, the first set of frequencies we see is for deceleration
rate of 0 to 1 m/s2. This is due to vehicles traveling at high speed and not decelerating at a
rate which would indicate to our system that the vehicle will successfully stop at the stop
line. There is zero frequency for deceleration rates of 1 to 3 m/s2 because the distance is
great from the stop line and the deceleration rate is high. We see the frequency of alarms
increasing as the vehicle approaches the stop line with a deceleration rate of 0 to 1 m/s2
because the system grows more confident of the vehicle breaking the red light.
As the vehicle approaches the stop line, we start seeing alarms triggered for vehicles
decelerating in the 1 to 3 m/s2 range. This is because of the speed of the vehicle being high
and the deceleration rate not being high enough.
The histogram confirms the validity of our road calculations because it shows what we
would expect theoretically.
55
5.3 GPS Inaccuracy
The aim of this analysis was to determine the inaccuracy of the GPS. We noted a location
in the Football Stadium using a Amherst Map from the W.E.B Dubois Library. We stood
still at the location with the GPS and noted down the changes in the longitude-latitude
data. Figure 52 shows the scatter plot of the data. The point circled in red is the actual
longitude-latitude of the location according to the Map.
42.377840
42.377830
42.377820
42.377810
42.377800
42.377790
42.377780
42.377770
42.377760
42.377750
42.377740
42.377730
-72.534300 -72.534250 -72.534200 -72.534150 -72.534100 -72.534050
Figure 52: Scatter Plot of GPS longitude-latitude data
Table 10 summarizes the relevant statistical information of the scatter plot.
Northings Westings Distance
Mean 42.377787 -72.534158 3.082612
Median 42.377784 -72.534158 3.177549
Mode 42.377785 -72.534153 4.064632
Std Dev 0.000021 0.000044 1.155778
Variance 0.000000 0.000000 1.335823
Skewness 0.085105 -0.052806 -0.360205
Maximum 42.377827 -72.534069 4.977798
Minimum 42.377743 -72.534248 0.374785
Range 84.183348 178.797882 8.603013
Count 91.000000 91 91
Table 10: GPS Inaccuracy Statistical Data
We conducted this test 91 times. We see that the mean distance error from the actual
point is about 3 meters. The range of inaccuracy is about 8 meters, which is within the
inaccuracy range specified by Garmin: ±5 meters.
This confirms the safety of the ranges we took into consideration to compensate for the
GPS inaccuracy in our road calculations.
56
5.4 Confidence of Transceiver Connection Range
We tested the distance within which there was a connection between the RSU and OBU.
We conducted this test 143 times and took the confidence interval to be 95%.
No. of tests = N = 143
Mean = 91.706 meters
Standard Deviation = 5.006 meters
Z* = 1.96
90.886 ≤ Sample Mean ≤ 92.526 meters
With 95% confidence we can say that there will be a connection at 91.706 ± 0.82 meters
Figure 53 shows the normal distribution of the range with the shaded region being the
confidence interval.
2.5% 2.5%
90.886 91.706 92.526
Figure 53: Normal Distribution of Transceiver Connection Range
Thus, the router falls short of its 100 meter specification by about 8 meters.
57
6 SUMMARY
6.1 Conclusion
We conclude that all specifications have been met. The system passed all tests and
performs within suitable parameters.
6.2 Future Work
• GPS Inaccuracy Correction
The scatter plot and statistical data on the GPS can be used to formulate
equations to provide for GPS inaccuracy correction. An example of this
method can be seen in [15].
The other option is to buy a more accurate GPS, some of which are
highlighted in Section 3.1.
• 300 meter range router
Replace the 100 meter router with a 300 meter router. Since the 300 meter
range is theoretical and the signal degrades as one approaches 300 meters, use
the 100 meter router as an Access Point to boost the signal across 300 meters.
The best alternative is to use DSRC transceivers, which unfortunately are only
available in 2008.
• All road calculations on OBE
To avoid institutional problems such as who pays for the repair of the RSE (US
DOT? State? Vendor?), all road calculations can be done on the OBE. Thus,
the RSE acts only to broadcast all messages received by it, which makes it an
economically replaceable unit.
• Robustness of Road Calculations
As noticed, our system at times gives out premature alarms. The current system
finds it difficult to accommodate sudden braking. Thus, the road calculations
pertaining to comfortable deceleration range and different speeds need to be
taken into account. The system needs to be ‘transient’ in nature versus the
current system where it works in black and white – above 1.5 m/s2 : alarm.
Else: No alarm.
• Improve Code Efficiency
A major improvement would be to abolish the necessity of HyperTerminal in
attaining GPS data. Other improvements include editing the current code into
a more compact version.
• Change to another Virtual Serial Configuration Program and Transceiver
Airbornedirect Serial Bridge is being phased out. VCOM has many bugs.
58
7 BIBLIOGRAPHY
[1] Integrated Project PReVENT
http://www.prevent-ip.org/
[2] Andreas Meier. Design of the Vehicular Safety Communication Architecture.
http://www.tik.ee.ethz.ch/~andreame/tik/public/20050801-ma.pdf
[3] Wikipedia
http://www.wikipedia.org/
[4] Quatech Airborne Evaluation Kit
http://www.dpactech.com/docs/wireless_products/ab%20eval%20kit.pdf
[5] OTTO on Board
http://www.ivhs.com/pdf/FactSheet_OTTO_FactSheet1_101105.pdf
[6] Proxim Tsunami QuickBridge
http://www.proxim.com/products/quickbridge/index.html
[7] Q-Free Products
http://www.q-free.com/m/pro/?mid=m467&vn=736&mn=64
[8] Trimble GPS Tutorial
http://www.trimble.com/gps/index.shtml
[9] United States Coast Guard DGPS Coverage
http://www.navcen.uscg.gov/dgps/default.htm
[10] FAA WAAS Coverage
http://gps.faa.gov/Programs/WAAS/waas-text.htm
[11] U.S. Department of Transportation. Examination of Signalized Intersection, Straight
Crossing Path Crashes and Potential IVHS Countermeasures
[12] Garmin GPS Spanner Download
https://buy.garmin.com/shop/store/downloadsDetails.jsp?id=1627&product=010-00321-
00&cID=139&pID=6445
[13] Bayer, Robertson. Windows Serial Port Programming
http://www.robbayer.com/files//serial-win.pdf
[14] Distance Using Longitude-Latitude
http://mathforum.org/library/drmath/view/54680.html
[15] Applied Single GPS Point Statistical Analysis to Geometric Correction of Digital
Satellite Imagery
http://www.gisdevelopment.net/technology/gps/me05_072a.htm
59
8 APPENDIX
8.1 RSE Code
RoadSideUnit.h
#ifndef _RoadSideUnit_H
#define _RoadSideUnit_H
#include <iostream>
#include <string>
#include <stdlib.h>
#include <cstdlib>
#include <windows.h>
#include <conio.h>
#include <mmsystem.h>
#include <ctype.h>
#include <process.h>
#include <sstream>
#include <stdio.h>
#include <fstream>
#include <math.h>
#include <iomanip>
using namespace std;
void clrscr();
void exit();
char byte_receive_traffic_light();
char byte_receive_airborne();
void byte_send(unsigned char byte);
void main_menu();
void com_menu(char menu);
void set_serial_timeouts(char menu);
void open_serial_port(char *port, char menu);
void set_serial_port(char menu);
60
void datatest();
void trafficlightdatatest();
void roadsideunit();
float receive_time();
float receive_latitude();
float receive_longitude();
void GPSdata();
float* data();
void test();
void RetrieveGPS();
void CalcDloc();
int CheckAcc();
int AccLess0();
int Acc0orMore();
int TimeGreen();
void Alarm();
void latencyflow();
void RSUlonglat();
#endif
ClearScreen.cpp
#include "RoadSideUnit.h"
void clrscr()
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {0, 0};
DWORD count;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);
SetConsoleCursorPosition(hStdOut, coord);
}
61
DataAcquisition.cpp
#include "RoadSideUnit.h"
float* data()
{
float *calcdata = new float[7];
char initilize;
char sign;
char hour[2];
char min[2];
char sec[2];
char traffictime[2];
char trafficstate;
char valid;
float validity;
float second;
float longitude;
float latitude;
float speed;
float state;
float ttime;
initilize = byte_receive_airborne();
while(initilize != '(')
{
initilize = byte_receive_airborne();
}
valid = byte_receive_airborne();
if(valid == 'A')
validity = 1;
if(valid == 'V')
validity = 0;
initilize = byte_receive_airborne();
while(initilize != ')')
{
initilize = byte_receive_airborne();
}
62
initilize = byte_receive_airborne();
while(initilize != '$')
initilize = byte_receive_airborne();
for(int i = 0; i < 2; i++)
{
hour[i] = byte_receive_airborne();
}
for(int i = 0; i < 2; i++)
{
min[i] = byte_receive_airborne();
}
for(int i = 0; i < 2; i++)
{
sec[i] = byte_receive_airborne();
}
second = atof(sec);
initilize = byte_receive_airborne();
while(initilize != '*')
initilize = byte_receive_airborne();
initilize = byte_receive_airborne();
while(initilize != '@')
initilize = byte_receive_airborne();
cout.precision(8);
char lat[10];
for(int i = 0; i < 9; i++)
lat[i] = byte_receive_airborne();
latitude = atof(lat);
sign = byte_receive_airborne();
if(sign == 'S')
latitude = -1*latitude;
initilize = byte_receive_airborne();
while(initilize != '#')
initilize = byte_receive_airborne();
initilize = byte_receive_airborne();
while(initilize != '!')
initilize = byte_receive_airborne();
cout.precision(8);
char lon[10];
63
for(int i = 0; i < 9; i++)
{
lon[i] = byte_receive_airborne();
}
longitude = atof(lon);
sign = byte_receive_airborne();
if(sign == 'W')
longitude = -1*longitude;
initilize = byte_receive_airborne();
while(initilize != '%')
initilize = byte_receive_airborne();
initilize = byte_receive_airborne();
while(initilize != '^')
initilize = byte_receive_airborne();
cout.precision(8);
char spe[10];
for(int i = 0; i < 9; i++)
spe[i] = byte_receive_airborne();
speed = atof(spe);
initilize = byte_receive_airborne();
while(initilize != '&')
initilize = byte_receive_airborne();
// initilize = byte_receive_traffic_light();
// while(initilize != '$')
// {
// initilize = byte_receive_traffic_light();
// }
// traffictime[0] = byte_receive_traffic_light();
// traffictime[1] = byte_receive_traffic_light();
// trafficstate = byte_receive_traffic_light();
// ttime = atoi(traffictime);
// if(trafficstate == 'R')
// state = 1;
// if(trafficstate == 'G')
// state = 2;
calcdata[0] = validity;
calcdata[1] = second;
calcdata[2] = latitude;
64
calcdata[3] = longitude;
calcdata[4] = speed;
// calcdata[5] = state;
// calcdata[6] = ttime;
return calcdata;
}
DataAcquisitionTest.cpp
#include "RoadSideUnit.h"
void datatest()
{
clrscr();
char initilize;
char traffictime[2];
char trafficstate;
char valid;
initilize = byte_receive_airborne();
for(;;)
{
initilize = byte_receive_airborne();
while(initilize != '(')
{
initilize = byte_receive_airborne();
}
valid = byte_receive_airborne();
cout << valid;
cout << " ";
initilize = byte_receive_airborne();
while(initilize != ')')
{
initilize = byte_receive_airborne();
}
initilize = byte_receive_airborne();
while(initilize != '$')
{
65
initilize = byte_receive_airborne();
}
int time = receive_time();
cout << " ";
initilize = byte_receive_airborne();
while(initilize != '*')
{
initilize = byte_receive_airborne();
}
initilize = byte_receive_airborne();
while(initilize != '@')
{
initilize = byte_receive_airborne();
}
float latitude = receive_latitude();
cout << " ";
initilize = byte_receive_airborne();
while(initilize != '#')
{
initilize = byte_receive_airborne();
}
initilize = byte_receive_airborne();
while(initilize != '!')
{
initilize = byte_receive_airborne();
}
float longitude = receive_longitude();
cout << " ";
initilize = byte_receive_airborne();
while(initilize != '%')
{
initilize = byte_receive_airborne();
}
initilize = byte_receive_airborne();
while(initilize != '^')
{
initilize = byte_receive_airborne();
}
66
cout.precision(8);
char spe[10];
for(int i = 0; i < 9; i++)
{
spe[i] = byte_receive_airborne();
}
float speed = atof(spe);
cout << speed;
initilize = byte_receive_airborne();
while(initilize != '&')
{
initilize = byte_receive_airborne();
}
cout << " ";
// initilize = byte_receive_traffic_light();
// while(initilize != '$')
// {
// initilize = byte_receive_traffic_light();
// }
// traffictime[0] = byte_receive_traffic_light();
// traffictime[1] = byte_receive_traffic_light();
// trafficstate = byte_receive_traffic_light();
// int ttime = atoi(traffictime);
// cout << ttime;
// cout << " ";
// cout << trafficstate;
cout << "\n";
RSUlonglat();
}
}
float receive_time()
{
char time[6];
for(int i = 0; i < 6; i++)
{
time[i] = byte_receive_airborne();
cout << time[i];
67
}
float inttime = atof(time);
return inttime;
}
float receive_latitude()
{
cout.precision(8);
char lat[9];
char sign;
for(int i = 0; i < 9; i++)
{
lat[i] = byte_receive_airborne();
}
float latitude = atof(lat);
sign = byte_receive_airborne();
if(sign == 'S')
latitude = -1*latitude;
cout << latitude;
return latitude;
}
float receive_longitude()
{
cout.precision(8);
char lon[9];
char sign;
for(int i = 0; i < 9; i++)
{
lon[i] = byte_receive_airborne();
}
float longitude = atof(lon);
sign = byte_receive_airborne();
if(sign == 'W')
longitude = -1*longitude;
cout << longitude;
return longitude;
}
68
LatencyCalculation.cpp
#include "RoadSideUnit.h"
static double gps[2][7], a, Dloc, a_pred, longitude, latitude, treach, v, vsq, Dstop;
static double phi1, theta1, phi2, theta2, c, R = 6356750.0, time;
static double l, w, Dcz, tl_start_sec, tl_start, tl_state;
static int q=0;
//gps array
// connect time latitude longitude speed TL(R/G) TL(s)
// old | 0,0 | 0,1 | 0,2 | 0,3 | 0,4 | 0,5 | 0,6 |
// new | 1,0 | 1,1 | 1,2 | 1,3 | 1,4 | 1,5 | 1,6 |
void RetrieveGPS()
{
//loops twice to get two sets of new GPS data
for(int i=0; i<2; i++)
{
float* gps1 = data(); //gps array
//transfer all gps data into a row of gps array
for(int j=0; j<5; j++)
{
// gps[0][j] = gps[1][j];
gps[i][j] = gps1[j];
}
//check if traffic light time is 1 s. If yes, restart countdown and change traffic light state
//else continue counting down
if(tl_start_sec == 1)
{
tl_start_sec = tl_start-1;
if(tl_state == 1)
tl_state = 2;
69
else
tl_state = 1;
}
else
tl_start_sec = tl_start_sec - 1;
//fill last two cells of gps array
// gps[0][5] = gps[1][5];
gps[i][5] = tl_state;
// gps[0][6] = gps[1][6];
gps[i][6] = tl_start_sec;
}
//compensate for new time: 00 and old time: 59
if(gps[1][1]<gps[0][1])
time = gps[1][1]+60-gps[0][1];
else
time = gps[1][1]-gps[0][1];
cout<<gps[0][0]<<"\t"<<gps[0][1]<<"\t"<<gps[0][2]<<"\t"<<gps[0][3]<<"\t"<<gps[0][4]<<"\t"<<gps[0][5]<
<"\t"<<gps[0][6]<<"\n";
cout<<gps[1][0]<<"\t"<<gps[1][1]<<"\t"<<gps[1][2]<<"\t"<<gps[1][3]<<"\t"<<gps[1][4]<<"\t"<<gps[1][5]<
<"\t"<<gps[1][6]<<"\n";
}
void CalcDloc()
{
//finds distance using longitude and latitude in degrees data
double longitudeOBU, latitudeOBU;
longitudeOBU = gps[1][3];
latitudeOBU = gps[1][2];
ofstream distance("distance.txt", ios::app);
phi2 = 90 - latitudeOBU;
theta2 = longitudeOBU;
c = sin(phi1)*sin(phi2)*cos(theta1-theta2)+cos(phi1)*cos(phi2);
70
Dloc = R*acos(c)*3.142/180;
cout.precision(8);
distance.precision(8);
cout<<"Dloc = "<<Dloc<<"\n";
distance<<time<<"\t"<<longitudeOBU<<"\t"<<latitudeOBU<<"\t"<<phi2<<"\t"<<theta2<<"\t"<<c<<"\t"<<Dloc<
<"\n";
distance.close();
}
void CalcDcz()
{
//calculates clearance zone distance
l = 4.2;
w = 14.63;
cout<<"Dcz: gps[1][4] = "<<gps[1][4]<<"\n";
cout<<"Dcz: gps[1][6] = "<<gps[1][6]<<"\n";
Dcz = gps[1][4]*gps[1][6] - l - w;
cout<<"Dcz = "<<Dcz<<"\n";
}
int CheckAcc()
{
//checks if car is accelerating/cruising or decelerating
a = (gps[1][4] - gps[0][4])/time;
// cout<<"CheckAcc: a = "<<a<<endl;
if(a>=0)
return 1; //acceleration >= 0
else
return 2; //acceleration < 0
}
71
int AccLess0()
{
//checks if Dstop < Dloc
Dstop = (gps[1][4]*gps[1][4])/(2*abs(a)) + (2*gps[1][4]);
CalcDloc();
cout<<"Dstop = "<<Dstop<<endl;
if (Dstop>Dloc)
return 1; //towards alarm - requires more distance to stop than is available
else
return 2;
}
int Acc0orMore()
{
CalcDloc();
// cout<<"Acc0orMore: Dloc = "<<Dloc<<endl;
a_pred = -(gps[1][4]*gps[1][4])/(2*Dloc);
cout<<"a_pred = "<<a_pred<<endl;
//different comfortable ranges for different distances
//too close to stop line - obviously, even small accelaration is dangerous
if(Dloc>30)
if (a_pred<-1.5)
return 1; //Towards alarm: not in comfortable range
else
return 2;
if(Dloc<=30 && Dloc>20)
if(a_pred<-0.3)
return 1; //Towards alarm: not in comfortable range
else
return 2;
72
if(Dloc<=20)
if(a_pred<0)
return 1;
else
return 2;
}
int TimeGreen()
{
//calculate time to reach stop line
vsq = (gps[1][4]*gps[1][4])+(2*(a-0.5)*Dloc);
cout<<"v squared = "<<vsq<<"\n";
if(vsq>0)
{
v = sqrt(vsq);
// cout<<"TimeGreen(): a = "<<a<<"\n";
if(a == 0)
treach = (2*Dloc)/(v + gps[1][4]);
else if(a != 0)
treach = (v - gps[1][4])/(a-0.5);
cout<<"treach = "<<treach<<"\n";
}
if(vsq==0)
cout<<"Car at stop line\n";
if(vsq<0)
return 2;
if(gps[1][5]==1) //20R....should cross before countdowns
if(treach>gps[1][6])
return 1; //Alarm
else
return 2;
73
if(gps[1][5]==2) //20G....should cross after countdowns
if(treach<gps[1][6])
return 1; //Alarm
else
return 2;
}
void Alarm()
{
//send alarm to OBE
byte_send('X');
//alarm in RSE
cout<<"Alarm"<<"\n\a";
}
void RSUlonglat()
{
//assumptions
longitude = -72.534322;
latitude = 42.376835;
phi1 = 90-latitude;
theta1 = longitude;
}
void latencyflowcontrol()
{
int c1, c2, c3, enter=0, check=0, alarm=0;
//set RSU longitude/latitude
RSUlonglat();
//output file containing trajectory data
ofstream outfile("output.xls");
outfile<<"c2\tv\tTime\tLatitude\tLongitude\tSpeed\tR/G\tTL\tDcz\tDstop\tDloc\tc1\tc2\tc3\tAcceleratio
n\tAcc_pred\tV-squared\tVelocity\ttreach\tAlarm"<<endl;
74
CalcDcz();
CalcDloc();
c2 = 0;
//always loop
while(c2 == 2 || enter == 0)
{
c1 = 0;
c2 = 0;
c3 = 0;
alarm = 0;
//not entered first time? yes; clearance zone check
if(enter != 0)
do
{
RetrieveGPS();
CalcDcz();
CalcDloc();
// cout<<"Dcz = "<<Dcz<<"\n";
// cout<<"Dloc = "<<Dloc<<"\n";
}
while(gps[0][0] == 0 || gps[1][0]==0);
//car not moving scenario
if(Dcz<-18.83)
{
cout<<"Either tl = 0 or car not moving"<<endl;
check = 1;
c2 = 2;
}
else
check = 0;
enter = 1;
//for green: car should be outside Dcz
if(gps[1][5] == 1)
75
{
if(Dloc<Dcz && check==0)
{
cout<<"In Clearance Zone\n";
c2=2;
}
}
//for red: car should be inside Dcz
if(gps[1][5] == 2)
{
if(Dloc>Dcz && check==0)
{
cout<<"In Clearance Zone\n";
c2=2;
}
}
//Decision for Check 1: Accelerating/cruising or decelerating
//for green
if(gps[1][5] == 1)
if(Dloc>Dcz && check==0)
c1 = CheckAcc();
//for red
if(gps[1][5] == 2)
if(Dloc<Dcz && check==0)
c1 = CheckAcc();
cout<<"c1 = "<<c1<<"\n";
//if not in clearance zone, enter
if (c1 == 1 && check==0)
c2 = Acc0orMore(); //if not in comfortable deceleration range: c2 = 1
else if(c1 == 2 && check==0)
c2 = AccLess0(); //if Dstop>Dloc: c2 = 1
if(Dloc == 0) //if at stop line, exit program
76
c2=0;
cout<<"c2 = "<<c2<<"\n";
outfile<<c2<<"\t";
//Check 3: Warning?
if (c2 == 1 && check==0)
{
c3 = TimeGreen(); //if time to reach stop line < time for light to turn
green: c3 = 1
if(vsq<0) //if negative: means decelerating and can stop before
stop line. no alarm
c2=2;
}
cout<<"c3 = "<<c3<<"\n";
//Check 4: Alarm?
if (c3 == 1 && check==0)
{
if(c1 == 2)
if(Dloc < 40 && gps[1][4] > 12) //to avoid premature alarms
{
alarm = 1;
Alarm();
}
if(c1 != 2)
{
alarm = 1;
Alarm();
}
c2 = 2;
}
c2 = 2;
//outputting to a file
outfile.precision(8);
77
outfile<<gps[1][0]<<"\t"<<gps[1][1]<<"\t"<<gps[1][2]<<"\t"<<gps[1][3]<<"\t"<<gps[1][4]<<"\t"<<gps[1][
5]<<"\t"<<gps[1][6]<<"\t"<<Dcz<<"\t"<<Dstop<<"\t"<<Dloc<<"\t"<<c1<<"\t"<<c2<<"\t"<<c3<<"\t"<<a<<"\t"<<a_pre
d<<"\t"<<vsq<<"\t"<<v<<"\t"<<treach<<"\t"<<alarm<<endl;
}
outfile.close();
}
void latencyflow()
{
//set traffic light length and starting state
tl_start = 91;
tl_state = 2;
tl_start_sec = tl_start;
//keep getting gps data until connected to satellite
do
{
RetrieveGPS();
// CalcDloc();
}
while(gps[0][0] == 0 || gps[1][0]==0);
latencyflowcontrol();
}
Menu.cpp
#include "RoadSideUnit.h"
void main_menu()
{
clrscr();
cout << " System Interface Setup for Road Side Unit (RSU)\n";
cout << "\n";
cout << "\n";
cout << "\n";
78
cout << " Main Menu\n";
cout << "\n";
// cout << " 1. Open/Configure Traffic Light Serial Port\n";
cout << "\n";
cout << " 2. Open/Configure Router Virtual Serial Port\n";
cout << "\n";
cout << " 3. Test GPS Data Transmission\n";
cout << "\n";
cout << " 4. Begin Road Side Calculation\n";
cout << "\n";
cout << " 5. Exit\n";
cout << "\n";
cout << "Enter Selection 1 - 5: \n";
cout << "\n";
int ch;
do
{
ch = _getch();
ch = toupper(ch);
}
while(ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5');
switch(ch)
{
case '1' :
com_menu('T');
break;
case '2' :
com_menu('A');
break;
case '3' :
datatest();
break;
case '4' :
// test();
latencyflow();
break;
case '5' :
exit();
79
}
}
void com_menu(char menu)
{
clrscr();
cout << " System Interface Setup for Road Side Unit (RSU)\n";
cout << "\n";
cout << "\n";
cout << "\n";
cout << " Serial Port Selection Menu\n";
cout << "\n";
cout << " 1. COM1\n";
cout << " 2. COM2\n";
cout << " 3. COM3\n";
cout << " 4. COM4\n";
cout << " 5. COM5\n";
cout << " 6. COM6\n";
cout << " 7. COM7\n";
cout << " 8. COM8\n";
cout << " 9. COM9\n";
cout << "\n";
cout << "Select Serial Port To Open 1 - 9 Or X To Exit To Main Menu: \n";
int ch;
if(menu == 'T')
{
do
{
ch = _getch();
ch = toupper(ch);
}
while(ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6' && ch != '7'
&&
ch != '8' && ch != '9' && ch != 'S' && ch != 's' && ch != 'X' && ch != 'x');
if(ch == 'X' || ch == 'x')
main_menu();
else if(ch == '1')
open_serial_port("//./COM1", 'T');
80
else if(ch == '2')
open_serial_port("//./COM2", 'T');
else if(ch == '3')
open_serial_port("//./COM3", 'T');
else if(ch == '4')
open_serial_port("//./COM4", 'T');
else if(ch == '5')
open_serial_port("//./COM5", 'T');
else if(ch == '6')
open_serial_port("//./COM6", 'T');
else if(ch == '7')
open_serial_port("//./COM7", 'T');
else if(ch == '8')
open_serial_port("//./COM8", 'T');
else if(ch == '9')
open_serial_port("//./COM9", 'T');
}
if(menu == 'A')
{
do
{
ch = _getch();
ch = toupper(ch);
}
while(ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6' && ch != '7'
&&
ch != '8' && ch != '9' && ch != 'S' && ch != 's' && ch != 'X' && ch != 'x');
if(ch == 'X' || ch == 'x')
main_menu();
else if(ch == '1')
open_serial_port("//./COM1", 'A');
else if(ch == '2')
open_serial_port("//./COM2", 'A');
else if(ch == '3')
open_serial_port("//./COM3", 'A');
else if(ch == '4')
open_serial_port("//./COM4", 'A');
else if(ch == '5')
81
open_serial_port("//./COM5", 'A');
else if(ch == '6')
open_serial_port("//./COM6", 'A');
else if(ch == '7')
open_serial_port("//./COM7", 'A');
else if(ch == '8')
open_serial_port("//./COM8", 'A');
else if(ch == '9')
open_serial_port("//./COM9", 'A');
}
}
PortConfiguartion.cpp
#include "RoadSideUnit.h"
HANDLE TrafficSerial;
DCB dcbTraffic;
HANDLE AirBorneSerial;
DCB dcbAirBorne;
void set_serial_timeouts(char menu)
{
if(menu == 'T')
{
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if(!SetCommTimeouts(TrafficSerial, &timeouts))
{
cout << "Error Setting Port Timeouts. Please Check Serial Port Connections And Try
Again\n";
exit();
}
82
}
if(menu == 'A')
{
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if(!SetCommTimeouts(AirBorneSerial, &timeouts))
{
cout << "Error Setting Port Timeouts. Please Check Serial Port Connections And Try
Again\n";
exit();
}
}
}
void open_serial_port(char *port, char menu)
{
if(menu == 'T')
{
CloseHandle(TrafficSerial);
char *zport = port;
TrafficSerial = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
if(TrafficSerial == INVALID_HANDLE_VALUE)
{
if(GetLastError() == ERROR_FILE_NOT_FOUND)
{
CloseHandle(TrafficSerial);
cout << "\n";
cout << "\n";
cout << "Serial Port Does Not Exist. Press Any Key To Continue\n";
_getch();
com_menu('T');
}
83
cout << "\n";
cout << "Unexpected Error\n";
exit();
}
clrscr();
cout << "\n";
cout << "\n";
cout << "Opening Serial Port ";
cout << zport[4];
cout << zport[5];
cout << zport[6];
cout << zport[7];
cout << zport[8];
cout << "........\n";
cout << "\n";
cout << "Please Wait While Port Parameters Are Set.....\n";
cout << "\n";
Sleep(1400);
set_serial_port('T');
}
if(menu == 'A')
{
CloseHandle(AirBorneSerial);
char *zport = port;
AirBorneSerial = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0);
if(AirBorneSerial == INVALID_HANDLE_VALUE)
{
if(GetLastError() == ERROR_FILE_NOT_FOUND)
{
CloseHandle(AirBorneSerial);
cout << "\n";
cout << "\n";
cout << "Serial Port Does Not Exist. Press Any Key To Continue\n";
_getch();
com_menu('A');
}
cout << "\n";
84
cout << "Unexpected Error\n";
exit();
}
clrscr();
cout << "\n";
cout << "\n";
cout << "Opening Serial Port ";
cout << zport[4];
cout << zport[5];
cout << zport[6];
cout << zport[7];
cout << zport[8];
cout << "........\n";
cout << "\n";
cout << "Please Wait While Port Parameters Are Set.....\n";
cout << "\n";
Sleep(1400);
set_serial_port('A');
}
}
void set_serial_port(char menu)
{
if(menu == 'T')
{
DCB dcbSerialParams = {0};
dcbTraffic.DCBlength = sizeof(dcbSerialParams);
if(!GetCommState(TrafficSerial, &dcbSerialParams))
{
cout << "Unexpected Error. Please Check Serial Port Connections And Try Again.\n";
exit();
}
dcbSerialParams.BaudRate = CBR_9600;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if(!SetCommState(TrafficSerial, &dcbSerialParams))
{
85
cout << "Error Setting Port Paramaters. Please Check Serial Port Connections And Try
Again\n";
exit();
}
set_serial_timeouts('T');
cout << "Port Timeouts Set.\n";
cout << "\n";
cout << "Baud Rate Set To 2400.\n";
cout << "\n";
cout << "Byte Size Set To 8.\n";
cout << "\n";
cout << "One Stop Bit.\n";
cout << "\n";
cout << "Parity Bit Set To None.\n";
cout << "\n";
cout << "Port Opened Successfully. Press Any Key To Continue\n";
_getch();
main_menu();
}
if(menu == 'A')
{
DCB dccSerialParams = {0};
dcbAirBorne.DCBlength = sizeof(dccSerialParams);
if(!GetCommState(AirBorneSerial, &dccSerialParams))
{
cout << "Unexpected Error. Please Check Serial Port Connections And Try Again.\n";
exit();
}
dccSerialParams.BaudRate = CBR_2400;
dccSerialParams.ByteSize = 8;
dccSerialParams.StopBits = ONESTOPBIT;
dccSerialParams.Parity = NOPARITY;
if(!SetCommState(AirBorneSerial, &dccSerialParams))
{
cout << "Error Setting Port Paramaters. Please Check Serial Port Connections And Try
Again\n";
exit();
}
86
set_serial_timeouts('A');
cout << "Port Timeouts Set.\n";
cout << "\n";
cout << "Baud Rate Set To 2400.\n";
cout << "\n";
cout << "Byte Size Set To 8.\n";
cout << "\n";
cout << "One Stop Bit.\n";
cout << "\n";
cout << "Parity Bit Set To None.\n";
cout << "\n";
cout << "Port Opened Successfully. Press Any Key To Continue\n";
_getch();
main_menu();
}
}
char byte_receive_traffic_light()
{
char byte;
DWORD dwBytesRead;
if(!ReadFile(TrafficSerial, &byte, 1, &dwBytesRead, NULL))
{
cout << "Unable To Recieve Data. Check If Correct Port Is Open. Press Any Key To Continue\n";
_getch();
CloseHandle(TrafficSerial);
main_menu();
}
return byte;
}
char byte_receive_airborne()
{
char byte;
DWORD dwBytesRead;
if(!ReadFile(AirBorneSerial, &byte, 1, &dwBytesRead, NULL))
{
cout << "Unable To Recieve Data. Check If Correct Port Is Open. Press Any Key To Continue\n";
87
_getch();
CloseHandle(AirBorneSerial);
main_menu();
}
return byte;
}
void byte_send(unsigned char byte)
{
DWORD dwBytesWritten;
if(!WriteFile(AirBorneSerial, &byte, 1, &dwBytesWritten, NULL))
{
cout << "Unable To Send Data. Check If Correct Port Is Open. Press Any Key To Continue\n";
_getch();
CloseHandle(AirBorneSerial);
main_menu();
}
}
void exit()
{
cout << "Exiting Program.....";
Sleep(2500);
CloseHandle(TrafficSerial);
CloseHandle(AirBorneSerial);
exit(1);
}
RoadSideUnit.cpp
#include "RoadSideUnit.h"
void main(void)
{
main_menu();
}
88
test.cpp
#include "RoadSideUnit.h"
void test()
{
for(;;)
{
float* calcdata = data();
cout << calcdata[0];
cout << " ";
cout << calcdata[1];
cout << " ";
cout << calcdata[2];
cout << " ";
cout << calcdata[3];
cout << " ";
cout << calcdata[4];
cout << " ";
cout << calcdata[5];
cout << " ";
cout << calcdata[6];
cout <<"\n";
}
}
8.2 OBE Code
stdafx.h
#pragma once
#ifndef _stdafx_H
#define _stdafx_H
89
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <cstdlib>
#include <windows.h>
#include <conio.h>
#include <ctype.h>
#include <process.h>
#include <sstream>
#include <stdio.h>
using namespace std;
void test1();
void test2();
void test3();
void test4();
void test5();
void Tester(char a, int position);
void GPS(char a, int position);
void print();
//void time(char a, int position);
//void counter(char a, int position);
void sort(char a, int position);
void separate();
void format();
void byte_send(unsigned char byte);
void set_serial_port();
void open_serial_port(char *port);
void set_serial_timeouts();
void clrscr();
void main_menu();
void com_menu();
char byte_receive();
#endif
90
GPS.cpp
#include "stdafx.h"
void main()
{
//delete all text files if they exist to prevent use of old data in these files
remove("GPS_Read.txt");
remove("output.txt");
remove("tester.txt");
//DOS OBU Menu
main_menu();
}
GPS_Read.cpp
#include "stdafx.h"
void test4()
{
int loop = 0, e = 0, tellg, position[2] = {0, 0};
char a;
//GPS data input may be slower than VC++ read speed
//Thus the program loops several times to guarantee the file has stopped updating
//Increase the number of loops if you possess a faster computer. DO NOT comment it out
//hereafter called update check
while(loop<1000)
{
while(e==0)
{
//opens the GPS file
ifstream myfile("GPS_Read.txt");
//gets and saves the last position of the cursor in the file
myfile.seekg(-1L,ios::end);
91
tellg = myfile.tellg();
//checks if last position in file == current position
if(tellg==position[0])
e=1;
//if file open and position is not == last position; enter
if(myfile.is_open() && e==0)
{
while(!myfile.eof())
{
//set cursor to position[0] from start of file
myfile.seekg(position[0], ios::beg);
//get character at position[0]
myfile.get(a);
//if not performed update check and last position not reached
if(loop == 0 && position[1] != tellg)
Tester(a, position[0]);
//since the if was entered, update has occurred. thus, set loop back to 0
loop = 0;
//once last position is reached, and we continue trying to read after it
//VC++ assigns position -1. Which is useless to us because it does not tell
us exactly
//how many positions from start of the text file the read cursor is at. To
solve this:
//update position[1] with old position
position[1] = position[0];
//update position[0] with new position after reading a
position[0] = myfile.tellg();
}
}
//to clear the buffer of old read data before closing it
92
//we keep opening and closing the text file to check for updates
//as the GPS keeps updating GPS_Read.txt but when we open it, we see data from one moment
//to get new data, we close and open again and we see appended data
myfile.clear();
myfile.close();
//endline is read as a character. so we decrement cursor to position right after last
character
position[0] = position[1]-1;
}
//set e to 0 for new update check
e=0;
//increment number of update checks done
loop=loop+1;
}
// outfile.close();
}
stdafx.cpp
// stdafx.cpp : source file that includes just the standard includes
// GPS_Read.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
Tester.cpp
#include "stdafx.h"
static char rest[70], start[6], time[6], con, longdeg[2], longrest[7], longdir, latdeg[3], latrest[7],
latdir, speed[7];
static int count=0, flag=0, enter,timecheck[6], pflag=0;
static double longd, longr, latd, latr, velocity, longitude, latitude;
HANDLE cSerial;
DCB dccSerial;
93
ofstream outfile;
ofstream tester;
// funtion to transmit the time to the RSU via the Airborne Direct
void transmit_time(char *time)
{
for(int i = 0; i < 8; i++) //transfers the elements of the array one at a time
{
byte_send(time[i]);
}
}
// funtion to transmit the latitude to the RSU via the Airborne Direct
void transmit_latitude(float flatitude, char hemisphere)
{
char latitude[10];
sprintf_s(latitude, "%2.6f", flatitude); //converts latitude from float to an array of characters
for(int i = 0; i < 9; i++) //transfers the elements of the array one at a time
{
byte_send(latitude[i]);
}
byte_send(hemisphere); //transfers hemisphere
}
// funtion to transmit the longitude to the RSU via the Airborne Direct
void transmit_longitude(float flongitude, char hemisphere)
{
char longitude[10];
sprintf_s(longitude, "%2.6f", flongitude); //converts longitude from float to an array of
characters
for(int i = 0; i < 9; i++)
{
byte_send(longitude[i]); //transfers the elements of the array one at a time
}
byte_send(hemisphere); //transfers hemisphere
}
94
// funtion to transmit the speed to the RSU via the Airborne Direct
void transmit_speed(float fspeed)
{
char speed[10];
sprintf_s(speed, "%2.6f", fspeed);
for(int i = 0; i < 9; i++)
{
byte_send(speed[i]); //transfers the elements of the array one at a time
}
}
void clrscr()
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = {0, 0};
DWORD count;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hStdOut, &csbi);
FillConsoleOutputCharacter(hStdOut, ' ', csbi.dwSize.X * csbi.dwSize.Y, coord, &count);
SetConsoleCursorPosition(hStdOut, coord);
}
//funtion that exits the program
void exit()
{
cout << "Exiting Program.....";
Sleep(2500);
//closes all open handles to avoid any errors
CloseHandle(cSerial);
exit(1);
}
void Tester(char a, int position)
{
//open testing/debugging files
outfile.open("output.txt", ios::app);
tester.open("tester.txt", ios::app);
enter = 0;
95
//if $GPRMC already read and now relevant data is to be parsed
if(flag == 6 && enter == 0)
{
//$ indicates new line so $GPRMC line finished reading
if(a == '$')
{
flag = 0;
count = 0;
//extract longitude, latitude, connection, speed, time data from rest[]
separate();
//convert longitude and latitude to degrees. convert speed to m/s
format();
//output data to output.txt and tester.txt and main_menu() DOS screen
print();
}
else
{
//save all data after $GPRMC in an array called rest[]
sort(a, position);
}
}
//enter until $GPRMC line found
if(flag < 6 && enter == 0)
GPS(a, position);
//close testing/debugging files
outfile.close();
tester.close();
}
void GPS(char a, int position)
{
//function accessed until $GPRMC read
96
outfile<<"Entered GPS()\n";
outfile<<"flag = "<<flag<<"\n";
outfile<<"position = "<<position<<"\n";
outfile<<a<<"\n";
enter = 1;
if(a == '$')
{
flag = 1;
start[0] = a;
}
if(a == 'G' && flag == 1)
{
flag = 2;
start[1] = a;
}
if(a == 'P' && flag == 2)
{
flag = 3;
start[2] = a;
}
if(a == 'R' && flag == 3)
{
flag = 4;
start[3] = a;
}
if(a == 'M' && flag == 4)
{
flag = 5;
start[4] = a;
}
97
if(a == 'C' && flag == 5)
{
flag = 6;
start[5] = a;
print();
}
}
void print()
{
//empties array holding $GPRMC
if(flag == 6)
{
for(int r=0; r<6; r++)
start[r] = ' ';
}
//print only if sorting, separating and formatting have all been done
if(flag == 0)
{
//sometimes a line is read twice by GPS_Read.txt
//this check if time is same as last time read by program, then don't transmit/print
for(int r=0; r<6; r++)
if(timecheck[r] == time[r])
pflag = pflag+1;
//if new data
if(pflag != 6)
{
cout.precision(8);
tester.precision(8);
cout<<time<<" "<<con<<" "<<latitude<<" "<<longitude<<" "<<velocity<<"\n";
tester<<time<<" "<<con<<" "<<latitude<<" "<<longitude<<" "<<velocity<<"\n";
}
//clear all arrays
pflag = 0;
98
for(int r=0; r<6; r++)
timecheck[r] = time[r];
for(int r=0; r<6; r++)
time[r] = ' ';
for(int r=0; r<7; r++)
{
longrest[r] = ' ';
latrest[r] = ' ';
speed[r] = ' ';
}
for(int r=0; r<2; r++)
longdeg[r] = ' ';
for(int r=0; r<3; r++)
latdeg[r] = ' ';
for(int r=0; r<70; r++)
rest[r] = ' ';
con = ' ';
longdir = ' ';
latdir = ' ';
}
}
void sort(char a, int position)
{
outfile<<"Entered sort()\n";
outfile<<"flag = "<<flag<<"\n";
outfile<<"position = "<<position<<"\n";
outfile<<a<<"\n";
enter = 1;
99
rest[count] = a;
count = count + 1;
}
void separate()
{
enter = 1;
int i = 0, select=-1, j=0, f=0;
//while whole array has not been read
while(i<70)
{
//',' separates different pieces of info in GPS data: latitude,longitude...
while(rest[i] != ',')
{
switch(select)
{
//extract time data
case 0:
{
time[j] = rest[i];
j=j+1;
break;
}
//extract data whether GPS is connected to satellite. 'V': not connected. 'A':
connected
case 1:
{
con = rest[i];
break;
}
//extract longitude data
case 4:
{
if(j < 3 && f == 0)
{
longdeg[j] = rest[i];
}
else
100
{
if(j == 3 && f == 0)
j = 0;
f = 1;
longrest[j] = rest[i];
}
j = j + 1;
break;
}
//extract E/W
case 5:
{
longdir = rest[i];
break;
}
//extract latitude data
case 2:
{
if(j < 2 && f == 0)
{
latdeg[j] = rest[i];
}
else
{
if(j == 2 && f == 0)
j = 0;
f = 1;
latrest[j] = rest[i];
}
j = j + 1;
break;
}
//extract N/S
case 3:
101
{
latdir = rest[i];
break;
}
//extract speed data
case 7:
{
speed[j] = rest[i];
j = j + 1;
break;
}
}
i = i + 1;
}
select = select + 1;
j = 0;
f = 0;
//condition for when speed = 0 which is shown as a comma by GPS data
if(select == 6)
{
if(rest[i+1] == ',')
{
for(int j=0; j<7; j++)
{
speed[j] = '0';
}
}
select = 7;
}
i = i + 1;
}
}
void format()
{
//change longitude and latitude to degrees
longd = atof(longdeg);
longr = atof(longrest);
102
longr = longr/60;
longitude = longd + longr;
latd = atof(latdeg);
latr = atof(latrest);
latr = latr/60;
latitude = latd + latr;
//change speed to m/s
velocity = atof(speed);
velocity = velocity/0.5144456334;
velocity = velocity*0.2777777778;
//to transmit data to RSU
byte_send('(');
byte_send(con);
byte_send(')');
byte_send('$');
transmit_time(time);
byte_send('*');
byte_send('@');
transmit_latitude(latitude, latdir);
byte_send('#');
byte_send('!');
transmit_longitude(longitude, longdir);
byte_send('%');
byte_send('^');
transmit_speed(velocity);
byte_send('&');
}
//funtion that sends data via the serial port
void byte_send(unsigned char byte)
{
DWORD dwBytesWritten;
if(!WriteFile(cSerial, &byte, 1, &dwBytesWritten, NULL)) //data in the byte variable is sent to the
serial ports one byte at a time
{
103
cout << "Unable To Send Data. Check If Correct Port Is Open. Press Any Key To Continue\n";
//in the event of error while sending data program is routed back to the main menu
_getch(); //wait for user input
CloseHandle(cSerial);
main_menu();
}
}
char byte_receive()
{
char byte;
DWORD dwBytesRead;
if(!ReadFile(cSerial, &byte, 1, &dwBytesRead, NULL))
{
cout<<"Unable to Receive Data. Check if correct port is open. Press any key to continue\a";
_getch();
CloseHandle(cSerial);
main_menu();
}
return byte;
}
// function that sets serial port parameters
void set_serial_port()
{
DCB dccSerialParams = {0};
dccSerial.DCBlength = sizeof(dccSerialParams);
if(!GetCommState(cSerial, &dccSerialParams))
{
cout << "Unexpected Error. Please Check Serial Port Connections And Try Again. Press any key to
continue.\n";
_getch(); //waits for user input
com_menu();
}
dccSerialParams.BaudRate = CBR_2400; //sets baud rate to 2400
dccSerialParams.ByteSize = 8; //sets byte size to 8
dccSerialParams.StopBits = ONESTOPBIT; //sets stop bit to one
dccSerialParams.Parity = NOPARITY; //sets parity to none
if(!SetCommState(cSerial, &dccSerialParams)) //assigns parameters to the serial port
104
{
cout << "Error Setting Port Paramaters. Please Check Serial Port Connections And Try Again.
Press any key to continue.\n";
_getch(); //waits for user input
com_menu();
}
set_serial_timeouts();
cout << "Port Timeouts Set.\n";
cout << "\n";
cout << "Baud Rate Set To 2400.\n";
cout << "\n";
cout << "Byte Size Set To 8.\n";
cout << "\n";
cout << "One Stop Bit.\n";
cout << "\n";
cout << "Parity Bit Set To None.\n";
cout << "\n";
cout << "Port Opened Successfully. Press Any Key To Continue\n";
_getch(); //waits for user input
main_menu();
}
// funtion that opens a desired serial port
void open_serial_port(char *port)
{
CloseHandle(cSerial);
char *zport = port;
cSerial = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
0);
if(cSerial == INVALID_HANDLE_VALUE)
{
if(GetLastError() == ERROR_FILE_NOT_FOUND) //in the event a time out occurs a program
routs back to the com menu
{
CloseHandle(cSerial);
cout << "\n";
cout << "\n";
105
cout << "Serial Port Does Not Exist. Press Any Key To Continue\n";
_getch(); //waits for user input
com_menu();
}
cout << "\n";
cout << "Unexpected Error. Press Any Key To Continue\n";
_getch(); //waits for user input
com_menu();
}
clrscr();
cout << "\n";
cout << "\n";
cout << "Opening Serial Port ";
cout << zport[4];
cout << zport[5];
cout << zport[6];
cout << zport[7];
cout << zport[8];
cout << "........\n";
cout << "\n";
cout << "Please Wait While Port Parameters Are Set.....\n";
cout << "\n";
Sleep(1400);
set_serial_port(); //calls funtion to set serial port parameters
}
// function that sets the time outs for a serial port
void set_serial_timeouts()
{
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if(!SetCommTimeouts(cSerial, &timeouts)) //in the event a time out occurs a program routs back to
the main menu
106
{
cout << "Error Setting Port Timeouts. Please Check Serial Port Connections And Try Again. Press
Any Key To Continue.\n";
_getch(); //waits for user input
main_menu();
}
}
void main_menu()
{
clrscr(); //clears screen
cout << " System Interface Setup for On Board Unit (OBU)\n";
cout << "\n";
cout << "\n";
cout << "\n";
cout << " Main Menu\n";
cout << "\n";
cout << " 1. Open/Configure Airborne Direct Serial Port\n";
cout << "\n";
cout << " 2. Start Transmitter\n";
cout << "\n";
cout << " 3. Exit\n";
cout << "\n";
cout << "Enter Selection 1 - 3: \n";
cout << "\n";
int ch;
do //checks for correct input
{
ch = _getch();
ch = toupper(ch);
}
while(ch != '1' && ch != '2' && ch != '3');
switch(ch) //switch statement directs the program to the correct function depending on user input
{
case '1' :
com_menu(); //calls the funtion to set the Airborn Direct Wireless serial port settings
break;
case '2' :
clrscr();
107
cout << "Time (GMT) Latitude Longitude Speed\n";
test4(); //calls the function to start the GPS Data acquision, parser and transmitter
break;
case '3' :
exit(); //exits the program
break;
}
}
// function that displays the serial port menu
void com_menu()
{
clrscr(); //clears screen
cout << " Global Positioning System Interface Setup\n";
cout << "\n";
cout << "\n";
cout << "\n";
cout << " Serial Port Selection Menu\n";
cout << "\n";
cout << " 1. COM1\n";
cout << " 2. COM2\n";
cout << " 3. COM3\n";
cout << " 4. COM4\n";
cout << " 5. COM5\n";
cout << " 6. COM6\n";
cout << " 7. COM7\n";
cout << " 8. COM8\n";
cout << " 9. COM9\n";
cout << "\n";
cout << "Select Serial Port To Open 1 - 9 Or X To Exit To Main Menu:";
int ch;
do //checks for correct input
{
ch = _getch();
ch = toupper(ch);
}
while(ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6' && ch != '7' &&
ch != '8' && ch != '9' && ch != 'S' && ch != 's' && ch != 'X' && ch != 'x');
108
if(ch == 'X' || ch == 'x') //exits to the main menu
main_menu();
//assigns a serial port to the Airborne Direct and calls funtion to open the desired serial port
else if(ch == '1')
open_serial_port("//./COM1");
else if(ch == '2')
open_serial_port("//./COM2");
else if(ch == '3')
open_serial_port("//./COM3");
else if(ch == '4')
open_serial_port("//./COM4");
else if(ch == '5')
open_serial_port("//./COM5");
else if(ch == '6')
open_serial_port("//./COM6");
else if(ch == '7')
open_serial_port("//./COM7");
else if(ch == '8')
open_serial_port("//./COM8");
else if(ch == '9')
open_serial_port("//./COM9");
}
109
Related docs
Get documents about "