Home
USB interfacing
Contents
1. VehOn Calibrated Value VehOft y inner Interval _y A Outer Interval J Figure 4 15 State Change Hysteresis Calibrated value in Figure 4 15 is a value of CCP1 counter obtained according to frequency measurement described in Chapter 4 3 2 When a vehicle enters the loop the loop inductance decreases see Chapter 2 4 1 and therefore oscillator frequency is increased according to Equation 2 1 and 2 3 the higher frequency the lower counter value It would be sufficient to implement left side of interval in Figure 4 15 only because a vehicle always causes lower counter value However the purpose of the ILD is to be versatile and therefore to detect ferromagnetic materials Chapter 2 4 1 as well Hence a symmetrical interval capable of detecting both types of materials has been introduced Code snippet in C language of the state machine follows if VehicleAbove ohe Ms oe if AverageCounter CalibCounter CalibCounterOff amp amp AverageCounter lt CalibCounter CalibCounteroff ate cec hate VehicleAbove false else fe dou glean Ike if AverageCounter lt CalibCounter CalibCounterOn AverageCounter gt CalibCounter CalibCounterOn O side abs oba loe VehicleAbove true CalibCounterOn and CalibCounterOff are hysteresis offsets they provide to set the device sensitivity Chapter 4 3 7 Both can be changed via on board DIP switches Chapter 4 3 7 CTU in Prague
2. Assignment Cesk vysok u eni technick v Praze Fakulta elektrotechnicka Katedra dic techniky ZAD N DIPLOMOV PR CE Student Miroslav Mach ek Studijn program Elektrotechnika a informatika magistersk strukturovan Obor Kybernetika a m en blok KMI dic technika N zev t matu Automatick s ta dopravy Pokyny pro vypracov n 1 Seznamte se s rodinou mikrokontrol r Microchip PIC18 Nastudujte mo nosti programov n a mo nosti periferi 2 Navrhn te a realizujte obvod pro sn m n induk n ch smy ek pro detekci vozidel v pohybu P i n vrhu berte v vahu nutnost rychl reakce detektoru vzhledem k mo n m vy m rychlostem vozidla Dbejte z rove na ochranu za zen proti p ep t a statick elekt in 3 Realizuje syst m pro sb r informac o rychlostech a d lk ch vozidel v etn nav z n na datab zov syst m a webov ho rozhran pro zobrazov n statistik o doprav 4 V e odzkou ejte a vypracujte podrobnou dokumentaci HW a SW v etn n vodu k obsluze Seznam odborn literatury Dod vedouc pr ce Vedouc Ing Michal Kutil Platnost zad n do konce zimn ho semestru 2009 2010 M Hi Oz LG gt prof Ing Michael ebek DrSc doc Ing Boris im k CSc vedouc katedry d kan V Praze dne 3 9 2008 IH A Abstract The aim of this thesis was to create a system for traffic data acquisition based on ind
3. The PIC18 microcontrollers can with some exceptions run at a clock speed up to 40MHz and they are generally equipped with the following on board peripherals e Watchdog timer e Internal clock oscillator CTU in Prague FEE Department of Control Engineering Page 10 of 100 Miroslav Mach ek Automatic Traffic Counter e PLL for multiplying the clock frequency e 8 16 Bit Timers 3 e Internal EEPROM memory e Synchronous Asynchronous Serial Interface USART e MSSP Peripheral for PC and SPI Communications e Compare Capture and PWM modules e Analog to digital converter e Analog Comparator There are many variants of PIC18 microcontrollers having different on board peripherals an example of a model in brackets e CAN 18F2480 e USB 18F2455 e Ethernet 18F66J60 3 1 2 Configuration Bits Every PIC microcontroller contains the configuration bits so called fuses whose are used to tell the microcontroller how it should handle external environment These bits are mapped at the start of program memory at 0x300000 and have to be set during programming the chip The fuses set behavior of PIC on board peripherals such as Watchdog Oscillator Memory protection and others Some important fuses are listed in Table 3 1 a full description of fuses can be found in the Microchip PIC device s data sheet 15 16 Detailed process of setting the fuses can be found in Chapter 3 3 4 Crystal oscillator lt 4Mhz Crystal oscillator
4. gt 4Mhz Crystal oscillator lt 4Mhz Crystal oscillator gt 4Mhz XTPLL pe H4 with frequency multiplier with 4x frequency multiplier NOWDT no Watchdog Timer NOLVP DUIS OV k e programming pin NODEBUG don t enable debug MCLR Master Clear Reset pins for ICD pin enabled NOPROTECT Code not protected NOEBTRB Boot block not protected from reading from table reads write protected Table 3 1 Microchip PIC Configuration bits selection CTU in Prague FEE Department of Control Engineering Page 11 of 100 Miroslav Mach ek Automatic Traffic Counter 3 1 Microchip MPLAB Development Environment MPLAB IDE Figure 3 2 is a free toolset for managing projects for Microchip microcontrollers writing source code compiling simulating and debugging It contains interface for additional Microchip or third party development tools such as C compilers and PIC emulators real time debuggers Application contains integrated MPASM assembler language compiler al USB serial MPLAB IDE v7 50 File Edit View Project Debugger Programmer Tools Configure Window Help ol sme Shwe Release v ap ld Rb O P O EB USB 5 m MPLAB IDE Editor ex usb serialc usb cdc h 18F2455 h 6 Fuse rs232 baud 19200 xmit PIN C6 rcv p definition LJ USB serial mcr Source Files Y Header Files compiler E Output Build Version Control Find in Fi
5. having the table structure according to the model in Figure 6 1 It implements multi client TCP server through socket connections Figure 6 2 demonstrates the operation of the server At first a socket server is established and then it waits for a new client or data from any currently connected client Communication and protocol are described in Chapter 5 5 6 When a new client is connected authorization in terms of receiving headers in Text mode has to be made Once the headers have been successfully acquired from the client the server awaits vehicle and temperature data in binary form In case of any error in communication the client is disconnected Once all vehicle or all temperature samples have been received they are converted to text form saved into text files and uploaded to the database Create Socket Server Initialisation Connect to Database Wait for Socket Event New client connected Data from current clients Process Authorization Headers i Binary Data Client Errors Disconnections Anything to Parse Convert Binary Traffic or to Text Temperature data Upload to Database Figure 6 2 Traffic Server Operation CTU 1n Prague FEE Department of Control Engineering Page 58 of 100 Miroslav Mach ek Automatic Traffic Counter 6 3 1 Sockets in PHP Sockets in PHP are similar to C language sockets The following PHP code snippet sets up a TCP socket for listening on port 10000 Ssocket s
6. the outcome is shown in Figure 6 5 gt f suneglebace sdatepweker 4 maxDate 0 datekormat o datcpicker WC SibowOm e bou DUGEOnImMage images cene o buttonImageOnly true firstbay I 1 From 2008 11 27 i il November 2008 i MO TU WE TH FR SA SU 112 al 4 5 6 7 ef 2 20 11 12 13 14 15 16 17 18 19 20 21 22 23 _ 24 25 26 27 28 29 30 Figure 6 5 Datepicker plugin for jQuery 6 4 1 3 Tablesorter Tablesorter 34 provides sorting feature and a nice graphical layout of HTML tables via jQuery library It is a former plugin of jQuery UI since it has been separated from jQuery Figure 6 6 demonstrates the result of Tablesorter plugin CTU in Prague FEE Department of Control Engineering Page 66 of 100 Miroslav Mach ek Automatic Traffic Counter Lane e OO s i a speed l Irec Ham Zc zt Dat n adat Fi t Numi J5 Direction Name Desc Last Data Update Limit Functions 0 1 Towards Centre 2008 12 04 23 25 57 50 Traffic Stats Traffic and LPR Temperature Stats Edit 1 0 From Centre 2008 12 04 20 53 07 Traffic Stats LPR and speed Temperature Stats Edit Figure 6 6 Tablesorter Plugin for jQuery The HTML table should contain THEAD and TBODY tags so that the tablesorter can be applied on the table The following code outlines the table structure table id myTable gt lt thead gt LTES lt th gt Last Name lt th gt lt th gt First Name lt th gt lt
7. this can be achieved by placing the following definition in source code right after device and fuses definitions ae ice 18 24 200 las device adc 10 F USES NOWDT No Watch Dog Timer FUSES WDT128 Watch Dog Timer uses 1 128 Postscale FUSES H4 High speed osc with HW enabled 4X PLL FUSES PROTECT Code not protected from reading fuse delay clock 40000000 START OF BOOTLOADER DEFINITION define MAX FLASH getenv PROGRAM MEMORY define LOADER SIZE OxFF siavolo size a a Out moce 200 Jayees 15 enough ouild reset 0x0000 0x0007 forg MAX FLASH LOADER SIZE MAX FLASH 1 void boot loader void END OF BOOTLOADER DEFINITION Page 22 of 100 Miroslav Mach ek Automatic Traffic Counter 4 Inductive Loop Detector Inductive Loop Detector ILD Figure 4 1 is a device developed for finding out whether a vehicle 1s above an inductive loop Particularly the presence of a conductive metal object i e axles or a chassis of a vehicle is recognized by a change in inductance of a loop embedded in the roadway Chapter 2 4 Figure 4 1 Inductive Loop Detector 4 1 Device Description Figure 4 2 depicts a system structure During the development of this device it was mandatory to keep in mind that the device had to respond in the shortest time interval possible Therefore given that it is quick and easy to implement one of the fastest ways for measuring inductance was to measure frequency change of a re
8. 0 a G Output Trotha oer TraPheCounter em Traffiecouniter hex Traffiacourie ppm Tra Pc pontes Jet TraFfeCpuniter ent iI Lanea ACIUALLPRE timers LAB MLIUALLANKE Timerzs D LAnes ACIUALLRME timersoLd Lames ACIUALLAME Seacess Tra fie outer PTT lan Cle amp riane ncCIUALLAME Trafficcouniier tre break Tra fec ouniter tta nass d 5 E 3 x A Lar it bic cest Currenrt AMCIUALLANE bic TEST Current ACIUALLAMNE z Lanea RCTUALLAME timers 3 get timer LE LADES AZCIVALLANL timersof 170 ifiLanesn ACIUALLANME rimera 3 cLanes ACIUALLAME cimers l Lanes ACIUALLANE rimeraof l Pb wei insert Pye tratficceunter Una Trafic counter d data taranuritrafficcounters Traffictaunberc Figure 3 6 CCS C Compiler IDE The compiler has to be obtained for particular PIC family or as a combination of them e PCB for 12 bit PIC MCUs PIC10 PICI2 e PCM for 14 bit PIC MCUs PIC16 e PCH for 14 bit PIC MCUs PIC18 e PCD for 24 bit PIC MCUs PIC24 dsPIC It should be noted that the PIC18 family only has been used for this thesis and hence PCWH IDE PCH compiler have been used for development 3 3 2 Installation The compiler is as default installed into C Program Files PICC directory There 1s the following structure of its subfolders e Devices header files h for PIC microcontrollers e Drivers libraries for various devices e g memories sensors displays drivers for CAN and USB modules e Examples ex
9. 25 of 100 Miroslav Mach ek Automatic Traffic Counter 4 2 Loop Oscillator Circuit In order to detect changes in inductance of a loop a resonant circuit has been introduced Detection 1s carried out by measuring a resonant freguency of the circuit that consists of parallel combination of inductor and capacitor The capacitor value 1s fixed whereas inductance of the loop changes as a conductive metal object comes near the loop Hence the presence of a vehicle near the loop causes change in the frequency of the oscillator Later on this signal 1s processed by a microcontroller described in Chapter 4 3 2 Two different oscillator circuits have been examined It should be noted that the second circuit has been employed in the final version of the ILD Their pros and cons are discussed in the following two subheads 4 2 1 Circuit based on Comparator The schematic based on 19 is shown in Figure 4 6 The main component is a comparator LM311 Components L1 and C1 creates a parallel LC circuit The advantage of this circuit is that 1t can be powered by single power supply only and that the output is already in TTL logic which simplifies a connection to the microcontroller Figure 4 6 Oscillator Circuit with Comparator This circuit was originally used for measuring small capacitors and inductors Unfortunately when a loop several meters of wire having non zero resistance is used in this circuit the output signal gets noisy Thi
10. 7 Transferring Samples Vehicle and temperature buffers are implemented and filled as described in Chapter 5 2 4 Once a connection to the server has been established and the station has been authorized by the server see headers in Chapter 5 5 6 both buffers are transferred to the server in binary form Both sample arrays have items encapsulated within union structure thus all data can be accessed via bytes array The following outlines the function for transferring data in binary form Every byte of the vehicle sample is sent to the GPRS modem Temperature buffer is handled in a similar way void BinarySendVehicle unsigned int16 index ehari iy EOC E O Lop eT a EON ore OPETE EEn eE pryt ee GPRS CTU in Prague FEE Department of Control Engineering Page 55 of 100 Miroslav Mach ek Automatic Traffic Counter 6 Server Applications Previous chapters deal with traffic data acquisition and uploading to the server in binary form over a TCP connection Thus there has to be a mainframe application Traffic Server Chapter 6 3 for receiving and processing at the server side The application communicates with Traffic Counter station over the Internet places the received data into files and uploads them to the database as well The latest part is a web interface Traffic Statistics Chapter 6 4 for viewing a state of stations and their traffic information Both applications scripts are written in PHP language 30 so
11. CTS signals no handshaking has been used However the modem sets the CD Carrier Detect pin 1 signal once a GPRS connection has been established 5 5 3 AT Commands The modem communicates via a standard modem AT command set Each command starts with 47 prefix and is processed by the device when inn CRLF string is received The response from the modem also ends with inn Modem configuration needs to be saved into its EEPROM memory AT amp W command Table 5 5 contains a list of selected AT commands full command set can be found in 17 x Set handshaking mode ex A7 IFC 0 0 AT CPIN val Sets PIN code for SIM card ATSPADDST ip Set Server IP address and Port ex ort a ATSPADDST 192 168 1 1 12345 CONNECT ATD 99 ERROR Open GPRS connection NO CARRIER Escape sequence switch from data to AT command mode Table 5 5 List of Important AT Commands 5 5 4 Modem Configuration Before using the modem it needs to be configured for active TCP connections The following describes configuring the modem for TCP mode for UDP and PPP modes the reader should refer to 16 CTU in Prague FEE Department of Control Engineering Page 52 of 100 Miroslav Mach ek Automatic Traffic Counter 1 Baud rate and handshaking NITIPR 1U9200X En ATIF C 0 OAT o 2 Network access point AT ce ON p terme wae wil 3 Active TCP connection ATSHOS TUE 2XE wn IS As qo ess SEI 4 Target IP and port ex
12. ERROR 5 5 6 Server Protocol Communication protocol is described in Figure 5 13 When a connection to the server application Traffic Server in Chapter 6 3 has been established according to process described in Chapter 5 5 5 the client e g Traffic Counter station sends headers to be recognized and authorized by the server Headers are sent in text mode id value and are separated by semicolon There are 8 mandatory headers Table 5 6 If they are not sent the client 1s disconnected Acquisition End unix timestamp Table 5 6 Client Authorization Headers Hence the header string look similarly to the following Afterwards in case of a proper authorization a binary mode is set and vehicle and temperature samples are transferred see Chapter 5 5 7 Every time a reply from a second side is expected there is a timeout so that connection is closed when an error occurs If server sends ERROR or BYE connection is also terminated All text messages are delimitered by nn CTU 1n Prague FEE Department of Control Engineering Page 54 of 100 Miroslav Mach ek Automatic Traffic Counter Traffic Counter Connect Establish TCP Connection Response HELLO Authorization Headers Response OK ERROR Close Con Vehicle Samples Transfer entire veh buffer Response OK ERROR Temperature Samples Transfer entire temp buffer Response i User GPRS Timer Figure 5 13 Client Server Communication Diagram 5 5
13. FEE Department of Control Engineering Page 35 of 100 Miroslav Mach ek Automatic Traffic Counter 4 3 6 LED Outputs There are three LED diodes position shown in Figure 4 3 on the ILD Green Yellow Red Each of them has a different meaning also depending on the device calibration state Their purpose is described in Appendix 5 4 3 7 Setting Device Parameters The detector is equipped with 2 blocks of DIP switches position shown in Figure 4 3 used for configuring the device a Oscillator frequency DIP switches in Figure 4 3 set the loop oscillator s frequency by adding parallel capacitors to the oscillator LC tank see C1 and Ll in Figure 4 7 Frequency decreases as capacitance grows Equation 2 1 There is a fixed 10nF capacitor In addition there are 2 switches for adding 33nF and 100nF capacitors to the circuit It is necessary to keep in mind that the oscillator frequency has a limited range of 20 kHz to 145 kHz in the firmware Chapter 4 3 2 When 2 detectors are working close to each other crosstalks may occur In other words one detector may influence the other one Therefore to avoid the crosstalk operating frequencies have to different from each other In order to determine the frequency easily the device expresses the actual operating frequency by yellow LED diode blinking see Appendix 5 Loop frequency can be selected by frequency switches see Figure 4 3 for position Their combinations and possible ind
14. GetMean unsigned int16 arr char length unsigned int32 Sum 0 echar Ly EOL O oa Wer yi mE ase aos Sum length RST S S Op o ERE unsigned ane lo GeebovieawLomtunswoned mat 6 2 unis ceo nmt do meanvyalue char length UMS a eS RES 6 unl 0 Sama 05 STE c Por Uk len lao sumi unsigned anto abs Usrgned int 32 arr a l meanvalue SUM S l Sum2 Sum1 Seen CASIO ASO Abr e JE to A eere HO ely a cial O o Suu It shall be noted that there is no square root function at the end of GetDeviation function Again the deviation value does not have to be calculated accurately and square root math function takes up plenty of machine cycles to be worked out Calibration is performed during the following events e Power up Reset e A loop is disconnected and connected again e The mean value changes during vehicle recognition mode e Vehicle is above the loop continuously for 5 minutes CTU in Prague FEE Department of Control Engineering Page 33 of 100 Miroslav Mach ek Automatic Traffic Counter It should be noted that the oscillator frequency is limited to 20kHz to 145kHz If frequency is out of range calibration will not be performed and the device will behave as if there was no signal see Chapter 4 3 6 Calibration 1s successful if the value obtained by GetDeviation function is lower than Deviation Threshold described in Chapter 4 3 7 4 3 5 Vehicle Recognition When the device is suc
15. TENcom SPEEDER RS 24 is shown in Figure 5 11 The modem communicates via a standard RS 232 interface CTU in Prague FEE Department of Control Engineering Page 50 of 100 Miroslav Mach ek Automatic Traffic Counter POWER DC SPEEDER RS cO ME Figure 5 11 TENcom SPEEDER RS GPRS Modem Modem highlights are listed in Table 5 4 The modem can be run at different baud rates and SW or HW handshaking can be used The modem provides embedded UDP and TCP IP stack which makes all network operations transparent to the user Power Supply 7 30V DC 900 1800 1900MHz F GSM Voice FR EFR HR SMS Text PDU MO MT GPRS Mode Class B Multislot Class 12 4Rx 4Tx Max 5 Slots Speed 85 6kb s Tx and Rx Interface RS 232 standard AT command set Speed 9600 115200 baud selectable SW or HW handshake UDP TCP IP stack PPP PAD CMUX Table 5 4 Speeder RS Specification 5 5 2 Communication The modem is a DCE with a Cannon 9 female connector There is a male connector on the Traffic Counter board so that it is a DTE Connection between the devices should be via a 1 1 RS 232 cable The communication properties have been chosen as the following modem factory defaults in brackets e 19200 115200 baud 8 bits no parity 1 stop bit no handshake RTS CTS CTU in Prague FEE Department of Control Engineering Page 51 of 100 Miroslav Mach ek Automatic Traffic Counter Even though the modem provides HW handshaking via RTS
16. connected with 2 inductive loops build in the roadway surface of the lane The device apart from vehicle data also takes samples of indoor and outdoor temperature and all data is transferred via a GPRS modem to the server Device parameters can be configured via a command line interface running over RS 232 line 2 Technical Data LED3 R SW LED2 Y O 1 LED1 G CTU in Prague FEE Department of Control Engineering Page 90 of 100 Miroslav Mach ek Appendix 9 Automatic Traffic Counter Board Dimensions 126 mm L x 125 mm W x 23 mm H excluding Detector boards Connectors Conl Con2 ARK2500V A 3P ARK2500F A 3P for cable side Con3 Cannon 9 pin Female Con4 Cannon 9 pin Male Con5 8 Cannon 25 pin Female Communication GPRS Modem RS 232 19200 8NI no handshake PC RS 232 115200 8N1 no handshake Date and Time RTC chip on board time keeping will be working several after power supply disconnect Traffic Data Capture Date Time Lane Speed Length Sample Buffer Memory up to 400 Vehicle and 70 Temperature Samples transferred to server over GPRS in time intervals Temperature Sensors 2 Digital sensors 1 On Board Indoor 1 On External Connector Outdoor Device Configuration Over PC RS 232 Command line Interface LEDs Green Device State Yellow Vehicle Sampling Red GPRS State CTU in Prague FEE Department of Control Engineering Page 91 of 100 Miroslav Mach ek Appendix 9 Automa
17. electrostatic discharge coming from the loop The following two types of surge protectors have been used a Gas Discharge Tube Figure 4 9a b TVS Diode Transil Figure 4 9b Figure 4 9 Overvoltage Protectors a Gas Discharge Tube b TVS Diode Gas Dicharge Tubes are gas filled components which protect against overvoltage from tens of Volts typically 100V They are characterized by low capacitance approx IpF and high currents thousands A they are able to withstand In spite of that TVS Diodes can protect the circuit even from several CTU in Prague FEE Department of Control Engineering Page 28 of 100 Miroslav Mach ek Automatic Traffic Counter Volts Hence it is a good practice to combine both types of protectors Figure 4 10 shows the protection used Normal diodes in bridge improve freguency behaviour of TVS Diodes gt To Circuit Za D gt To Circuit Loop Figure 4 10 Overvoltage Protection 4 3 Microcontroller Chapter 4 2 described the approach of measuring the inductance of the loop The sine wave output of the oscillator has been converted into a TTL signal whose frequency is to be measured and processed by the microcontroller This chapter describes the microcontroller its peripherals used and the firmware implementation The operation diagram is depicted in Figure 4 11 After the device is powered on the microcontroller peripherals such as Timers Ports are configured Afterwards th
18. enabled 4X PLL Resistor Capacitor Osc Internal RC Osc no CLKOUT Internal RC Osc Fail safe dock monitor disabled Fail safe clock monitor enabled Internal External Switch Over mode enabled Internal External Switch Over mode disabled No Power Up Timer Power Up Timer Brownout controlled by configuration bit in special file register Brownout enabled during operation disabled during SLEEP Reset when brownout detected No brownout reset Figure 3 7 CCS C Compiler Fuses Quick View CTU in Prague FEE Department of Control Engineering Page 16 of 100 Miroslav Mach ek Automatic Traffic Counter 3 3 5 Interrupts The Microchip PIC family offers various internal external interrupts such as timer overflow external edge trigger serial line receive and others Similarly to previous subchapter the CCS Compiler IDE provides a quick list Figure 3 8 of interrupts available for particular microcontroller 6 Valid INT Keywords PICT 8F 2620 Timer O overflow using ATCC name Timer 0 overflow using TIMERO name Timer 1 overflow Timer 2 overflow Timer 3 overflow External interrupt External interrupt 1 External interrupt 2 Part B any change on B4 B Analog to digital conversion complete H5232 receive data available AS232 transmit buffer empt SPI ar 2C activit Capture ar Compare an urit 1 Capture ar Compare on unit 2 Bus collision F igure 3 8 CCS C Compiler Interrupt Quick View PIC18 family introduce
19. external resistors There is a 10MHz crystal oscillator connected to the microcontroller The microcontroller uses its frequency multiplier H4 fuse in Table 3 1 which yields 40MHz input clock to the microcontroller and 10MHz of effective clock further details in 15 CTU in Prague FEE Department of Control Engineering Page 30 of 100 Miroslav Mach ek Automatic Traffic Counter AL RFT KRI3IPGD TL RES KBIZ PGC 26 RES KBIV PGM MCLR VEPJRE3 eL 1 RAO ANO lt RAVANT lt RA2IAN2 VREF CVREF RA3 AN3 VRErF RAA TOCKI C1OUT LJ RAS ANA SS HLVDINIC20UT lt Ves OSCVCLKURAT OSC2 CLKO RA6 10 RCO T10SO T13CK 11 RCUTIOSIICCP2l a e 12 RC2 CCP1 1413 RC3 SCK SCL 14 Figure 4 12 PICIGF2420 pinout REU INTQ FLTO AN 12 4 20 Voo PIC18F2420 PIC18F2520 17 RC6 TXICK 16 4 RC5 SDC 15 RC4 SDI SDA 4 3 2 Frequency measurement Capture Compare PWM module CCP is a PIC on board peripheral for timing inputs outputs It can be configured in Capture mode that allows interrupt on change when rising falling edge appears on the CCP1 input pin 13 Figure 4 13 depicts the function of CCP module when it 1s configured in Capture mode G Prescaler Falling Rising Capture Timer se 1 4 16 Edge Set Interrupt pin Figure 4 13 CCP module in Capture mode The following has to be set to con
20. has to select a COM port where the microcontroller is connected to and the communication speed 1 e baud rate A hex file containing compiled user firmware has to be opened via Browse button After that the target microcontroller has to be put in reset by disconnecting its power supply or by pulling low its MCLR pin Consecutively the user has to release the microcontroller from reset state e g pull MCLR pin high followed by clicking on Write Flash button Finally the user application should be flashed into the microcontroller If the user does not click on Write Flash Button 1 e PC application will not send initialization to the chip the user firmware in a microcontroller will be executed CTU in Prague FEE Department of Control Engineering Page 21 of 100 Miroslav Mach ek Automatic Traffic Counter Interface ta TinvBootLoader v1 3 8 contact claudia chiculitacugal ra http Aneto ugal ra cchiculia saftware picbootlaader Hhtrn cornd COM 1 CTU in Prague FEE Department of Control Engineering Figure 3 11 Tiny Bootloader PC Application 3 4 3 Changes to the User s Source Code The Tiny Bootloader resides at the very end of program memory Thus when compiling the user source code the compiler has to be aware of the fact that nothing can be placed at the end of program memory where the bootloader program resides Otherwise the bootloader code would be overwritten and therefore destroyed Within the CCS C Compiler
21. main loop see Chapter 5 4 2 The following function receives a character when it is ready saves it into the buffer and sets process flag inline void PCBufferIsr 6 echar e c fgetc PC nr wap ime PCBufterPointer gt 0 CE a PO Cle bane Me ABA Se EXEUDIem oret PCBuffer PCBufferPornter N0 susc DITE IECIT O EOB rem js PCBufferPointer 0 PCBUPEPCrPT ecess cerue CTU in Prague FEE Department of Control Engineering Page 48 of 100 Miroslav Mach ek Automatic Traffic Counter else PeBunirer PCRBULrrere Om wer e if PCBufferPointer lt PC_BUFFER_LENGTH 1 POB OS m m 5 4 2 Buffer Processing There are 2 types of command with or without value Character buffer contains entire string received over the serial line Figure 5 10 depicts the processing algorithm At first it is verified that the command exists If the command cannot contain a value a response to the command is generated Otherwise if the command received contains a value it means that the users is going to change device configuration Hence the value 1s parsed and saved Process Buffer Look up the command no Command exists Reply Error Message Find the command in the array of available commands Any numeric value after the command Value is present Process and Reply Change configuration Process Value Figure 5 10 Buffer Processing Algorithm CTU 1n Pr
22. maxim ic com quick view2 cfm qv pk 2812 t a1 gt viewed 1 January 2009 Maxim Integrated Products Inc MAX232 Multichannel RS 232 Drivers Receivers Data Sheet online Available from http www maxim ic com quick view2 cfm qv pk 1798 gt viewed 1 January 2009 Microchip Technology Inc PIC18F2420 2520 4420 4520 Data Sheet online Available from lt http www microchip com wwwproducts Devices aspx dDocName en0102 70 gt viewed 1 January 2009 Microchip Technology Inc PIC18F2525 2620 4525 4620 Data Sheet online Available from lt http www microchip com wwwproducts Devices aspx dDocName en0102 84 gt viewed 1 January 2009 Enfora L P Enfora Enabler G GSM GPRS Radio Modem AT Command Set Reference version 1 13 published on 7 June 2004 Shane Tolmie MicrochipC com PIC micros and C online Available from lt http www microchipc com gt viewed 1 January 2009 Midland Amateur Radio Club Inc LC Meter online Available from lt http www marc org au gt viewed January 2009 Tecnick com s r l Inductance Calculator online Available from lt www technick net gt viewed 1 January 2009 The PHP Group PHP Language Manual online Available from lt http www php net manual en gt viewed 1 January 2009 John Resig and the Query Team jQuery JavaScript Library online Available from lt http jguery com gt viewed 1 January 2009 Aditus Consulting JpGraph Documentation online Available fr
23. representations The Traffic Counter device uses little endian byte order as described in Chapter 5 2 4 Table 6 2 contains unpack function unpacking format char 1byte short 2bytes long 4bytes Signed Char Unsigned Char Unsigned Short Unsigned Long Table 6 2 Unpack Function Little endian Parameters 6 3 5 Event Log Client communication events are into files in LOG FILES PATH folder Chapter 6 3 6 Filename is Fdate log for normal logs and ERR date log for error logs where date is a variable containing the date of logging e g 2008 12 24 log The log file is a csv file having the following structure Datetime Client ID Event Message When a client is authorized all headers obtained are listed in the log Example of log file CTU 1n Prague FEE Department of Control Engineering Page 62 of 100 Miroslav Mach ek Automatic Traffic Counter 2008 12 15 PI SID 1 PVER 10 Vsus DOSES Eee DIFPFROM 1228150807 DTTO 1228151807 AONE ao A ZOD o OG ares CEN ERROR COS CEO M SBS Chet vae GAS 2008 12 15 16 07 30 SA ABO DAS 55 6 3 6 Server Configuration File ServerSettings php contains definitions listed in Table 6 3 necessary to be set before the server is run The server script uses some function from the web interface and vice versa Therefore it is mandatory to set an appropriate path All paths are absolute and need to end with or character depending on Operating System Debug mess
24. 7 January 2009 Virgil F Totten Application of Vehicle Detector Waveforms in Vehicle Re Identification and Evaluating Detector Installation Performance Indiana Purdue University 2008 Seyed Mohmamad Tahib Vehicle Re Identification Based On Inductance Signature Matching University of Toronto 2001 Carlos Sun An Investigation in the Use of Inductive Loop Signatures for Vehicle Classification California PATH University of California 2000 Report No UCB ITS PRR 2000 4 Future Technology Devices International Limited USB Chips online Available from lt http www ftdichip com gt viewed 14 January 2009 Custom Computer Service Inc C Compiler Reference Manual online Available from lt http www ccsinfo com downloads php gt viewed 1 January 2009 Custom Computer Service Inc Developers forum online Available from lt http ccsinfo com forum gt viewed 1 January 2009 CTU 1n Prague FEE Department of Control Engineering Page 74 of 100 Miroslav Mach ek Automatic Traffic Counter 12 13 14 15 16 17 18 19 20 21 22 23 24 Maxim Integrated Products Inc DS 302 Trickle Charge Timekeeping Chip Data Sheet online Available from lt http www maxim ic com quick view2 cfm qv pk 2685 t al viewed 1 January 2009 Maxim Integrated Products Inc DS78B20 Programmable Resolution 1 Wire Digital Thermometer Data Sheet online Available from lt http www
25. CZECH TECHNICAL UNIVERSITY IN PRAGUE FACULTY OF ELECTRICAL ENGINEERING DEPARTMENT OF CONTROL ENGINEERING MASTER S THESIS Automatic Traffic Counter Prague 2009 Bc Miroslav Mach ek BEng Declaration I Miroslav Mach ek declare that this thesis is my own work and that to the best of my knowledge it contains no material previously published or substantially overlapping with material submitted for the award of any other degree at any institution except where due acknowledgment is made January 17 2009 Prague Signed Minsku Madak Prohl en Prohla uji Ze jsem svou diplomovou pr ci vypracoval samostatn a pou il jsem pouze podklady literaturu projekty SW atd uveden v p ilo en m seznamu M is V Praze dne 17 1 2009 Mitos has Mad 9 podpis Acknowledgements and dedications I would like to thank Ing Michal Kutil the supervisor of this thesis for his guidance and comments and for always being kind and helpful I must also express my thanks to Taranis Invest s r o company for providing facilities for in the field tests The biggest words of thanks go to my parents for easing up the years of my studies and for dedicating so much effort to raise me and teach me and generally for helping me out even during my adulthood Without them I would not have been able to write any thesis at all This thesis is dedicated to my family and all my friends especially those from Cabuzi village II
26. Chapter 5 2 2 are saved into RAM buffer as discussed in Chapter 5 2 4 to RAM storage CTU in Prague FEE Department of Control Engineering Page 42 of 100 Miroslav Mach ek Automatic Traffic Counter 5 2 2 Date and Time It is essential that the device saves a timestamp along with vehicle s speed and length For that purpose it was mandatory to employ a RTC peripheral to establish a time base Maxim DS1302 12 is a RTC chip in PDIP8 package with a simple 3 wire TTL interface It provides time keeping calendar functions up to the year 2099 A basic circuit is depicted in Figure 5 7 In order to keep time base even if power supply is not connected an external back up capacitor can be attached on pin 8 The chip contains internal diode and resistors charger Trickle Charger in the device data sheet for the capacitor so it 1s charged when the main power supply is available When a capacitor is fully charged the time keeping will be functional up to several days Figure 5 7 Maxim DS1302 Basic Circuit The CCS C Compiler Chapter 3 3 comes with a DS1302 driver DS1302 c and standard C language library time h Therefore the following only describes the functions of the driver Further information on the 3 wire interface can be found in the device data sheet rtc init Initialize the chip l Write date and time to the rtc set datetime chip EA Table 5 1 DS1302 Driver API It should be noted that the chip does not a
27. Detector Schematic ooooooonnnnnnccncnnnnnnnnnnnnnnnnnnnnnnnannccnanonnnnos 78 Appendix 3 Inductive Loop Detector PC B sooo otto dee eevee 79 Appendix 4 Inductive Loop Detector Bill of Materials 2 80 Appendix 5 Inductive Loop Detector User s Manual u 81 Appendix o Traffic Counter CA be d uda ta ie ed edis 86 Appendix 7 Trattie Counter PCB oett rptu ee rione lov 87 Appendix 8 Traffic Counter Bill of Materials ccccccccccceceeceessssssssseeeeeeeeeeeeees 89 Appendix 9 Traffic Counter User s Mantaal ccccccccccccecceececeeeeessssssesseeeeeeeeeeees 90 Appendix 10 Traffic Counter List of Commands esses 96 Appendix 11 Database Create Pcs 98 Appendix 12 Example Source Code for CCS C Compiler 100 VII List of Figures Fiore Tid SVG Le MOO VET A dani by olado c l Figure 2 1 Inductive Eoop and Vehicle Presence ied ener ire i 5 Figure 2 2 Detection and Object Orientation nennen 6 Froure 2 5 Vehicle Measurement Principles iii 8 Figure 2 4 Signals From OO pS aii 8 Figure 3 1 PICISE2320 in PDIP package deese ioter tue tasa edo ista sc eua dedctus 10 Figure 2 2 Mhcrochip MPLAB IDE layout nut ERES P HER ED UM E E 12 Ficure 2 9 ASEX PRESTO PIOSTQUHIGE titi 13 Figure 3 4 ASIX UP Flashing Environment 0cceeseeeeeeseeeeeesseseeesseesesseeeseeenens 13 Figure 3 5 PIC Standard PDIP Programming PINOUSS oooooooooanonoccccn
28. E ae INDEX ROH S dlc eese eco INDEX idlane_2 idlane dt ENGINE MY ISAM ROW FORMAT fixed SET FOREIGN_KEY_CHECKS 1 Drop View TrafficOverview DROP VIEW IF EXISTS TrafficOverview CREATE VIEW TrafficOverview AS SELE Me ciona AS tt BOR ao Dae Sotaa or Sed s da caup S ECM ROUND AVG tempout FROM temperatures WHERE dt BETWEEN NOW INTERVAL 1 HOUR AND NOW AS tempout SELECT ROUND AVG tempin FROM temperatures WHERE temperatures idstation stations idstation AND dt BETWEEN NOW INTERVAL 1 HOUR AND NOW AS tempin SES NC QUU NA 2 Min teeta cease Chee celis RO AN anes USINE sn areis ERBLTESES lanes idstation stations idstation AND dt BETWEEN NOW INTERVAL 1 DAY AND NOW AS vehday CS Boot CAS GONNA RO DIE recae B SP ON ames 0 SING Ma clanes A EE E lanes idstation stations idstation AND dt BETWEEN NOW INTERVAL 1 HOUR AND NOW AS vehhour BROM Sao ORDER BY ei arronsymane CTU 1n Prague FEE Department of Control Engineering Page 99 of 100 Miroslav Mach ek Appendix 12 Automatic Traffic Counter Appendix 12 Example Source Code for CCS C Compiler rinclude LDof24555h HOS cce fuses HSPLL PLL5 CPUDIV3 NOVREGEN NOWDT NOPROTECT NOLVP NODEBUG NOPBADEN WRTB MCLR NOCPD NOWRTC fuse fast 10 B use delay clock 24000000 fuse rs232 baud 115200 xmit PIN_C6 rcv PIN C7 STREAM RS232 OS EOS SIS SIE CONDE 20 ARO One Gera PE B SDS SOE de 1 ees oS LS called unsigned m
29. In order to avoid crosstalks and other noise interferences the sequence 1s strictly given 1 Vehicle enters the first loop 2 Vehicle enters the second loop 3 Vehicle leaves the fist loop 4 Vehicle leaves the second loop LOOP 1 LOOP2 to t to tz Figure 2 4 Signals From Loops CTU in Prague FEE Department of Control Engineering Page 8 of 100 Miroslav Mach ek Automatic Traffic Counter Other sequences will be ignored Thus there arises a limitation of this method Vehicles shorter than Loop Distance will be not be measured However in practice loop distance 1s approximately 2 meters vehicles shorter than that value are not considered as vehicles Therefore this limitation is just a minor drawback 2 5 2 Measurement of Time Intervals The measurement starts when a vehicle enters the first loop ti When the vehicle enters the second loop t2 its speed can be calculated l d Vi m s f f m s 2 6 Subsequently When the vehicle leaves the first loop t3 its length can be calculated bey t t 1 m m s s 2 7 Another speed and length can be calculated when the vehicle leaves the first and the second loop respectively ts t4 td m s 2 8 t t V m s y t ze m m s s 2 9 In theory the both inductive loop detectors are supposed to behave the same and to detect a vehicle in the same point of its chassis Therefore the following equations are s
30. In other words to find out whether a vehicle enters is above the loop The detector has to have the ability to cope with different loop inductances as well as temperature drifts and therefore an auto calibration feature had to be introduced Web Vehicles Interface Traffic m Counter OA Don Inductive R Loops and Detectors Modem Figure 1 1 System Overview For gathering traffic data such as speed and length of vehicles another device has been developed Traffic Counter Chapter 5 uses simple principle to measure speed and length of a vehicle by placing two inductive loops including two ILDs within a traffic lane The device can gather data from up to 2 traffic lanes samples are stored in an internal memory and from time to time the buffer in binary form is transferred over a GPRS connection to the server Furthermore station temperature data is also logged and transferred to the server The Traffic Counter provides a command line interface so that the user can configure and monitor the device A server application Traffic Server in Chapter 6 3 for receiving data from stations has been written in PHP language which allows the developer to use high level functions without the necessity of taking care of matters whose are implicit in PHP such as memory management Another advantage is the possibility of running the application on different platforms such as Linux or Microsoft Windows be
31. OE A A 14 A o eee P O er ee oe re 15 3 3 3 Compiling from the command line eee eee onen nen 16 3 34 Sette the Conticurati n Bits sicot e e toes Eo o koa Codi bou z v su 16 Deseo D Stonea cust eds 17 3 3 6 General Structure of Source Code essent 18 3 4 N 19 3 4 1 Compiling Bootloader Source Code esses 20 IA IS ct R a a a M 21 3 49 Changes tothe Users Source Ode tisu ias 22 A Inducuve Loop Detect ON sooo SS Datum au aat ene E E 23 4 1 Device DeScriDIOD iso aliadas 23 4 2 Loop Oscillator C IECULL oco oa 26 42 1 Circuit based on COMPA ri 26 4 2 2 Circuit based on Operational Amplifier occccccnnnnnnonccnnnnnnnnnnnnononnccnnnnnnnnnnnnos 21 AD A3SUPSC KOZ OTO IRO O L P ONDUE Dd 28 4 3 NICtocono SF ia 29 ASA PELAS LA cc 30 45 2 JBrequenoy THedsUfe Med 3l 432 3ample DU ds 32 qd CIDI 01 PROP ef ENDS O MEAN aL SEMINE a DE 33 Ao NEMCIGIRCCO ONIN OM de 34 ASO LED OPUS 36 A3 Seti Deco PAS i 36 5 Taie COMME il A incomes da imd nd 38 5 1 TS VCS ICSC 6101010 ash atats ORP R ER AOK MOK PERO ice iaa aber RO taie PPL 39 5 2 Firmware implemen ato ss seve pea toov n Le M ata e 41 32 h M ehiclelVICasurc ne ot Pes tide RUE HIRED ids k aaa pM aera 4 D22 IDA TO ausos on A Mt M EA RUD M RE E LIESS 43 32 9 CASA TOmpectal lee esconde ideato toe E teria tense doas dt aus 44 5 2 4 Vehicle and Temperature Samples Buffer cocccccnoo
32. Program memory view EEPROM memory view LPT pose Table Read Protector Besant Tesis bugs pora a v Fr rr o rere err Fr IF FF C38 BEZE SEFF 5034 ESF CEM FE CERO 1 t tred Dod d rB B ETB 321 138 F Fr FF FF FF FF FF CT it IFFFIFF FF JF FT FT FF FF FH T ai h k F FF FF FF FF FF Li ng nz zs F FF FF FF FF FF LAA 7 ALLA LA ALA L JLA LL aa FF FF FF FF EF FF FF FF EF FF FE PRS Sees O70 FF FF FF FF esky d Figure 3 4 ASIX UP Flashing Environment PO PACTO CTU in Prague FEE Department of Control Engineering Page 13 of 100 Miroslav Mach ek Automatic Traffic Counter Within the application a hex file containing compiled source code has to be loaded and a microcontroller can be flashed with the file afterwards It should be noted that even though the hex file contains settings for Configuration bits Chapter 3 1 2 of the microcontroller the application allows the user to change those bits just before flashing see Configuration bits settings in Figure 3 4 Figure 3 5 18 contains standard programming pinouts for PDIP package moo Cc cn 03 R3 O Figure 3 5 PIC Standard PDIP Programming Pinouts 3 3 CCS C Compiler 3 3 1 Description CCS C Compiler 27 is an ANSI C compiler developed exclusively for Microchip PIC microcontrollers It comes with an extensive collection of libraries RS232 CAN SPI I2C USB and others as well as many
33. REATE TABLE Llanes 1 idlane mediumint 8 UNSIGNED NOT NULL AUTO INCREMENT idstation mediumint 8 UNSIGNED NOT NULL namon varchar o N CHARACTER O O OE is oC NO NU ele SC 110 OIN E IUOS CEC TER Ed Eo COLLATE EE Oe CC Ro e NOME NA lanenumber tinyint 3 UNSIGNED NOT NULL Adi ojan a eo ae AN SNA CU S EIS ER ROSC OMMEN SO p eT cres UA HE Speco imate B UN S SND COMMEN T Mama les Seedy ae AES TD Ereaved davecime NOT Nu Ras ie aa o ANC deactivated datetime lastdataupdate datetime PRIMARY KEY idlane CTU in Prague FEE Department of Control Engineering Page 98 of 100 Miroslav Mach ek Appendix 11 Automatic Traffic Counter ENGINE MYISAM ROW FORMAT dynamic Drop table cemperatureg DROP SAP IET TEXTO is E Cm BAS CREATE TABLE temperatures at emp ota 20 UNSLGNED NOT NU AULOOENCREMEN TE ase Ao mediumint 8 UNSIGNED NOT NULL Vt datetime NOT NULL tempin tinyint 4 NOT NULL COMMENT indoor temperature penmpoub samy ent 2 NOT NUDGE COMMENT Vourdoorm temperatures PEB ERO OTROS ENGINE MYISAM ROW FORMAT fixed DROP tab Loa EEPedae 3 DROE BEE EE SOM EN METH CREATE CABLE CE Gat dra ci omo ca ANS SNB OB UA OA U apo ZN B PAD Men dus idlane mediumint 8 UNSIGNED NOT NULL Gia datetime NOT NULL datecol date NOT NULL COMMENT contains date of dt spec me ans UN TONED NOT NUEL COMMENT kino hie Mendea Ss mato UNS T CONE DS NOTON OLEA C OMBRE TN SAO E PRIMARIO EE A O
34. S modem in Chapter 5 5 So that the sample size is as small as possible some reductions have been made Given that number of lanes within a station will surely never be higher than 16 we need just 4 bits for that value Moreover length of a vehicle will certainly be lower than 40 meters thus only 12 bits are required to hold the length value in centimetres 12 bits 4096 cm Those two variables can be assembled into one 16 bit variable CTU in Prague FEE Department of Control Engineering Page 45 of 100 Miroslav Mach ek Automatic Traffic Counter Vehicle 7B Temperature 6B 4B 2B 1B 4B 1B 1B TS IO Timestamp LaneNumber Speed Indoor Outdoor Length Temperature Figure 5 9 Samples Memory Layout Structure of a vehicle 7 bytes and a temperature 6 bytes sample is shown in Figure 5 9 The CCS C Compiler uses Little endian byte ordering the least significant bit byte is stored at the memory with the lowest address In order to provide access to single bytes of each sample the entire sample is encapsulated in a union which provides access to different variables at the same location in RAM memory see Chapter 5 5 7 for usage demonstration typedef union ate bytes ii SE LC unsigned int32 DateTime Unsigned inclo Laneclength lower 2 bits length ino cm higher 4 bits lane unsigned int8 Speed vehicle p Vehicle Vehicle VehicleBuffer VEHICLE_BUFFER_LENGTH Finally variable VehicleBuffer is the m
35. SC RTC SPI List of Abbreviations American National Standards Institute Controller Area Network Comma Separated Values Czech Technical University Data Communication Equipment Dual In line Package Document Object Model Data Terminal Equipment Electrically Erasable and Programmable Read Only Memory Faculty of Electrical Engieering General Packet Radio Service Global Positioning System Global System for Mobile communications HyperText Markup Language In Circuit Serial Programming Integrated Development Environment Inductive Loop Detector Intelligent Transportation Systems Light Emitting Diode Licence Plate Recognition Master Synchronous Serial Port Personal Computer Printed Circuit Board Plastic Dual In Line Package Hypertext Preprocessor Language Programmable Intelligent Computer Phase Locked Loop Pulse Width Modulation Reduced Instruction Set Computer Real Time Clock Serial Peripheral Interface XI SOL TTL TVS UART USB UTC WIM Server Query Language Transistor Transistor Logic Transient Voltage Surpressor Universal Asynchronous Receiver Transmitter Universal Serial Bus Coordinated Universal Time Weight In Motion XII Miroslav Mach ek Automatic Traffic Counter 1 Introduction The overview of the system is depicted in Figure 1 1 The thesis deals with the development of an Inductive Loop Detector ILD Chapter 4 used for sensing the presence of a conductive metal object near the loop
36. a column datecol containing a date extracted from dt column decreased the query time because almost every query for CTU in Prague FEE Department of Control Engineering Page 70 of 100 Miroslav Mach ek Automatic Traffic Counter generating a chart is date limited In addition adding a multi column index to trafficdata table on idlane datecol also improved the query time Table 6 6 summarizes the effect of good bad indexes on execution time It proves the fact that a wrong index slows down the query in this case because dt column contains datetime which is almost everytime unique the index misleads the database engine In case the table contains several indexes EXPLAIN keyword can be used in the query The database returns a list of reasonable used indexes Table 6 6 MySQL Query Benchmark CTU 1n Prague FEE Department of Control Engineering Page 71 of 100 Miroslav Mach ek Automatic Traffic Counter 7 Conclusion 7 1 System Summary The outcome of this thesis is a fully functional stand alone system for traffic data acquisition such as speed and length of vehicles The system developed consists of 4 parts The first part the Inductive Loop Detector finds out the presence of a vehicle with the help of a wired loop embedded within the roadway However given that it generally detects metal objects it can be used in various types of automation such as proximity detection and others The second part Traffic C
37. ages will be displayed in console DEBUG bool output SERVER PORT Port number the server will be running at Path to the web interface directory to the WEB PATH string folder where index php file 1s Where to store binary files which have not BINARY FILES PATH string been parsed yet BINARY FILES _ Where to store parsed binary files traffic and string PATH PARSED temperature Where to store text data files traffic and DATA FILES PATH string temperature LOG FILES PATH Where to store server log files Table 6 3 Server Configuration Attributes 6 3 7 Running the Server The PHP script has to be executed not as a website but as a command line script At first the server has to be configured see Chapter 6 3 6 a Linux The executable script has to have the following at the beginning 1ssue which php command for finding out the path sat Use DIN PRE It also requires executable permission for running CTU in Prague FEE Department of Control Engineering Page 63 of 100 Miroslav Mach ek Automatic Traffic Counter chmod x Server php Server php b Windows Consider that the PHP environment is installed in C Iphpl directory The server can be started issuing the following command C php php exe C path_to_server Server php 6 4 Traffic Statistics Traffic Statistics a screenshot in Figure 6 4 is a PHP web application developed for administration of stations their lanes and for their mo
38. ague FEE Department of Control Engineering Page 49 of 100 Miroslav Mach ek Automatic Traffic Counter The value can be various depending on the command It is mostly a numeric value bool uint8 uint16 However in some cases it can also be a datetime or an 1p address 5 4 3 Usage The serial line at the PC side shall be set according to the following e 115200 baud 8 bits no parity 1 stop bit no handshake The list of all available commands can be found in Appendix 10 All commands have to end with r or r n characters Otherwise the device will not reply If the received command exists the device replies with the command otherwise an unknown command string is sent back In case of commands with value if the user sends the command without any value it is considered as reading the command value and the device replies with the value If the user sends a command space followed by a value this value is parsed and saved into an appropriate configuration property Some examples of commands follow e Get actual temperature GETTEMP r e Get the device date and time DTIr e Set the device date and time 2008 12 12 15 43 DT 0812121543 r e Set the server IP address SERVERIP 192 168 1 1 r 5 5 GPRS Modem A GPRS modem has been introduced for transferring data to the server see Traffic Server in Chapter 6 3 The modem is connected with the Traffic Counter via Modem connector depicted in Figure 5 3 5 5 1 Description
39. ain buffer where vehicle samples are saved into and from where the data is read for server upload Temperature buffer is implemented in the similar manner Table 5 2 summarizes some combinations of vehicle and temperature buffer sizes with regard to the available RAM memory space the combination in bold which provides a reasonable ratio between both types of samples has been used Number of Vehicle Number of Temperature Total RAM Usage Samples Samples Table 5 2 Memory Space and Buffer Sizes CTU 1n Prague FEE Department of Control Engineering Page 46 of 100 Miroslav Mach ek Automatic Traffic Counter 5 3 Device Settings and Parameters In order to save settings such as inductive loop dimensions server s 1p address station id it 1s necessary to save the configuration into a memory which keeps its content even without power supply Fortunately the microcontroller contains an internal IKB EEPROM memory Device configuration properties listed in Table 5 3 can be changed via PC serial interface Chapter 5 4 It should be noted that configuration is load from EEPROM memory after power up If the user wants to save the configuration to EEPROM the WRITE command refer to Appendix 10 has to be issued Length of a loop dm Time interval of taking temperature samples TempTime uint8 minutes Table 5 3 Device Parameters There is a data structure in the program which can be written read into the EEPROM m
40. ample UE SPP SW 1921631172000 Sae vict 5 Write settings RARE Bs aa 5 5 5 GPRS Connection to Server Samples are transferred to the server if GprsSend property is true in intervals given by GprsTime property Table 5 3 At first GprsPin Serverlp and ServerPort properties have to be configured GPRS Connect Figure 5 12 outlines how a GPRS Set SIM card PIN Set Server IP and Port Close Connection connection is established used and released AT CPIN mypin It is implemented as a state machine In every State there is a timeout for a reply from the modem If the modem replies OK another AT PADDST ip port state is set In case of error the gprs connection is closed and entire process starts ATD 99 over Once a PIN code is set properly the Authorize modem connects to GSM network and replies Transfer Traffic and Temperature buffers OK After the ATD 99 command is issued a GPRS connection to the server is about to be TH established This may take several up to gt Figure 5 12 GPRS Connection Process several tens of seconds The modem sends CONNECT in case it has been successfully connected to the server If a connection is closed by the server or GSM network CTU in Prague FEE Department of Control Engineering Page 53 of 100 Miroslav Mach ek Automatic Traffic Counter the modem sends NO CARRIER message If a connection cannot be established the modem replies
41. ample source codes CTU in Prague FEE Department of Control Engineering Page 15 of 100 Miroslav Mach ek Automatic Traffic Counter 3 3 3 Compiling from the command line We do not need any IDE for compiling a source code since it can also be compiled directly from the command line which contains main function of the PIC application example Ccsc exe FH C picsources file c 3 3 4 Setting the Configuration Bits The compiler produces a hex file ready to be flashed into a we can run C Program Files PICC Ccsc exe and select a C file in case of compiling directly from the command line there is the following format Ccsc exe options filename where options are described in 10 microcontroller The hex file also contains Configuration bits Chapter 3 1 2 Therefore in order to get the fuses configured a special keyword in the source code followed by fuse description has to be used SSE SAN ONDA IS OE TRO EC NOLVE NOPBADEN EE T NOCEDO NOWNRTO In case of using the CCS Compiler IDE Chapter 3 3 1 Figure 3 6 a list of fuses available Figure 3 7 for selected target microcontroller can be viewed by choosing View gt Valid Fuses from the IDE menu toolbar Low power osc 200 khz Crystal osc lt 4mhz for PCM PCH 3mhz to 10 mhz for PCD High speed Osc gt 4mhz for PCM PCH 7 10mhz for PCD Resistor Capacitor Osc with CLKOUT External dock with CLKOUT External dock High speed osc with HW
42. ash memories through 8 32 Bit microcontrollers to CPLD FPGA microprocessors An important list of devices supported can be found in Table 3 2 The programmer supports ICSP programming and since it is usb powered it does not need any power supply for programming CTU in Prague FEE Department of Control Engineering Page 12 of 100 Miroslav Mach ek Automatic Traffic Counter microcontrollers Given that the device uses an USB interface chip from FTDI company 9 it is possible to use the programmer either under Windows or Linux AMX b P1 VPP 13V vO N C P2 C P3 VDD PWR ON LINE P4 GND PWR P5 DATA MOSI WO P6 CLOCK OUT P7 MISO P8 LVP _ T ACTIVE PRESTO ge oU Figure 3 3 ASIX PRESTO Programmer Devices Supported Manufacturer Devices Supported PIC16 PIC18 dsPIC Atmel Philips ARM Xilinx Altera CPLD and FPGA NXP Lattice devices Serial EEPROM and Flash Various memories Table 3 2 List of Important Devices Supported by ASIX PRESTO 3 2 2 Flashing Environment The programmer has its own environment Asix UP 25 in both English and Czech languages Figure 3 4 for flashing microcontrollers which can also be run under Linux Configuration bits settings LE et LA gt ida aT inate ern ep LAE AEC hara feeder Up Tiara Hylke Mugewe Ppi Z H E ma B B B A E m 1 Ue Prog DRON ars Pragae ad Pipa naai e id 2 oe Cell hon T I PRESTO PRCTGF DO
43. atisfied Speed f 7t t f 2 10 Length t t t t 2 11 However in the real application the equalities will never be satisfied For instance detector responses are not exactly the same or a vehicle does not enter both loops in the same position In order to make vehicle speed and length more accurate calculated values v v2 and l can be averaged CTU in Prague FEE Department of Control Engineering Page 9 of 100 Miroslav Mach ek Automatic Traffic Counter 3 Microchip PIC and Equipment Microchip PIC microcontrollers are popular because of low cost availability various collections of source codes and free cheap development tools Those 8 bit microcontrollers have Harvard architecture program and data memory spaces are separated which together with RISC instruction set ensures that the most instructions are executed within one machine cycle 3 1 PIC18 Family 3 1 1 Description PIC18 family example shown in Figure 3 1 is based on the previous PIC16 family fixes its drawbacks and introduces upgrades such as e Much deeper call stack 31 levels e The call stack may be read or write e Conditional branch instructions e Indexed addressing mode Figure 3 1 PICI8F2320 in PDIP package The most important is the deeper call stack and highly optimised instruction set optionally with extended instructions This delivers the possibility of using a higher level programming language such as C language
44. bin Example of temperature file 2008 12 04 22 21 41 T bin a Binary File The structure of a binary file is depicted in Figure 6 3 The file contains Prefix TRAFDATA in ASCII form so that the file can be distinguished from other files Number of Headers N is a count of all consecutive headers After that there is N of header items Header I to N each consists of Header ID and a variable length value depending on the particular header see Table 6 1 After the last header item there are traffic each 7 bytes temperature 6 bytes samples in the same format as it 1s sent by the station in see Chapter 5 5 2 CTU 1n Prague FEE Department of Control Engineering Page 60 of 100 Miroslav Mach ek Automatic Traffic Counter Prefix A ESSI u Header ID ID Eo Samples Headers Value Eo 8B 1 1B TRAFDATA N see Text a Text Header 1 N Figure 6 3 Binary File Structure Header Size B Name Description So SID Station ID WU PVER he MR Protocol Version EE Sonia eim 0 3 HWVER Station Hardware Version AN DTFROM Acquisition Start Unix timestamp DTTO Acquisition End Unix timestamp 6 1 TYPE Type of Data O traffic 1 temperature SMPLNO Number of Samples b A A A OC XOU So xs Table 6 1 Binary File Headers Text File Its format is straight forward and self explanatory Every line contains one value headers begin with character Samples are separated by comma and have the fo
45. ble and is written in assembler language for PIC it can easily be adapted to any PIC device running at various clock rate and having various serial line speed Assets of the bootloader are its size which is merely 100 words and also the fact that it comes with a PC application for writing a hex file into the microcontroller The following subchapters describe process of compiling and employment of the Tiny Bootloader Empty space Figure 3 9 Tiny Bootloader Memory Layout The bootloader memory structure is depicted in Figure 3 9 It resides at the end of program memory When the microcontroller 1s powered on it waits for a while for an initialization char over its serial line When there is nothing received user CTU in Prague FEE Department of Control Engineering Page 19 of 100 Miroslav Mach ek Automatic Traffic Counter firmware is executed Otherwise the bootloader is run and begins to communicate with the PC 3 4 1 Compiling Bootloader Source Code The bootloader comes with source code written in assembler languages MPASM for PIC and several precompiled hex files In order to use it with a PIC having a custom Configuration baud rate fuses frequency the source code has to be modified and compiled before flashing it into the microcontroller At first Microchip MPLAB IDE Chapter 3 1 has to be installed since it contains assembler language compiler The compiler has a limitation on path length of compi
46. c configuration I Managing Configuration and Device LOADDEF Loads factory defaults always use for new devices SHOWSET Shows current configuration Restarts the device Note Do not forget to issue WRITE command if you have changed any device parameter II Measurement Configuration The following commands have to be used in order to configure the device for taking vehicle samples 1 Set Lane Number Loop Length and Distance between loops Commands LANENUM LOOPLEN LOOPDIST 2 Start or stop measurement Commands START STOP AUTOSTART 3 Listen to measured vehicles samples will be sent to the PC Commands LISTEN NOLISTEN 4 Check vehicle buffer Commands VEHCOUNT SHOWVEH CLEARVEH CTU in Prague FEE Department of Control Engineering Page 94 of 100 Miroslav Mach ek Appendix 9 Automatic Traffic Counter III Server Upload The following should be configured for proper data upload to the server 1 Station ID Lane Number for appropriate server database upload Commands SID LANENUM 2 Server IP address and Port Commands SERVERIP SERVERPORT 3 Enable GPRS transfer Time period SIM card PIN code Commands GPRSSEND GPRSTIME GPRSPIN 4 Try to connect to the server Commands GPRSNOW CTU in Prague FEE Department of Control Engineering Page 95 of 100 Miroslav Mach ek Appendix 10 Automatic Traffic Counter Appendix 10 Traffic Counter List of Commands Commands without write values Vehic
47. cause both Operating systems support PHP scripting The server application gathers binary data CTU in Prague FEE Department of Control Engineering Page 1 of 100 Miroslav Mach ek Automatic Traffic Counter from stations puts them into files and also uploads them to the database for further processing For an user friendly output a PHP web interface Traffic Statistics Chapter 6 4 has been created Charts and statistical information on stations such as speed and length categories number of vehicles per day hour with the possibility of selecting date range and other constraints can be generated via the web interface CTU in Prague FEE Department of Control Engineering Page 2 of 100 Miroslav Mach ek Automatic Traffic Counter 2 Motivation and Methodology In nowadays road and highway traffic has become a great concern because of continuous increase in traffic which calls for new roads to be built One matter is to build them the second one is to optimise the current transportation system and therefore to improve efficiency of existing roads Because of that it is essential to gather traffic data not only for statistical information but mainly for analysis and further traffic control There are many technologies for gathering traffic data Chapter 2 2 One of well working principles 1s acquisition based on inductive loops embedded in the roadway which 1s the concern of this thesis Chapter 2 4 and Chapter 2 5 deal
48. cessfully calibrated vehicle recognition mode 1s set The device calculates the mean value and the deviation Chapter 4 3 3 of Sample buffer and based on the calibrated mean value it decides whether a vehicle 1s above the loop or not Recognition is implemented as a state machine depicted in Figure 4 14 There are 2 states No vehicle VehOff Vehicle VehOn Transition between them 1s done according to Figure 4 15 Out of the Outer Interval Init Within the Inner Interval Figure 4 14 Vehicle Recognition State Machine Actual mean average value of frequency is continuously calculated GetMean function from the sample buffer and compared to the calibrated value Averaging process provides filtration of unwanted detections If the actual value gets out of the outer interval 1 e a metal object 1s close to the inductive loop it is considered as vehicle above and transition to VehOn state is made Similarly when the actual value returns back to the inner interval it implies that the vehicle has left the loop and VehOff state is set In order to provide setting the sensitivity of the device both intervals can be set via on board switches Chapter 4 3 7 The device is automatically recalibrated if the device remains in VehOn state longer than 5 minutes CTU 1n Prague FEE Department of Control Engineering Page 34 of 100 Miroslav Mach ek Automatic Traffic Counter Paramagnetic Object Ferromagnetic Zas Hysteresis
49. cncnnnnnnnnnnnnnnnnnnnnnnnannos 14 Figure o CC C ComptilerTIDE unione node esee ae eate sa eds enjeu beber ee d lt A Add u n 15 Ficure 5 7 CCS Compiler Fuses QUICK Vi Wisin 16 Figure 3 8 CCS C Compiler Interrupt Quick View esses 17 Figure 3 9 Tiny Bootloader Memory Layout eese 19 Figure 3 10 Tiny Bootloader Source Code Modification ccccsseesseseeseessessessseeeeeseens 20 Figure 5 11 Tiny Bootloader PC Application acasin 22 Figure 4 T Inductive EoopoDetecfoOF 22 39 9 9 191 sisi 23 Froure 42 IED System Verve W Sad oct uc neto eco etai uei D bM HT DUM 24 Figure 4 ILD Board La OU ni m 24 Figure 44 ID LOOP CONNEC O i i e coda 25 Figure 4 5 ILD Main C Onn 6 GLOT cad 25 Figure 4 6 Oscillator Circuit with Comparator eese 26 Figure 4 7 Oscillator Cicuit with Operational Amplifier eee 27 Figure 4 8 Simple Conversion from Sine Wave to TTL Signal 28 Figure 4 9 Overvoltage Protectors essere nnne eene nnns 28 Figur 4 TO OVervoltage Protection sd 29 E1vure 4 LE TED Operation Did oraiiis x oie oec eii E EE 30 Figure 412 PIG 185E2420 DINOU basilical lio 31 Fieure 4 I5 CCP modulem Capture mode 31 Figure 4 14 Vehicle Recognition State Machine esses 34 Fene 4 L5 State C hanpe SS de 35 Pigure Sl ratio Counter deiade cone aha koz tutes dqe
50. cript Diagram Name ERmodel SOBA te COM 24220010 Z SET FOREIGN_KEY_CHECKS 0 Z Prop eoo S60 DROP T TABLE TET EXI To Stati Ne y CREAME TABLE Sado idstation mediumint e UNSIGNED NOT NULL AUTO_INCREMENT Homies yar enar oO CHARACTER OET BOOT UC O Lo NOA ANI HOS Sera 1 OE ON eso O TARAC JEP NE ESOS OI ARES oo e mem ao U IN OB INOS bal COMMENT SS Sri 1on AE OE KPO O SHO created datetime NOT NULL lastdataupdate datetime COMMENT last data update poc a DARAN AO Aa PE ee deactivated datetime PRIMARY KEY idstation ENGINE MY ISAM ROW_FORMAT dynamic Drop table uploadedfiles DERO E EXI o IS plo de oko S CREATE TABLE uploadedfiles idfile mediumint 8 UNSIGNED NOE NULL AUTO_INCREMENT idstation mediumint 8 UNSIGNED NOT NULL Filename varchar c HARACIER BC COLLATE UCE C STO CN OA daca Gate COMMEND date oi eacquis Crion dtirem datetime NOT NULL COMMENT dt ot the timst sample of the file Ig oS Ce SE RS UN ON UR COMM Nie OS KES Es mode orn lie SS RODA SO lake Ola dCi So css OIN ATHE Sese ena ooo Lo CO EA ohe ale PROEOGOW 7510 SH BCA GE RAGE Pe OO BU SSS C re rare naaa lo Me ARAS Ro dies our COM BU ESK eel TICs IUNCTUS diuploaded datetime NO EE Shoe comme me 0 NBT COMMENT TROV many ea Cle samples temperaturecount emaliini Ss UNSIGNED COMMENT how many temperature samples PMR KEY dic ENGINE MYISAM ROW FORMAT dynamic Drop taole sa BENDA oo C
51. ddc decet codutoo tup hag ayo 38 Figure 5 2 Traffic Counter System Overview esses eene 39 Ficure 5 3 hannie Counter Board Way Out ciet iaa 40 Figure 5 4 PC and GPRS Modem Connectors esses 40 Figure 5 5 Detectors and Microcontroller Connection ssssssseeeesessseeeseessessesessseeees 4 Figure 5 6 Vehicle Measurement State Machin ii reo eU Ce basa kase 42 Figure 5 7 Maxim DS1302 Basic CAtGUILU iai vada daodisuiess ota suco a re tasa cito inia da dod 43 Figure 5 8 Maxim DS18B20 Pinout and Circuit iso ooicad eeu op io aaa es ea eae 45 Figure 5 9 Samples Memory Layout 4 atrae k duet doas eco dae ide dul sb Devua va boule 46 Figure 5 10 Buffer Processing Algorithm occccccccccnnnnnnnnnonoonononoconnnnnnnnnnnnnnnnnnnnonnnnnnananons 49 Figure 5 11 TENcom SPEEDER RS GPRS Modena 51 Figure 5 12 OPRS Connection Process uin ioca qu qo a d 53 Figure 5 13 Client Server Communication Diagram eese 55 Figure 6 1 DatabaseoMOGeL sid sitet e t ede doe cio a 57 igure 6 2 rate Server Operation oie modeii A 58 VII Figure 6 3 Binary File SE UCUIEe Jeden eee tt douce de itat E 61 Figure 6 4 Traffic Statistics Web Application c csssssssssesesseeeeeeeecccceecseeneenasssseseeees 64 Figure 6 5 Datepicker plugin for QUE iiir t o repe trie Ee Pe xd ee vid kde 66 Figure 6 6 Tablesorter Plugin for JOUGTY ii 67 Ficure 6 7 Simple Line Plot via JpGraph LIDTATY i aeo te e
52. e 40 of 100 Miroslav Mach ek Automatic Traffic Counter 5 2 Firmware Implementation 5 2 1 Vehicle Measurement The device implements loop signals measurement as described in Chapter 2 5 There are 4 inductive loop detectors connected to the Traffic Counter each detector provides vehicle TTL signal VEHTTL on its pin 13 see Table 4 1 Those signals are connected to the microcontroller s PORTB Figure 5 5 that has interrupt on change feature on its 4 to 7 bits Inductive Loop Detectors Pin 13 PORTB 6 Microcontroller PORTB 4 PORTB PORTB 7 Figure 5 5 Detectors and Microcontroller Connection The PORTB interrupt is called once rising falling edge has occurred on pins PORTB 4 to PORTB 7 In order to find out what event has happened the previous state has to be memorized The following snipped outlines the PORTB interrupt routine does not include vehicle measurement algorithm int_RB HIGH void NBA OLO dui uae CL a aus Stato are lasts statie ints boOLtevent current E OU EHO by pice ne cursen ase ca 7 get change if bitevent amp 3 gt 0 something with laneO event on ildl or ild2 if bitevent 12 gt 0 something with lanel event on ild3 or ild4 dti Last current Vehicle measurement is carried out via state machine as depicted in Figure 5 6 Measurement starts when a vehicle enters the first loop A state transition 1s made according to Figure 2 4 and in case of an
53. e 5 3 The device needs 15V DC supplied by an external power supply through a power connector There are 4 connectors for ILDs Chapter 4 which are used for measuring vehicles The device contains two RS 232 connectors for PC and a GPRS modem Finally there are 2 temperature sensors one for board indoor temperature the latter should be placed outside the box and connected by cable to external temperature sensor connector for outdoor temperature CTU in Prague FEE Department of Control Engineering Page 39 of 100 Miroslav Mach ek Automatic Traffic Counter GPRS Modem RS 232 ig r Nau External Temperature Power Supply Connector EAE 3 con LEDS 4 js AG CTI Bl AL me 8 14 15 16 17 18 19 20 21 22 23 24 00000000000 0000000000000 1 2 3 4 5 6 7 8 10 11 12 13 M Inductive Loop Detector Connectors Figure 5 3 Traffic Counter Board Layout Communication connectors and their pinout is shown in Figure 5 4 a straight cable should be used for connecting the PC and a modem Both connectors have a standard RS 232 pinout CANNON 9 CANNON 9 1 CD Male Female 2 RX in 1 5 5 1 gt se 3 TX out Board 6 9 9 6 GPRS Modem PC Figure 5 4 PC and GPRS Modem Connectors The user is notified about the state of the device by 4 on board LEDs whose purpose 1s described in Appendix 9 CTU in Prague FEE Department of Control Engineering Pag
54. e Code Modification Source codes particularly for PIC18 family are located under picsource pic18 directory If the user wants to use an universal bootloader tinvbldISF asm file has to be modified see Figure 3 10 according to the following e Select device by writing its model name 1 e 1812420 It is also necessary to change the device in MPLAB environment from Menu Toolbar Configure gt Select Device Otherwise it will be compiled incorrectly e Modify crystal speed and serial line baud rate CTU 1n Prague FEE Department of Control Engineering Page 20 of 100 Miroslav Mach ek Automatic Traffic Counter e Set Configuration bits A complete list of fuses suitable for a device including fuse description can be found in device s inc file e g Pl8F2420 INC under C Program Files Microchip MPASM Suitel An example of device configuration taken from the beginning of tinybld18F asm file LIST P 18F2420 xtal EQU 20000000 baud c UN CONFIE OSC HAS FCOMEN ON IESO ON PWREI ON CONPIG BOREN OFER WOT OFF MCERE ON LPTIOSC OFF CONFIG PBADEN OFF CCP2MX PORTC STVREN ON CONFIE XINSI OFP DEBUG OPP Oe Once the source code has been successfully compiled it can be flashed into the microcontroller 3 4 2 Usage The Tiny Bootloader contains a PC application Figure 3 11 for downloading the user firmware to the microcontroller The use of the application is straight forward The user
55. e device waits until there is a signal from loop oscillator circuit and waits 5 seconds so that it gathers some frequency samples Chapter 4 3 3 and frequency mean value and deviation Chapter 4 3 4 are calculated If the samples deviation 1s lower than some particular threshold the device 1s calibrated and vehicle detecting mode is set Otherwise the deviation implies that there is something happening to the inductive loop and the device tries to recalibrate itself again Even during vehicle detecting mode due to temperature and other impacts the device needs to check occasionally whether it requires recalibration CTU 1n Prague FEE Department of Control Engineering Page 29 of 100 Miroslav Mach ek Automatic Traffic Counter Power On or Reset Initialisation Signal from Oscillator Calibrate Small Deviation Calibrate to the mean value Normal Operation Needs Recalibration Setup Ports Timers and other peripherals Wait until there is a frequency signal Calculate mean value and deviation of sample buffer Recognize vehicles No Signal Figure 4 11 ILD Operation Diagram 4 3 1 PIC18F2420 PIC18F2420 is a 28 pin microcontroller which has 16Kb flash program memory and 768 bytes of RAM Its pinout is shown in Figure 4 12 PORTB pins 21 28 contains internal pull up resistors which can be switched on off by software They are convenient for switches there is no need for
56. e user can check how stations upload data e lanes each station consists of one or more traffic lanes e trafficdata raw vehicle samples speed and length of vehicles for every lane mediumint E FK SE n ir 30 A idstation mediumint E FK varchar 30 iption im varchar 30 date iption tinytext datetime nr na t 10 6 Ref 02 tinyint 3 datetime n beti jon tinyint 1 warchar 5 i i tinyint 1 varchar 5 i varchar 5 mediumint 10 BS temperaturecount smallint 5 Lid ES tempin tinyint 4 Ea tempout tinyint 4 Figure 6 1 Database Model The following columns are important since they have to be set properly in the Traffic Counter device at a station see Chapter 5 e stations idstation an unique id of a station SID parameter in Appendix 10 e lanes lanenumber id of lane within a station LANENUM parameter is Appendix 10 Even though anes idlane is a unique identifier it is easier to use lanes lanenumber which is only unique per station The reason is that anenumber is CTU in Prague FEE Department of Control Engineering Page 57 of 100 Miroslav Mach ek Automatic Traffic Counter an offset which can be modified when adding more lanes to the station See property LANENUM in Chapter 5 3 for station configuration of lanenumber item 6 3 Traffic Server The Traffic Server is a PHP script which receives data from station over network puts it into files and also upload to the MySQL database
57. ehicle passing above the loop embedded in the roadway The device provides self tuning feature so that a wide range of loop inductances is achieved the loop operating frequency can be set by on board switches The user is notified about the state of the device by 3 on board LEDs 2 Technical Data LED1 G SW3 4 LED2 Y LED3 R CTU in Prague FEE Department of Control Engineering Page 81 of 100 Miroslav Mach ek Appendix 5 Automatic Traffic Counter A x2 mm GB Mounting Pillar 4x 3mm hole distance 61 mm 63 mm OS Connector Plug in Connectors Conl ARK2500V A 3P ARK2500F A 3P for cable side Con2 Cannon 25 pin Male Surge Protection On Loop inputs Gas Discharge Tube TVS Diodes Fully Automatic Inductance Range Theoretical 8 to 6000 uH Loop Operating Frequency 20 145kHz 4 selectable positions via SW3 switches Sensitivity 4 selectable positions via SW2 switches Low Medium Low Medium High High Digital Outputs TTL outputs Vehicle Above Opto isolated outputs Vehicle Above Vehicle Above Impulse Green Vehicle Presence Yellow Calibration Operating Frequency Red Error 3 Connectors CONI Loop and Grounding front view 3 Loop 2 Loop 1 PE Device Grounding 3 2 1 CON2 Main Connector front view 1 13 14 25 Board CTU in Prague FEE Department of Control Engineering Page 82 of 100 Miroslav Mach ek Appendix 5 Automatic Traffic C
58. emory example Cy PECE SE CE pac OPE DEDISSE O TARI Feb MEASUREAVG intl GPRSSEND UNStoMmed Ines GPRS EME Jot DME SO OCIO BC SHE Kola CTU 1n Prague FEE Department of Control Engineering Page 47 of 100 Miroslav Mach ek Automatic Traffic Counter The following two functions implements reading and writing from the internal EEPROM memory whole data structure at particular offset can be written Vion OM OMA AE e e es LOTO E TCO PE Lor eon count lt num Count Orte Count READ EEPROM addr come i FORO Me OM MNE PC OE MU ellie EGET LAT COUNT LOr Count 0 Count HE Count r TESTE ER EG EO ES OC CE OS e o ae ECO d e To save the configuration structure the following command is used PEE ROME AD SC ONT E ui AKON SMS O UD OTEC NEM BST 5 14 Command line Interface In order to configure the device see Chapter 5 3 a simple command line interface has been implemented It receives characters from PC serial line buffers them and when a delimiter character is sent the entire buffer 1s processed The list of available commands can be found in Appendix 10 5 4 1 Character Buffer Each character received through the device HW UART causes a RDA interrupt routine to be called The character is saved into a receive buffer If a Ar character is received the content of the buffer 1s copied so that serial line receive works when the buffer is processed and is processed in the program
59. ere IV ADSI AKE enc t S OM OOP uud as Ce pua O O O pua DUM Sd aC MEE IV Table OF COMENTS NER V tot PAUSA ia eo M DUM duu VIII Imi e so X Pito ADO VIJHOTS sacco c doe ands ented Oe Rokk ee eo elits Eod ny XI ll AMO AICA oii ott oe eesti eee tvi Meier metuas l 2 Motivation and Methodology ooooooonnnncccccccnnnnnnnnnnnnnnnnnnonnnonnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnos 3 24 Reason ror This Te SIS era OO e d HM ME Ee 3 22 Review of Vehicle Detection Technologies ccccccccccnnnncnonnnnooonccncccnnnononononononoss 4 2 2 1 Non Intrusive Over ROadWay ooccccccccccnoncnnnononononnnononncnnnnnnnnnnnnnnnnnnnnnnnnnnananans 4 222 2 Intrusived Hi ROad way zed tante kok dees t volt aaah odori ui dde ao dno 4 23 Inductive Loops in Genre 5 2 4 Vehicle Detecuon Principle Uli lili ads 6 Dek Chances ii Inductance bae 6 DAZ Resonant Erequelbio Vou A i n 6 243 Inductance Values and Calculator i n T 2 5 TrarteNeasurement Principle WSCC occas ssi a 8 23 4 iphals TOM Detection li 8 2 5 2 Measurement or Timo Intervalo tal 9 3 Microchip PIC and FQuipment atados 10 3 1 PTCA GP up A A AA A e 10 LL Descipion esse a a 10 Dele Cone UG AMON DSi 11 3 1 Microchip MPLAB Development Environment seen 12 3 2 ASIA PRESTO Prog tamine ea t e vertus E E E 12 SL NEMINEM 12 3228 jblashino Environ Db soe ioo A 13 3 3 CCS CC Omi pier oe o o NM 14 Z
60. es a sensor built in the roadway the latter employs a sensor mounted above or at the side of the roadway Both technologies have their pros and cons An in depth discussion on both principles can be found 1n 2 3 5 2 2 1 Non Intrusive Over Roadway Non intrusive technology uses microwave ultrasonic active and passive infrared acoustic and laser principle An advantage is the ease of installation above or at the side of the roadway A disadvantage is the need for sensor cleaning and the susceptibility to weather condition such as fog heavy rain and others Some of over roadway detection devices use more than one sensors in order to overcome the drawbacks of each sensor In nowadays video image processors have been incorporated within traffic sensors They are easy to set up and are able to monitor several traffic lanes at a time Moreover it 1s also possible to introduce Licence Plate Recognition LPR to the system since an image of a vehicle 1s already present in digital form 2 2 2 Intrusive In Roadway Examples of this category are inductive and magnetic loops magnetometers tape switches and piezoelectric cables Installation and maintenance of one of those sensors means disruption of traffic However especially reliability is usually better than in non intrusive sensors since in roadway sensor measurement in not susceptible to weather conditions The latest inductive loop detectors also provide a better accuracy than ove
61. examples which make it very easy to use It can be bought with or without IDE Figure 3 6 it should be noted that the compiler itself can be integrated into Microchip MPLAB IDE Chapter 3 1 However the advantage of the original IDE 1s that it fully supports compiler features such as prompt list of fuses interrupts see Chapter 3 3 4 and Chapter 3 3 5 statistics and memory usage whose improve and speed up development process Thus given that I have used the IDE for this thesis I think that it 1s worth to get the IDE as well CTU in Prague FEE Department of Control Engineering Page 14 of 100 Miroslav Mach ek Automatic Traffic Counter um m a Ele Project Edit Options Compile View Tools Debug Help s ax Trafficcoumter c Confguraon c GPRS rea Traffictounteh Fuera DSIXULC Seth temperatures mire meh x switch Lanes ACIUALLAME race case J I EBLE Stet Current ACTUALLARE I bit SEST current ALIJALLANES Lanes ACTUALLANE Heasuring rrue Lanes ACTOALLANE c mers ger rimer Lanta ACTUALLAME Statt t saquear A ipai a Break case 1 SE BLE Gest current ACIUALLANEL Bit pest current ALIDALLAWE Lanea RCTUALLAME timersa 1 get timer Lanes ACTUALLAME SLAate else Cleariane ACTUALLAHE break case 2 if bir t eat current ACTUALLAME 1 7 bir feat current ACTUALLAHEJ Lines ACTUALOAME t m xa d g t tamert if Lan s ACIVALLAME Timersof 015 gt
62. figure the CCP e Switch to Capture Mode e Select Timer for capturing Timerl Timer3 e Select occurrence Rising edge Falling edge every 4 Rising edge every 16 Rising edge e Enable CCP interrupt Given that the frequency of the oscillator is expected between 20 kHz and 145 kHz Chapter 2 4 2 it is convenient to set the signal prescaler to 16 so that the interrupt routine is not called so often Furthermore dividing the signal by 16 also produces signal filtration which is desired Therefore the snippet in C language for CCS C Compiler Chapter 3 3 for CCP configuration 1s the following CTU 1n Prague FEE Department of Control Engineering Page 31 of 100 Miroslav Mach ek Automatic Traffic Counter setup OSA T IDs DIY _1LO CCP_USE_ TIMERS Z SOE O MS SoN E SORTE RNA TIT ST GIVE ERES enable interrupts INT CCP1 enable interrupts GLOBAL CCP interrupt routine high priority Chapter 3 3 5 2 dint CCP1 HIGH LOIRA CL isr BSS theo Cer memo nc Chae ally Sa LOTUS Int Ine CES CCPtemp CCP 1 get the captured value of Timer3 CPactual CePeemo Cerprew Ecc Lame NO DNE wee O EC Ies Ob S GREG signal ee ec cs aig Oo S06 4P So Variable CCPactual contains count of Timer3 ticks between 16 periods of the input signal Hence the signal frequency 1s calculated Fosc 16777 440 10 _ _ A EE Hz 4 1 CCPactual CCPactual s 4 3 3 Sample Buffer In order to collect frequency samples fo
63. geret a Est 68 Figure 6 8 Charts Generated in Traffic Charts API 70 IX List of Tables Table 3 1 Microchip PIC Configuration bits Selection ccccccccccccceeeeeeeeeeeeeeeeseeeeeees 11 Table 3 2 List of Important Devices Supported by ASIX PRESTO 13 Table 4 1 ILD Connector Description i e crie p oi rh en ERU HERR Da desate kabela diddatiska 25 Table 42 Breque ey Conft9UurattOli n s o REO RO DIN p pae qn pM 36 Table 4 3 Device Sensitivity COSTAN ei eec ee ec SUR E X audi nea edk ed ekon 37 Table 5 115 1902 DV SEA T sce eei o ere ARD aene A etae o ono 43 T ble 5 2 Memory Space and Buiter SIZE Srur er e tesis tee vein tu een Osea pets 46 Tables Device PATAS adi detiene 47 Table 34 Speeder AS SpeciHc ato a 51 Table 5 5 List of Important AT Commands coccccnnnnnnnnnocccnnnnnnnnnnnnonoccnnnnnnnonnnnnonccnnnnnnnnnnaninonoss 52 Table 5 6 Client Authorization Heades AA 54 T3ble 6 ALD matey Beads ts esos E tes neta eee te ee 61 Table 6 2 Unpack Function Little endian Parameters ocoooooononnncnnnnnnnnnnnnnooccnnnnnnnnnnnnanoconos 62 Table 6 3 Server Configuration Attributes ias 63 Table 6 4 Trathic Charts API Variables a dobu te ois ede tas 69 Tabte 6 5 Trathe Charts APT ooo take tet citadela n k asd teda ak 69 Table 6 0 My SQE Overy Bencina 71 ANSI CAN CSV CTU DCE DIP DOM DTE EEPROM FEE GPRS GPS GSM HTML ICSP IDE ILD ITS LED LPR MSSP PC PCB PDIP PHP PIC PLL PWM RI
64. hange in inductance only 2 4 3 Inductance Values and Calculations The following formulas have been used to determine loop inductance and dimension refer to 20 for further description a b Circular loop L N Rug LEJ 2 4 where L Inductance H N Number of turns R Radius of the circle m uo 4n 10 Permeability of vacuum H m ur Relative permeability a Radius of the wire m Rectangular loop N Hola 2 2 w h 24h w h ln m ess T wtvh w 2w 2h w In OE A ln w In a a 2 5 where L Inductance H W N Number of turns w Width of the rectangle m h Height of the rectangle m h a Radius of the wire m CTU in Prague FEE Department of Control Engineering Page 7 of 100 Miroslav Mach ek Automatic Traffic Counter 2 5 Traffic Measurement Principle Used The principle is shown in Figure 2 3 There are 2 inductive loops built within the roadway Each loop has length meters and there is d meters distance between the loops Each loop is connected to one inductive loop detector and signals carrying vehicle presence are used Loop 1 Loop 2 LLL E gt Road d Loop Loop Length Distance Figure 2 3 Vehicle Measurement Principle 2 5 1 Signals from Detectors The measurement is carried out through a sequence of impulses loop detectors see Figure 2 4
65. hart Range of date to be shown 1 gt show data per day 0 gt show data per hour day interval 1 e how many days to show 1 gt length categories will be generated showlength 0 gt speed categories will be generated Table 6 4 Traffic Charts API Variables Variables datefrom and dateto are dates in MySQL format ex 2008 12 24 and they limit date period to be shown in the chart In some charts idlane idstation are array variables ex idlane This allows to plot data from several lanes station in one chart idlane Number of Vehicles in a VehiclesPerDay php datefrom dateto lane per day hour daily Average speed in a lane idlane or idstation AvgSpdPerHour php per hour datefrom dateto idlane Speed and length datefrom PercentagePie php categories of a lane interval showlength idstation AvgTempPerHour php Average temperatures datefrom dateto Table 6 5 Traffic Charts API In order to show traffic data of several lanes in one graph idlane GET variable is passed as an array and the URL may look similarly to the following CTU in Prague FEE Department of Control Engineering Page 69 of 100 Miroslav Mach ek Automatic Traffic Counter If it is desired to embed the chart within a web page this URL query can be put in an img tag within the HTML code Configuration of Traffic Charts API is under charts chartfunctions inc where also speed and length categories ca
66. he loop inputs In order to let the environment know about the state of the device CTU in Prague FEE Department of Control Engineering Page 24 of 100 Miroslav Mach ek Automatic Traffic Counter and the presence of a vehicle above the loop there are several LED diodes on the ILD whose function is described in Chapter 4 3 6 Similarly the device parameters such as sensitivity can be set via on board DIP switches Figure 4 3 depicts the board layout An inductive loop can be either connected through the main connector or the loop connector Figure 4 4 The device should also be grounded via its pin 1 The device has to be powered through its main connector Figure 4 5 where inputs and outputs can also be found Their purpose is described in Table 4 1 3 Loop 2 Loop 1 PE Device Grounding 3 2 1 Figure 4 4 ILD Loop Connector 1 13 14 25 Board Figure 4 5 ILD Main Connector Se e BRC iene Vae os S CT TNT 6 19 GND h System Ground Positive Voltage Power Supply 7 to 12V External Reset with opto isolation against 922 RST In EXTGND Vehicle Above 100ms Impulse with opto 10 23 VEHI Out isolation against EXTGND Vehicle Above Permanent with opto 11 24 VEH Out isolation against EXTGND 12 25 EXTGND Ground for opto isolation VEHTTL Vehicle Above TTL signal against GND Table 4 1 ILD Connector Description CTU in Prague FEE Department of Control Engineering Page
67. ine in Con4 5 Attach 15V DC power supply to Conl 6 Configure the device according to paragraph 5 IIl GPRS Modem Configuration The modem interface 1s configured in default 115200 8N1 RTS CTS This has to be changed to 19200 8N1 No handshake In order to reconfigure the modem interface connect the modem to PC terminal and issue the following AT IPR 19200 r n AT IFC 0 0 r n And write out the new settings AT amp Vir n and reconfigure your PC terminal according to those new settings Change TCP stack settings AT HOSTIF 2 r n AT ACTIVE I r n Subsequently set GPRS properties according to your GSM provider internet is an example AT CGDCONT 1 IP internet vn And write out the settings to modem memory AT amp W r n CTU in Prague FEE Department of Control Engineering Page 93 of 100 Miroslav Mach ek Appendix 9 Automatic Traffic Counter 5 Configuration The device is configured via its PC serial line Connect a PC to Con4 and set the following in PC s terminal application 115200 8N1 no handshake Once a device is powered on a message Traffic Counter is sent to the PC and the user can communicate with the device via commands A command consists of 2 parts Text and Value If Value 1s not present it 1s considered as reading Otherwise the value is processed by the device and saved into configuration A list of available commands can be found in Appendix 10 The following 3 paragraphs summarize basi
68. ion As for the traffic statistics web interface different charts can be added and integration into ITS for further data analysis and traffic control could be performed CTU in Prague FEE Department of Control Engineering Page 73 of 100 Miroslav Mach ek Automatic Traffic Counter 8 References and Bibliography 1 2 3 4 5 6 7 8 9 10 11 Pavel P ibyl Radim Mach dic syst my silni n dopravy 1 printing Prague Vydavatelstv CVUT 2003 ISBN 80 01 02811 9 Lawrence A Klein Traffic Detector Handbook Third Edition Volume I Milton K Mills David R P Gibson 3 Edition Wash D C Federal Highway Administration U S Department of Transportation 2006 Publication No FHWA HRT 06 108 Lawrence A Klein Traffic Detector Handbook Third Edition Volume II Milton K Mills David R P Gibson 3 Edition Wash D C Federal Highway Administration U S Department of Transportation 2006 Publication No FH WA HRT 06 139 Carlos Sun Stephen G Ritchie Individual Vehicle Speed Estimation Using Single Loop Inductive Waveforms Berkeley University of California 1999 ISSN 1055 1417 Luz Elena Y Mimbela A Summary of Vehicle Detection and Surveillance Technologies used in Intelligent Transportation Systems online Lawrence A Klein Ph D P E New Mexico The Vehicle Detector Clearinghouse 2007 Available from lt http www nmsu edu traffic gt viewed 1
69. is that it is simpler than two loop system because of saw cuts and measurement equipment However this method can only estimate the vehicle speed based on statistical information 4 there is no possibility to measure length of the vehicle In contrast the two loop method is capable to measure vehicle speed and length quite accurately This method has been used in this thesis and is discussed in Chapter 2 5 and Chapter 5 Furthermore it can also be achieved to specify the vehicle class by calculating the number of axles of the vehicle 8 The loop frequency is sampled in periods of milliseconds and the resulting curve contains information on the axle count similarly the same method can be used to produce a vehicle signature 6 7 which can be used for vehicle matching between two remote places CTU 1n Prague FEE Department of Control Engineering Page 5 of 100 Miroslav Mach ek Automatic Traffic Counter 2 4 Vehicle Detection Principle Used 2 4 1 Changes in Inductance The inductive loop detector behaves as a tuned electrical circuit When a vehicle passes above the loop the vehicle induces eddy currents in wire of the loop which decreases its inductance The outcome is a change in oscillator frequency of the circuit Figure 2 2 shows the effect of orientation of a metal object on the detection There is a misconception that the detection is based on metal mass Instead of that surface metal area has the biggest impact Ob
70. ject Object a detectable b undetectable Figure 2 2 Detection and Object Orientation In addition there is a ferromagnetic effect caused by the iron mass of the engine transmission or differential This effect causes an increase of inductance when such part of a vehicle enters the loop Nonetheless the surrounding metal of the vehicle always has a stronger impact and therefore the overall inductance will decrease in spite of that 2 4 2 Resonant Frequency The resonant frequency of LC tank circuit 1s f osc Az H F 2 1 y 2z4 LC In order to maintain fast responses of the detector the resonant frequency should be set approximately between 20 kHz and 120 kHz The Quality factor of the loop is expressed by 2af Ls Hz H Ohm 2 2 O Where Ls Loop series inductance Rs Loop series resistance The resulting frequency is given by CTU in Prague FEE Department of Control Engineering Page 6 of 100 Miroslav Mach ek Automatic Traffic Counter Fosc 27 i Q Hz H F 2 3 An important thing to note is that the resonant frequency changes slightly when there is resistance in the circuit In this application when the inductive loop in the road is about 20 40 meters long its resistance might be up to several Ohms which influences the oscillation frequency a bit Nevertheless the task of the ILD is not to measure the value of the loop inductance accurately but to detect the c
71. king temperature samples can be set by TEMPTIME attribute Table 5 3 via the command line interface described in Chapter 5 4 DS18B20 is a 3 pin variable precision temperature sensor in TO 92 package it communicates via Maxim 1 Wire interface which is a master slave half duplex protocol on a single wire Figure 5 8 contains DS18B20 pinout and basic circuit There has to be a pull up resistor on the data lane for proper work of the 1 Wire The description of the interface 1s out of scope of this thesis since the CCS C Compiler contains a driver for the sensor CTU 1n Prague FEE Department of Control Engineering Page 44 of 100 Miroslav Mach ek Automatic Traffic Counter Several 1 Wire devices can be placed on a single 1 Wire bus However for ease of employing 2 temperature sensors the both are placed on separated 1 Wire buses The device driver has been modified so that it handles two different buses and also allows for having no sensor connected in case of the external sensor The following describes the modified driver API ds1820 init initiates the on board sensor ds1820 init2 initiates the external sensor ds1820 read intl sensor returns sensor temperature in degree Celsius sensor 0 gt on board 1 gt external if sensor 1s not connected returns 128 5 2 4 Vehicle and Temperature Samples Buffer Both types of samples need to be saved into RAM memory where they are uploaded from later on see GPR
72. le samples will be sent to the PC for 5 minutes em LOADDEF Load default settings READ Read settings from EEPROM memory edison EFRON O MM MN HELP Show list of available commands GPRSNOW Connect and transfer buffers veh temp to the server GPRSDISCON Close and reset GPRS modem START Begin measurement STOP Stop measurement Commands for Configuration read write value Start Measurement after power up AUTOSTART 0 no l yes CTU in Prague FEE Department of Control Engineering Page 96 of 100 Miroslav Mach ek Appendix 10 Automatic Traffic Counter Set Get actual date and time set command without seconds DT format YYMMDDHHmm ex 0812301545 2009 12 30 15 45 00 Measure speed and length by averagin MEASUREAVG i a dis 0 no l yes Transfer samples to the server GPRSSEND 0 no l yes Time interval of transferring GPRSTIME minutes PIN code for a SIM card in the GPRS modem GPRSPIN 0 for no PIN Distance between loops LOOPDIST dm Length of loop LOOPLEN dm Lane offset LaneNumber of the first lane LANENUM LaneNumber 1 of the second lane IP address of the server SERVERIP XXX XXX XXX XXX Server port SERVERPORT 0 65535 How often to get temperature samples TEMPTIME minutes 0 don t take any samples CTU 1n Prague FEE Department of Control Engineering Page 97 of 100 Miroslav Mach ek Appendix 11 Automatic Traffic Counter Appendix 11 Database Create S
73. led files Therefore it is suggested to place all bootloader files directly in a folder located in the root directory of a drive Otherwise in case of long path to files the compilation of the source code will fail Device select Crystal speed in Hz LIST E 18F2420 change also Configure gt SelectDevice from Mplab xtal EQU 20000000 you may want to change XT OSC baud EQU 115200 the desired baud rate Ihe above 3 lines can be changed and buid a bootloader for the desired frequency and PIC type de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de Baud Rate of serial line Tiny Bootloader 18F series Size 100words claudiu chiculitafGugal ro de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de e de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de de include icdpictypes inc takes care of includ M mD include spbrgselect inc RoundResult and baud ra define first address max flash 200 100 words Configuration FCMEN ON IESC ON PWRT ON BOREN OFF WDT OFF MCLRE ON LPT10SC OFF CONFIG OS HS bits CONFIG PBADEN OFF CCP2MX PORTC STVREN ON XINST OFF DEBUG OFF LVE OFF mer Figure 3 10 Tiny Bootloader Sourc
74. les Memory usage ROM 26 RAM 32 36 0 Errors 7 Warnings Loaded D CVUT FEL Coventry University Bachelor Project sources PIC USB senal ex_usb_senal cof BUILD SUCCEEDED Sun Apr 01 19 27 16 2007 lt lt PIC18F2455 W 0 novzdcc bank 0 source code window ih Ry x7FF i 18 O pu list of files in a project oxsrr e D 1 interrupt LOADER END 9 2 pic18 ust i E usb h ET FOTO JEDER_END nothing vill replace the bootloader IE usb cc END OF bootloader definition E usb desc ER Configuration Bits E Other Files Address Value Category Fail Safe Clock Monitor Enable Disabled Internal External Switch Disabled 300002 3F USB Voltage Regulator Enabled gt gt gt Warming 202 D CVUT FEL Coventry University Bachelor Project sources PIC USB serial ex_usb_serial c Line 189 6 11 Variable never used value 300000 25 Full Speed USB Clock Source Selection Clock src from 96M 4LL 2 CPU System Clock Postscaler OSC1 05C2 Src 96MHz PLL Src 2 96MHz PLL Prescaler Divide by 6 24M input 300001 OE Oscillator HS HS PLL USB HS Power Up Timer Disabled messages from a Brown Out Detect Enabled in hardware SBOREN disabled Brown Out Voltage 2 0V Figure 3 2 Microchip MPLAB IDE layout 3 2 ASIX PRESTO Programmer 3 2 1 Description ASIX PRESTO Programmer Figure 3 3 is an USB 1 1 2 0 programmer which supports many devices ranging from Serial EEPROM Fl
75. llow to set seconds Hence when calling rct set datetime function it always sets seconds to 0 CTU 1n Prague FEE Department of Control Engineering Page 43 of 100 Miroslav Mach ek Automatic Traffic Counter For purpose of saving vehicle samples into buffer the sample size matters because there is a limited RAM size of the microcontroller Therefore it is more efficient to save a Unix timestamp having 4 bytes rather than saving date and time separately The compiler s time h contains mktime function which accepts struct tm and which returns a timestamp i e number of seconds since January 1 1970 00 00 00 UTC All date and time functions of the compiler time library have years since 1900 for instance number 108 means the year 2008 etc Months and days begin at 0 not 1 The following demonstrates how to get a timestamp SUrUCE em Actual Mime unsigned int32 timestamp ActualTime tm year year 100 ActualTime tm mon month 1 ActualTime tm mday day 1 ActualTime tm hour hour ActualTime tm_min min ActualTime tm sec sec timestamp mktime amp ActualTime 5 2 3 Measuring Temperature As well as gathering vehicle samples the Traffic Counter provides taking indoor and outdoor temperature samples by two Maxim DS18B20 13 digital temperature sensors One is placed on the board the latter should be connected by 3 wires to the external sensor connector shown in Figure 5 3 and placed outside the case The period of ta
76. llowing format Traffic text file example is below Traffic lanenumber datetime speed length Temperature datetime tempin tempout Tractie Data fiis CESES e 2 O SID 1 PVER 1 0 FWVER 0 9 HWVER 1 0 PERO OUO ISDN Epor Oak is o TYPE 0 SMP LNO 2 pO ROS OO OM o oO B2000 A Po ESO cod OS CTU in Prague FEE Department of Control Engineering Page 61 of 100 Miroslav Mach ek Automatic Traffic Counter 6 3 4 Binary Data Conversion As described in Chapter 5 5 7 traffic and temperature data is transferred from stations in binary form and it is necessary to unpack them before uploading to the database PHP language contains unpack function for conversion from binary format The following code snippet contains a function for vehicle sample conversion UIE ion o elas Len aM OSDI ie ino sumpackedd ata npac V ada e time villane l engt ls pecar Sb rng Svehiclesample array Svehiclesample unixtimestamp Sunpackeddata datetime SZ cde S mos ci om ae a moe ed aa ante i ayy convert unix timestamp svehnelesamp lel darecok gmeatbe mA sunpackeodatall estet ime 10 Svehiclesample lane Sunpackeddata lanelength gt gt 12 the highest 4 DIES Svehiclesample length Sunpackeddata lanelength amp 0Oxfff the lowest Woes Svehiclesample speed Sunpackeddata speed Gee lich Vee sm The unpack function is capable of converting data from little endian big endian and machine byte order
77. m gt viewed January 2009 MicroOLAP Technologies Ltd MicroOLAP Database Designer for MySQL online Available from lt http www microolap com products database mysql designer gt viewed 1 January 2009 Paul Bakaus and the jQuery Team Inc jQuery UI online Available from lt http u1 jquery com gt viewed 1 January 2009 Christian Bach Tablesorter Plugin for jQuery online Available from lt http tablesorter com docs gt viewed 1 January 2009 Aditus Consultiong JpGraph online Available from lt http www aditus nu jpgraph gt viewed January 2009 CadSoft Computer GmbH EAGLE online Available from lt www cadsoft de gt viewed 1 January 2009 CTU in Prague FEE Department of Control Engineering Page 76 of 100 Miroslav Mach ek Appendix 1 Automatic Traffic Counter Appendix 1 Content of the Attached CD e DP2009 Machacek pdf This thesis in Adobe PDF format e Docs Documentation Data Sheets Manuals e Install Installation and Setup Executables e PCB PCBs Schematics Bill of Materials o ILD Inductive Loop Detector o TrafficCounter Station Device e Sre Source Codes and Executables o DataServer PHP TCP Server o ILD Inductive Loop Detector o TrafficCounter station Device o TrafficStats PHP Web Application CTU 1n Prague FEE Department of Control Engineering Page 77 of 100 Miroslav Mach ek Appendix 2 Automatic Traffic Counter Appendix 2 Inductive Loop Detector Schematic g
78. ment of Control Engineering Page 87 of 100 Miroslav Mach ek an O 6000600000000 oO ero Un Ti O GQ E 0000000 Caron 25 Female El 000 0 0 t b Er E 128V m rA ae V AO oon Appendix 7 Canon 25 Female Canon 25 Female Automatic Traffic Counter Canon 25 Male I o Oo 100n a MAX2IACPE Canon 25 Female CTU in Prague FEE Department of Control Engineering o CN eco ore 3 i o 9 6606 J 2999999999799 Canon 25 Female 15 iG UT n a ul oz 560506000 la JO 39 ARKIZEVAIP Or ah ATH EL de i La JB Page 88 of 100 Miroslav Mach ek Appendix 8 Automatic Traffic Counter Appendix 8 Traffic Counter Bill of Materials Ouantity 1 R3 OR EY rj 32 768kHz m C T M C3 C4 C5 C6 C10 C11 C12 C13 C14 C17 C18 C1 9 C20 C21 C22 C25 C7 C8 C9 C1 C2 CON7 CON8 1 CONI CON3 CON4 CON5 CON6 1 CON2 IOS External Temperature Sensor I LED1 LED2 LED3 LED4 105 106 104 SWI l l l l l l l CTU in Prague FEE Department of Control Engineering Page 89 of 100 Miroslav Mach ek Appendix 9 Automatic Traffic Counter Appendix 9 Traffic Counter User s Manual 1 Introduction The Traffic Counter is a device for measuring speed and length of vehicles The device allows to gather data from up to 2 traffic lanes Each lane 1s monitored by 2 Inductive Loop Detectors that are
79. n be changed Examples of charts generated via the Traffic Charts API are depicted in Figure 6 8 Number of vehicles per day Odry Towards Centre Speed categories oy tomes tenere ur ue m 4 7 2008 to 7 7 2008 17264 vehicles 1 2 M 0 49 kmph 8839 Bl 50 79 knph 8282 O 80 129 kmph 141 130 159 kmph 2 E 160 kmph 0 Da Oe Ub 3425 vehicles over D kmph 46 0x Generated on 28 12 05 20 52 46 in 0 76 seconds Figure 6 8 Charts Generated in Traffic Charts API 6 5 Database Benchmarking Table trafficdata model in Chapter 6 2 has been filled with roughly 400000 pre generated samples This table contains data of vehicle samples of all stations and queries for generating charts are executed on this table Therefore its performance is vital The following code has been run in order to measure query execution time the query 1s taken from chart generating function PRE mysql MysqlConnect y oStream explode Emu Tote l SSE mies mM gt BEGIN there should be operations to be measured Sg mysqlquenry Shel COUNT CS ERR GTI oC WHERE idlanec s 1 AND Cares oia DUIS TON E OO 0 RENI MORTO ASIE DIG 0 A SAND E Ta Cue Dr BETWEEN 500 AND SIONIS END pendim explode we eine d obe SLOH ecc tmi e no Str E ODE Sone inti 5 ie CCI o loba een jesse S count myo dgl Tec Ch Tow es echo Scount MysqlClose smysql ce It turned out that adding an extr
80. n be monitored each of them has to be equipped with 2 inductive loops which has to be away from each other some particular distance so that measurement can be carried out Chapter 2 5 Figure 5 2 contains an overview of the Traffic Counter The device incorporates an on board RTC chip Chapter 5 2 2 so that date and time is also logged when a vehicle is measured Furthermore there is ambient temperature monitoring Chapter 5 2 3 and both indoor and outdoor temperatures can be logged The device can be configured via the implemented command line interface Chapter 5 4 running on its PC RS 232 As the last task performed in case a GPRS modem is connected to the device vehicle and temperature samples gathered are transferred to the server in particular time intervals CTU in Prague FEE Department of Control Engineering Page 38 of 100 Miroslav Mach ek Automatic Traffic Counter Figure 5 2 Traffic Counter System Overview 5 1 Device Description The device is based on PIC18F2620 it is exactly the same microcontroller as PIC18F2420 Chapter 4 3 1 except for ROM and RAM sizes which are 32kB and 4KB The microcontroller has been chosen because of large memory since the device has to buffer vehicle samples meanwhile it is not connected to the Internet via a GPRS modem The layout of the device is shown in Figur
81. ned with the help of a GPS device that provided reliable speed information The Traffic Counter speed measurement error increases rapidly at speed lower than approx 25 kmph It is caused CTU in Prague FEE Department of Control Engineering Page 72 of 100 Miroslav Mach ek Automatic Traffic Counter by different reactions of both ILDs in the traffic lane The speed error remains at approx 5 for speeds above the threshold It should be noted that the test was conducted up to speeds of 90 kmph 7 3 Further Work As further extension of the thesis some features could be added to the Inductive Loop Detector Because of its universality there are various ways how to use that device Therefore a convenient feature would be to allow the user to set parameters such as trigger delay via the unused on board switches Moreover the IDL could be modified to continuously sample loop frequency when a vehicle passes over the loop and create a vehicle signature which could be used for recognizing number of axles of the vehicle Similarly it could also be employed in vehicle matching at two remote places as mentioned in Chapter 2 3 With regard to the Traffic Counter in order to increase the number of monitored traffic lanes an auxiliary microcontroller peripheral 1 e port expander for increasing the number of detectors connected could be employed A possibility of saving data on a SD card would come in useful at places without a GPRS connect
82. ngside line and pie plots has been used The usage of the JpGraph library 1s straight forward and well documented in 23 and it would be beyond the range of this thesis to provide a description of the library The following PHP code only demonstrates the simplicity of using the library Figure 6 7 contains the chart generated lt php meud t MS or ara jojo include Us Octal Lias php S a E a 71590 13 5 1 2 7 Sous ciue Sgraph new Graph 250 250 auto Create the graph These two calls are always required sarah Sb o calocoma Slineplot new LinePlot Sydata Create the lincar plot e ae ae eo oa Ue Sm pi Adda mp Add the plot to tha graph See cuenten etos 0 P DSO lie Cree Tint Ce Figure 6 7 Simple Line Plot via JpGraph Library 6 4 3 Traffic Charts API In order to provide the transparency of JpGraph functions an API for generating traffic charts based on database samples has been implemented Scripts for chart generating are in charts folder under the main web interface directory i e where index php can be found Each file generates different type of chart which 1s generated right into the screen and variables are passed over query string GET array whose variables are listed in Table 6 4 CTU in Prague FEE Department of Control Engineering Page 68 of 100 Miroslav Mach ek Automatic Traffic Counter Traffic lane s to be shown in the chart idstation Station s to be shown in the c
83. nitoring including generating graphical outputs 1 e charts Facts and Figures Online Stations Constraints Lanes From 2008 07 01 lt 2 To 20080730 Clear Dates gt Upload Chart Type PE Number of Vehicles Average Speed Traffic Mirek Station Odry Test station Vehicles hour Miroslav Machacek Figure 6 4 Traffic Statistics Web Application The application employs jQuery UI 33 Javascript Library for sorting tables and for easy selection of date intervals and JpGraph 35 PHP library for generating charts The following outlines the features of the application CTU in Prague FEE Department of Control Engineering Page 64 of 100 Miroslav Mach ek Automatic Traffic Counter e Station Management Create edit station its description view station last update date e Lanes Management Create Edit station lanes their lane number description view lane last update e Upload history Binary files upload view upload history and details e Stats Lane Charts number of vehicles per hour day average speed per hour day speed and length categories Station Charts indoor and outdoor temperature e Export Raw lane data export into CSV files 6 4 1 jQuery jQuery is a open source Javascript library 22 which simplifies HTML document access event handling and animations through abstractions of low level functions and attributes Particularly jQuery UI is its part which
84. ocket create AF INET SOCK STREAM SOL TCP Lt lis resource Ss socket 4 echo Unable to create socket SOCket screrror socker last o qo e exit i try to re use address and port MES OE KOL se toto no So ee o OS O RES OR AUS E ADD RE TII echo Unable bosch Ope nom on SOCKEB 3 socker srtrerror socker last error ty eoe MS HS oce eod als ocre 07100006 echo Unable to bind sockets o sOoCket screrror socket lasc error NS exit socket_listen Ssocket 5 Unfortunately PHP language does not provide threads but it supports both non blocking and blocking sockets Given that the data transfer from a station takes only several seconds and is carried out in a period of several minutes blocking socket can be used without any problems Connection or client disconnection can be recognized by reading from the socket where the event occurred Sresult socket read clients 1 socket 7 PHP_BINARY READ HERE duc Slice FALSE I c MR socket last error Sclients Si socket 104 15 6 3 2 Handling Multiple Clients The server application provides the possibility of having several clients stations connected at a time Even though blocking sockets have been used a simple principle for dealing with multiple clients has been employed The scripts waits until there is either a new client connected or data from one of the current clients is available The following outlines the main loo
85. of a microcontroller 3 3 6 General Structure of Source Code Like other C language compilers source codes consists of c and h files and there also has to be main function within the main c file All microcontroller firmware codes written within this thesis have the following structure and order e Include device header file ex include lt 18f2420 h gt e Set internal device configuration device command e Set configuration bits Zfuses command e Include other project files h c and function prototypes e Interrupt handler routines other functions e Main function void main An example of source code can be found in Appendix 12 CTU in Prague FEE Department of Control Engineering Page 18 of 100 Miroslav Mach ek Automatic Traffic Counter 3 4 Tiny Bootloader Generally the term bootloader means a small block of code that is executed once a device is reset or powered on In terms of embedded systems the bootloader is used for downloading a firmware to a device without the need for programming equipment 1 e programmer Tiny Bootloader 26 is a bootloader for Microchip PIC16 PIC18 dsPIC30 families that provide self programming It allows flashing the microcontroller via its serial line interface which is usually present within every application This speeds up development markedly because the chip does not have to be taken out of a board Given that the source code of the bootloader is freely availa
86. om lt http www aditus nu jpgraph documentation php gt viewed 1 January 2009 TENcom s r o GPRS Modem Configuration Manual online Available from lt http www tencom cz download php gt viewed 1 January 2009 CTU in Prague FEE Department of Control Engineering Page 75 of 100 Miroslav Mach ek Automatic Traffic Counter 9 Software and Packages Used 25 26 27 28 29 30 31 32 33 34 35 36 ASIX s r o ASLX UP online Available from lt http tools asix net prg presto htm gt viewed 1 January 2009 Claudiu Chiculita Tiny PIC bootloader online Available from lt http www etc ugal ro cchiculita software picbootloader htm gt viewed 1 January 2009 Custom Computer Services Inc PCWH C Compiler for Microchip PIC online Available from lt http ccsinfo com gt viewed 1 January 2009 Microchip Technology Inc MPLAB Integrated Development Environment online Available from lt http www microchip com stellent idcplg IdcService SS GET PAGE amp no deId 1406 amp dDocName en019469 amp part SW007002 gt viewed 1 January 2009 The Apache Software Foundation The Apache HTTP Server Project online Available from lt http httpd apache org gt viewed 1 January 2009 The PHP Group PHP Language online Available from lt www php net gt viewed 1 January 2009 The Sun Microsystems Inc MySQL Database Server online Available from lt www mysql co
87. on power Wrong power connection Check power feed up Red LED is still on Faulty loop of feeder Check loop installation and connection connection Loop operating frequency Select different frequency out of range settings SW3 The detector cannot Crosstalks with adjacent Select different frequency calibrate e g Red LED detector settings SW3 blinks occasionally CTU 1n Prague FEE Department of Control Engineering Page 85 of 100 Automatic Traffic Counter doo hos l mil c ran bc on Appendix 6 x eue zdoo Appendix 6 Traffic Counter Schematic Miroslav Mach ek CECXV A NO M 9 p 9D Uepoyi NIZA 1NOZYH u oDo 3 NL 1nol3 D Ji POW T 1nozL NIZ L k A INOLL NIL L NI L L MCV NICL LNCEeL LMOla NILH IMO NIC AGZMOO L ZAP 3 i v la 75 13 PI NASON LLI 13534 241892 ASt m N N x Z Josues dua Ly Ap 4 m x lt Josuas duwa TP at Lop io r cof J as ekok N s N gt Co M E MN 1 I2 h2 Ih ho Tho sic pe Qe i led n Go Jo c co zi on II o 1 OW Mo ZOO eol ZO ml oD I e Ac Ji dd cdoa Z oue pdoo Page 86 of 100 CTU in Prague FEE Department of Control Engineering Miroslav Macha ek Appendix 7 Automatic Traffic Counter Appendix 7 Traffic Counter PCB vart Ha vere tugtuo amp SE 2 7 O 122 mm 126 mm CTU in Prague FEE Depart
88. ononnncnnnnnnnnnononononcnnnnnnos 45 5 3 D viceet nps dand Paramete is bosse beo Eb uim eee E Ebr QE 47 5 4 Command line Meade rr RETE Vau aTi 48 SAT AAT ACT BU M TET END 48 24012 Butler Processor aetna u AG eaten tent tutt 49 x MERLO zoo Casa ania ici 50 2 9 GPRS MOS siae eo MMC 50 SoA JDCSCHPUOM kde P PRD MOO bt ua a eddie Ud aod bedient E UE 50 5 27 rs O eed eaten acta machetes 51 LIS JAT C 6 10 01 1 0021 6 cane a 52 394 Moden CON ut NO er n TS E E OER 52 23 GPRS Contieclion TO SEU 53 o ougan E agenesis PO 54 o Transternte Sample aid 55 O Severa ppliCaulofblS eusosi treni eie a 56 6 1 DeEver Ifistallatlofi osmotic eno oils O 56 6 2 Database Mode irradiaci n S6 6 3 BERN OS RS ERE PT 58 6 9 Sockets dE 59 632 Handling Multiple Hes ti 59 O eae 60 034 Binary Data CON version o eise A buceo Habl set siund 62 fe A A A O erent ree 62 63 6 Server CONMO MI AlON ouo o eee a Wn ieee ase 63 0 9 7 Rim NOS CU escent sere vests UE EMI de ade es ee 63 6 4 Trae CALS VCS RR CEE haa O chet ae che teams oo oh on 64 6AL JOU Cen 65 040 2 IPOD tanta diia 68 CA Trate Chats ADI A 68 6 5 Brida AAA EE 70 US EIE 72 7 1 SS A Sa V T OE 12 22 LESS INC TCI m t O O O O T 72 73 PEE OW A PP R O OR O O O O caliente ens 73 V References and Biblio Crap ay uu ee eter eie etu ese wands a 74 2 Sottwaresand Packages USCC dad 76 Appendix 1 Content of the Attached CD eee 0000000000000 TI Appendix 2 Inductive Loop
89. ounter Inductive Loop 2 15 Grounding to the earth 3 16 Inductive Loop FGND Negative Voltage Power Supply 7 to 12V 6 19 GND In System Ground oe ee A Positive Voltage Power Supply 7 to 12V External Reset with opto isolation against EXTGND Input Current 5mA Vehicle Above 100ms Impulse with opto isolation against EXTGND Vehicle Above Permanent with opto isolation against EXTGND 12 25 EXTGND Ground for opto isolation VEHTTL Vehicle Above TTL signal against GND 4 Settings CTU in Prague FEE Department of Control Engineering SWI Reset Button SW2 Device Parameters Wo Mme SW3 Loop Frequency Settings LA Page 83 of 100 Miroslav Mach ek Appendix 5 Automatic Traffic Counter 5 LED purpose There is no loop connected or the No Signal oscillator frequency is out of range has to be 20 kHz 145 kHz Calibrating Calibration in progress HM Blinks once if calibration was not Calibrating om Blinks for 2 seconds in case of Calibrating Yellow successful calibration Vehicle M Green No Vehicle above the loop recognition Vehicle M Green Vehicle above recognition Blinks according to the actual loop Vehicle M Yellow freguency recognition e g 30 kHz 3x 80 kHz 8x 6 Operating Instructions I Principle of Operation The detection is based on sensing a change of loop inductance when a metal part app
90. ounter employs 4 loop detectors and gathers traffic data from 2 lanes The data collected is in particular time interval transferred to the server via a GPRS modem The last part of the system comprises two server applications The first one receives data from multiple stations and uploads them to the database The latter is a web interface for monitoring traffic at stations and generating statistical and graphical outputs Once the entire system has been configured it automatically gathers traffic data from lanes of stations transfers them to the server where samples are used for statistical information such as speed and length categories and lane occupancy 7 2 Tests in the field The entire system has been placed in the field for some period to gather traffic data The Inductive Loop Detector has been tested with an inductive loop built in a tar roadway The loop was rectangular with dimensions 2 m x 2 m and inductance of approx 100uH The loop frequency was perfectly stable having almost zero variation hence the overall device sensitivity is very high A small vehicle 1000 kg weight 3 7 m length even though the loop inductance was so low caused a change in inductance of 2 Such a substantial change can be detected by the device without any problems To summarize the ILD device could also be used to detect motorbikes or even bicycles with different loop size in normal traffic Speed accuracy of the Traffic Counter has been exami
91. p of the data server script while 1 SRS socks copy Ele Malm socker bo dercce a New client POS i lt count C STRES E S qu cie ts esa 1 NULL i44 uec pote S Oi cul cuiu Jens mes Seda Mc Kent es ocre m Sready socket select read Swrite NULL Sexcept NULL tv sec NUE BLOCKS CTU in Prague FEE Department of Control Engineering Page 59 of 100 Miroslav Mach ek Automatic Traffic Counter ii Mamma 0 ck mede EA qme Come comme eue d ROTO Ibe Sal sie clients i ccr eS Iie AMO CS S00 SA Tocem cec OM curro Cliente ny The read array contains all client sockets including the server socket Function socket select blocks until at least one event occurs on read array and removes those sockets from rea array which do not have any event Function parameters have to be passed by reference the reason for write except 5tv sec variables 6 3 3 File Formats Once all vehicle samples have been acquired from the station the file containing those samples is saved into BINARY FILES PATH directory Afterwards the binary file is processed and uploaded to the database In case of a successful upload the file is moved to BINARY FILES PATH PARSED directory and is also converted from binary to text form and saved into DATA FILES PATH Filename is always the following SID DATETIME EXT where SID Station ID DATETIME MySQL timestamp EXT bin txt Example of traffic file 2008 12 04 22 21 41
92. provides easy to implement user interface effect such as resizing sorting drag amp drop and others This thesis employs two plugins from jQuery UI Datepicker and Tablesorter Therefore facts mandatory to get those two plugins working are mentioned only For an extensive description of jQuery features the reader should refer to 22 and 33 6 4 1 1 Usage The heart of the entire Library is the file jquery js It has to be included in HTML source code at first jQuery functions can be used as soon as the DOM is ready after which the Query code can be run The following demonstrates how to achieve that so DP bype texte javascript CAO SME TE REC UT SOM ZVS once the MOM SBS Dub st s meet code heise SAC einen iO Li 1 caca Hello oe IEG Ce acd CTU 1n Prague FEE Department of Control Engineering Page 65 of 100 Miroslav Mach ek Automatic Traffic Counter Which does the same as the following code without jQuery lt a href onelick alerrt Hello yor leo aa els 6 4 1 2 Datepicker It is a plugin embedded in jQuery UI package It provides an easy date selection via a small calendar menu It can also be configured so that it allows to select a date range The Datepicker is bound to an input tag lt input type text size 10 value id startDate gt After that the following to be placed into ready function see Chapter 6 4 1 1 causes a calendar to pop up when the text field is focused
93. r calibration and for recognizing vehicles samples buffering has been introduced For both purposes the only properties necessary to know are the mean value and deviation of samples gathered Thus samples can be saved into a circular buffer which rolls from its end to the beginning The following outlines the circular buffer implementation define SAMPLES_NO 64 unsigned int16 Samples SAMPLES NO unsigned int8 SamplePointer 0 Writing into the buffer Samples SamplePointer CCPactual SamplePointer ik Sample POTRT e A EES NO samp lebornter 0 There is no need for calculating frequency according to Equation 4 1 All computations can be worked out with counter values which 1s much faster because samples do not have to be converted to frequency value Hence Samples array is continuously filled with counter values gathered according to Chapter 4 3 2 and it contains the most recent 64 frequency samples CTU in Prague FEE Department of Control Engineering Page 32 of 100 Miroslav Mach ek Automatic Traffic Counter 4 3 4 Calibration At the start up and every time an inductive loop is connected calibration process has to be carried out If there 1s a loop connected to the device the device gathers samples into a calibration circular buffer see Chapter 4 3 3 for algorithm used for 5 seconds and calculates the mean value and the deviation of the samples x 4 2 c 4 3 In C language unsigned int16
94. r roadway sensors Recently there has been a demand for Weight in Motion WIM technology 5 which is capable to measure speed length and grosstaxle weight of a vehicle The WIM usually combines piezoelectric and inductive loop sensors into one system and it is mainly used to detect overweight vehicles CTU in Prague FEE Department of Control Engineering Page 4 of 100 Miroslav Mach ek Automatic Traffic Counter 2 3 Inductive Loops in General The detection is based on sensing a change of loop inductance when a vehicle approaches the loop The loop 1s embedded in the pavement where saw cuts are made to place the wire into the roadway A change in magnetic flux caused by a vehicle 1 e its chassis is depicted in Figure 2 1 There are several approaches of detecting the change of inductance such as resonant and phase shift methods The resonant principle is based on an oscillator circuit where the inductive loop is its part The change in inductance causes a change in resonant frequency Therefore in the detector frequency measurement has to be carried out which is a simple task since it can be achieved easily with a microcontroller The resonant method Chapter 2 4 has been used in this thesis ILD device in Chapter 4 Pus LC 7 x EY nd L P T gane N N in JP E Road S Figure 2 1 Inductive Loop and Vehicle Presence Vehicle measurement can be performed by a single inductive loop The advantage
95. roaches the loop Loop inductance depends on loop dimensions number of turns feeder length and the ambient environment II Start Up 1 Connect the loop either via Conl or via Con2 Feeder cable to the loop should be twisted in pair so that crosstalks and other interferences are as lower as possible 2 Connect the power supply through Con2 CTU in Prague FEE Department of Control Engineering Page 84 of 100 Miroslav Mach ek Appendix 5 Automatic Traffic Counter III Calibration The calibration is fully automatic When a power 1s supplied to the device or a reset 1s performed the detector will automatically tune itself to the loop it 1s connected to In case the loop is not in steady state 1 e metal parts are passing by the loop the detector tries to recalibrate Once the device has been calibrated detection of metal objects is turned on The detector also handles environmental effects temperature etc which cause slow changes in inductance by auto recalibrating on the fly IV Operation If there is no loop connected or the loop frequency is out of range the red LED lights The yellow LED 1s turned on when a calibration is taking place If calibration 1s not successful the red light blinks once During the normal operation when the device is calibrated the yellow LED signalizes the current loop frequency by blinking The green LED shows whether a metal part 1s near the loop 7 Troubleshooting No LED lights
96. s causes a small CTU in Prague FEE Department of Control Engineering Page 26 of 100 Miroslav Mach ek Automatic Traffic Counter variation in the output frequency and therefore a lower sensitivity of detection because the signal has to be averaged or filtered which is a major drawback of this circuit 4 2 2 Circuit based on Operational Amplifier With regard to the issue mentioned in the previous subchapter another oscillator circuit has been examined The circuit in Figure 4 7 employs an operational amplifier components C1 and Ll forms a parallel LC circuit Resistor R3 controls the energy fed into the LC circuit Figure 4 7 Oscillator Cicuit with Operational Amplifier The schematic overcomes the drawback of the previous circuit However a disadvantage 1s the need for dual power supply In addition the output signal is a sine wave which needs further conversion to TTL logic Figure 4 8 In spite of the fact that more components are necessary to be introduced this circuit has been used in the analog part of the ILD CTU in Prague FEE Department of Control Engineering Page 27 of 100 Miroslav Mach ek Automatic Traffic Counter Figure 4 8 Simple Conversion from Sine Wave to TTL Signal 4 2 3 Surge Protection The inductive loop built within the roadway is connected with the oscillator through twisted pair cable Due to outdoor environmental conditions the circuit needs to be protected against overvoltage caused by
97. s priority interrupts where an interrupt can either be low or high priority High priority interrupt events will interrupt any low level interrupts that may be in progress Entire interrupt logic can be found in 15 3 3 5 1 Setting an Interrupt The compiler provides function for dealing with interrupts At first a peripheral which will fire an interrupt has to be set setup timer Tl INTERNA TP DIV BY o Subsequently the appropriate interrupt including general interrupt flag has to be enabled enable interrupts INT_TIMER1 enable interrupts GLOBAL Finally an interrupt service routine has to be put somewhere in the source code int TIMER1I void TIMER1I_ isr ZE rcoucine is exec redentor em lowe CTU in Prague FEE Department of Control Engineering Page 17 of 100 Miroslav Mach ek Automatic Traffic Counter 3 3 5 2 High priority Interrupt If the user intends to use high priority interrupts the following has to be placed at the beginning of source code After that the user has to mark some particular interrupt with high priority dint CCP1 HIGH voice ESP que a ici Palo a It shall be pointed out that according to my experience if the user enables high priority interrupts and he does not set any interrupt to be high priority the microcontroller behaves strange and unpredictably when the compiled source code is flashed and run This might either be a compiler bug or a bug
98. sonant LC so called tank whose oscillation frequency changes as one of the values of its components changes CTU in Prague FEE Department of Control Engineering Page 23 of 100 Miroslav Mach ek Automatic Traffic Counter Twisted pair connection 4 Inductive 9 pe 1 iu E in TTL i Logic Figure 4 2 ILD System Overview Furthermore in order to measure loops having a broad range of inductance the device contains auto calibration feature which also compensates small differences in inductance caused by temperature drifts The device itself contains an analog part for measuring inductance and a digital part for analysis calculations calibration and decisions The latter comprises a Microchip PICISF2420 microcontroller Chapter 4 3 running at the highest possible frequency 40 MHz taking into account the amount of calculations to be carried out and some minor peripherals described in Chapter 4 3 6 and Chapter 4 3 7 Frequency Settings a LI gt 4 E v M z L m e LE LJ Li LU Ed 7 A LU a Ll LS RJ Li Connector amp Grounding B Lo Pal Pad ONO gt Pa II hs Connector Cannon 25 Male Figure 4 3 ILD Board Layout Moreover given that loops are supposed to be placed within the roadway the device contains surge protectors transient voltage surpressors Chapter 4 2 3 on t
99. t L LL eo AG 100uF 1 6Y 19 C11 100nF 100nF E mmTEERICE 8 9 b T L NO e N C 1 O N OO LOI CO l o r o Lo xr e CN CNE CNE CNI ONT CNI CC CNI CNI 100uF 16V 4 REI o e lt N E N E DORA A S ANT KA O O ze Q a a ono ea lolol lap W L J ga CTU in Prague FEE Department of Control Engineering Page 78 of 100 Miroslav Mach ek Appendix 3 Automatic Traffic Counter Appendix 3 Inductive Loop Detector PCB 74 mm N Pa I F24 000000 E EF 0000000000000 diro a gU UU 0000 Qd 205 a 0000 nnnnnnn Canon 25 Male CTU in Prague FEE Department of Control Engineering Page 79 of 100 Quantity D1 D2 D3 D4 1N4007 DIPSW2 2xdipswitch 4k7 10k OK1 CTU in Prague FEE Department of Control Engineering Miroslav Mach ek Appendix 4 Automatic Traffic Counter Appendix 4 Inductive Loop Detector Bill of Materials Page 80 of 100 Miroslav Mach ek Appendix 5 Automatic Traffic Counter Appendix 5 Inductive Loop Detector User s Manual 1 Introduction The Inductive Loop Detector is a microcontroller based device device for detecting an electrically conducting metal object near the inductive loop The main purpose of the device is to detect vehicle presence by sensing an inductance change caused by the v
100. t LO n INT FCEE lowell Me Tunes SEO ies A eee ISR SOON tempng 0 OLE DOC S PIN BO Io le iN ESO duse oni o RUE 00 e else SS Bo van ene MANO INT_extl void extinct 1 Pa SE RTA void main char Ao DT sse Ma sl Se PNE Soo output_low PIN_BO0 SME CGS C OA setup Copil CCP2_PWM gt Sour PMS aes ZD TAB Lo sec see pum cdurcy 512 set tame ro 0 exteros bom MOIR Cy PRN IPR Ness Ce GROSS 3723 SEINE m OO IESUS enable interrupts INT TIMERO enable interrupts INT EXT1 enable interrupts GLOBAL while 1 atoms Ms eda ani uo n c getc pumas DIGG N ie Win ae am Oe iat eV Ser MCV z else if c 1 set pwml duty 10 else ak c 2 sec wm he Z3 CTU in Prague FEE Department of Control Engineering Page 100 of 100
101. th gt Email lt th gt lt th gt Due lt th gt lt th gt Web Site lt th gt E lt thead gt lt tbody gt LCL eL me ed acl do la o aa a y sm elec dio c ao V eel eol 7550 9 0 EL S Me um ema la Come wel ee lt tbody gt lt table Tablesorter javascript file should also be included in the HTML file SOUD EIS bere Ease aioe Sus o Uhm Joer elo le sc miners lt Seo Sis muse et exe scum Ms Un query metadatos Seo If the users wants to use jQuery inline function metadata js needs to be included Subsequently jQuery code has to be added to ready function described in Chapter 6 4 1 1 Sta Wesorter detalles wedge zebra p MVA coke sort em some TIo Olh The code above sets the first column of table MyTable as the sorting column and zebra widget makes different color of every second row of the table Inline functions provide the functionality of changing Tablesorter properties through code placed within the object tag For instance the following disables sorting feature on the associated column lt th elass estie ges P Eee ons lt A CTU 1n Prague FEE Department of Control Engineering Page 67 of 100 Miroslav Mach ek Automatic Traffic Counter 6 4 2 JpGraph Is an object oriented PHP library for generating various types of charts such as line bar pie and ring plots A chart can either be saved as an image file or shown directly within a web site Within this thesis the second method alo
102. that the entire server side can be run on various operating systems such as Microsoft Windows or Linux 6 1 Server Installation In order to get server applications working the following packages have to be installed and configured both tasks are out of scope of this thesis and can be found on the Internet e Apache Web Server 29 version 2 and higher e PHP Preprocessor Language 30 version 5 and higher e MySQL Database Server 31 version 5 and higher Moreover for proper function of the server application it is also mandatory to install the following modules e Mod rewrite for Apache e GD library plugin for PHP e JpGraph library for PHP 35 e jQuery Javascript Library 22 33 6 2 Database Model The database structure has been designed keeping in mind the purpose of traffic data and its later processing Table attributes are mainly used within the web interface described in Chapter 6 4 Database table layout designed in 32 is shown in Figure 6 1 SQL create script can be found in Appendix 11 The model containts the following tables CTU in Prague FEE Department of Control Engineering Page 56 of 100 Miroslav Mach ek Automatic Traffic Counter e stations contains nodes 1 e Traffic Counter Chapter 5 each node uploads data over the internet e temperatures indoor and outdoor temperature samples of stations e uploadedfiles every time a station uploads a file the file details are inserted so that th
103. tic Traffic Counter Connectors Con3 Con4 Modem and PC Serial Lines front view CANNON 9 CANNON 9 nga 1 CD a RX in 1 3 ll a EL Board Pus noe Con1 Con2 Power Supply External Temperature Sensor front view BOTTOM VIEW Conl Con2 Pin No Power Supply In Ext Temp Sens 15V DC 5V sensor pin 3 15V DC GND sensor pin 1 Con5 8 Loop Detectors refer to Inductive Loop Detector User s Manual 3 LED signalization On Device is powered Green Blink Data acquisition is in progress START command 2 Yellow Blink ball ia sample has been taken p qp ow 1 Not Used Future Purpose in 2 minutes GPRS connection has been established vehicle 4 Red and temperature samples being tranferred 20 fast blinks means GPRS connection error retry CTU 1n Prague FEE Department of Control Engineering Page 92 of 100 Miroslav Mach ek Appendix 9 Automatic Traffic Counter 4 Operating Instructions I Start Up 1 Connect external temperature sensor over a 3 wire cable to Con2 Place the sensor outside the box so that it measures outdoor temperature 2 Plug in 2 or 4 loop detectors Lanel Con5 6 Lane2 Con7 8 Connect corresponding loops to the detectors 3 Set operating frequencies of the detectors so that there are no crosstalks between them Rule of thumb The closer two loops the bigger frequency span Set appropriate sensitivity of each detector 4 Plug PC serial l
104. uctance values are listed in Table 4 2 Total Capacitance Loop Inductance DIP Switch On Range uH 120 6000 30 1500 10 600 8 450 Table 4 2 Frequency Configuration CTU in Prague FEE Department of Control Engineering Page 36 of 100 Miroslav Mach ek Automatic Traffic Counter b Detection Sensitivity The device apart from previously described freguency setting also allows to set the sensitivity of detection In other words how small metal object can be detected The calibration deviation threshold Chapter 4 3 4 also changes according to the sensitivity configuration The higher the sensitivity the higher deviation threshold that allows the device to be calibrated There are 8 DIP switches the switches 7 8 are used only Table 4 3 The reset of switches are not used and may be used in the future DIP Switch On Device Sensitivity Calibration Deviation Threshold Table 4 3 Device Sensitivity Configuration CTU in Prague FEE Department of Control Engineering Page 37 of 100 Miroslav Mach ek Automatic Traffic Counter 5 Traffic Counter Previous chapter deals with recognition whether a vehicle is above an inductive loop With the help of the Inductive Loop Detector we can therefore determine the vehicle presence and position Figure 5 1 Traffic Counter The Traffic Counter Figure 5 1 1s a device developed for measuring speed and length of vehicles Maximally two traffic lanes ca
105. uctive loops built within the roadway The first part of the thesis involves development of an inductive loop detector for sensing whether a car 1s above the inductive loop The second part comprises the realization of a device which employs inductive loop detectors for measuring speed and length of vehicles The device logs the vehicle data and transfers it to a server via a GPRS connection The last two parts deal with implementation of a server application for receiving and saving remote data from stations to the database together with a web interface for showing statistical information and charts about stations and their traffic Abstrakt Diplomov pr ce popisuje n vrh syst mu pro sb r dopravn ch dat pomoc induk n ch smy ek ve vozovce Prvn Cast pr ce popisuje v voj detektoru induk n smy ky pro zji t n zda se vozidlo nach z nad smy kou Druh st obsahuje n vrh za zen pro m en rychlosti a d lky vozidla pomoc detektor induk n ch smy ek v etn pr b n ho nahr n posb ran ch dat na server pomoc GPRS spojen Posledn dv sti pr ce se zab vaj v vojem serverov aplikace pro p jem a ukl d n dat z jednotliv ch stanic do datab ze a implementac webov ho rozhran pro zobrazov n dopravn ch statistik a pr b h na jednotliv ch stanic ch IV Table of Contents BSA i A0 ORP O RR eet BE OPPO RR o E I Acknowledgements and dedications os II ML III i docu
106. with the principles of that method Later on the traffic data collected can be used for analysis prediction and control of traffic in higher level technology ITS whose aim is to increase safety and to reduce road congestions and fuel consumption The traffic data can also be used as a source for information guidance and assistance systems for drivers 2 1 Reason for this Thesis Vehicle detection and measurement based on inductive loops has been in place for tens of years and it is the most used technology Over the world especially in the US it is quite easy to buy an inductive loop detector device and a traffic counter device However in the Czech Republic it is not so easy since companies either get those devices from abroad or develop and use them for their own purpose without further providing selling them Therefore the purpose of this thesis was to develop both detector and counter based on simple and well available components Given that the inductive loop detector can also be used at stop bar places in parking where vehicle presence needs to be found out or in automation for metal proximity sensing it was a major concern to develop own and low cost detector CTU in Prague FEE Department of Control Engineering Page 3 of 100 Miroslav Mach ek Automatic Traffic Counter 2 2 Review of Vehicle Detection Technologies Vehicle detection technologies are non intrusive and intrusive The non intrusive principle us
107. y unexpected state of the detector inputs transition to the idle state is made CTU in Prague FEE Department of Control Engineering Page 41 of 100 Miroslav Mach ek Automatic Traffic Counter IDLE Loop 1 rising Start Both Low Measurement Init tO get timerO Loop 2 falling Vehicle is Loop 2 risin measured Not allowed P 9 t3 get timerO signal on loops t1 get timerO t2 get timerO Loop1 falling Figure 5 6 Vehicle Measurement State Machine Time measurement is performed via timer0 which is a 16 bit timer After every transition timerO ticks are saved into t0 t3 variables For the purpose of vehicle measurement a slower timer 1s better The highest prescaler value of the timer 1s 256 thus the timer has the following properties with regard to 20Mhz crystal clock of the device e Timer tick 51 2us e Overflow every 3355ms Given that 3 3 seconds 1s not enough to measure long vehicles the number of timer overflows of 1s counted and its value 1s added to length calculations 3600000 oopdis tan ce looplength kmph dm dm ticks ticks 5 1 512 t1 10 Y j 5127 t2 10 of 65536 l JOJoopleneth 360000 iio 5 2 lcm kmph ticks ticks dm Similar calculations are done with t2 t3 values to calculate v l2 if measurement averaging is set by the user refer to MEASUREAVG in Chapter 5 3 and Appendix 10 Vehicle samples including timestamp described in
Download Pdf Manuals
Related Search
Related Contents
ICARO ICARO FM Cisco Systems TEG-S2500i User's Information Guide DV-BH250取扱説明書 -操作編- Instructions - Reliance Industries テレビューティリティーキッ ト TK-S5 ー 取扱説明書/保証書 iogear GCS1716TAA KVM switch 2541 HL-Primo-FR USER MANUAL Doro AUB 200h Manual del propietario Copyright © All rights reserved.
Failed to retrieve file