Difference between revisions of "S14: Need For Speed"

From Embedded Systems Learning Academy
Jump to: navigation, search
(Objectives)
(Android App Package)
 
(186 intermediate revisions by 3 users not shown)
Line 1: Line 1:
== Abstract ==
+
[[File:Cmpe244_s14_NFS_Final.jpg|thumb|right|530px|NEED FOR SPEED..!!]]
[[File:CMPE_244_F14_PU17.png|right|150px|Android RC Car]]
+
 
 +
== '''Abstract''' ==
 +
[[File:CMPE_244_F14_PU17_fig2.png|thumb|250px|Icon for our Android App]]
 
This page contains design and implementation of our Embedded Software project, Need For Speed. It's about maneuvering an RC vehicle using the Acceleration Sensor in a smart phone. An Android Application is developed to transmit the Acceleration Sensor Signals to the vehicle via Bluetooth. The car is mounted with a Bluetooth module to receive data from the phone. And the acceleration and turning of the vehicle will be based on this data.
 
This page contains design and implementation of our Embedded Software project, Need For Speed. It's about maneuvering an RC vehicle using the Acceleration Sensor in a smart phone. An Android Application is developed to transmit the Acceleration Sensor Signals to the vehicle via Bluetooth. The car is mounted with a Bluetooth module to receive data from the phone. And the acceleration and turning of the vehicle will be based on this data.
 
The vehicle is also mounted with two Infrared Sensor modules for collision detection, one in the front and other in the rear.Detection of any obstacle in the vehicles path will bring the vehicle to a halt state immediately.
 
The vehicle is also mounted with two Infrared Sensor modules for collision detection, one in the front and other in the rear.Detection of any obstacle in the vehicles path will bring the vehicle to a halt state immediately.
  
== Introduction ==
+
== '''Introduction''' ==
 
In this project we are using JY-MCU Bluetooth module to be the wireless link between the smartphone and the battery powered RC vehicle. The Android application is developed to transmit a particular byte for every threshold value of the Acceleration Sensor i.e. when the phone is one byte for front tilt and another for back. This received byte is compared by the SJOne board with few predefined values and accordingly PWM signals are given to the motors.
 
In this project we are using JY-MCU Bluetooth module to be the wireless link between the smartphone and the battery powered RC vehicle. The Android application is developed to transmit a particular byte for every threshold value of the Acceleration Sensor i.e. when the phone is one byte for front tilt and another for back. This received byte is compared by the SJOne board with few predefined values and accordingly PWM signals are given to the motors.
  
 
The input of the IR sensors is connected to the hardware interrupts on the SJOne board, the interrupt subroutine will be called every time there is an obstacle in the path of the vehicle, this subroutine will in turn stop the vehicle.
 
The input of the IR sensors is connected to the hardware interrupts on the SJOne board, the interrupt subroutine will be called every time there is an obstacle in the path of the vehicle, this subroutine will in turn stop the vehicle.
  
== Objectives ==
+
== '''Objectives''' ==
 
As this project is both software and hardware based, our objectives were as follows;
 
As this project is both software and hardware based, our objectives were as follows;
  
*  Hardware Objectives
+
'''Hardware Objectives'''
 
**  To achieve a constant 6V DC supply for the motors and 5V DC for the board from the battery.
 
**  To achieve a constant 6V DC supply for the motors and 5V DC for the board from the battery.
 
**  To interface the motors to the SJOne board via L298 motor driver.
 
**  To interface the motors to the SJOne board via L298 motor driver.
 
**  To calibrate the IR sensors to sense obstacle in 6" proximity.
 
**  To calibrate the IR sensors to sense obstacle in 6" proximity.
*  Software Objectives
+
'''Software Objectives'''
 
**  To develop an Android application to send the data from Acceleration Sensor via Bluetooth.
 
**  To develop an Android application to send the data from Acceleration Sensor via Bluetooth.
 
**  To develop a FreeRTOS code to receive these signals and process them.
 
**  To develop a FreeRTOS code to receive these signals and process them.
Line 22: Line 24:
 
**  To develop a FreeRTOS code to accept interrupt from the IR sensors and take actions accordingly.
 
**  To develop a FreeRTOS code to accept interrupt from the IR sensors and take actions accordingly.
  
== Team Members & Responsibilities ==
+
== '''Team Members & Responsibilities''' ==
*  Amey Patil
+
'''Amey Patil'''
 
**  Hardware Design  
 
**  Hardware Design  
 
**  Free RTOS (Part 1: To interface motors and LPC1758 using PWM)
 
**  Free RTOS (Part 1: To interface motors and LPC1758 using PWM)
 +
**  Free RTOS (Part 2: To configure the Bluetooth module)
 +
*  '''Siddhata Patil'''
 +
**  Free RTOS (Part 3: To send and receive data between Bluetooth module and LPC1758)
 
**  Android Application(Part1: To send data from Android Phone to LPC1758)
 
**  Android Application(Part1: To send data from Android Phone to LPC1758)
*  Siddhata Patil
 
**  Free RTOS (Part 2: To form pairing of LPC1758 and Bluetooth module)
 
**  Free RTOS (Part 3: To send and receive data between Bluetooth module and LPC1758)
 
 
**  Android Application(Part2: To send results of accelerometer sensor from Android Phone to LPC1758)
 
**  Android Application(Part2: To send results of accelerometer sensor from Android Phone to LPC1758)
  
== Schedule ==
+
== '''Schedule''' ==
  
 
{| class="wikitable"
 
{| class="wikitable"
Line 42: Line 44:
 
! scope="col"| Status
 
! scope="col"| Status
 
|-
 
|-
! scope="row"| 1
+
| scope="row"| 1
! 3/6
+
| 3/6
! 3/13
+
| 3/13
! Planning Hardware and placing order for the required components
+
| Planning Hardware and placing order for the required components
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 2
+
| scope="row"| 2
! 3/20
+
| 3/20
! 3/20
+
| 3/20
! Designing and Assembling the Hardware(Motors+Motor Driver+LPC1758)
+
| Designing and Assembling the Hardware(Motors+Motor Driver+LPC1758)
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 3
+
| scope="row"| 3
! 3/20
+
| 3/20
! 3/20
+
| 3/20
! Reviewing Datasheet, Pin Selection and Setting up the Software
+
| Reviewing Datasheet, Pin Selection and Setting up the Software
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 4
+
| scope="row"| 4
! 3/27
+
| 3/27
! 3/27
+
| 3/27
! Designing and Assembling the Hardware(Bluetooth Module+LPC1758)
+
| Designing and Assembling the Hardware(Bluetooth Module+LPC1758)
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 5
+
| scope="row"| 5
! 3/27
+
| 3/27
! 3/27
+
| 3/27
! Free RTOS pairing between LPC1758 and Bluetooth Module
+
| Free RTOS pairing between LPC1758 and Bluetooth Module
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 6
+
| scope="row"| 6
! 3/28
+
| 3/28
! 3/28
+
| 3/28
! Testing the pairing of Bluetooth and LPC1758
+
| Testing the pairing of Bluetooth and LPC1758
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 7
+
| scope="row"| 7
! 4/3
+
| 4/3
! 4/3
+
| 4/3
! Free RTOS code for PWM
+
| Free RTOS code for PWM
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 8
+
| scope="row"| 8
! 4/11
+
| 4/11
! 4/18
+
| 4/18
! Free RTOS code for sending and receiving data from Bluetooth
+
| Free RTOS code for sending and receiving data from Bluetooth
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 9
+
| scope="row"| 9
! 4/18
+
| 4/18
! 4/24
+
| 4/24
! Android App Designing and learning basics of Android SDK
+
| Android App Designing and learning basics of Android SDK
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 10
+
| scope="row"| 10
! 4/24
+
| 4/24
! 4/24
+
| 4/24
! Android App Designing
+
| Android App Designing
! Completed
+
| Completed
 
|-
 
|-
! scope="row"| 11
+
| scope="row"| 11
! 5/1
+
| 5/1
!
+
| 5/4
! Android App java code to transfer data from phone to LPC1758
+
| Android App java code to transfer data from phone to LPC1758
!
+
| Completed
 
|-
 
|-
! scope="row"| 12
+
| scope="row"| 12
! 5/1
+
| 5/7
!
+
| 5/7
! Android App java code to send values of accelerometer sensor to LPC1758
+
| Android App java code to send values of accelerometer sensor to LPC1758
!
+
| Completed
 
|-
 
|-
! scope="row"| 13
+
| scope="row"| 13
! 5/1
+
| 5/22
! 5/
+
| 5/22
! Final Project Report
+
| Final Demo  
!
+
| Completed
|-
 
! scope="row"| 14
 
! 5/8
 
! 5/8
 
! Final Demo  
 
!
 
 
|-
 
|-
 
|}
 
|}
  
 
+
== '''Parts List & Cost''' ==
== Parts List & Cost ==
 
  
 
{| class="wikitable"
 
{| class="wikitable"
Line 139: Line 134:
 
! scope="col"| Total Cost
 
! scope="col"| Total Cost
 
|-
 
|-
! scope="row"| Electronics
+
| scope="row"| Electronics
! SJOne Board
+
| SJOne Board
! 1
+
| 1
! 80.00
+
| 80.00
! 80.00
+
| 80.00
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! 9.6V 1600mAh Rechargeable Ni-Mh Battery
+
| 9.6V 1600mAh Rechargeable Ni-Mh Battery
! 1
+
| 1
! 14.42
+
| 14.42
! 14.42
+
| 14.42
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! 6V DC Gear Motor with Tyres
+
| 6V DC Gear Motor with Tyres
! 4
+
| 4
! 3.25
+
| 3.25
! 13.00
+
| 13.00
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! JY-MCU Bluetooth Module
+
| JY-MCU Bluetooth Module
! 1
+
| 1
! 7.68
+
| 7.68
! 7.68
+
| 7.68
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! IR Transceiver Module
+
| IR Transceiver Module
! 2
+
| 2
! 1.00
+
| 1.00
! 2.00
+
| 2.00
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! L298 Motor Driver
+
| L298 Motor Driver
! 1
+
| 1
! 7.50
+
| 7.50
! 7.50
+
| 7.50
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! LM 7806 Voltage Regulator
+
| LM 7806 Voltage Regulator
! 1
+
| 1
! 0.45
+
| 0.45
! 0.45
+
| 0.45
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! LM 7805 Voltage Regulator
+
| LM 7805 Voltage Regulator
! 1
+
| 1
! 0.32
+
| 0.32
! 0.32
+
| 0.32
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! 10uF Electrolytic Capacitor
+
| 10uF Electrolytic Capacitor
! 2
+
| 2
! 0.13
+
| 0.13
! 0.26
+
| 0.26
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
! 1uF Ceramic Capacitor
+
| 1uF Ceramic Capacitor
! 2
+
| 2
! 0.10
+
| 0.10
! 0.20
+
| 0.20
 
|-
 
|-
! scope="row"| Chassis
+
| scope="row"| Chassis
! Smart Car Chassis
+
| Smart Car Chassis
! 1
+
| 1
! 10.00
+
| 10.00
! 10.00
+
| 10.00
 
|-
 
|-
! scope="row"| Connections
+
| scope="row"| Connections
! Nuts, Bolts and Spacers
+
| Nuts, Bolts and Spacers
!
+
|
!
+
|
! 3.00
+
| 3.00
 
|-
 
|-
! scope="row"| Phone  
+
| scope="row"| Phone  
! Android Smart Phone
+
| Android Smart Phone
! 1
+
| 1
!
+
|
!
+
|
 
|-
 
|-
! scope="row"|  
+
| scope="row"|  
!
+
|
!
+
|
! TOTAL  
+
| TOTAL  
! $138.83
+
| $138.83
 
|-
 
|-
 
|}
 
|}
  
 +
=='''Design and Implementation'''==
 +
 +
[[File:cmpe244_s14_NFS_Block_Diagram.jpg|900px|centre|thumb|System Block Diagram]]
 +
 +
The above Block Diagram shows the overall implementation of the project. The accelerometer values (x, y, z) are used as an input by the android application. Depending on the instantaneous values, tilt will be determined. This tilt value will be provided to the Bluetooth for transmission.
 +
At the receiver, this tilt data will be received by the Bluetooth Module and provided to the LPC 1758 board via an UART channel. The on board processor will compare the received data with the stored values and generate PWM signals accordingly. The motor driver upon reception of this will driver the vehicle in the respective direction.
 +
We will see detailed explanation of the hardware and software in their respective sections.
 +
 +
 +
===Flowchart===
 +
[[File:Cmpe244_s14_NFS_fig19.jpg|center|thumb|400px|Flowchart for the System]]
 +
 +
===Hardware Interface===
 +
 +
Let us understand the whole structure piece by piece.
 +
 +
====1. LPC 1758 SJOne Board====
 +
 +
This board was a part of our course on Embedded Software at San Jose State University. For more information on the SJOne board [http://www.socialledge.com/sjsu/index.php?title=SJ_One_Board Click_me].
 +
 +
[[File:Cmpe244_s14_NFS_Power_Schematic.jpg|thumb|400px|Power Supply Schematic.]]
 +
====2. Power Supply====
 +
We need to generate steady 5V supply for the board while 6V for the motors without any current limitation otherwise the motors will not give its optimum output. To our luck, LM7806 voltage regulators are also available in the market along with the LM7805. The circuit schematic is as shown in the figure above.
 +
 +
The total current requirement of the circuit is around 1Amp. If this much current is to be drawn through the regulators then we must make sure the heat generated is properly dissipated, so we use heat sink. Most of the current will be driven through the LM7806 regulator as it drives the motors hence, we made sure that it is not surrounded by any other component. As, the LM7805 regulator just drives the SJOne board and IR module, current flowing through it is around 100mA. Hence, this regulator won't heat as much as the other one.
 +
 +
 +
 +
[[File:Cmpe244_s14_NFS_L298_Schematic.jpg|thumb|400px|Motor Driver Schematic.]]
 +
====3. L298 Motor Driver====
 +
 +
You must be thinking why didn't I use L293D as it is best for 6V motors and much easy to interface. Well, one of our motor consumes 200mA of current, which makes the total current 800mA that too in no load conditions. With load it might have seared upto 1A. Now the maximum handling capacity of L293D is 1A while that of L298 is 2A. Hence, for safety reasons I went for L298 motor driver.
 +
The pin connect for this interface is as shown in the above figure. The functions of the pins are as follows;
 +
 +
IN1 receives 'PWM input for left motor +' from LPC 1758 and drives OUT1
 +
 +
IN2 receives 'PWM input for left motor -' from LPC 1758 and drives OUT2
 +
 +
IN3 receives 'PWM input for right motor +' from LPC 1758 and drives OUT3
 +
 +
IN4 receives 'PWM input for right motor -' from LPC 1758 and drives OUT4
 +
 +
SENSE A limits the current for Left Motor
 +
 +
SENSE B limits the current for Right Motor
 +
 +
VS: Supply voltage for the Motors
 +
 +
For more information on L298 Driver, [http://blog.pennybuying.com/down/f/F815A.pdf Click_me].
 +
 +
 +
[[File:Cmpe244_s14_NFS_IR_Schematic.jpg|thumb|400px|IR Module Schematic.]]
 +
====4. IR module====
 +
 +
The IR module we are using is custom made. It is is designed to output logic '1' if any obstacle is detected or else logic '0'. The output signal from the IR receiver is directly proportional to the amount of IR waves falling on it. Hence, the output voltage for an obstacle far from the receiver will be less than that of a closer object.
 +
 +
In any case this output is in millivolts hence, we gave it as an input to LM358 which is a dual op-amp IC. This op-amp is configured in comparator mode. When the input at the non-inverting terminal is higher than the threshold voltage provided to the inverting terminal, the op-amp will give a logic high output. Hence, the threshold voltage is inversely proportional to the distance of the obstacle. So we connected a potentiometer at the input of the threshold voltage by which we can vary the range of obstacle detection.
 +
 +
In the case of IR the sensitivity of the reciever is not sufficient to detect obstacle at a longer distance. We were able to acheive obstacle detection in 2 inches of proximity. If, you are looking for detection at a longer distance, we would suggest you to go for Ultrasonic sensor modules which can even give you the distance of the obstacle from the vehicle.
 +
 +
Figure shows the circuit schematic of the IR module. This is circuit for one of the IR module. Two such circuits are implemented for front and back.
 +
 +
 +
[[File:Cmpe244_s14_NFS_Bluetooth.jpg|thumb|right|400px|Bluetooth Module]]
 +
====5. Bluetooth Module====
 +
 +
The module has 4 pins labeled on the back, VCC, GND, TXD and RXD. You might buy a module with two more pins KEY and STATE but it won't matter if you leave them open. The controller which it is interfaced with considers it as an serial UART device. So make sure you connect the RX and TX of the controller with TXD and RXD of the bluetooth module respectively.
 +
 +
 +
This module works best if you are running on 3.3V, in case you are working on TTL logic then you might use a voltage divider for proper operation of the module. According to the datasheet the VCC pin is capable to handle supply ranging from 3-6V so it is fine to give TTL logic supply but, do not give TTL logic signal to the RXD pin, it cannot take anything more than 3.3V, doing such will damage the pin and hence the module.
 +
 +
The communication for configuration of the module is based on AT commands. There is one command for every thing, to set the device name, set the pin, set the baud rate and much more. All you have to do is to save these AT commands in the form of string and send each byte serially to the module using a simple for loop. Initially the baud rate is set to 9600. Following table shows few of the AT commands which you may require.
 +
 +
{| class="wikitable"
 +
|-
 +
! scope="col"|Command
 +
! scope="col"|Response
 +
! scope="col"|Use
 +
|-
 +
| scope="row"|AT||OK || Used to verify communication
 +
|-
 +
| scope="row"|AT+NAMExyz||OKsetname||Sets the module name to “xyz”
 +
|-
 +
| scope="row"|AT+PIN1234||OKsetPIN||Sets the module PIN to 1234
 +
|-
 +
| scope="row"|AT+BAUD1||OK1200||Sets the baud rate to 1200
 +
|-
 +
| scope="row"|AT+BAUD2||OK2400||Sets the baud rate to 2400
 +
|-
 +
| scope="row"|AT+BAUD3||OK4800||Sets the baud rate to 4800
 +
|-
 +
| scope="row"|AT+BAUD4||OK9600||Sets the baud rate to 9600
 +
|-
 +
| scope="row"|AT+BAUD5||OK19200||Sets the baud rate to 19200
 +
|-
 +
| scope="row"|AT+BAUD6||OK38400||Sets the baud rate to 38400
 +
|-
 +
| scope="row"|AT+BAUD3||OK4800||Sets the baud rate to 4800
 +
|-
 +
| scope="row"|AT+BAUD4||OK9600||Sets the baud rate to 9600
 +
|}
  
==Design and Implementation==
 
 
===Hardware Design===
 
===Hardware Design===
  
[[]]
+
It was really a task to adjust all the above mentioned tasks on an 25cm * 15 cm chasis which is made of some paper mache material (less strength). The BOT weighs around a pound increasing the load on the motor drastically. The following image on left shows the BOT in the design stage while the one on the right is our final product.
The next block diagram displays the buses and interfaces used in the hardware design:
+
 
[[(click to enlarge).]]
+
[[File:Cmpe244_s14_NFS_Hardware.jpg|thumb|left|530px|Work in progress...]]
 +
[[File:Cmpe244_s14_NFS_fig1.jpg|thumb|530px|Android TA DA..!!]]
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
===FreeRTOS Programming===
 +
 
 +
In this section we will walk you through the source code for the SJOne board. Whenever a character is sent by the Bluetooth module, the UART interrupt handler code is executed. The code is as shown below.
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
    void UART3_IRQHandler()
 +
    {
 +
        Uart3::getInstance().handleInterrupt();
 +
        Uart3::getInstance().getChar(&in, 10000);
 +
        printf("%c", in);
 +
        motion = in;
 +
    }
  
===Hardware Implementation===
+
As you can see above the data received from the Bluetooth module is stored in the motion variable. Make sure you declare the motion variable as volatile because in the main function we will be using it in an infinite while loop. Making it volatile will help the compiler understand that this variable is gonna get updated from some other source and it will compile it inside the while loop.
====Frame and Inner Placement====
 
[[]]For convenience, a New Bright toy RC car was purchased and disassembled. The motors and wheels were already pre-mounted onto the chassis. Motor controllers could easily control the motors to drive and steer the vehicle. On the chassis, slots above the wheel wells were large enough to house motor controllers while the center of the chassis provided enough room to include a small breadboard and the microcontroller. All wires were shortened to the shortest length possible to reduce clutter.
 
  
====Sensor and Alarm Placement====
+
The following piece of code shows the initialization of the Port 2 pins P2.0, P2.1, P2.2, P2.3. Make sure you include the "lpc_pwm.hpp" before using this piece of code.
The sensors, which guided car control, were strategically mounted in front and above the car. This increased visibility of the sensors. Three distance sensors were used to detect obstacles: a left-, a center-, and a right-side sensor was used to determine steering of the vehicle. A front-mounted sensor sought motion as the car was stopped. Once motion was detected, the car promptly sounded the piezo buzzer alarm after determining that the motion was legitimate.
 
  
====Power Supply====
+
    void PWM_init(){
The battery box beneath the car provided additional convenience. It housed five 1.5-volt AA batteries that supplied up to 7.5 volts in series. This power supply provided enough power to run all of the components of this project. Whenever existing batteries began to run low on power, new batteries could be swapped into place easily. The following list describes the power requirements of each part used:
+
        PWM left_positive(PWM::pwm1, 50);  //P2.0 --> IN1
 +
        PWM left_negative(PWM::pwm2, 50);  //P2.1 --> IN2
 +
        PWM right_positive(PWM::pwm3, 50);  //P2.2 --> IN3
 +
        PWM right_negative(PWM::pwm4, 50);  //P2.3 --> IN4
 +
    }
  
<table class="wikitable">
+
Below mentioned are the controlling functions for the motors. The code is well commented, one look through will be enough for you to understand the code.
<th>Part</th><th>Voltage Range</th>
 
<th>Source</th>
 
<tr>
 
<td align="center">Distance Sensors (Parallel)</td>
 
<td align="center">+5V</td>
 
<td align="center">Microcontroller Pin</td>
 
</tr>
 
<tr>
 
<td align="center">LPC2148 Microcontroller</td>
 
<td align="center">+7V to +20V</td>
 
<td align="center">Battery Pack</td>
 
</tr>
 
<tr>
 
<td align="center">Motion Sensors</td>
 
<td align="center">+5V to +12V</td>
 
<td align="center">Battery Pack</td>
 
</tr>
 
<tr>
 
<td align="center">Motor Controllers</td>
 
<td align="center">+7V to +30V</td>
 
<td align="center">Battery Pack</td>
 
</tr>
 
<tr>
 
<td align="center">Piezo Buzzer</td>
 
<td align="center">+3V to +6V</td>
 
<td align="center">Microcontroller Pin</td>
 
</tr>
 
</table>
 
  
====Motion Sensor====
+
    void left_halt(){
[[]]
+
        left_positive.set(0);
The passive infrared sensor measures changes in the environment, using heat as an indicator. It signals the pin low when it detects a change in heat. Three pins, with associated wire colorings, are used: red for voltage source, brown for ground, and black for alarm signal. The alarm signal can be connected to any pin on the microcontroller that can handle GPIO. Also, a pull up resistor is needed on the pin to GPIO. The pull up resistor is required because the sensor alarm pin is an open collector. Without this resistor, the value of the alarm will merely fluctuate between low and high constantly. Shown below are the connections between the microcontroller and the alarm:
+
        left_negative.set(0);
 +
    }
 +
   
 +
    void right_halt(){
 +
        right_positive.set(0);
 +
        right_negative.set(0);
 +
    }
 +
   
 +
    void left_forward(float speed){
 +
        if (LPC_GPIO2->FIOPIN & (1 << 7)){  // If front IR senses an obstacle.
 +
            left_halt();
 +
            right_halt();
 +
        }
 +
        else{
 +
            left_positive.set(speed);
 +
            left_negative.set(0);
 +
        }
 +
    }
 +
   
 +
    void left_reverse(float speed){
 +
        if (LPC_GPIO2->FIOPIN & (1 << 6)){  // If rear IR senses an obstacle.
 +
            left_halt();
 +
            right_halt();
 +
        }
 +
        else{
 +
            left_positive.set(0);
 +
            left_negative.set(speed);
 +
        }
 +
    }
 +
   
 +
    void right_forward(float speed){
 +
        if (LPC_GPIO2->FIOPIN & (1 << 7)){  // If front IR senses an obstacle.
 +
            left_halt();
 +
            right_halt();
 +
        }
 +
        else{
 +
            right_positive.set(speed);
 +
            right_negative.set(0);
 +
        }
 +
    }
 +
   
 +
    void right_reverse(float speed){
 +
        if (LPC_GPIO2->FIOPIN & (1 << 6)){  // If rear IR senses an obstacle.
 +
            left_halt();
 +
            right_halt();
 +
        }
 +
        else{
 +
            right_positive.set(0);
 +
            right_negative.set(speed);
 +
        }
 +
    }
  
<table class="wikitable">
+
The main function which we defined is sufficiently long hence we are giving few cases off our code to give an idea, you can use the above functions according to your requirement. Make sure the character which you send from the smartphone for a particular inclination is declared for that particular direction in the main.
<th>Microcontroller</th><th>Motion Sensor</th>
 
<tr>
 
<td align="center">VCC (7.5V) </td>
 
<td align="center">VCC (7.5V) </td>
 
</tr>
 
<tr>
 
<td align="center">GND</td>
 
<td align="center">GND</td>
 
</tr>
 
<tr>
 
<td align="center"> P0.10 </td>
 
<td align="center">Alarm (AL)</td>
 
</tr>
 
</table>
 
  
 +
    int main(void)
 +
    {
 +
        LPC_GPIO2->FIODIR &= ~(1 << 7);    //Front IR as input.
 +
        LPC_GPIO2->FIODIR &= ~(1 << 6);    //Rear IR as input.
 +
   
 +
        //INITIALIZED TO A HALT STATE
 +
        left_halt();
 +
        right_halt();
 +
   
 +
        Uart3::getInstance().init(9600, 64, 64);
 +
   
 +
        while(1){
 +
             
 +
            switch (motion){   
 +
            case 'a': // halt
 +
                left_halt();
 +
                right_halt();
 +
                break;
 +
            case 'n': // forward, left speed -> 50 & right speed -> 50
 +
                left_forward(50);
 +
                right_forward(50);
 +
                break;
 +
            case 's': // forward, left speed -> 100 & right speed -> 100
 +
                left_forward(100);
 +
                right_forward(100);
 +
                break;           
 +
            case 'i': // reverse right turn, left speed -> 0 & right speed -> -50
 +
                left_halt();
 +
                right_reverse(50);
 +
                break;
 +
            default:
 +
                left_halt();
 +
                right_halt();
 +
                break;
 +
            }
 +
        }
 +
   
 +
        return -1;
 +
    }
  
 +
===Android App Developement Design===
  
====Distance Sensor====
+
[[File:CMPE_244_F14_PU17_fig4.png|thumb|300px|Bluetooth Pairing]]
[[]]
+
==== Using Android SDK ====
The SRF02 ultrasonic range finder (distance sensor) can operate through serial mode or I2C mode. This device carries five pins: +5V VCC, SDA, SCL, Mode, and Ground. Since the I2C mode is used, the mode pin doesn’t need to connect to anything. The SCL and SDA lines are connected to the pins that support SCL0 and SDA0 on the microcontroller. These pins also need a pair of resistors because I2C is an open collector.
+
In our Android Application our objective was to pair Bluetooth device on our phone with the Bluetooth module that we used with SJOne Board. For pairing of devices we used the search and scan method of Bluetooth devices instead of using IP address. Thus making it more User friendly. In the image on the right you can see how all the available Bluetooth connections show up when we start the application.  
  
<table class="wikitable">
+
Once the pairing was done successfully we moved to the next step, which was designing of Controller for the RC Car. In this process we designed lots of controllers like remote based controller where, as you can see in the images, user can press buttons on the display to drive the BOT.
<th>Microcontroller</th><th>Distance Sensor</th>
 
<tr>
 
<td align="center">Regulator (+5V) </td>
 
<td align="center">VCC (+5V) </td>
 
</tr>
 
<tr>
 
<td align="center"> P0.2 </td>
 
<td align="center"> SDA </td>
 
</tr>
 
<tr>
 
<td align="center"> P0.3 </td>
 
<td align="center"> SCL </td>
 
</tr>
 
<tr>
 
<td align="center"> GND</td>
 
<td align="center">GND</td>
 
</tr>
 
</table>
 
  
====5A Motor Controllers====
+
After the success in the first attempt we went for the joystick based approach where, as in the play station remote, you can swipe the joystick up and down to control the BOT.  
[[File:CMPE_146_F12_EWD_MC.png|thumb|220px|5A motor controller.]]
 
The motor controllers were used to adjust speed on the motors. The controllers maintain a continuous 5A current while applying voltage. Interfacing the motor controllers requires three pins: PWM, direction, and ground. Pins were initiated prior to using the motor controllers. The rear motor used PWM while the front motor used GPIO in place of PWM.  
 
  
<table class="wikitable">
+
Then finally, we went for what was our goal, motion controller, with the help of the in built Acceleration sensor of the android device. The device was calibrated to send one character for every threshold range. For example, send 'a' when the phone is held in proper viewing angle, for halt. Now when you incline the phone forward, send another character for forward motion, when you incline the phone backward, send another character for backward motion.
<th>Microcontroller</th><th>Front Motor Controller</th>
 
<tr>
 
<td align="center">VCC (7.5v) </td>
 
<td align="center">VCC (7.5v) </td>
 
</tr>
 
<tr>
 
<td align="center"> P0.9 </td>
 
<td align="center"> PWM </td>
 
</tr>
 
<tr>
 
<td align="center"> P0.6 </td>
 
<td align="center"> DIR </td>
 
</tr>
 
<tr>
 
<td align="center"> GND</td>
 
<td align="center">GND</td>
 
</tr>
 
</table>
 
  
<table class="wikitable">
+
Sending character was opted because, it's easy to send one character than sending the values of x, y and z which are declared as float. Also, it's always efficient to send one byte (char) instead of 12 (float*3).
<th>Microcontroller</th><th>Rear Motor Controller</th>
 
<tr>
 
<td align="center">VCC (7.5v) </td>
 
<td align="center">VCC (7.5v) </td>
 
</tr>
 
<tr>
 
<td align="center"> P0.7 </td>
 
<td align="center"> PWM </td>
 
</tr>
 
<tr>
 
<td align="center"> P0.8 </td>
 
<td align="center"> DIR </td>
 
</tr>
 
<tr>
 
<td align="center"> GND</td>
 
<td align="center">GND</td>
 
</tr>
 
</table>
 
  
==== Switch ====
+
[[File:CMPE_244_S14_PU17_fig17.png|left|thumb|700px|Joystic controller screen]]
[[]]
+
[[File:CMPE_244_F14_PU17_fig3.png|thumb|300px|Controller stage in Progress]]
A single-pole double-throw switch was added to the board to quickly connect and disconnect power to the system.
+
[[File:CMPE_244_S14_PU17_fig18.png|left|thumb|700px|Accelerometer Controller screen]]
 +
[[File:CMPE_244_F14_PU17_fig5.png|thumb|300px|Circled is our Android App]]
  
===Software Design===
 
==== Using FreeRTOS ====
 
FreeRTOS, a real-time operating system, was used to program the hardware used on the vehicle. FreeRTOS mainly uses C while allowing for some expansion into C++. Its support for tasks and semaphores made it a convenient platform for writing and implementing software for this project. Furthermore, FreeRTOS requires a small amount of memory while running tasks quickly and efficiently.
 
  
Several labs built using FreeRTOS were completed prior to starting this project, which contributed to a good understanding of the FreeRTOS system. The basic coding structure used for the labs also served as the basic coding framework for the Evil Watchdog.
 
  
==== Part-by-part Expansion ====
 
Once all the necessary parts were collected, each part received its own dedicated piece of code and its own testing before becoming integrated with the other parts used for the car. Intuitively, the motor controllers were selected as the first parts for writing code, because the vehicle's movement depended entirely on the motors and wheels. Each motor controller can regulate the speed at which the attached wheels spin, through the use of pulse-width modulation (PWM). Looking at the car, only the rear wheels need speed control. It was not necessary to implement PWM on the front wheels because those wheels are used for steering and simply require steering extreme left, extreme right, or straight, thanks to the car's small size. The rear wheels were controlled through PWM, and the front wheels through GPIO.
 
  
==== Pulse-width Modulation ====
+
\
Pulse-width modulation, or PWM, allows a motor controller to govern the speed at which a motor turns. Two key features of a PWM driver are the frequency, which determines how often a cycle repeats, and the duty cycle, which controls the speed of the motor spinning. The PWM driver allows the microcontroller to send out pulses based on the frequency and duty cycle settings, similar to a person flapping a rope up and down with the other end of the rope attached to a wall. By changing the PWM's frequency, the vehicle's rear motors could be slowed down or sped up. The board pins were set up accordingly:
 
# Reset P0.7
 
# Assign P0.7 for PWM2
 
# Assign P0.8 for direction (GPIO)
 
# Set P0.8 direction as output
 
  
The PWM driver was initialized, too:
 
[[File:CMPE_146_F12_EWD_PWMinit.png|thumb|center|175px|Initializing the PWM driver.]]
 
The PWM registers had to be set accordingly. Looking at the LPC2148 datasheet, the registers shown above were configured:
 
* PWMTCR: Timer control. Reset first with bit 1.
 
* PWMPR: Prescale. Increments every PCLK cycle. Set to zero.
 
* PWMMCR: Match control. Control if interrupt is generated. Will reset on MR0.
 
* PWMPCR: Control. Enables PWM in single-edge mode.
 
* PWMMR0: PWM period. Set to 48000 Hz to match CPU.
 
* PWMMR2: Duty cycle/PWM width. Compared to PWMMR0. Output duty is inversely related to PWMMR0.
 
* PWMLER: Latch enable. Latch in all PWMMRx.
 
* PWMTCR: Timer control (again). Enable counter with bits 0 and 3.
 
  
With the PWM registers initialized, the duty cycle could later be modified to change motor speed. PWMMR2 was used in this case. Therefore, if a change in motor speed was necessary, PWMMR2 could be set inclusively between 0 and 48000 to change the duty cycle.
 
  
==== Steering Control ====
 
At first, it seemed a good idea that PWM be used on the front motor controller. After attempting to establish PWM on the steering side of the car, Preet recommended that GPIO could handle the steering job just as well. The pins had to be initialized first:
 
# Assign P0.9 as GPIO for controlling full or zero power
 
# Set P0.9 as output
 
# Assign P0.6 as GPIO for direction
 
# Set P0.6 as output
 
The most difficult part of using GPIO for steering was mapping out which voltages corresponded to which steering direction. The motor controller could turn extreme left, extreme right, or stayed straight. To help determine the directions, a handy table was created:
 
<table class="wikitable">
 
<th>Controller</th>
 
<th>GPIO Low (0V)</th><th>GPIO High (+3.3V)</th>
 
<tr>
 
<td align="center">PWM Pin</td>
 
<td align="center">Power</td>
 
<td align="center">No Power</td>
 
</tr>
 
<tr>
 
<td align="center"> DIR Pin</td>
 
<td align="center"> Left</td>
 
<td align="center"> Right</td>
 
</tr>
 
</table>
 
Changing the motor between go/stop and left/right was done by either setting the P0.6 or P0.9 pins, respectively, to 1 or 0 using IOSET0 and IOCLR0. Using the help of LEDs, the correct directions and power distribution was mapped for the motor controller. It was interesting to note that to get back to center, a change of direction had to take place. For example, if the car was heading left, it had to be steered back to the right to "release" the left steering before returning to center position.
 
  
==== Distance Sensors: I2C ====
 
The distance sensors were designed for use on the I2C or serial buses. Based on pin availability and software convenience, I2C was used to gather distance information from the sensors. The next question was: How would the microcontroller distinguish between the three sensors? A glance at the technical specifications provided the solution. Each sensor was equipped with a handy LED that flashed its address in a recognizable sequence. Each sequence was one long flash, accompanied by a number of short flashes. The short flashes represented the difference in the current address from 0xE0 in increments of 0x02, up to 15 short flashes. Legal addresses ranged from 0xE0 to 0xFE.
 
  
By comparing the sequence emitted, a programmer could determine the sensor's set address. Also, its address could be altered to allow the I2C to accommodate additional sensors, though each sensor must be programmed individually, one at a time. This sequence was used to set each sensor:
 
# Get sensor address
 
# Send 0xA0 to address
 
# Send 0xAA to address
 
# Send 0xA5 to address
 
# Send new address to address
 
  
For convenience, the following addresses were selected for the sensors: 0xE2 for the left sensor, 0xE4 for the center, and 0xE6 for the right.
 
[[]]
 
An I2C call is made when the microcontroller wants to retrieve information from the distance sensors. The I2C bus is shared, and the program allocates enough time to release slave devices when required. The "unit_command" variable was set to 81 to force the sensor to measure distances in centimeters. If the user wants to opt for measurements in inches, the variable can simply be changed to 80.
 
  
Locations 2 and 3 hold the newest reading in a 16-bit unsigned integer format. Through high and low bytes, the sensor readings could be retrieved. The datasheet warns that it is best to give a minimum of 65 milliseconds for the pings to fade away properly. In the code, a 75 ms vTaskDelay was added to accommodate for the wait.
 
  
====Motion Sensor ====
 
As with the front motor, the pins for the motion sensor were initialized:
 
# Assign P0.10 as GPIO
 
# Set P0.10 as input
 
  
A GPIO input pin was designated on the microcontroller to interact with the motion sensor. The motion sensor dropped its voltage to zero whenever motion was detected, which registered sufficient data for the pin on the board.
 
  
To check for motion, the code looked for a zero on the P0.10 pin.
 
  
The system surveyed for motion eight times in 500 millisecond intervals. When motion was detected in five out of those eight intervals, the alarm was sounded. This prevented false alarms from occurring, in the event that stray, non-legitimate motion came across the sensor's environment. This diagram shows the motion surveying method:
 
[[]]
 
  
 +
==== Android Application Developement====
 +
For Connection and Pairing of Devices, I have used the Bluetooth APIs available like Bluetooth Adapter, Bluetooth Device etc.
 +
To work with Bluetooth it is very important that you add Permissions in the Android Manifest.xml.
 +
The three permissions that I used were:
 +
1. android.permission.INTERNET(not needed since first we were trying to work with IP adress and wifi)
 +
2. android.permission.BLUETOOTH_ADMIN
 +
3. android.permission.BLUETOOTH
 +
Here the Bluetooth Adapter is used as the first step to setup the Bluetooth connection and to verify if the bluetoothis supported or not. The Bluetooth Adapter is returned when we call  static BluetoothAdapter.getDefaultAdapter().
 +
Secondly, it is very important that you enable the Bluetooth and this is done by calling startActivityForResult(). According to your requirement you can either BluetoothAdapter.ACTION_REQUEST_ENABLE or BluetoothAdapter.ACTION_STATE_CHANGED.
 +
Third Task is the Discovery, for this we have to call startbtAdapter.startDiscovery().
 +
Next Task is to scan the devices available for Pairing. This is done by BluetoothAdapter.ACTION_DISCOVERY_STARTED and BluetoothAdapter.ACTION_DISCOVERY_FINISHED. And if nothing is happening check if the Bluetooth is ON if not turnOnBT().
 +
Next task is to pair the Devices. This is done by calling btAdapter.getBondedDevices(). This will return already paired devices with the Android Device you using.
 +
Next step is to connect the devices which are not already paired. These devices are paired by entering the password for the device.
 +
Next step is to initiate a Bluetooth Connection for sending the data. For this simply copy the code for "private class ConnectThread extends Thread" from the Bluetooth|Android Developer site.
 +
Final task is set the UUID to "00001101-0000-1000-8000-00805F9B34FB" and you are good to go.
  
  
==== Loading the Software ====
 
[[]]Once the program was built and compiled, a .hex file was generated, which contained the program that will be read by the microcontroller. The .hex file was transferred from computer to microcontroller through a USB cable. HyperLoad 1.1 was run on the programming computer to interact with the microcontroller via USB. Setting up HyperLoad 1.1 included changing the COM port speed to 500000 bps and target CPU frequency to 48000000. The .hex file was chosen, the proper port was opened, and the file was transferred.
 
  
===Software Implementation===
 
==== Task Flowchart ====
 
The program was designed to run by employing tasks that handled sensor readings and appropriate outputs. A "drive" task was assigned to handle vehicular driving, and a "SensorValue" task was assigned to continuously capture data from the distance and motion sensors. When combined, the tasks worked to drive the vehicle safely through a path. The below illustrates how the general function of the program used to control the Evil Watchdog:
 
[[]]
 
A timer, in conjunction with the vTaskDelay command, allowed the microcontroller to switch between driving mode and motion sensing mode. It is important to note that scanning for motion while the vehicle is moving is pointless. Unless there was a way to filter out motion caused by the vehicle, it was better to stop the vehicle briefly to look for motion before continuing driving.
 
  
== Testing ==
 
=== Motor Controllers ===
 
The motor controllers were the first components tested once the PWM driver was written. At first, the assumption was that setting PWMMR2 to zero meant a full stop. That became untrue as the dog tried to run away at full speed. Once it was realized that a higher duty cycle corresponded to slower motion, the rear controller was successfully configured. The front motor controller was tested too. The main difficulty was in mapping out the voltage levels and voltage directions to see whether they corresponded to left, right, or center steering. Using LEDs helped figure out the mappings. An interesting point to note is that to return to center steering via GPIO, a change in steering direction must take place.
 
  
=== Distance Sensors ===
 
Prior to implementation, the distance sensors were placed on a breadboard to verify the accuracy of their readings. The sensors featured measurements at the centimeter level, allowing for more detailed integer readings compared to readings in inches. During testing, a tape measure was used to confirm sensor measurements. The error found was no more than 3-5% at distances up to 250 cm, which showed that the sensors were highly reliable for providing the vehicle's sight.
 
  
=== Motion Sensor ===
 
The motion sensor was tested independently with a voltage generator and a digital multimeter. During everything, the multimeter showed that the sensor was very sensitive to nearby movement. Another observation was that when higher voltage was applied, the motion sensor captured motion from further distances. Lastly, it was noted that there was a delay between returning from "motion detected" to "no motion detected." It turns out that the alarm signal stayed low when detecting motion for about 3 seconds before returning to high. An open collector circuit caused the delays observed.
 
  
  
==Technical Challenges==
 
=== Battery Life ===
 
  
  
=== Distance Sensor Placement ===
 
  
  
=== Motion Sensor Polling ===
 
  
=== Vehicle Weight ===
 
  
  
==Conclusion==
 
  
  
== Finished Product ==
 
  
  
==References==
 
  
=== Thanks To... ===
+
 
* Preet Kang: Lecturer
+
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
 
 +
====  Android App Package ====
 +
In our Android App Package, CMPE_244_NEED_FOR_SPEED, we have developed two activities. Our first Activity is the MainActivity which searches all the Bluetooth Devices possibly available and pairs the one we click on. For this purpose we have used the scanning of devices method instead of the IP Address technique. Once the pairing is successful, it will go to the next activity which is JSActivity which sends charachters and integers via bluetooth to the SJOne Board. This different data are send with the help of accelerometer Sensor in the Android Device. This is done by tilting the device. These sensor values were calibrated using the code in JSActivity. For accelerometer results, we find values of x, y and z values. These values are thus converted into integers and send via Bluetooth. We have made many projects before, until we finalized this one. We also made one spare application, in which we had a joystick kind of controller. This was done using Android Widgets. But we liked the accelerometer android app more and decided to go with it. Thus for this app, we have two files in source folder, one is MainActivity.java and other is JSActivity.java. Their corresponding xml file were written in Relative Layout format. One is activity_main.xml and other is remote_active.xml. And finally in AndroidManifest we declare the MainActivity first and after that we declare the JSActivity.
 +
 
 +
==== Testing the Android Application ====
 +
 
 +
 
 +
[[File:CMPE_244_S14_PU17_fig6.png|right|thumb|600px|Testing on Hercules]]
 +
 
 +
The Testing was carried out by using the android device in developement mode. In this mode, we had enabled USB debugging which allowed us to run our Android Application directly on our Android Device, thus saving lot of our time due to the slow emulator. When the project was  build successfully, the APK file was then transfered to another android device and thus double testing was carried out.
 +
After the Android Application was ready, it was time to test the interface of the hardware. For this, we had to first check whether the android device was able to send data to the SJOne Board via bluetooth. This was done by connecting the SJOne Board to the Laptop. The result were seen on Hercules. If you enlarge the image you can see various numbers which show a successfull sending of the data. We have conditions like Forward, Backward, Right, Left and Halt. Each one is assigned a different integer value as seen in the screenshot.
 +
 
 +
== '''Technical Difficulties''' ==
 +
*The very first Technical Difficulty that we faced was even if the Android App Project was building successfully, it was crashing after we tried going to the controller screen. We searched online for answers and figured out that we had a problem with initialisation. So we made the required changes in onCreate method from our MainActivity and thus the problem was solved.
 +
*The second difficulty that we faced was that even if the devices are paired successfully, the JSActivity was not able to send data. This was happening because we first wrote a code such that the bluetooth connection was lost as soon as we switched to the next activity. Thus we modified our code and got our desired results.
 +
 
 +
== '''Acknowledgement''' ==
 +
 
 +
We would like to thank our professor Preet. We appreciate him for the board which he has designed, it's very handy and fun to work on.
 +
To all the people who found this documentation helpful, always remember, "There is no such thing as magic. There is a reason behind everything, find the reason you will find the solution."
 +
 
 +
== '''References''' ==
 +
*  [https://sourceforge.net/projects/sjsu/files/CmpE244_SJSU_S2014/ Sourceforge source code link]
  
 
=== Datasheets ===
 
=== Datasheets ===
* [1] Philips Semiconductors. LPC214x datasheet. August 2006.
+
* [1] Philips Semiconductors. LPC1758 datasheet
* [2] Robot Electronics. SRF02 ultrasonic range finder datasheet. Retrieved from http://www.robot-electronics.co.uk/htm/srf02techI2C.htm
+
* [2] LM 7805 - http://www.fairchildsemi.com/ds/LM/LM7805.pdf
 +
* [3] LM 7806 - http://www.fairchildsemi.com/pf/LM/LM7806.html
 +
* [4] L298 - https://www.sparkfun.com/datasheets/Robotics/L298_H_Bridge.pdf
 +
 
 +
=== Links ===
 +
* [1] Bluetooth Connectivity Thread - http://developer.android.com/guide/topics/connectivity/bluetooth.html
 +
* [2] Joystick Controller Display Screen - http://code.google.com/p/mobile-anarchy-widgets/source/browse/#svn%2Ftrunk%2FWidgets%2Fsrc%2Fcom%2FMobileAnarchy%2FAndroid%2FWidgets%2FJoystick%253Fstate%253Dclosed
 +
* [3] Bluetooth Pairing Lectures - http://www.youtube.com/watch?v=OTQHZ16q0Ik
 +
* [4] L298 Motor Driver - http://blog.pennybuying.com/down/f/F815A.pdf
 +
* [5] Bluetooth Module - http://mcuoneclipse.com/2013/06/19/using-the-hc-06-bluetooth-module/
  
 
=== Appendix ===
 
=== Appendix ===
 
*  [Project source code is available at SourceForge]
 
*  [Project source code is available at SourceForge]
 
*  [Project Demonstration Video]
 
*  [Project Demonstration Video]

Latest revision as of 22:48, 3 June 2016

NEED FOR SPEED..!!

Abstract

Icon for our Android App

This page contains design and implementation of our Embedded Software project, Need For Speed. It's about maneuvering an RC vehicle using the Acceleration Sensor in a smart phone. An Android Application is developed to transmit the Acceleration Sensor Signals to the vehicle via Bluetooth. The car is mounted with a Bluetooth module to receive data from the phone. And the acceleration and turning of the vehicle will be based on this data. The vehicle is also mounted with two Infrared Sensor modules for collision detection, one in the front and other in the rear.Detection of any obstacle in the vehicles path will bring the vehicle to a halt state immediately.

Introduction

In this project we are using JY-MCU Bluetooth module to be the wireless link between the smartphone and the battery powered RC vehicle. The Android application is developed to transmit a particular byte for every threshold value of the Acceleration Sensor i.e. when the phone is one byte for front tilt and another for back. This received byte is compared by the SJOne board with few predefined values and accordingly PWM signals are given to the motors.

The input of the IR sensors is connected to the hardware interrupts on the SJOne board, the interrupt subroutine will be called every time there is an obstacle in the path of the vehicle, this subroutine will in turn stop the vehicle.

Objectives

As this project is both software and hardware based, our objectives were as follows;

  • Hardware Objectives
    • To achieve a constant 6V DC supply for the motors and 5V DC for the board from the battery.
    • To interface the motors to the SJOne board via L298 motor driver.
    • To calibrate the IR sensors to sense obstacle in 6" proximity.
  • Software Objectives
    • To develop an Android application to send the data from Acceleration Sensor via Bluetooth.
    • To develop a FreeRTOS code to receive these signals and process them.
    • To develop a FreeRTOS code to send PWM sigal to the motor for variable speed.
    • To develop a FreeRTOS code to accept interrupt from the IR sensors and take actions accordingly.

Team Members & Responsibilities

  • Amey Patil
    • Hardware Design
    • Free RTOS (Part 1: To interface motors and LPC1758 using PWM)
    • Free RTOS (Part 2: To configure the Bluetooth module)
  • Siddhata Patil
    • Free RTOS (Part 3: To send and receive data between Bluetooth module and LPC1758)
    • Android Application(Part1: To send data from Android Phone to LPC1758)
    • Android Application(Part2: To send results of accelerometer sensor from Android Phone to LPC1758)

Schedule

Week# Planned Date Completed Date Tasks Status
1 3/6 3/13 Planning Hardware and placing order for the required components Completed
2 3/20 3/20 Designing and Assembling the Hardware(Motors+Motor Driver+LPC1758) Completed
3 3/20 3/20 Reviewing Datasheet, Pin Selection and Setting up the Software Completed
4 3/27 3/27 Designing and Assembling the Hardware(Bluetooth Module+LPC1758) Completed
5 3/27 3/27 Free RTOS pairing between LPC1758 and Bluetooth Module Completed
6 3/28 3/28 Testing the pairing of Bluetooth and LPC1758 Completed
7 4/3 4/3 Free RTOS code for PWM Completed
8 4/11 4/18 Free RTOS code for sending and receiving data from Bluetooth Completed
9 4/18 4/24 Android App Designing and learning basics of Android SDK Completed
10 4/24 4/24 Android App Designing Completed
11 5/1 5/4 Android App java code to transfer data from phone to LPC1758 Completed
12 5/7 5/7 Android App java code to send values of accelerometer sensor to LPC1758 Completed
13 5/22 5/22 Final Demo Completed

Parts List & Cost

Category Item Quantity Unit Cost Total Cost
Electronics SJOne Board 1 80.00 80.00
9.6V 1600mAh Rechargeable Ni-Mh Battery 1 14.42 14.42
6V DC Gear Motor with Tyres 4 3.25 13.00
JY-MCU Bluetooth Module 1 7.68 7.68
IR Transceiver Module 2 1.00 2.00
L298 Motor Driver 1 7.50 7.50
LM 7806 Voltage Regulator 1 0.45 0.45
LM 7805 Voltage Regulator 1 0.32 0.32
10uF Electrolytic Capacitor 2 0.13 0.26
1uF Ceramic Capacitor 2 0.10 0.20
Chassis Smart Car Chassis 1 10.00 10.00
Connections Nuts, Bolts and Spacers 3.00
Phone Android Smart Phone 1
TOTAL $138.83

Design and Implementation

System Block Diagram

The above Block Diagram shows the overall implementation of the project. The accelerometer values (x, y, z) are used as an input by the android application. Depending on the instantaneous values, tilt will be determined. This tilt value will be provided to the Bluetooth for transmission. At the receiver, this tilt data will be received by the Bluetooth Module and provided to the LPC 1758 board via an UART channel. The on board processor will compare the received data with the stored values and generate PWM signals accordingly. The motor driver upon reception of this will driver the vehicle in the respective direction. We will see detailed explanation of the hardware and software in their respective sections.


Flowchart

Flowchart for the System

Hardware Interface

Let us understand the whole structure piece by piece.

1. LPC 1758 SJOne Board

This board was a part of our course on Embedded Software at San Jose State University. For more information on the SJOne board Click_me.

Power Supply Schematic.

2. Power Supply

We need to generate steady 5V supply for the board while 6V for the motors without any current limitation otherwise the motors will not give its optimum output. To our luck, LM7806 voltage regulators are also available in the market along with the LM7805. The circuit schematic is as shown in the figure above.

The total current requirement of the circuit is around 1Amp. If this much current is to be drawn through the regulators then we must make sure the heat generated is properly dissipated, so we use heat sink. Most of the current will be driven through the LM7806 regulator as it drives the motors hence, we made sure that it is not surrounded by any other component. As, the LM7805 regulator just drives the SJOne board and IR module, current flowing through it is around 100mA. Hence, this regulator won't heat as much as the other one.


Motor Driver Schematic.

3. L298 Motor Driver

You must be thinking why didn't I use L293D as it is best for 6V motors and much easy to interface. Well, one of our motor consumes 200mA of current, which makes the total current 800mA that too in no load conditions. With load it might have seared upto 1A. Now the maximum handling capacity of L293D is 1A while that of L298 is 2A. Hence, for safety reasons I went for L298 motor driver. The pin connect for this interface is as shown in the above figure. The functions of the pins are as follows;

IN1 receives 'PWM input for left motor +' from LPC 1758 and drives OUT1

IN2 receives 'PWM input for left motor -' from LPC 1758 and drives OUT2

IN3 receives 'PWM input for right motor +' from LPC 1758 and drives OUT3

IN4 receives 'PWM input for right motor -' from LPC 1758 and drives OUT4

SENSE A limits the current for Left Motor

SENSE B limits the current for Right Motor

VS: Supply voltage for the Motors

For more information on L298 Driver, Click_me.


IR Module Schematic.

4. IR module

The IR module we are using is custom made. It is is designed to output logic '1' if any obstacle is detected or else logic '0'. The output signal from the IR receiver is directly proportional to the amount of IR waves falling on it. Hence, the output voltage for an obstacle far from the receiver will be less than that of a closer object.

In any case this output is in millivolts hence, we gave it as an input to LM358 which is a dual op-amp IC. This op-amp is configured in comparator mode. When the input at the non-inverting terminal is higher than the threshold voltage provided to the inverting terminal, the op-amp will give a logic high output. Hence, the threshold voltage is inversely proportional to the distance of the obstacle. So we connected a potentiometer at the input of the threshold voltage by which we can vary the range of obstacle detection.

In the case of IR the sensitivity of the reciever is not sufficient to detect obstacle at a longer distance. We were able to acheive obstacle detection in 2 inches of proximity. If, you are looking for detection at a longer distance, we would suggest you to go for Ultrasonic sensor modules which can even give you the distance of the obstacle from the vehicle.

Figure shows the circuit schematic of the IR module. This is circuit for one of the IR module. Two such circuits are implemented for front and back.


Bluetooth Module

5. Bluetooth Module

The module has 4 pins labeled on the back, VCC, GND, TXD and RXD. You might buy a module with two more pins KEY and STATE but it won't matter if you leave them open. The controller which it is interfaced with considers it as an serial UART device. So make sure you connect the RX and TX of the controller with TXD and RXD of the bluetooth module respectively.


This module works best if you are running on 3.3V, in case you are working on TTL logic then you might use a voltage divider for proper operation of the module. According to the datasheet the VCC pin is capable to handle supply ranging from 3-6V so it is fine to give TTL logic supply but, do not give TTL logic signal to the RXD pin, it cannot take anything more than 3.3V, doing such will damage the pin and hence the module.

The communication for configuration of the module is based on AT commands. There is one command for every thing, to set the device name, set the pin, set the baud rate and much more. All you have to do is to save these AT commands in the form of string and send each byte serially to the module using a simple for loop. Initially the baud rate is set to 9600. Following table shows few of the AT commands which you may require.

Command Response Use
AT OK Used to verify communication
AT+NAMExyz OKsetname Sets the module name to “xyz”
AT+PIN1234 OKsetPIN Sets the module PIN to 1234
AT+BAUD1 OK1200 Sets the baud rate to 1200
AT+BAUD2 OK2400 Sets the baud rate to 2400
AT+BAUD3 OK4800 Sets the baud rate to 4800
AT+BAUD4 OK9600 Sets the baud rate to 9600
AT+BAUD5 OK19200 Sets the baud rate to 19200
AT+BAUD6 OK38400 Sets the baud rate to 38400
AT+BAUD3 OK4800 Sets the baud rate to 4800
AT+BAUD4 OK9600 Sets the baud rate to 9600

Hardware Design

It was really a task to adjust all the above mentioned tasks on an 25cm * 15 cm chasis which is made of some paper mache material (less strength). The BOT weighs around a pound increasing the load on the motor drastically. The following image on left shows the BOT in the design stage while the one on the right is our final product.

Work in progress...
Android TA DA..!!



















FreeRTOS Programming

In this section we will walk you through the source code for the SJOne board. Whenever a character is sent by the Bluetooth module, the UART interrupt handler code is executed. The code is as shown below.












   void UART3_IRQHandler()
   {
       Uart3::getInstance().handleInterrupt();
       Uart3::getInstance().getChar(&in, 10000);
       printf("%c", in);
       motion = in;
   }

As you can see above the data received from the Bluetooth module is stored in the motion variable. Make sure you declare the motion variable as volatile because in the main function we will be using it in an infinite while loop. Making it volatile will help the compiler understand that this variable is gonna get updated from some other source and it will compile it inside the while loop.

The following piece of code shows the initialization of the Port 2 pins P2.0, P2.1, P2.2, P2.3. Make sure you include the "lpc_pwm.hpp" before using this piece of code.

   void PWM_init(){
       PWM left_positive(PWM::pwm1, 50);   //P2.0 --> IN1
       PWM left_negative(PWM::pwm2, 50);   //P2.1 --> IN2
       PWM right_positive(PWM::pwm3, 50);  //P2.2 --> IN3
       PWM right_negative(PWM::pwm4, 50);  //P2.3 --> IN4
   }

Below mentioned are the controlling functions for the motors. The code is well commented, one look through will be enough for you to understand the code.

   void left_halt(){
       left_positive.set(0);
       left_negative.set(0);
   }
   
   void right_halt(){
       right_positive.set(0);
       right_negative.set(0);
   }
   
   void left_forward(float speed){
       if (LPC_GPIO2->FIOPIN & (1 << 7)){  // If front IR senses an obstacle.
           left_halt();
           right_halt();
       }
       else{
           left_positive.set(speed);
           left_negative.set(0);
       }
   }
   
   void left_reverse(float speed){
       if (LPC_GPIO2->FIOPIN & (1 << 6)){  // If rear IR senses an obstacle.
           left_halt();
           right_halt();
       }
       else{
           left_positive.set(0);
           left_negative.set(speed);
       }
   }
   
   void right_forward(float speed){
       if (LPC_GPIO2->FIOPIN & (1 << 7)){  // If front IR senses an obstacle.
           left_halt();
           right_halt();
       }
       else{
           right_positive.set(speed);
           right_negative.set(0);
       }
   }
   
   void right_reverse(float speed){
       if (LPC_GPIO2->FIOPIN & (1 << 6)){  // If rear IR senses an obstacle.
           left_halt();
           right_halt();
       }
       else{
           right_positive.set(0);
           right_negative.set(speed);
       }
   }

The main function which we defined is sufficiently long hence we are giving few cases off our code to give an idea, you can use the above functions according to your requirement. Make sure the character which you send from the smartphone for a particular inclination is declared for that particular direction in the main.

   int main(void)
   {
       LPC_GPIO2->FIODIR &= ~(1 << 7);     //Front IR as input.
       LPC_GPIO2->FIODIR &= ~(1 << 6);     //Rear IR as input.
   
       //INITIALIZED TO A HALT STATE
       left_halt();
       right_halt();
   
       Uart3::getInstance().init(9600, 64, 64);
   
       while(1){
              
           switch (motion){     
           case 'a': // halt
               left_halt();
               right_halt();
               break;
           case 'n': // forward, left speed -> 50 & right speed -> 50
               left_forward(50);
               right_forward(50);
               break;
           case 's': // forward, left speed -> 100 & right speed -> 100
               left_forward(100);
               right_forward(100);
               break;            
           case 'i': // reverse right turn, left speed -> 0 & right speed -> -50
               left_halt();
               right_reverse(50);
               break;
           default:
               left_halt();
               right_halt();
               break;
           }
       }
   
       return -1;
   }

Android App Developement Design

Bluetooth Pairing

Using Android SDK

In our Android Application our objective was to pair Bluetooth device on our phone with the Bluetooth module that we used with SJOne Board. For pairing of devices we used the search and scan method of Bluetooth devices instead of using IP address. Thus making it more User friendly. In the image on the right you can see how all the available Bluetooth connections show up when we start the application.

Once the pairing was done successfully we moved to the next step, which was designing of Controller for the RC Car. In this process we designed lots of controllers like remote based controller where, as you can see in the images, user can press buttons on the display to drive the BOT.

After the success in the first attempt we went for the joystick based approach where, as in the play station remote, you can swipe the joystick up and down to control the BOT.

Then finally, we went for what was our goal, motion controller, with the help of the in built Acceleration sensor of the android device. The device was calibrated to send one character for every threshold range. For example, send 'a' when the phone is held in proper viewing angle, for halt. Now when you incline the phone forward, send another character for forward motion, when you incline the phone backward, send another character for backward motion.

Sending character was opted because, it's easy to send one character than sending the values of x, y and z which are declared as float. Also, it's always efficient to send one byte (char) instead of 12 (float*3).

Joystic controller screen
Controller stage in Progress
Accelerometer Controller screen
Circled is our Android App



\







Android Application Developement

For Connection and Pairing of Devices, I have used the Bluetooth APIs available like Bluetooth Adapter, Bluetooth Device etc. To work with Bluetooth it is very important that you add Permissions in the Android Manifest.xml. The three permissions that I used were: 1. android.permission.INTERNET(not needed since first we were trying to work with IP adress and wifi) 2. android.permission.BLUETOOTH_ADMIN 3. android.permission.BLUETOOTH Here the Bluetooth Adapter is used as the first step to setup the Bluetooth connection and to verify if the bluetoothis supported or not. The Bluetooth Adapter is returned when we call static BluetoothAdapter.getDefaultAdapter(). Secondly, it is very important that you enable the Bluetooth and this is done by calling startActivityForResult(). According to your requirement you can either BluetoothAdapter.ACTION_REQUEST_ENABLE or BluetoothAdapter.ACTION_STATE_CHANGED. Third Task is the Discovery, for this we have to call startbtAdapter.startDiscovery(). Next Task is to scan the devices available for Pairing. This is done by BluetoothAdapter.ACTION_DISCOVERY_STARTED and BluetoothAdapter.ACTION_DISCOVERY_FINISHED. And if nothing is happening check if the Bluetooth is ON if not turnOnBT(). Next task is to pair the Devices. This is done by calling btAdapter.getBondedDevices(). This will return already paired devices with the Android Device you using. Next step is to connect the devices which are not already paired. These devices are paired by entering the password for the device. Next step is to initiate a Bluetooth Connection for sending the data. For this simply copy the code for "private class ConnectThread extends Thread" from the Bluetooth|Android Developer site. Final task is set the UUID to "00001101-0000-1000-8000-00805F9B34FB" and you are good to go.



















Android App Package

In our Android App Package, CMPE_244_NEED_FOR_SPEED, we have developed two activities. Our first Activity is the MainActivity which searches all the Bluetooth Devices possibly available and pairs the one we click on. For this purpose we have used the scanning of devices method instead of the IP Address technique. Once the pairing is successful, it will go to the next activity which is JSActivity which sends charachters and integers via bluetooth to the SJOne Board. This different data are send with the help of accelerometer Sensor in the Android Device. This is done by tilting the device. These sensor values were calibrated using the code in JSActivity. For accelerometer results, we find values of x, y and z values. These values are thus converted into integers and send via Bluetooth. We have made many projects before, until we finalized this one. We also made one spare application, in which we had a joystick kind of controller. This was done using Android Widgets. But we liked the accelerometer android app more and decided to go with it. Thus for this app, we have two files in source folder, one is MainActivity.java and other is JSActivity.java. Their corresponding xml file were written in Relative Layout format. One is activity_main.xml and other is remote_active.xml. And finally in AndroidManifest we declare the MainActivity first and after that we declare the JSActivity.

Testing the Android Application

Testing on Hercules

The Testing was carried out by using the android device in developement mode. In this mode, we had enabled USB debugging which allowed us to run our Android Application directly on our Android Device, thus saving lot of our time due to the slow emulator. When the project was build successfully, the APK file was then transfered to another android device and thus double testing was carried out. After the Android Application was ready, it was time to test the interface of the hardware. For this, we had to first check whether the android device was able to send data to the SJOne Board via bluetooth. This was done by connecting the SJOne Board to the Laptop. The result were seen on Hercules. If you enlarge the image you can see various numbers which show a successfull sending of the data. We have conditions like Forward, Backward, Right, Left and Halt. Each one is assigned a different integer value as seen in the screenshot.

Technical Difficulties

  • The very first Technical Difficulty that we faced was even if the Android App Project was building successfully, it was crashing after we tried going to the controller screen. We searched online for answers and figured out that we had a problem with initialisation. So we made the required changes in onCreate method from our MainActivity and thus the problem was solved.
  • The second difficulty that we faced was that even if the devices are paired successfully, the JSActivity was not able to send data. This was happening because we first wrote a code such that the bluetooth connection was lost as soon as we switched to the next activity. Thus we modified our code and got our desired results.

Acknowledgement

We would like to thank our professor Preet. We appreciate him for the board which he has designed, it's very handy and fun to work on. To all the people who found this documentation helpful, always remember, "There is no such thing as magic. There is a reason behind everything, find the reason you will find the solution."

References

Datasheets

Links

Appendix

  • [Project source code is available at SourceForge]
  • [Project Demonstration Video]