ANDROID CONTROLLED SMART CAR WITH LIGHTS AND OBSTACLE DETECTION Mihai-Gabriel Tolgoi COORDINATOR Ș.L.dr.ing.Dumitrașcu Eugen JULY 2018 CRAIOVA… [311749]
[anonimizat]
Ș.L.dr.ing.Dumitrașcu Eugen
JULY 2018
[anonimizat]
Ș.L.dr.ing.Dumitrașcu Eugen
JULY 2018
CRAIOVA
„Învățătura este o comoară care își urmează stăpânul pretutindeni.”
[anonimizat], student: [anonimizat], Calculatoare și Electronică a [anonimizat], [anonimizat]:
cu titlul „ANDROID CONTROLLED SMART CAR WITH LIGHTS AND OBSTACLE DETECTION”,
coordonată de Ș.L.dr.ing.[anonimizat] 2018.
[anonimizat]:
reproducerea exactă a [anonimizat]-o [anonimizat]-o [anonimizat],
[anonimizat], [anonimizat] a unor aplicații realizate de alți autori fără menționarea corectă a [anonimizat] a [anonimizat].
Pentru evitarea acestor situații neplăcute se recomandă:
plasarea între ghilimele a citatelor directe și indicarea referinței într-o [anonimizat] a [anonimizat] a sursei originale de la care s-a [anonimizat] s-[anonimizat], figuri, imagini, statistici, [anonimizat], a căror paternitate este unanim cunoscută și acceptată.
Data, Semnătura candidat: [anonimizat],
PROIECTUL DE DIPLOMĂ
REFERATUL CONDUCĂTORULUI ȘTIINȚIFIC
În urma analizei lucrării candidat: [anonimizat]:
[anonimizat]:
Data, [anonimizat] a [anonimizat]. [anonimizat]’s lights on demand and detect obstacles in front or the back of it and automatically react in order to avoid collisions.
In order to achieve this goal the toy car will be contolled with the help of ATMEL’s ATMega2560 microcontroller. The obstacle detection will be handled by four sonar sensors.
An android application will be developed to control the car. The application’s interface will be user friendly and easy to use.
Key terms: car, smart,senosr,obstacle,lights,Arduino,Android,Bluetooth.
Acknowledgements
I would like to thank my coordinator teacher for his support and advices.
PROLOG
Contents
List of figures
Figure 1 Intel’s 8bit 8051 Microcontroller 2
Figure 2. Simplified microcontroller scheme 3
Figure 3. COP8CBR9 microcontroller by Texas Instruments 4
Figure 4. ATmega 2560 mictocontroller 5
Figure 5. ATmega 2560 Pinout 6
Figure 6. Arduino Logo 7
Figure 7. Arduino Uno board 8
Figure 8. Arduino Due board 8
Figure 9. Arduino Micro board 9
Figure 10. Arduino Mega board 9
Figure 11. Arduino LilyPad board 9
Figure 12. Genuino Zero board 10
Figure 13. Arduino MKR GSM 1400 board 10
Figure 14. Arduino Esplora board 11
Figure 15. Arduino Mega board 12
Figure 16. Arduino Mega board components[MAN18] 13
Figure 17. Arduino Mega board components 15
Figure 18. HC-SR04 Sonar Sensor 15
Figure 19. Sonar Sensor representation 2[HUL18] 16
Figure 20. HC-05 Bluetooth module 17
Figure 21. HC-05 Bluetooth module connection to the Arduino board 18
Figure 22. Voltage divider example 19
Figure 23. HC-05 Bluetooth pins 20
Figure 24. L298N module 21
Figure 25. Simple H-bridge 21
Figure 26. L298N Pinout 22
Figure 27. L298N Connection Example 22
Figure 28. 5mm Orange LED 23
Figure 29. 2K Ω Resitor 23
Figure 30. 0.1 µF Capacitor 23
Figure 31. Wires 24
Figure 32. Small 6V DC motor 24
Figure 33. 9V alkaline battery 24
Figure 34. Android Logo 25
Figure 35. HTC Dream – the first commercially released device to use the Android OS 25
Figure 36. Google Play logo 29
Figure 37. Android version distribution [ADR18] 31
Figure 38. Android Studio Logo 32
Figure 39. Android Studio user interface 33
Figure 40. Arduino IDE 35
Figure 41. Arduino IDE user interface 36
Figure 42. Fritzing layout example 38
Figure 43. Fritzing Logo 38
Figure 44. Components connection 39
Figure 45. Electric schematic 40
Figure 46. Software architecture 41
Figure 47. Main activity layout 41
Figure 48. Button not pressed 42
Figure 49. Button Pressed 42
Figure 50. Activate Bluetooth & connect to car 42
Figure 51. Select device list 42
Figure 52. Connection pending 43
Figure 53. Disconnect from car 43
Figure 54. Obstacle detection ON 44
Figure 55. Obstacle detection OFF 44
Figure 56. Turn left light button 44
Figure 57. Landscape mode 44
Figure 58. ”ConnectBT” class 45
Figure 59. Arduino code snippet 46
Table list
Table 1. Arduino Mega technical specs 12
Table 2. Ultrasonic Sensor Pin Configuration 16
Table 3. Android Versions [ADR18] 31
Table 4. Pin Configuration 49
iNTRODUCTION
Scope
The purpose of this project is to show that a terminal, such as a toy car, can be controlled remotely through the bluetooth module of an Android OS smartphone.
Motivation
Building a robot was always one of my goals ever since I finished middle school. The first attempt (and last ever since) of building one was in highschool when me and a friend tried to build a simple line following robot as cheap as possible using an ice scream stick, two DC 3V motors ,some rubber band, a reflective object sensor and roller skates bearings. We finshed building it, but it never followed any line since we damaged the sensor in the „assembly” process. This failed attempt slightly discuraged me, knowing very well that my skills in electronics needed much improvment.
Some years passed since and the smart-phone era began, people being now able to connect to almost everything, everywhere using their phones. My goal hasn't been achieved, I built a robot but it never worked, so when the time came to choose a diploma project I thought to myself : „Why not build that robot that I always wanted to build?”. But not a line-crawler, in the meantime I learnt to program , and why should my robot follow a line when I can make it follow my commands?
Since smart-phones are popular and can be used to control a variety of devices I decided that my robot will also be able to be controled using one.
the hardware Used
Microcontroller
“Referred to as an embedded controller or MCU (microcontroller unit) microcontrollers can be found everywhere around us: vehicles, robots, office machines, medical devices, mobile phones, vending machines, home appliances and among many other devices.” [IoT17]
Figure 1 Intel’s 8bit 8051 Microcontroller
“A microcontroller is a compact integrated circuit designed to govern a specific operation in an embedded system. A typical microcontroller includes a processor, memory and input/output (I/O) peripherals on a single chip. A microcontroller's processor will vary by application. Options range from the simple 4-bit, 8-bit or 16-bit processors to more complex 32-bit or 64-bit processors. The memory that microcontrollers generally use: RAM (the volatile memory in which the operating system and the data of the running applications are kept that gets deleted when there’s no power), EPROM (erasable programmable read-only memory-memory that can be erased and re-used), EEPROM (electrically erasable programmable read-only memory) or flash memory (nonvolatile memory – a combination of EPROM & EEPROM).” [ IoT17]
„Microcontrollers are used in multiple industries and applications, including in the home and enterprise, building automation, manufacturing, robotics, automotive, lighting, smart energy, industrial automation, communications and internet of things (IoT) deployments.
The simplest microcontrollers facilitate the operation of electromechanical systems found in everyday convenience items, such as ovens, refrigerators, toasters, mobile devices, key fobs, video games, televisions and lawn-watering systems. They are also common in office machines such as photocopiers, scanners, fax machines and printers, as well as smart meters, ATMs and security systems.
More sophisticated microcontrollers perform critical functions in aircraft, spacecraft, ocean-going vessels, vehicles, medical and life-support systems, and robots. In medical scenarios, microcontrollers can regulate the operations of an artificial heart, kidney or other organ. They can also be instrumental in the functioning of prosthetic devices.” [IoT17]
Microcontrollers vs. microprocessors
„The distinction between microcontrollers and microprocessors has gotten less clear as chip density and complexity has become relatively cheap to manufacture and microcontrollers have thus integrated more "general computer" types of functionality. On the whole, though, microcontrollers can be said to function usefully on their own, with direct connection to sensors and actuators, where microprocessors are designed to maximize compute power on the chip, with internal bus connections (rather than direct I/O) to supporting hardware such as RAM and serial ports. Simply put, coffee makers use microcontrollers; desktop computers use microprocessors. Microcontrollers are less expensive and use less power than microprocessors. Microprocessors do not have built in RAM, read-only memory (ROM) or other peripherals on the chip, but rather attach to these with their pins. A microprocessor can be considered the heart of a computer system, whereas a microcontroller can be considered the heart of an embedded system.” [IoT17]
Some of the most know microcontroller families are:
PIC (Microchip Technology – American manufacturer )
Renesas (Renesas Electronics Corporation – Japanese manufacturer )
AVR (Atmel Corporation – American manufacturer )
COP (Texas instruments – American manufacturer )
8051 (Intel Corporation – American manufacturer )
The ATmega 2560 mictocontroller
„The Atmel Atmega 2560 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. The Atmel AVR core combines a rich instruction set with 32 general purpose working regis-ters. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers.” [ATM14]
“The ATmega 2560 provides the following features:
256K bytes of In-System Programmable Flash
4Kbytes EEPROM
8Kbytes SRAM
86 general purpose I/O lines
32 general purpose working registers
12 PWM channels (16 bits resolution)
16 ADC channels
The Atmega 2560 AVR is supported with a full suite of program and system development tools including: C compilers, macro assemblers, program debugger/simulators, in-circuit emulators, and evaluation kits. [ATM14]”
Arduino Microcontrollers
About Arduino
„Arduino was born at the Ivrea Interaction Design Institute (Northern Italy) as an easy tool for fast prototyping, aimed at students without a background in electronics and programming. As soon as it reached a wider community, the Arduino board started changing to adapt to new needs and challenges, differentiating its offer from simple 8-bit boards to products for IoT applications, wearable, 3D printing, and embedded environments.„ [ARD18]
„Arduino is an open-source electronics platform based on easy-to-use hardware and software. Arduino boards are able to read inputs – light on a sensor, a finger on a button,- and turn it into an output – activating a motor, turning on an LED. Thanks to its simple and accessible user experience, Arduino has been used in thousands of different projects and applications. The Arduino software is easy-to-use for beginners, yet flexible enough for advanced users. The Arduino software is easy-to-use for beginners, yet flexible enough for advanced users. It runs on Mac, Windows, and Linux.” [ARD18]
„Arduino board designs use a variety of microprocessors and controllers. The boards are equipped with sets of digital and analog input/output pins that may be interfaced to various expansion boards or Breadboards and other circuits. The boards feature serial communications interfaces, including Universal Serial Bus (USB) on some models, which are also used for loading programs from personal computers. The microcontrollers are typically programmed using a dialect of features from the programming languages C and C++. In addition to using traditional compiler toolchains, the Arduino project provides an integrated development environment (IDE) based on the Processing language project.” [ARW18]
Arduino Boards
„Most Arduino boards consist of an Atmel AVR microcontrollers with varying amounts of flash memory, pins, and features.The boards use single or double-row pins or female headers that facilitate connections for programming and incorporation into other circuits. These may connect with add-on modules termed shields. Most boards include a 5 V linear regulator and a 16 MHz crystal oscillator or ceramic resonator.
Current Arduino boards are programmed via Universal Serial Bus (USB). The Arduino board exposes most of the microcontroller's I/O pins for use by other circuits. These pins are on the top of the board, via female 0.1-inch (2.54 mm) headers. Several plug-in application shields are also commercially available.” [ARW18]
Examples of Arduino boards:
Arduino Uno
“Arduino Uno is a microcontroller board based on the ATmega328P. It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz quartz crystal, a USB connection, a power jack, an ICSP header and a reset button. It contains everything needed to support the microcontroller.” [UNO18]
Arduino Due
„The Arduino Due is a microcontroller board based on the Atmel SAM3X8E ARM Cortex-M3 CPU. It is the first Arduino board based on a 32-bit ARM core microcontroller. It has 54 digital input/output pins (of which 12 can be used as PWM outputs), 12 analog inputs, 4 UART, a 84 MHz clock, an USB OTG capable connection, 2 DAC (digital to analog), 2 TWI, a power jack, an SPI header, a JTAG header, a reset button and an erase button.Unlike most Arduino boards, the Arduino Due board runs at 3.3V.”[DUE18]
Arduino Micro
“Arduino Micro is the smallest board of the family, easy to integrate it in everyday objects to make them interactive. The Micro is based on the ATmega32U4 microcontroller developed in conjunction with Adafruit , featuring a built-in USB which makes the Micro recognizable as a mouse or keyboard. It has 20 digital input/output pins (of which 7 can be used as PWM outputs and 12 as analog inputs), a 16 MHz crystal oscillator, a micro USB connection, an ICSP header, and a reset button. It contains everything needed to support the microcontroller. It has a form factor that enables it to be easily placed on a breadboard.” [MIC18]
Arduino Mega
The board I used to make my project, it will be detailed in it’s own sub-chapter.
Arduino LilyPad
“The LilyPad Arduino Board is based on the ATmega168V (the low-power version of the ATmega168) or the ATmega328P. The LilyPad Arduino is designed for e-textiles and wearables projects. It can be sewn to fabric and similarly mounted power supplies, sensors and actuators with conductive thread.” [LYL18]
Genuino Zero
„The Genuino Zero is a simple and powerful 32-bit extension of the platform established by the Uno. The Zero board expands the family by providing increased performance, enabling a variety of project opportunities for devices, and acts as a great educational tool for learning about 32-bit application development. The Zero applications span from smart IoT devices, wearable technology, high-tech automation, to robotics. The board is powered by Atmel’s SAMD21 MCU, which features a 32-bit ARM Cortex® M0+ core. One of its most important features is Atmel’s Embedded Debugger (EDBG), which provides a full debug interface without the need for additional hardware, significantly increasing the ease-of-use for software debugging. Unlike most Arduino & Genuino boards, the Zero runs at 3.3 V.” [ZER18]
Arduino MKR GSM 1400
„Arduino MKR GSM 1400 has been designed to offer a practical and cost effective solution for makers seeking to add global GSM connectivity to their projects with minimal previous experience in networking. It is based on the Atmel SAMD21 and a SARAU201 GSM module. The design includes the ability to power the board using a LiPo battery or external power source rated 5V. Switching from one source to the other is done automatically. A good 32 bit computational power similar to the Zero board, the usual rich set of I/O interfaces, gobal GSM communication and the ease of use of the Arduino Software (IDE) for code development and programming. All these features make this board the preferred choice for the emerging IoT battery-powered projects in a compact form factor. Unlike most Arduino & Genuino boards, the MKR GSM 1400 runs at 3.3V.” [MKR18]
Arduino Esplora
„The Arduino Esplora is a microcontroller board derived from the Arduino Leonardo. The Esplora differs from all preceding Arduino boards in that it provides a number of built-in, ready-to-use set of onboard sensors for interaction. It's designed for people who want to get up and running with Arduino without having to learn about the electronics first. The Esplora has onboard sound and light outputs, and several input sensors, including a joystick, a slider, a temperature sensor, an accelerometer, a microphone, and a light sensor. It also has the potential to expand its capabilities with two Tinkerkit input and output connectors, and a socket for a color TFT LCD screen. Like the Leonardo board, the Esplora uses an Atmega32U4 AVR microcontroller with 16 MHzcrystal oscillator and a micro USB connection capable of acting as a USB client device, like a mouse or a keyboard.” [ESP18]
The Arduino Mega 2560
“The Arduino MEGA 2560 is designed for projects that require more I/O lines, more sketch memory and more RAM. With 54 digital I/O pins, 16 analog inputs and a larger space for your sketch it is the recommended board for 3D printers and robotics projects. This gives your projects plenty of room and opportunities maintaining the simplicity and effectiveness of the Arduino platform.” [MEG18]
Table 1. Arduino Mega technical specs
„The Mega 2560 board can be programmed with the Arduino Software (IDE).The ATmega2560 on the Mega 2560 comes preprogrammed with a bootloader that allows the upload of new code to it without the use of an external hardware programmer.
The Mega 2560 has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.
The Mega 2560 can be powered via the USB connection or with an external power supply. The power source is selected automatically.External (non-USB) power can come either from an AC-to-DC adapter (wall-wart) or battery. The adapter can be connected by plugging a 2.1mm center-positive plug into the board's power jack. Leads from a battery can be inserted in the GND and Vin pin headers of the POWER connector.The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.”[MME18]
The analog pins are used for reading signals like light sensors, pressure sensors, temperature sensors, humidity sensors, proximity sensors etc.
The digital pins are can be configured as either inputs or outputs, are mostly used for tactile or digital sensors, like buttons and switches.
PWM pins are digital pins too. The difference is that they can also be used by the built in PWM (Pulse width modulation – a technique for getting analog results with digital means) module in the microcontroller.
“The Mega 2560 board has a number of facilities for communicating with a computer, another board, or other microcontrollers. The ATmega2560 provides four hardware UARTs for TTL (5V) serial communication. The Arduino Software (IDE) includes a serial monitor which allows simple textual data to be sent to and from the board. The RX and TX LEDs on the board will flash when data is being transmitted via the ATmega chip and USB connection to the computer.” [MME18]
„Rather then requiring a physical press of the reset button before an upload, the Mega 2560 is designed in a way that allows it to be reset by software running on a connected computer. One of the hardware flow control lines (DTR) of the ATmega8U2 is connected to the reset line of the ATmega2560 via a 100 nanofarad capacitor. When this line is asserted (taken low), the reset line drops long enough to reset the chip. The Arduino Software (IDE) uses this capability to allow you to upload code by simply pressing the upload button in the Arduino environment. This means that the bootloader can have a shorter timeout, as the lowering of DTR can be well-coordinated with the start of the upload.” [MME18]
Ultrasonic Sensor
“As the name indicates, an ultrasonic sensor measure distance by using ultrasonic waves.
The sensor head emits an ultrasonic wave and receives the wave reflected back from the target. Ultrasonic Sensors measure the distance to the target by measuring the time between the emission and reception. „ [ULT18]
“The distance can be calculated with the following formula:
L = 1/2 × T × C
where L is the distance, T is the time between the emission and reception, and C is the sonic speed 340m/s. (The value is multiplied by 1/2 because T is the time for go-and-return distance.)” [ULT18]
In the construction of my project I used the HC-SR04 ultransonic module:
„HC-SR04 Ultrasonic (US) sensor is a 4 pin module, whose pin names are Vcc, Trigger, Echo and Ground respectively. This sensor is a very popular sensor used in many applications where measuring distance or sensing objects are required. The module has two eyes like projects in the front which forms the Ultrasonic transmitter and Receiver.” [CUL18]
„In order to use the sensor it has to be powerd using a regulated +5V through the Vcc ad Ground pins of the sensor. The current consumed by the sensor is less than 15mA and hence can be directly powered by the on board 5V pins. The Trigger and the Echo pins are both I/O pins and hence they can be connected to I/O pins of the microcontroller. To start the measurement, the trigger pin has to be made high for 10uS and then turned off. This action will trigger an ultrasonic wave at frequency of 40Hz from the transmitter and the receiver will wait for the wave to return. Once the wave is returned after it getting reflected by any object the Echo pin goes high for a particular amount of time which will be equal to the time taken for the wave to return back to the sensor.” [CUL18]
„The amount of time during which the Echo pin stays high is measured by the MCU/MPU as it gives the information about the time taken for the wave to return back to the Sensor. Using this information the distance is measured.” [CUL18]
Table 2. Ultrasonic Sensor Pin Configuration
HC-05 Bluetooth module
“HC‐05 module is an easy to use Bluetooth SPP (Serial Port Protocol) module, designed for transparent wireless serial connection setup. The HC-05 Bluetooth Module can be used in a Master or Slave configuration, making it a great solution for wireless communication. This serial port Bluetooth module is fully qualified Bluetooth V2.0+EDR (Enhanced Data Rate) 3Mbps Modulation with complete 2.4GHz radio transceiver and baseband.” [WBL16]
“The Bluetooth module HC-05 is a MASTER/SLAVE module. By default, the factory setting is SLAVE. The slave modules cannot initiate a connection to another Bluetooth device, but can accept connections. Master module can initiate a connection to other devices. “[WBL16]
“Once it is paired to a master Bluetooth device such as PC, smart phones and tablet, its operation becomes transparent to the user. All data received through the serial input is immediately transmitted over the air. When the module receives wireless data, it is sent out through the serial interface exactly at it is received. The HC-05 supports two work modes: Command and Data mode. The work mode of the HC-05 can be switched by the onboard push button. The HC-05 is put in Command mode if the push button is activated. In Command mode, user can change the system parameters (e.g. pin code, baud rate, etc.) using host controller itself of a PC running terminal software using a serial to TTL converter. Any changes made to system parameters will be retained even after power is removed. Power cycle the HC-05 will set it back to Data Mode. Transparent UART data transfer with a connected remote device occurs only while in Data Mode. The HC-05 can be re-configured by the user to work as a master Bluetooth device using a set of AT commands. Once configured as master, it can automatically pair with a HC-05 in its default slave configuration, allowing point to point serial communications.” [SGB18]
„Features: [SGB18]
Bluetooth v2.0+EDR
2.4GHz ISM band frequency
Supported baud rate: 9600 (default), 19200,38400, 57600, 115200, 230400, 460800.
Speed: Asynchronous: 2.1Mbps(Max) / 160 kbps, Synchronous: 1Mbps/1Mbps
Power supply: 3.6V to 6V DC
Passkey: 1234 „
The HC-05 will work with supply voltage of 3.6VDC to 6VDC, however, the logic level of RXD pin is 3.3V and is not 5V tolerant. In order to avoid damaging the Bluetooth module I used a simple voltage divider using 2 resitors.
„A voltage divider circuit is a very common circuit that takes a higher voltage and converts it to a lower one by using a pair of resistors. The formula for calculating the output voltage is based on Ohms Law and is shown below:
Figure 22. Voltage divider example
Where:
VS is the source voltage, measured in volts (V),
R1 is the resistance of the 1st resistor, measured in Ohms (Ω).
R2 is the resistance of the 2nd resistor, measured in Ohms (Ω).
Vout is the output voltage, measured in volts (V) „[OHM18]
Pin Description
The HC-05 Bluetooth Module has 6 pins. They are as follows:
“ENABLE: When enable is pulled LOW, the module is disabled which means the module will not turn on and it fails to communicate. When in enable is left open or connected to 3.3V, the module is enabled.
Vcc: Supply Voltage 3.3V to 5V
GND: Ground pin
TXD & RXD: These two pins act as an UART interface for communication
STATE: When the module is not connected to / paired with any other Bluetooth device, signal goes Low. At this low state, the led flashes continuously which denotes that the module is not paired with other devices. When this module is connected to/paired with any other Bluetooth device, the signal goes High. At this high state, the led blinks with a constant delay say for example 2s delay which indicates that the module is paired.
BUTTON SWITCH: This is used to switch the module into AT command mode. To enable AT command mode, press the button switch for a second. With the help of AT commands, the user can change the parameters of this module but only when the module is not paired with any other BT device. When the module is connected to any other Bluetooth device, it starts to communicate with that device and fails to work in AT command mode.” [WBL16]
L298N Dual Motor Controller Module
„This motor controller from Tronixlabs Australia is based on the L298N heavy-duty dual H-bridge controller, which can be used to drive two DC motors at up to 2A each, with a voltage between 5 and 35V DC – or one stepper motor with ease. The controller has fast short-circuit protection diiodes, and a heatsink to keep the L298N from overheating.” [LDM18]
The L298N motor controller follows the H-bridge configuration, which is useful when controlling the direction of rotation of a DC motor.
“The motor rotates in the direction dictated by the switches. When S1 and S4 are on, the left motor terminal is more positive than the right terminal, and the motor rotates in a certain direction. On the other hand, when S2 and S3 are on, the right motor terminal is more positive than the left motor terminal, making the motor rotate in the other direction.” [TLD18]
Module pinouts:
The +12V pin is where the motor power is attached. This pin can accept voltages from +7VDC to +35VDC.
“Using the L298N if straightforward. To rotate in one direction, apply a high pulse to IN1 and a low pulse to IN2. To reverse the direction, reverse the pulses to IN1 and IN2.” [TLD18]
Other hardware components used
5MM LEDs
These LEDs are low cost and require almost no thermal management. Combined with their compact size they are perfect for indicator lights.
Resistors
I have used 220 Ω resistors for protecting the LEDs and 1K Ω respectively 2K Ω resitors for the voltage divider necessary to operate de Bluetooth module’s RX pin.
Capacitors
Used to reduce the electrical 'noise' produced by DC motor's commutators constantly making and breaking the circuit as they spin. Without them, the motors might create interference to cordless phones, TVs etc.
Wires
Basic jumper wires, used to connect the components
DC motors
The car already had two 6V DC small motors – one for steering one for moving back and forward.
9V Battery
Used one 9V alkaline batteriy power the Arduino board.
The software used
Android Platform
„Android is a mobile operating system developed by Google, based on a modified version of the Linux kernel and other open source software and designed primarily for touchscreen mobile devices such as smartphones and tablets. In addition, Google has further developed Android TV for televisions, Android Auto for cars, and Wear OS for wrist watches, each with a specialized user interface. Variants of Android are also used on game consoles, digital cameras, PCs and other electronics.“ [ADR18]
„The core Android source code is known as Android Open Source Project (AOSP- an open source initiative led by Google), and is primarily licensed under the Apache License. Android is developed by Google until the latest changes and updates are ready to be released, at which point the source code is made available to the AOSP. The AOSP code can be found without modification on select devices, mainly the Nexus and Pixel series of devices. The source code is, in turn, customized and adapted by original equipment manufacturers (OEMs) to run on their hardware.” [ADR18]
„Android's default user interface is mainly based on direct manipulation, using touch inputs that loosely correspond to real-world actions, like swiping, tapping, pinching, and reverse pinching to manipulate on-screen objects, along with a virtual keyboard. The response to user input is designed to be immediate and provides a fluid touch interface, often using the vibration capabilities of the device to provide haptic feedback to the user. Internal hardware, such as accelerometers, gyroscopes and proximity sensors are used by some applications to respond to additional user actions.” [ADR18]
„List of features in Android[WAF18]:
Messaging: SMS and MMS are available forms of messaging, including threaded text messaging and Android Cloud To Device Messaging (C2DM) and now enhanced version of C2DM, Android Google Cloud Messaging (GCM) is also a part of Android Push Messaging services.
Auto Correction and Dictionary: Android Operating System has an interesting feature called Auto Correction. When any word is misspelled, then Android recommends the meaningful and correct words matching the words that are available in Dictionary. Users can add, edit and remove words from Dictionary as per their wish.
Web browser: The web browser available in Android is based on the open-source Blink (previously WebKit) layout engine, coupled with Chrome's V8 JavaScript engine. Then the WebKit-using Android Browser scored 100/100 on the Acid3 test on Android 4.0 ICS; the Blink-based browser currently has better standards support. The browser is variably known as 'Android Browser', 'AOSP browser', 'stock browser', 'native browser', and 'default browser'. Starting with Android 4.4 KitKat, Google has mandated that the default browser for Android proper be Google Chrome. Since Android 5.0 Lollipop, the WebView browser that apps can use to display web content without leaving the app has been separated from the rest of the Android firmware in order to facilitate separate security updates by Google.
Voice-based features: Google search through voice has been available since initial release. Voice actions for calling, texting, navigation, etc. are supported on Android 2.2 onwards.As of Android 4.1, Google has expanded Voice Actions with ability to talk back and read answers from Google's Knowledge Graph when queried with specific commands.The ability to control hardware has not yet been implemented.
Multi-touch: Android has native support for multi-touch which was initially made available in handsets such as the HTC Hero. The feature was originally disabled at the kernel level (possibly to avoid infringing Apple's patents on touch-screen technology at the time). Google has since released an update for the Nexus One and the Motorola Droid which enables multi-touch natively.
Multitasking: Multitasking of applications, with unique handling of memory allocation, is available.
Screen capture: Android supports capturing a screenshot by pressing the power and home-screen buttons at the same time. Prior to Android 4.0, the only methods of capturing a screenshot were through manufacturer and third-party customizations (apps), or otherwise by using a PC connection (DDMS developer's tool). These alternative methods are still available with the latest Android.
TV recording: Android TV supports capturing video and replaying it.
Video calling: Android does not support native video calling, but some handsets have a customized version of the operating system that supports it, either via the UMTS network (like the Samsung Galaxy S) or over IP. Video calling through Google Talk is available in Android 2.3.4 (Gingerbread) and later. Gingerbread allows Nexus S to place Internet calls with a SIP account. This allows for enhanced VoIP dialing to other SIP accounts and even phone numbers. Skype 2.1 offers video calling in Android 2.3, including front camera support. Users with the Google+ Android app can perform video chat with other Google+ users through Hangouts.
Multiple language support: Android supports multiple languages.
Accessibility: Built-in text-to-speech is provided by TalkBack for people with low or no vision. Enhancements for people with hearing difficulties are available, as are other aids.
Connectivity:
Android supports connectivity technologies including GSM/EDGE, Bluetooth, LTE, CDMA, EV-DO, UMTS, NFC, IDEN and WiMAX.
Bluetooth: Supports voice dialing and sending contacts between phones, playing music, sending files (OPP), accessing the phone book (PBAP), A2DP and AVRCP. Keyboard, mouse and joystick (HID) support is available in Android 3.1+, and in earlier versions through manufacturer customizations and third-party applications.
Tethering Android supports tethering, which allows a phone to be used as a wireless/wired Wi-Fi hotspot. Before Android 2.2 this was supported by third-party applications or manufacturer customizations.
Media:
Streaming media support: RTP/RTSP streaming 3GPP PSS, ISMA), HTML progressive download (HTML5 <video> tag). Adobe Flash Streaming (RTMP) and HTTP Dynamic Streaming are supported by the Flash plugin. Apple HTTP Live Streaming is supported by RealPlayer for Android, and by the operating system since Android 3.0 (Honeycomb).
Media support: Android supports the following audio/video/still media formats: WebM, H.263, H.264, AAC, HE-AAC (in 3GP or MP4 container), MPEG-4 SP, AMR, AMR-WB (in 3GP container), MP3, MIDI, Ogg Vorbis, FLAC, WAV, JPEG, PNG, GIF, BMP, and WebP.
External storage: Most Android devices include microSD card slots and can read microSD cards formatted with the FAT32, Ext3 or Ext4 file systems. To allow use of external storage media such as USB flash drives and USB HDDs, some Android devices are packaged with USB-OTG cables. Storage formatted with FAT32 is handled by the Linux Kernel vFAT driver, while 3rd party solutions are required to handle some other file systems such as NTFS, HFS Plus and exFAT.
Hardware support:
Android devices can include still/video cameras, touchscreens, GPS, accelerometers, gyroscopes, barometers, magnetometers, dedicated gaming controls, proximity and pressure sensors, thermometers, accelerated 2D bit blits (with hardware orientation, scaling, pixel format conversion) and accelerated 3D graphics.
Other
Java support: While most Android applications are written in Java, there is no Java Virtual Machine in the platform and Java byte code is not executed. Java classes are compiled into Dalvik executables and run on using Android Runtime or in Dalvik in older versions, a specialized virtual machine designed specifically for Android and optimized for battery-powered mobile devices with limited memory and CPU. J2ME support can be provided via third-party applications.
Handset layouts: The platform works for various screen sizes from smartphone sizes and to tablet size, and can potentially connect to an external screen, e.g. through HDMI, or wirelessly with Miracast. Portrait and landscape orientations are supported and usually switching between by turning. A 2D graphics library, 3D graphics library based on OpenGL ES 2.0 specifications is used.
Storage: SQLite, a lightweight relational database, is used for data storage purposes.
Native Apps: Android apps are also written in HTML.
Instant Apps: Android apps are hosted on a specific website path and load instead of the website itself. They are part-apps and load almost instantly without the need for an installation. One of the first apps being developed with such functionality is the B&H app.”
About Applications
Figure 36. Google Play logo
„Applications ("apps"), which extend the functionality of devices, are written using the Android software development kit (SDK) and, often, the Java programming language. Java may be combined with C/C++, together with a choice of non-default runtimes that allow better C++ support. The Go programming language is also supported, although with a limited set of application programming interfaces (API). In May 2017, Google announced support for Android app development in the Kotlin programming language.” [ADR18]
„The SDK includes a comprehensive set of development tools, including a debugger, software libraries, a handset emulator based on QEMU, documentation, sample code, and tutorials. Initially, Google's supported integrated development environment was Eclipse using the Android Development Tools (ADT) plugin; in December 2014, Google released Android Studio, based on IntelliJ IDEA, as its primary IDE for Android application development. Other development tools are available, including a native development kit (NDK) for applications or extensions in C or C++, Google App Inventor, a visual environment for novice programmers, and various cross platform mobile web applications frameworks. In January 2014, Google unveiled an framework based on Apache Cordova for porting Chrome HTML 5 web applications to Android, wrapped in a native application shell.” [ADR18]
„Android has a growing selection of third-party applications, which can be acquired by users by downloading and installing the application's APK (Android application package) file, or by downloading them using an application store program that allows users to install, update, and remove applications from their devices. Google Play Store is the primary application store installed on Android devices that comply with Google's compatibility requirements and license the Google Mobile Services software. Google Play Store allows users to browse, download and update applications published by Google and third-party developers; as of July 2013, there are more than one million applications available for Android in Play Store. As of July 2013, 50 billion applications have been installed. Some carriers offer direct carrier billing for Google Play application purchases, where the cost of the application is added to the user's monthly bill. As of May 2017, there are over one billion active users a month for Gmail, Android, Chrome, Google Play and Maps.” [ADR18]
„Due to the open nature of Android, a number of third-party application marketplaces also exist for Android, either to provide a substitute for devices that are not allowed to ship with Google Play Store, provide applications that cannot be offered on Google Play Store due to policy violations, or for other reasons. Examples of these third-party stores have included the Amazon Appstore, GetJar, and SlideMe. F-Droid, another alternative marketplace, seeks to only provide applications that are distributed under free and open source licenses.” [ADR18]
„Since Android devices are usually battery-powered, Android is designed to manage processes to keep power consumption at a minimum. When an application is not in use the system suspends its operation so that, while available for immediate use rather than closed, it does not use battery power or CPU resources. Android manages the applications stored in memory automatically: when memory is low, the system will begin invisibly and automatically closing inactive processes, starting with those that have been inactive for the longest amount of time. Lifehacker reported in 2011 that third-party task killer applications were doing more harm than good.” [ADR18]
Table 3. Android Versions [ADR18]
Since Gingerbread & Ice Cream Sandwich devices are nearly all gone the application developed by me will be able to run only on devices with at least Android Jelly Bean.
Android Studio
„Android Studio is the official integrated development environment (IDE) for Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed specifically for Android development. It is available for download on Windows, macOS and Linux based operating systems. It is a replacement for the Eclipse Android Development Tools (ADT) as primary IDE for native Android application development.” [WAS18]
„Android Studio was announced on May 16, 2013 at the Google I/O conference. It was in early access preview stage starting from version 0.1 in May 2013, then entered beta stage starting from version 0.8 which was released in June 2014. The first stable build was released in December 2014, starting from version 1.0. The current stable version is 3.1.3 released in June 2018.” [WAS18]
„Android Studio uses Gradle as the foundation of the build system, with more Android-specific capabilities provided by the Android plugin for Gradle. This build system runs as an integrated tool from the Android Studio menu, and independently from the command line. You can use the features of the build system to do the following:
Customize, configure, and extend the build process.
Create multiple APKs for your app, with different features using the same project and modules.
Reuse code and resources across sourcesets. ” [DAS18]
„The Android Studio IDE is free to download and use. A one-time, $25 developer's license is required to publish apps to Google Play App Store. Android Studio offers features that enhance the productivity when building Android apps, such as:
A flexible Gradle-based build system
A fast and feature-rich emulator
A unified environment to develop for all Android devices
Instant Run to push changes to your running app without building a new APK
Code templates and GitHub integration to help you build common app features and import sample code
Extensive testing tools and frameworks
Lint tools to catch performance, usability, version compatibility, and other problems
C++ and NDK support
Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and App Engine” [DAS18]
„1 )The toolbar lets you carry out a wide range of actions, including running your app and launching Android tools.
2) The navigation bar helps you navigate through your project and open files for editing. It provides a more compact view of the structure visible in the Project window.
3) The editor window is where you create and modify code. Depending on the current file type, the editor can change. For example, when viewing a layout file, the editor displays the Layout Editor.
4) The tool window bar runs around the outside of the IDE window and contains the buttons that allow you to expand or collapse individual tool windows.
5) The tool windows give you access to specific tasks like project management, search, version control, and more. You can expand them and collapse them.
6) The status bar displays the status of your project and the IDE itself, as well as any warnings or messages.” [DAS18]
Arduino IDE
“Arduino IDE is a lightweight, cross-platform application that introduces programming to novices. It has both an online editor and an on-premise application, for users to have the option whether they want to save their sketches on the cloud or locally on their own computers.” [FAR18]
„The open-source Arduino Software (IDE) runs on Windows, Mac OS X, and Linux. The environment is written in Java and based on Processing and other open-source software.This software can be used with any Arduino board. Arduino Software (IDE) contains a text editor for writing code, a message area, a text console, a toolbar with buttons for common functions and a series of menus. It connects to the Arduino and Genuino hardware to upload programs and communicate with them.” [ARD18]
“The syntax, the words and structure of the code, are like Java and C/C++. Programs written using Arduino Software (IDE) are called sketches. These sketches are written in the text editor and are saved with the file extension “.ino”. The editor has features for cutting/pasting and for searching/replacing text. The message area gives feedback while saving or exporting and displays errors. The console displays text output by the Arduino Software (IDE), including complete error messages and other information. The bottom righthand corner of the window displays the configured board and serial port. The toolbar buttons allow you to verify and upload programs, create, open, and save sketches, and open the serial monitor.” [ARD18]
Figure 41. Arduino IDE user interface
“1) Menu: Selections of software features
2) Verify: Compiles and verifies the sketch for errors
3) Upload: Compiles & Uploads the code to the configured board
4) New: Creates a new sketch window
5) Open: Opens an existing sketch
6) Save: Saves the current active sketch
7) Serial Monitor: Opens the serial monitor (displays serial sent from the Arduino or Genuino board over USB or serial connector)
8) Editor: Code editor area
9)Message: The IDE reports success or failure messages in this zone” [STE18] & [ARD18]
“Arduino IDE comes with a board management module, where users can select the board they want to work with at the moment. If they wish to change it, they can do so easily from the dropdown menu. Modifying their selection also automatically updates the PORT info with the data they need in relation to the new board.” [FAR18]
“Arduino IDE has more than 700 libraries integrated. These were written and shared by members of the Arduino community that other users can utilize for their own projects without having to install anything. This enables programmers to add a different dimension to their sketches. While Arduino IDE is designed specifically for Arduino boards, it also supports connections with third-party hardware. This makes the use of the application more extensive rather than limited to proprietary boards.” [FAR18]
Fritzing
„Fritzing is an open-source initiative to support designers, artists, researchers and hobbyists to take the step from physical prototyping to actual product. We are creating this software in the spirit of Processing and Arduino, developing a tool that allows users to document their Arduino and other electronic-based prototypes, and to create a PCB layout for manufacturing. The complementing website helps users to share and discuss drafts and experiences as well as to reduce manufacturing costs.
It was developed at the University of Applied Sciences of Potsdam (Germany). Fritzing is essentially an Electronic Design Automation software with a low entry barrier, suited for the needs of designers and artists. It uses the metaphor of the breadboard, so that it is easy to transfer hardware sketches to the software.”[FRI18]
The hardware architecture
With the help of the Fritzing software I was able to prototype my project connections. The L298N Dual Motor Controller part was not availble from the Fritzing’s library but thanks to one of the Fritzing users I was able to download and use the part already made by github user „yohendry”. [YOH14]
Figure 44. Components connection
Also with the help of the Fritzing software I created the electric schema:
Figure 45. Electric schematic
The android application
Figure 46. Software architecture
The android application
In order to control the toy car using an Android phone I had to implement an andorid application.
When first oppening the application the user will see the car control layout. In order to start to control the car the user must first connect via Bluetooth to it. If the user tries to use the control buttons the application will prompt an error message.
To be easier for the user to use the application each control button looks different when it’s pressed:
To control the car the user will have to connect to it first. He will do so using the connect button:
This button will open an activity that will allow the user to select from a list of paired devices.
Note that devices in this list are only paired devices. In order for the car’s Bluetooth module to appear on this list it has to be first paired with the phone.
After a device from the list is selected, an attempt to connect to it will be made.
While the attempt is made a loading, dialog will appear. During this time the application can’t be used.
In case the connection can’t be established the user will be notified via an error message.
If the connection with the car is established the Bluetooth button will change it’s apperance. If it’s pressed again the phone will disconnect from the car and the list of devices will apear again.
In case of a failed connection the button will change back to it’s original apperance.Once connected the car can be controled. The commands are sent as long a button is pressed and kept pressed.
The obstacle detection sensors can also be disabled or enabled.
The turn lights can be activated using the green arrow buttons:
A landscape layout mode is also supported:
The android application implementation
The application uses the version 1.8.0_73 of Java Development’s kit. It was implemented using Android Studio’s 2.1.2 version. It requiers „BLUETOOTH_ADMIN” permisions to work.
The application consists of three clases: the „MainActivity” class , the „ConnectBT” and the „SettingsActivity” class.
The „MainActivity” class contains the implementation for the car’s controls and maintaining the bluetooth connection active. It also handles the confirm/error messages that appear on screen. The „SettingActivity” class is for activating the Bluetooth functionality in case it’s not already activated and for the selection of the car’s bluetooth module. The „ConnectBT” is used to connect the Android device to the car.
The Arduino application
The Arduino application is the application that will be downloaded to the arduino board. This application will configure the pins of the board, and will „listen” to commands from the Android application. This application will also receive inputs from the sonar sensors and take over the commands of the car in case of collision danger.
In order to handle multiple functionalities at the same time as turn signals blinking while the car is beeing controlled I used the „SoftTimer” library.
SoftTimer enables a higher level Arduino programing, while its lightweight and easy to use. The programmer is often faced with the problem that he/she needs to run multiple tasks at the same time. With SoftTimer, the programmer is able create Tasks that run periodically.All code will is event driven, all processes run asynchronously, eliminating the need for any blocking code (like sleep).[AST17]
To use this library it needs to be included in the program: „#include <SoftTimer.h>”. After that a task has to be created: „Task t1(2000, callBack1);” where 2000 represents that the time the function „callBack1” is called is every 2000 miliseconds.
The functions used by the Arduino application are:
The „setup()” function – the function responsible for setting the pins as input or output , initialize variables. This function runs only once after each powerup or reset of the board.
The „myLoop()” function – With the SoftTimer library, the "loop" function of the Arduino can’t be used. This function acts like the original Arduino’s “loop” function. Using this function, the Arduino reads the commands received by the Bluetooth trough the serial communication pins and based on those commands calls the functions responsible for controlling the input/output pins.
The „forward()” function is responsible of actuating the M1 motor to move the car forward.
The „backward()” function is responsible of actuating the M1 motor to move the car backwards.
The „leftTurn()” function is repsonsible of actuating the M2 motor to steer the car to the left.
The „rightTurn()” function is repsonsible of actuating the M2 motor to steer the car to the right.
The „stopMotor1()” function is responsible of deactivating the M1 motor.
The „stopMotor2()” function is responsible of deactivating the M2 motor.
The „stopBothMotors()” function is responisble of deactivating both M1 and M2 motor.
The „breakHardFront()” function is called when an obstacle is detected and the car is moving fast. The M1 motor is deactivated briefly and then it’s actuated in reverse to avoid sliding into the detected obstacle.
The „breakSoftFront()” function is called when an obstacle is detected and the car just started moving. This function is implemented to avoid using the „breakHardFront” function that will cause the car to move backwards if a obstacle is detecte briefly after the car starts moving .
The „obstacleDetected()” function enables/disables a global flag in case the sensors detect an obstacle. Based on this flag the „myLoop” function will triger the reaction.
The „SonarSensor()” function is used by all the sonar sensors to compute the distance between the car and an obstacle.
The „TurnRightBlink()” and „TurnLeftBlink()” functions are called when the user wants to use the turn light signals.
The „HeadlightsOn” function is called when the user wants to turn on the headlights.
The „HazardLightOn” function is called when the user wants to turn on the HazardLight.
Table 4. Pin Configuration
Conclusion
After finishing the project I finnaly achived the feat of building my own robot. Also I was able to imporve my Android software development skills, Android beeing a continuously growing OS with countless applications in the real world. It’s a huge leap from my first attempt (the „ice-cream stick line crawler” robot) and I am happy that this one actually works. A good ammout of the topics I learnt in facualty like OOP, android programing, logical design, microcontroler design, electronics, and even photoshop helped me to complete this project.
As applicabilities in the real world this project can simply be used as a recreational device, but it can also be used on a larger scale and some modifications to control for example an electric wheelchair.It can also be equiped with other kinds of sensors like temperature/gas/humidity sensors to fullfill other purposes.
The issues I have faced during the development of this project :
The SR04 sonar sensors altough are cheap they are not very accurate. Sometimes they give false readings that trigger unnecessary events. To minimize the impact on the system I had to use filter their readings.
Having the turn lights blinking at a constant rate while the car was being controlled was one of the challenges of this project.
The cost of the whole project was low, the fact that I did not used an original Arduino board helped lower the costs reaching to a total of just under 30$.
This project can be improved further, by using laser sensors for increased accuracy and speed reaction, the car can be programmed to go around obstacles, have a camera mounted on it and be controlled wirelessly via an internet connection.As another improvement it’s speed could be also adjusted while moving.
BibliograPHY
[MAS11] Massimo Banzi – „Getting Started with Arduino” Second Edition, 2011
[JOH15] John Horton – „Android Programming for Beginners”, 2015
[BIL15] Bill Phillips and Chris Stewart – „Android Programming: The Big Nerd Ranch Guide”, 2015
[CHA15] Charles Platt – „Make: Electronics” , 2015
web rEFERENCES
[ATM14] Atmel Corporation, “Atmel ATmega640/V-1280/V-1281/V-2560/V-2561/V” can be found at: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
[IOT17] https://internetofthingsagenda.techtarget.com/definition/microcontroller
[ARD18] https://www.arduino.cc/en/Guide/Introduction
[ARW18] https://en.wikipedia.org/wiki/Arduino
[UNO18] https://store.arduino.cc/arduino-uno-rev3
[DUE18] https://store.arduino.cc/arduino-due
[MIC18] https://store.arduino.cc/arduino-micro
[LYL18] https://store.arduino.cc/lilypad-arduino-main-board
[ZER18] https://store.arduino.cc/genuino-zero
[MKR18] https://store.arduino.cc/mkr-gsm-1400
[ESP18] https://store.arduino.cc/arduino-esplora
[MEG18] https://www.arduino.cc/en/Guide/ArduinoMega2560
[MAN18] http://www.mantech.co.za/datasheets/products/A000047.pdf
[MME18] https://www.arduino.cc/en/Main/arduinoBoardMega2560/
[ULT18] https://www.keyence.com/ss/products/sensor/sensorbasics/ultrasonic/info/
[CUL18] https://components101.com/ultrasonic-sensor-working-pinout-datasheet
[HUL18] https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
[WBL16] https://wiki.eprolabs.com/index.php?title=Bluetooth_Module_HC-05
[SGB18] https://www.sgbotic.com/index.php?dispatch=products.view&product_id=1939
[OHM18] http://www.ohmslawcalculator.com/voltage-divider-calculator
[LDM18] https://tronixlabs.com.au/robotics/motor-controllers/l298n-dual-motor-controller-module-2a-australia/
[TLD18] https://www.teachmemicro.com/use-l298n-motor-driver/
[ADR18] https://en.wikipedia.org/wiki/Android_(operating_system)
[WAF18] https://en.wikipedia.org/wiki/List_of_features_in_Android
[WAS18] https://en.wikipedia.org/wiki/Android_Studio
[DAS18] https://developer.android.com/studio/intro/
[FAR18] https://reviews.financesonline.com/p/arduino-ide/
[ARD18] https://www.arduino.cc/en/guide/Environment
[STE18] http://learn.stemtera.com/en/begin/img/arduino_ide.svg
[FRI18] http://fritzing.org/about/context/S
[YOH14] https://github.com/yohendry/arduino_L298N
[AST17] https://github.com/prampec/arduino-softtimer/blob/wiki/SoftTimer.md
sOURCE CODE
Arduino Code:
#include <SoftTimer.h>
#include <BlinkTask.h>
#define led 41
#define led2 48
#define ledObstacle 53
#define motor1Plus 24
#define motor1Minus 26
#define echoPin1 12
#define trigPin1 13
#define echoPin2 10
#define trigPin2 11
#define echoPin3 8
#define trigPin3 9
#define motor2Plus 28
#define motor2Minus 30
char command;
String string;
int dir;
long duration, distance, distance2;
long frontSensor2FirstMeas, frontSensor2SecondMeas, frontSensor2ThirdMeas;
long frontSensorFirstMeas, frontSensorSecondMeas, frontSensorThirdMeas;
long backSensorFirstMeas, backSensorSecondMeas, backSensorThirdMeas;
boolean alreadyBreaked;
boolean alreadyBreakedBack;
volatile boolean ledBlinking;
boolean blinkingStared;
boolean ledOn;
long i;
boolean isFrontObstacleDetected = false;
boolean isBackObstacleDetected = false;
unsigned long forwardTime = 1;
void myLoop(Task* me);
Task t1(0, myLoop);
BlinkTask BlinkLeft(led2, 500, 500, 4 , 500);
BlinkTask BlinkRight(led, 500, 500, 99, 2000);
void setup()
{
SoftTimer.add(&t1);
blinkingStared = false;
i = 1;
ledOn = false;
ledBlinking = false;
alreadyBreaked = true;
alreadyBreakedBack = true;
frontSensorFirstMeas = 100;
frontSensorSecondMeas = 100;
frontSensorThirdMeas = 100;
frontSensor2FirstMeas = 100;
frontSensor2SecondMeas = 100;
frontSensor2ThirdMeas = 100;
backSensorFirstMeas = 100;
backSensorSecondMeas = 100;
backSensorThirdMeas = 100;
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(motor1Plus, OUTPUT);
pinMode(motor1Minus , OUTPUT);
pinMode(motor2Plus, OUTPUT);
pinMode(motor2Minus , OUTPUT);
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
pinMode(trigPin3, OUTPUT);
pinMode(echoPin3, INPUT);
pinMode(ledObstacle, OUTPUT);
}
void myLoop(Task* me)
{
if (Serial.available() > 0)
{
string = "";
}
while (Serial.available() > 0)
{
command = ((byte)Serial.read());
if (command == ':')
{
break;
}
else
{
string += command;
}
delay(1);
}
if (ledBlinking == true)
{
if (!blinkingStared)
{
BlinkLeft.start();
BlinkRight.start();
blinkingStared = true;
}
}
else
{
blinkingStared = false;
BlinkLeft.stop(); BlinkRight.stop();
digitalWrite(led2, LOW);
digitalWrite(led, LOW);
}
dir = string[0];
switch (dir) {
case 'F':
forwardTime++;
if (FrontObstacleDetected())
{ digitalWrite(ledObstacle, HIGH);
if (alreadyBreaked)
{
stopMotor1();
}
else
{
if (forwardTime > 10)
{
breakHardFront();
forwardTime = 0;
}
else
{
breakSoftFront();
forwardTime = 0;
}
}
}
else
{
digitalWrite(ledObstacle, LOW);
forward();
alreadyBreaked = false;
}
break;
case 'B':
digitalWrite(ledObstacle, LOW);
if (BackObstacleDetected())
{
if (alreadyBreakedBack)
{
stopMotor1();
}
else
{
breakHardBack();
}
}
else
{
backward();
alreadyBreakedBack = false;
}
forwardTime = 0;
break;
case 'L':
if (FrontObstacleDetected())
{
leftTurn();
digitalWrite(ledObstacle, HIGH);
if (alreadyBreaked)
{
// do nothing
}
else
{
breakSoftFront();
}
}
else
{
digitalWrite(ledObstacle, LOW);
leftTurn();
alreadyBreaked = false;
}
break;
case 'R':
if (FrontObstacleDetected())
{ rightTurn();
digitalWrite(ledObstacle, HIGH);
if (alreadyBreaked)
{
//do nothing
}
else
{
breakSoftFront();
}
}
else
{
digitalWrite(ledObstacle, LOW);
rightTurn();
alreadyBreaked = false;
}
break;
case 'S':
stopMotor1();
forwardTime = 0;
alreadyBreaked = true;
break;
case 'O':
stopMotor2();
forwardTime = 0;
break;
case 'U':
stopBothMotors();
forwardTime = 0;
alreadyBreaked = true;
break;
case 'Q':
startBlinking();
break;
case 'A':
stopBlinking();
break;
}
}
void startBlinking()
{
ledBlinking = true;
}
void stopBlinking()
{
ledBlinking = false;
}
void forward()
{
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, HIGH);
delay(20);
}
void backward()
{
digitalWrite(motor1Plus, HIGH);
digitalWrite(motor1Minus, LOW);
delay(10);
}
void leftTurn()
{
digitalWrite(motor2Plus, LOW);
digitalWrite(motor2Minus, HIGH);
delay(10);
}
void rightTurn()
{
digitalWrite(motor2Plus, HIGH);
digitalWrite(motor2Minus, LOW);
delay(10);
}
void stopMotor1()
{
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, LOW);
delay(20);
}
void stopMotor2()
{
digitalWrite(motor2Plus, LOW);
digitalWrite(motor2Minus, LOW);
delay(20);
}
void stopBothMotors()
{
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, LOW);
digitalWrite(motor2Plus, LOW);
digitalWrite(motor2Minus, LOW);
delay(20);
}
void breakHardFront()
{
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, LOW);
delay(25);
digitalWrite(motor1Plus, HIGH);
digitalWrite(motor1Minus, LOW);
delay(300);
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, LOW);
alreadyBreaked = true;
}
void breakHardBack()
{
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, LOW);
delay(25);
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, HIGH);
delay(200);
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, LOW);
alreadyBreakedBack = true;
}
void breakSoftFront()
{
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, LOW);
delay(25);
digitalWrite(motor1Plus, HIGH);
digitalWrite(motor1Minus, LOW);
delay(100);
digitalWrite(motor1Plus, LOW);
digitalWrite(motor1Minus, LOW);
alreadyBreaked = true;
}
boolean FrontObstacleDetected()
{
frontSensorThirdMeas = frontSensorSecondMeas;
frontSensorSecondMeas = frontSensorFirstMeas;
frontSensorFirstMeas = SonarSensor(trigPin1, echoPin1);
frontSensor2ThirdMeas = frontSensor2SecondMeas;
frontSensor2SecondMeas = frontSensor2FirstMeas;
frontSensor2FirstMeas = SonarSensor(trigPin2, echoPin2);
if ((frontSensorFirstMeas < 50 && frontSensorSecondMeas < 50 && frontSensorThirdMeas < 50) || (frontSensor2FirstMeas < 50 && frontSensor2SecondMeas < 50 && frontSensor2ThirdMeas < 50))
{
isFrontObstacleDetected = true;
}
else
{
isFrontObstacleDetected = false;
}
return isFrontObstacleDetected;
}
boolean BackObstacleDetected()
{
backSensorThirdMeas = backSensorSecondMeas;
backSensorSecondMeas = backSensorFirstMeas;
backSensorFirstMeas = SonarSensor(trigPin3, echoPin3);
if (backSensorFirstMeas < 50 && backSensorSecondMeas < 50 && backSensorThirdMeas < 50)
{
isBackObstacleDetected = true;
}
else
{
isBackObstacleDetected = false;
}
return isBackObstacleDetected;
}
long SonarSensor(int trigPin, int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
return distance;
}
Android code:
ConnectBT class:
private class ConnectBT extends AsyncTask<Void, Void, Void>
{
private boolean ConnectSuccess = true;
@Override
protected void onPreExecute()
{
progress = ProgressDialog.show(MainActivity.this, "Connecting…", "Please wait!"); //show a progress dialog
}
@Override
protected Void doInBackground(Void… devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if ((btSocket == null || !isBtConnected)&& SettingsActivity.isDeviceSelected )
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(savedAddress);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a SPP connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, check the exception here
}
return null;
}
@Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Try again.");
bluetoothButton.setChecked(false);
isBtConnected = false;
SettingsActivity.isDeviceSelected=false;
}
else
{
msg("Connected.");
isBtConnected = true;
}
progress.dismiss();
}
}
}
The SettingsActivity class:
public class SettingsActivity extends MainActivity {
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
Button btnPaired;
ListView deviceList;
static boolean isDeviceSelected=false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportActionBar().hide();
deviceList = (ListView)findViewById(R.id.listView);
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
finish();
}
else
{
if (myBluetooth.isEnabled())
{ }
else
{
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
}
pairedDevicesList();
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView av, View v, int arg2, long arg3)
{
isDeviceSelected=true; //flag that a bluetooth device is already selected
String info = ((TextView) v).getText().toString(); // Get the device MAC address, the last 17 chars in the View
String address = info.substring(info.length() – 17);
Intent i = new Intent(SettingsActivity.this, MainActivity.class); // Make an intent to start next activity.
// /Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at the mainActivity
startActivity(i);
}
};
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
deviceList.setAdapter(adapter);
deviceList.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
Intent i = new Intent(SettingsActivity.this, MainActivity.class);
startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
}
CD / DVD
Index
A
android application 41
Android Platform 25
Android Studio 32
Applications 29
Arduino IDE 35
Arduino Mega 2560 12
Arduino Microcontrollers 7
ATmega 2560 5
B
Bibliography 51
C
Contents xi
F
Fritzing 38
H
hardware architecture 39
HC-05 Bluetooth module 17
L
L298N Dual Motor Controller Module 21
List of figures xiii
List of tables xv
M
Microcontroller 2
P
Pin Configuration 49
U
Ultrasonic Sensor 15
Copyright Notice
© Licențiada.org respectă drepturile de proprietate intelectuală și așteaptă ca toți utilizatorii să facă același lucru. Dacă consideri că un conținut de pe site încalcă drepturile tale de autor, te rugăm să trimiți o notificare DMCA.
Acest articol: ANDROID CONTROLLED SMART CAR WITH LIGHTS AND OBSTACLE DETECTION Mihai-Gabriel Tolgoi COORDINATOR Ș.L.dr.ing.Dumitrașcu Eugen JULY 2018 CRAIOVA… [311749] (ID: 311749)
Dacă considerați că acest conținut vă încalcă drepturile de autor, vă rugăm să depuneți o cerere pe pagina noastră Copyright Takedown.
