Difference between revisions of "S24: Team X"
(→Parts List & Cost) |
(→Checkpoint Algorithm) |
||
(138 intermediate revisions by the same user not shown) | |||
Line 19: | Line 19: | ||
=== Team Members & Responsibilities === | === Team Members & Responsibilities === | ||
− | + | [[File: TeamX_GroupPicture.jpeg]] | |
− | |||
− | |||
− | |||
− | |||
+ | [https://gitlab.com/ashley.n.ho/sjtwo-c Gitlab Project - Team X] | ||
{| class="wikitable" | {| class="wikitable" | ||
Line 148: | Line 145: | ||
* <font color = "green">Completed | * <font color = "green">Completed | ||
* <font color = "green">Completed | * <font color = "green">Completed | ||
− | * <font color = " | + | * <font color = "green">Completed |
* <font color = "green">Completed | * <font color = "green">Completed | ||
|- | |- | ||
Line 182: | Line 179: | ||
* <font color = "green">Completed | * <font color = "green">Completed | ||
* <font color = "green">Completed | * <font color = "green">Completed | ||
− | * <font color = " | + | * <font color = "green">Completed |
* <font color = "green">Completed | * <font color = "green">Completed | ||
|- | |- | ||
Line 191: | Line 188: | ||
* Finish RC car prototype 1 | * Finish RC car prototype 1 | ||
* Start outdoor testing at garage rooftop | * Start outdoor testing at garage rooftop | ||
− | * Complete basic mobile app with destination, start/stop | + | * Complete basic mobile app with destination, start/stop button |
* Interface motor and steering | * Interface motor and steering | ||
* Set up LED fault indicators | * Set up LED fault indicators | ||
Line 198: | Line 195: | ||
* <font color = "green">Completed | * <font color = "green">Completed | ||
* <font color = "green">Completed | * <font color = "green">Completed | ||
− | |||
* <font color = "green">Completed | * <font color = "green">Completed | ||
− | * <font color = " | + | * <font color = "green">Completed |
+ | * <font color = "green">Completed | ||
|- | |- | ||
! scope="row"| 10 | ! scope="row"| 10 | ||
Line 207: | Line 204: | ||
| | | | ||
* Edit Wiki report, continue updating through next few weeks | * Edit Wiki report, continue updating through next few weeks | ||
− | * Fine tune mobile app to display | + | * Fine tune mobile app to display map to choose destination |
* Display debug information on LCD | * Display debug information on LCD | ||
− | + | * Continue RC outdoor tests | |
− | * Continue RC outdoor tests | ||
| | | | ||
− | * <font color = " | + | * <font color = "green">Completed |
− | * <font color = " | + | * <font color = "green">Completed |
− | * <font color = " | + | * <font color = "green">Completed |
− | * <font color = " | + | * <font color = "green">Completed |
− | |||
|- | |- | ||
! scope="row"| 11 | ! scope="row"| 11 | ||
Line 229: | Line 224: | ||
| | | | ||
− | * <font color = " | + | * <font color = "green">Completed |
+ | * <font color = "green">Completed | ||
+ | * <font color = "green">Completed | ||
+ | * <font color = "green">Completed | ||
|- | |- | ||
! scope="row"| 12 | ! scope="row"| 12 | ||
Line 238: | Line 236: | ||
* Continue outdoor testing | * Continue outdoor testing | ||
* Fine tune navigational system | * Fine tune navigational system | ||
− | * | + | * Continue refining obstacle avoidance algorithm |
| | | | ||
− | * <font color = " | + | * <font color = "green">Completed |
+ | * <font color = "green">Completed | ||
+ | * <font color = "green">Completed | ||
+ | * <font color = "green">Completed | ||
|- | |- | ||
! scope="row"| 13 | ! scope="row"| 13 | ||
Line 252: | Line 253: | ||
| | | | ||
− | * <font color = " | + | * <font color = "green">Completed |
+ | * <font color = "green">Completed | ||
+ | * <font color = "green">Completed | ||
|- | |- | ||
! scope="row"| 14 | ! scope="row"| 14 | ||
Line 261: | Line 264: | ||
| | | | ||
− | * <font color = " | + | * <font color = "green">Completed |
|- | |- | ||
Line 280: | Line 283: | ||
! scope="row"| 1 | ! scope="row"| 1 | ||
| RC Car | | RC Car | ||
− | | Traxxas | + | | [https://l.messenger.com/l.php?u=https%3A%2F%2Fwww.hobbytown.com%2Ftraxxas-slash-bl2s-1-10-rtr-2wd-brushless-short-course-truck-green-tra58134-4-grn%2Fp1531653&h=AT2UCO46yJC6FLs5eMMt_WG6b_-2srfPT20Ht30KuNimfT0CtY9eEXN27DIXlvtf-1y2p0tokwHIKXE1SR_LavnhOkAFO_w7IiHUljwLAk6A498c2O3RGqQaW_X21kB9LZfa7w Traxxas] |
| 1 | | 1 | ||
| $250.00 | | $250.00 | ||
Line 286: | Line 289: | ||
! scope="row"| 2 | ! scope="row"| 2 | ||
| RC Car Battery | | RC Car Battery | ||
− | | Traxxus | + | | [https://www.hobbytown.com/traxxas-ezpeak-2s-single-completer-pack-multichemistry-battery-charger-tra2992/p581147 Traxxus] |
− | | | + | | 1 |
− | | $ | + | | $110 |
|- | |- | ||
! scope="row"| 3 | ! scope="row"| 3 | ||
| CAN Transceivers MCP2551-I/P | | CAN Transceivers MCP2551-I/P | ||
− | | | + | | [http://www.microchip.com/wwwproducts/en/en010405 Microchip] |
| 8 | | 8 | ||
| Free Samples | | Free Samples | ||
Line 298: | Line 301: | ||
! scope="row"| 4 | ! scope="row"| 4 | ||
| MB1010 LV-MaxSonar | | MB1010 LV-MaxSonar | ||
− | | | + | | [https://maxbotix.com/products/mb1010?variant=41051364556851¤cy=USD&utm_term=&utm_source=google&utm_medium=cpc&gad_source=1&gclid=CjwKCAjwo6GyBhBwEiwAzQTmc0ryxB-TKemhuO9FuxpdqVA01VtM8ZU8mlnqouS3UIvo1jzjhxK4SRoCSZAQAvD_BwE MaxBotix] |
| 4 | | 4 | ||
| $29.95 | | $29.95 | ||
+ | |- | ||
+ | ! scope="row"| 5 | ||
+ | | GPS Module | ||
+ | | [https://www.amazon.com/Navigation-Positioning-Microcontroller-Compatible-Sensitivity/dp/B0B31NRSD2/ref=sr_1_3?crid=O8LGB2AZCR8K&dib=eyJ2IjoiMSJ9.QFx4oBZl1-dUCGV1D5L0XybyGebhmhfPAXI5ECw0VEaanwtTNAbZ2jLtyeXw1-1rqp40g2PVfxx2LxUOZRPhlh3mO8ZWTN9SnkzwfWuBPVSM4e4E33_H6bUyEb4jMuTZLK2C0yiLu6A0zc024ajAqH7LVdrmTMgSc4YnJaSRKbrDYeeLV54PEoneAAd6BigfYQrbG9EuIouTUmV5kAtRnhIyyaMP2gxipOCB_yc4UzA.ZYspItku9lWRgwbcPp9KWQUcP16jgLm9n76jIO-6DDA&dib_tag=se&keywords=gps+module+arduino&qid=1716055609&sprefix=gps+module%2Caps%2C123&sr=8-3 Amazon] | ||
+ | | 1 | ||
+ | | $18.99 | ||
+ | |- | ||
+ | ! scope="row"| 6 | ||
+ | | BMM150 Magnetometer | ||
+ | | [https://www.amazon.com/waveshare-Magnetometer-Measurement-Interface-Raspberry/dp/B0C5XY3J3B/ref=sr_1_1?crid=1E3MMU8B85MFT&dib=eyJ2IjoiMSJ9.WKN3LVNKtVPIBPBc5_emzouPizZxgR3vsz-6R4ST2A5wR3EeyBvmzlTiUkQqXOrjqBTYtVFE6HJwK8v0tyUIm-IxYzxZeCZsfMtPKOqxzeihzH4uCQ5YyukR_72pW255ZSYR9R941H_vSZOeh7dqnVKY8Bx4kdxNcTvyYoOAYLsR5u17q0dgOJzIW0qTQPTkSc-6mvfwrOj7l_XLafIktSrxUjMB4fgLqSEwj_3jZv8.Ic_theuXAJJDADFV1Eu89Hy_Wvl_E3-sROhwDDwLc-Y&dib_tag=se&keywords=magnetometer+bmm150&qid=1716055546&sprefix=magnetometer+bmm150%2Caps%2C131&sr=8-1 Amazon] | ||
+ | | 1 | ||
+ | | $12.49 | ||
+ | |- | ||
+ | ! scope="row"| 7 | ||
+ | | LCD | ||
+ | | [https://www.amazon.com/SunFounder-Serial-Module-Display-Arduino/dp/B01GPUMP9C/ref=asc_df_B019K5X53O/?tag=hyprod-20&linkCode=df0&hvadid=693601922380&hvpos=&hvnetw=g&hvrand=15162836172036316902&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9032166&hvtargid=pla-563014027379&mcid=d8869fd4bb8c3e78a3b0ed4cc311f13b&gad_source=1&gclid=CjwKCAjw0YGyBhByEiwAQmBEWtir6ToCY71keb4T8u84nxll4q-pBoWD5p5W88PQJlnLNyOFNyd48BoCXrQQAvD_BwE&th=1 Amazon] | ||
+ | | 1 | ||
+ | | $11.69 | ||
+ | |- | ||
+ | ! scope="row"| 8 | ||
+ | | BLE Module | ||
+ | | [https://www.adafruit.com/product/2479] | ||
+ | | 1 | ||
+ | | $17.50 | ||
|- | |- | ||
|} | |} | ||
Line 307: | Line 334: | ||
<BR/> | <BR/> | ||
− | == | + | == CAN Communication == |
− | + | Each node is connected to a CAN transceiver that are connected to a bus with a 120 Ohm resistor on each end. We handled each message on the 10Hz, with the sensor and motor messages having the highest priority. | |
− | + | ||
+ | Specifically, we classified each node with these (see table below) message IDs. | ||
− | + | {| class="wikitable" | |
− | + | |- | |
− | == | + | ! scope="col"| |
− | + | ! scope="col"| Node | |
+ | ! scope="col"| Message ID Range | ||
+ | |- | ||
+ | ! scope="row"| 1 | ||
+ | | MOTOR | ||
+ | | 300 - 310 | ||
+ | |- | ||
+ | ! scope="row"| 2 | ||
+ | | SENSOR | ||
+ | | 200 | ||
+ | |- | ||
+ | ! scope="row"| 3 | ||
+ | | GEO | ||
+ | | 400 - 450 | ||
+ | |- | ||
+ | ! scope="row"| 4 | ||
+ | | DEBUG | ||
+ | | 600 - 700 | ||
+ | |- | ||
+ | |} | ||
=== Hardware Design === | === Hardware Design === | ||
− | + | [[File:Can.drawio.png|500px]] | |
=== DBC File === | === DBC File === | ||
− | + | [https://gitlab.com/ashley.n.ho/sjtwo-c/-/blob/master/dbc/project.dbc?ref_type=heads Gitlab DBC File] | |
+ | Shown below are the messages utilized in our DBC file: | ||
+ | BO_ 200 SENSOR_SONARS: 4 SENSOR | ||
+ | SG_ SENSOR_SONARS_left : 0|10@1+ (1,0) [6|254] "inch" DRIVER | ||
+ | SG_ SENSOR_SONARS_right : 10|10@1+ (1,0) [6|254] "inch" DRIVER | ||
+ | SG_ SENSOR_SONARS_middle : 20|10@1+ (1,0) [6|254] "inch" DRIVER | ||
+ | |||
+ | BO_ 300 MOTOR_CMD: 1 DRIVER | ||
+ | SG_ MOTOR_CMD_steer: 0|4@1- (1,0) [-2|2] "" MOTOR | ||
+ | SG_ MOTOR_CMD_forward: 4|4@1- (1,0) [-5|5] "" MOTOR | ||
+ | |||
+ | BO_ 310 MOTOR_STOP: 1 SENSOR | ||
+ | SG_ MOTOR_STOP_stop: 0|1@1+ (1,0) [0|0] "" MOTOR | ||
+ | |||
+ | BO_ 400 GPS_NAV: 2 GEO | ||
+ | SG_ GPS_NAV_latitude : 0|8@1- (1,0) [-90|90] "" DRIVER | ||
+ | SG_ GPS_NAV_longitude : 8|8@1- (1,0) [-180|180] "" DRIVER | ||
+ | |||
+ | BO_ 420 GPS_HEADING: 4 SENSOR | ||
+ | SG_ GPS_HEADING_RAW_DEGREES: 0|16@1+ (1,0) [0|0] "Degrees" GEO | ||
+ | |||
+ | BO_ 430 GEO_STATUS: 4 GEO | ||
+ | SG_ GEO_STATUS_COMPASS_HEADING : 0|5@1+ (1,0) [0|18] "Degrees" DRIVER | ||
+ | SG_ GEO_STATUS_COMPASS_BEARING : 5|5@1+ (1,0) [0|18] "Degrees" DRIVER | ||
+ | SG_ GEO_STATUS_DISTANCE_TO_DESTINATION : 10|16@1+ (0.1,0) [0|0] "Meters" DRIVER | ||
+ | |||
+ | BO_ 450 GPS_DESTINATION_LOCATION: 8 DRIVER | ||
+ | SG_ GPS_DEST_LATITUDE_SCALED_100000 : 0|32@1- (1,0) [0|0] "Degrees" GEO | ||
+ | SG_ GPS_DEST_LONGITUDE_SCALED_100000 : 32|32@1- (1,0) [0|0] "Degrees" GEO | ||
+ | |||
+ | BO_ 600 DBG_MSG_MOTOR: 4 MOTOR | ||
+ | SG_ SPEED_M_PER_S : 0|32@1+ (0.001,-100) [0|0] "" SENSOR | ||
+ | |||
+ | BO_ 700 DBG_MSG_GPS: 3 GEO | ||
+ | SG_ DBG_GPS_latitude : 0|8@1- (1,0) [-90|90] "" DBG | ||
+ | SG_ DBG_GPS_longitude : 8|8@1- (1,0) [-180|180] "" DBG | ||
+ | SG_ DBG_GPS_lock : 16|1@1+ (1,0) [0|0] "" DBG | ||
<HR> | <HR> | ||
<BR/> | <BR/> | ||
== Sensor and Bridge Controller ECU == | == Sensor and Bridge Controller ECU == | ||
− | + | [[File:teamxsensors.jpg|500px]] [[File:bluetoothmodule.jpg|400px]] | |
+ | |||
+ | [https://gitlab.com/ashley.n.ho/sjtwo-c/-/tree/master/projects/sensor_node?ref_type=heads Gitlab Sensor and Bridge Controller Node Link] | ||
+ | |||
+ | The sensor node utilized the 10Hz to handle message transmission and reception. Meanwhile, the 1Hz periodics receives the sensor data directly from the utrasonic sensor modules. (see Software Design for more details) | ||
− | + | <syntaxhighlight lang="c"> | |
+ | void periodic_callbacks__1Hz(uint32_t callback_count) { | ||
+ | if (callback_count == 0) { | ||
+ | delay__us(450000); // start up delay | ||
+ | return; | ||
+ | } | ||
+ | ultra_sonic_sensor_data_s data; | ||
+ | ultrasonic_sensor__run_once(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | void periodic_callbacks__10Hz(uint32_t callback_count) { | ||
+ | sensors__transmit_once(); | ||
+ | bridge_get_data(); | ||
+ | sensor_msg_bank__handle_msg(); | ||
+ | heading_sensor_run_once(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
=== Hardware Design === | === Hardware Design === | ||
+ | [[File:sensor_design.png|600px]] | ||
=== Software Design === | === Software Design === | ||
− | + | [[File:Sw_design_teamx.png]] | |
+ | |||
+ | The ultrasonic get sensor data task occurs in the 1hz, but we range 8 times in the 1hz function. The 3 ultrasonic sensors are chained together to prevent crosstalk. The SJ2 board will send a trigger signal to the left sensor which will then trigger the middle sensor, then the left. This process repeats 8 times in 1 second. Due to the chaining, the sample rate is significantly reduced, but the incoming data for each sensor is more accurate. Without the chaining, the sensor readings appear to be unstable. | ||
+ | |||
+ | The bridge task is responsible for receiving data from the APP via bluetooth. We utilize a Adafruit module (see above for part) which acts as a uart-bluetooth bridge making it extremely easy to integrate into our system without diving too deep into making bluetooth drivers. The main messages we receive are the GPS destination coordinates, and an emergency stop request. | ||
+ | |||
+ | The emergency stop task is a task that is constantly sending a "stop" flag. This flag is false by default and only set true if received from the APP. Once the vehicle stops, our the sensor node must be manually reset to continue operation. | ||
+ | |||
+ | ==== Sensor Modules ==== | ||
+ | |||
+ | <syntaxhighlight lang="c"> | ||
+ | void ultrasonic_sensor__run_once() { | ||
+ | // left, middle, right respectively | ||
+ | for (int i = 0; i < 8; i++) { | ||
+ | uint16_t adc_raw[3]; | ||
+ | |||
+ | // start range and wait till all sensors are done | ||
+ | ultrasonic_range_once(); | ||
+ | |||
+ | adc_raw[0] = adc__get_adc_value(ADC__CHANNEL_2); | ||
+ | adc_raw[1] = adc__get_adc_value(ADC__CHANNEL_4); | ||
+ | adc_raw[2] = adc__get_adc_value(ADC__CHANNEL_5); | ||
+ | |||
+ | // printf("adc2: %d\n", adc_raw[0]); | ||
+ | sensor_data.left = ((float)adc_raw[0] * SCALE_FACTOR); // / 2.0; | ||
+ | sensor_data.middle = ((float)adc_raw[1] * SCALE_FACTOR); // / 2.0; | ||
+ | sensor_data.right = ((float)adc_raw[2] * SCALE_FACTOR); // / 2.0; | ||
+ | |||
+ | if (sensor_data.left < 36) { | ||
+ | gpio__reset(board_io__get_led3()); | ||
+ | } else { | ||
+ | gpio__set(board_io__get_led3()); | ||
+ | } | ||
+ | |||
+ | if (sensor_data.middle < 36) { | ||
+ | gpio__reset(board_io__get_led2()); | ||
+ | } else { | ||
+ | gpio__set(board_io__get_led2()); | ||
+ | } | ||
+ | |||
+ | if (sensor_data.right < 36) { | ||
+ | gpio__reset(board_io__get_led1()); | ||
+ | } else { | ||
+ | gpio__set(board_io__get_led1()); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | ==== Bridge Controller ==== | ||
+ | <syntaxhighlight lang="c"> | ||
+ | void bridge_get_data(void) { | ||
+ | char byte; | ||
+ | const uint32_t zero_timeout = 0; | ||
+ | |||
+ | while (uart__get(bridge_uart, &byte, zero_timeout)) { | ||
+ | printf("received byte: %c\n", byte); | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang="c"> | ||
+ | void bridge_send_data(void *buf, uint8_t buf_size, uint8_t msg_id) { | ||
+ | // Format the float value from the buffer | ||
+ | char tx_buf[30]; | ||
+ | if (msg_id == 0) { | ||
+ | float speed = *(float *)buf; | ||
+ | snprintf(tx_buf, sizeof(tx_buf), "spd: %f\n", (double)speed); | ||
+ | } else if (msg_id == 1) { | ||
+ | dbc_GEO_STATUS_s *msg = (dbc_GEO_STATUS_s *)buf; | ||
+ | snprintf(tx_buf, sizeof(tx_buf), "hd: %d, br: %d\n", msg->GEO_STATUS_COMPASS_HEADING, | ||
+ | msg->GEO_STATUS_COMPASS_BEARING); | ||
+ | } | ||
+ | uart_printf(bridge_uart, "%s", tx_buf); | ||
+ | // printf("sent: %s\n", tx_buf); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang="c"> | ||
+ | static void process_uart_data_buf(void) { | ||
+ | int temp; | ||
+ | char *token; | ||
+ | int coord_received = 0; | ||
+ | |||
+ | token = strtok(uart_rx_buf, ","); | ||
+ | temp = atoi(token); | ||
+ | if (temp != 0) { | ||
+ | dest_latitude = temp / 1000000.0f; | ||
+ | printf("la: %f ", (double)dest_latitude); | ||
+ | coord_received++; | ||
+ | } | ||
+ | |||
+ | token = strtok(NULL, ","); | ||
+ | temp = atoi(token); | ||
+ | if (temp != 0) { | ||
+ | dest_longitude = temp / 1000000.0f; | ||
+ | printf("lo: %f\n", (double)dest_longitude); | ||
+ | coord_received++; | ||
+ | } | ||
+ | if (coord_received == 2) { | ||
+ | dbc_GPS_DESTINATION_LOCATION_s dest_location; | ||
+ | dest_location.GPS_DEST_LATITUDE_SCALED_100000 = dest_latitude * 100000; | ||
+ | dest_location.GPS_DEST_LONGITUDE_SCALED_100000 = dest_longitude * 100000; | ||
+ | can__msg_t can_msg = {}; | ||
+ | dbc_message_header_t header; | ||
+ | header = dbc_encode_GPS_DESTINATION_LOCATION(can_msg.data.bytes, &dest_location); | ||
+ | |||
+ | can_msg.msg_id = header.message_id; | ||
+ | can_msg.frame_fields.data_len = header.message_dlc; | ||
+ | can__tx(can1, &can_msg, 0); | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
=== Technical Challenges === | === Technical Challenges === | ||
− | + | Our main problems with the sensors occurred once we began outdoor testing. When testing indoors, we encountered no issues with the sensors incorrectly detecting obstacles. However, when moving outdoors, the sensors would detect the ground; thus, we resolved the issue by re-mounting the sensors at an angle in order to avoid detecting the ground. Additionally, we found that when initially calibrating the sensors on startup, there must not be any objects in its way for proper calibration, otherwise we would run into undefined behavior. | |
− | |||
<HR> | <HR> | ||
Line 344: | Line 561: | ||
== Motor ECU == | == Motor ECU == | ||
− | + | [[File:Motormodule.jpg|500px]] | |
− | + | [https://gitlab.com/ashley.n.ho/sjtwo-c/-/tree/master/projects/motor_node?ref_type=heads Gitlab Motor Node Link] | |
+ | |||
+ | The motor node utilized the 10Hz to handle message transmission and reception as well as for setting the PWM value. Meanwhile, the 100Hz periodics processed the inputs and transferred the data received to their respective local data structures (see Software Design for more details). | ||
+ | |||
+ | <syntaxhighlight lang="c"> | ||
+ | void periodic_callbacks__10Hz(uint32_t callback_count) { | ||
+ | motor_msg_bank__handle_msg(); | ||
+ | motor_msg_bank__service_mia_10hz(); | ||
+ | motor_pwm__set_pwm(); | ||
+ | if (callback_count % 7 == 0) { | ||
+ | motor_rpm_driver_calc_speed(); | ||
+ | } | ||
+ | motor_speed_pid_run_once(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | void periodic_callbacks__100Hz(uint32_t callback_count) { | ||
+ | motor_pwm__process_input(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
=== Hardware Design === | === Hardware Design === | ||
+ | |||
+ | The motor is directly connected to the RC car's ESC device, which is what initially controlled the car's PWMs prior to hijacking. The SJ2 now becomes the PWM transmitter as opposed to the remote and sends the corresponding PWMs based on driver signals (see Software Design for more details) | ||
+ | |||
+ | [[File:motornode.png|600px]] | ||
=== Software Design === | === Software Design === | ||
− | + | ||
+ | The motor software takes in driver-motor commands through the CAN bus and based on those commands, modifies the PWMs of the motor and the servo to move the wheels forward, backward, left, or right. We mapped the PWM values (See tables below). | ||
+ | |||
+ | {| class="wikitable" | ||
+ | |- | ||
+ | ! scope="col"| | ||
+ | ! scope="col"| Motor PWM | ||
+ | ! scope="col"| Direction | ||
+ | |- | ||
+ | ! scope="row"| 1 | ||
+ | | 16.2 | ||
+ | | Forward | ||
+ | |- | ||
+ | ! scope="row"| 2 | ||
+ | | 14.5 | ||
+ | | Backward | ||
+ | |- | ||
+ | ! scope="row"| 3 | ||
+ | | 15.02 | ||
+ | | Idle | ||
+ | |- | ||
+ | |} | ||
+ | {| class="wikitable" | ||
+ | |- | ||
+ | ! scope="col"| | ||
+ | ! scope="col"| Servo PWM | ||
+ | ! scope="col"| Direction | ||
+ | |- | ||
+ | ! scope="row"| 1 | ||
+ | | 11.0 | ||
+ | | Hard Left | ||
+ | |- | ||
+ | ! scope="row"| 2 | ||
+ | | 13.0 | ||
+ | | Slight Left | ||
+ | |- | ||
+ | ! scope="row"| 3 | ||
+ | | 15.48 | ||
+ | | Straight | ||
+ | |- | ||
+ | ! scope="row"| 4 | ||
+ | | 17.0 | ||
+ | | Slight Right | ||
+ | |- | ||
+ | ! scope="row"| 5 | ||
+ | | 19.0 | ||
+ | | Hard Right | ||
+ | |- | ||
+ | |} | ||
+ | |||
+ | Additionally, we utilized a general state machine that allowed for fluid transitions between forward and reverse (see diagram below). Without a delay in a neutral state, the car's motor would not be able to easily transition from forward to reverse and vice versa, but would rather just stop. As such, we implemented the diagram in the code below and thus allowed for the car to easily transition between the states of forward and reverse. | ||
+ | |||
+ | [[File:motor_states.png|400px]] | ||
+ | |||
+ | <syntaxhighlight lang="c"> | ||
+ | void motor_pwm__set_pwm(void) { | ||
+ | motor_pwm__set_motor_pwm(); | ||
+ | motor_pwm__set_servo_pwm(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | static void motor_pwm__set_servo_pwm(void) { | ||
+ | static float set_servo_duty_cycle = servo_pwm_idle_duty_cycle; | ||
+ | |||
+ | if (motor_cmd_local.MOTOR_CMD_steer == 0) { | ||
+ | // idle | ||
+ | set_servo_duty_cycle = servo_pwm_idle_duty_cycle; | ||
+ | } else if (motor_cmd_local.MOTOR_CMD_steer == 1) { | ||
+ | // slightly right | ||
+ | set_servo_duty_cycle = 17.00; | ||
+ | } else if (motor_cmd_local.MOTOR_CMD_steer == 2) { | ||
+ | // max right | ||
+ | set_servo_duty_cycle = 19.00; | ||
+ | } else if (motor_cmd_local.MOTOR_CMD_steer == -1) { | ||
+ | // slightly left | ||
+ | set_servo_duty_cycle = 13.00; | ||
+ | } else if (motor_cmd_local.MOTOR_CMD_steer == -2) { | ||
+ | // max left | ||
+ | set_servo_duty_cycle = 11.00; | ||
+ | } | ||
+ | |||
+ | pwm1__set_duty_cycle(servo_pwm, set_servo_duty_cycle); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | static void motor_pwm__set_motor_pwm(void) { | ||
+ | static float set_motor_duty_cycle = motor_pwm_idle_duty_cycle; | ||
+ | |||
+ | if (motor_stop_local.MOTOR_STOP_stop) { | ||
+ | motor_speed_pid_set_target_pwm(motor_pwm_idle_duty_cycle); | ||
+ | } else { | ||
+ | if (!ignore_cmds) { | ||
+ | if (motor_cmd_local.MOTOR_CMD_forward == -1) { // Reverse | ||
+ | set_motor_duty_cycle = 14.50; | ||
+ | if (reverse_flag == false) { | ||
+ | motor_speed_pid_set_target_pwm(motor_pwm_idle_duty_cycle); | ||
+ | ignore_cmds = true; | ||
+ | start_time = sys_time__get_uptime_ms(); | ||
+ | reverse_flag = true; | ||
+ | return; | ||
+ | } | ||
+ | } else if (motor_cmd_local.MOTOR_CMD_forward == 0) { // Stop | ||
+ | set_motor_duty_cycle = motor_pwm_idle_duty_cycle; | ||
+ | } else if (motor_cmd_local.MOTOR_CMD_forward == 3) { // Forward | ||
+ | set_motor_duty_cycle = 16.2; // 15.7 originally?, 16.2 | ||
+ | |||
+ | if (reverse_flag == true) { | ||
+ | motor_speed_pid_set_target_pwm(motor_pwm_idle_duty_cycle); | ||
+ | ignore_cmds = true; | ||
+ | start_time = sys_time__get_uptime_ms(); | ||
+ | reverse_flag = false; | ||
+ | return; | ||
+ | } | ||
+ | } | ||
+ | motor_speed_pid_set_target_pwm(set_motor_duty_cycle); | ||
+ | } else if (sys_time__get_uptime_ms() - start_time >= DIRECTION_CHANGE_DELAY) { | ||
+ | ignore_cmds = false; | ||
+ | } else { | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
=== Technical Challenges === | === Technical Challenges === | ||
− | + | The main issue we had with the motor controller occurred during PWM hacking because we did not want the motor running the car too fast. As such, we had to guess and check a good PWM value to run the motor so that the car would move at the slowest speed possible without running into issues where it could not move. However, with continual tests, we managed to identify the ideal range we wanted to run the motor. | |
+ | |||
+ | Additionally, we encountered minor issues where, when transitioning from reverse to forward and vice versa, the car would go into neutral and never exit from the neutral state. We found that this issue occurred due to the delay being too small, and so the motor would not have enough time to truly go into neutral and thus would remain in that state. To counter this, we increased the delay and also slightly increased the forward PWM in order to combat the potential that it was stopping due to having too low of a PWM value. | ||
<HR> | <HR> | ||
Line 362: | Line 725: | ||
== Geographical Controller == | == Geographical Controller == | ||
− | + | [[File:Gpsmodule.jpg|400px]] [[File:Compassmodule.jpg|500px]] | |
− | + | [https://gitlab.com/ashley.n.ho/sjtwo-c/-/tree/master/projects/geo_node?ref_type=heads Gitlab Geo Node Link] | |
+ | |||
+ | The Geo node utilized the 10Hz to handle message transmission and reception as well as receiving the compass and GPS data directly from the hardware modules. Meanwhile, the 1Hz periodics processed the GPS lock and would toggle the LED on the SJ2 board accordingly (see Software Design for more details). | ||
+ | |||
+ | <syntaxhighlight lang = "c"> | ||
+ | void periodic_callbacks__1Hz(uint32_t callback_count) { | ||
+ | int gps_lock_status = geo_sensors_gps__get_gps_lock_status(); | ||
+ | // printf("GPS lock status: %d\n", gps_lock_status); | ||
+ | if (!gps_lock_status) { | ||
+ | gpio__toggle(board_io__get_led0()); | ||
+ | } else { | ||
+ | gpio__reset(board_io__get_led0()); | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang = "c"> | ||
+ | void periodic_callbacks__10Hz(uint32_t callback_count) { | ||
+ | |||
+ | geo_msg_bank__handle_msg(); | ||
+ | geo_msg_bank__service_mia_10hz(); | ||
+ | geo_msg_bank__transmit_msg(); | ||
+ | |||
+ | geo_sensors_gps__run_once(); | ||
+ | // geo_sensors_compass_lsm__run_once(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
=== Hardware Design === | === Hardware Design === | ||
+ | |||
+ | [[File: Geo_HW.png]] | ||
=== Software Design === | === Software Design === | ||
− | < | + | |
+ | [[File:geo_periodics.png]] | ||
+ | |||
+ | ==== GPS ==== | ||
+ | |||
+ | <syntaxhighlight lang = "c"> | ||
+ | bool geo_sensors_gps__run_once(void) { | ||
+ | bool gps_transfer_success = false; | ||
+ | |||
+ | gps_transfer_success = geo_sensors_gps__transfer_data_from_uart_driver_to_line_buffer(); | ||
+ | gps__parse_coordinates_from_line(); | ||
+ | |||
+ | return gps_transfer_success; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang = "c"> | ||
+ | bool geo_sensors_gps__transfer_data_from_uart_driver_to_line_buffer(void) { | ||
+ | char byte_read; | ||
+ | const uint32_t zero_timeout = 0; | ||
+ | bool gps_status_reading = false; | ||
+ | |||
+ | while (uart__get(uart_gps, &byte_read, zero_timeout)) { | ||
+ | gps_status_reading = true; | ||
+ | line_buffer__add_byte(&line, byte_read); | ||
+ | } | ||
+ | |||
+ | return gps_status_reading; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang = "c"> | ||
+ | static void gps__parse_coordinates_from_line(void) { | ||
+ | char gps_line[1000]; | ||
+ | if (line_buffer__remove_line(&line, gps_line, sizeof(gps_line))) { | ||
+ | // Check if the line is a GPGGA stream | ||
+ | if (strncmp(gps_line, "$GPGGA,", 7) == 0) { | ||
+ | char *token; | ||
+ | int field_idx = 0; | ||
+ | int latitude_flag = 1; | ||
+ | int longitude_flag = 1; | ||
+ | float latitude = 0.0; | ||
+ | float longitude = 0.0; | ||
+ | |||
+ | token = strtok(gps_line, ","); | ||
+ | while (token != NULL) { | ||
+ | token = strtok(NULL, ","); | ||
+ | field_idx++; | ||
+ | |||
+ | if (field_idx == 2) { // Latitude is field 2 in GPGGA | ||
+ | latitude = atof(token); | ||
+ | } else if (field_idx == 3) { // N/S direction is field 3 in GPGGA | ||
+ | char c = token[0]; | ||
+ | if (c == 'S') { | ||
+ | latitude_flag *= -1; | ||
+ | } | ||
+ | } else if (field_idx == 4) { // Longitude is field 4 in GPGGA | ||
+ | longitude = atof(token); | ||
+ | } else if (field_idx == 5) { // E/W direction is field 5 in GPGGA | ||
+ | char c = token[0]; | ||
+ | if (c == 'W') { | ||
+ | longitude_flag *= -1; | ||
+ | } | ||
+ | } else if (field_idx == 6) { | ||
+ | char c = token[0]; | ||
+ | // printf("GPS QUALITY: %c\n", c); | ||
+ | if (c == '0') { | ||
+ | gps_quality = 0; | ||
+ | } else if (c == '1') { | ||
+ | gps_quality = 1; | ||
+ | // printf("GPS lock successful\n"); | ||
+ | } else { | ||
+ | // printf("Trying to acquire GPS fix\n"); | ||
+ | } | ||
+ | } else if (field_idx > 6) { | ||
+ | break; | ||
+ | } | ||
+ | } | ||
+ | |||
+ | int latitude_days = latitude / 100; | ||
+ | int longitude_days = longitude / 100; | ||
+ | float latitude_minutes = latitude - 3700.00; | ||
+ | float longitude_minutes = longitude - 12100.00; | ||
+ | |||
+ | latitude_minutes /= 60; | ||
+ | longitude_minutes /= 60; | ||
+ | |||
+ | parsed_coordinates.latitude = ((1.0 * latitude_days) + latitude_minutes) * latitude_flag; | ||
+ | parsed_coordinates.longitude = ((1.0 * longitude_days) + longitude_minutes) * longitude_flag; | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | ==== Compass Module ==== | ||
+ | <syntaxhighlight lang = "c"> | ||
+ | void geo_sensors_compass_lsm__run_once(void) { geo_sensors_compass__read(); } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang = "c"> | ||
+ | void geo_sensors_compass__read(void) { | ||
+ | uint8_t buffer[6]; | ||
+ | float mag[3]; | ||
+ | |||
+ | i2c__read_slave_data(current_i2c, magnetometer_read, LSM303AGR_MAG_OUTX_L_REG, buffer, 6); | ||
+ | |||
+ | mag[0] = (int16_t)(buffer[1] << 8 | buffer[0]); | ||
+ | mag[1] = (int16_t)(buffer[3] << 8 | buffer[2]); | ||
+ | mag[2] = (int16_t)(buffer[5] << 8 | buffer[4]); | ||
+ | |||
+ | geo_sensors_compass__calculate_heading(mag); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang = "c"> | ||
+ | static void geo_sensors_compass__calculate_heading(float mag[3]) { | ||
+ | float magnitude = sqrtf(mag[0] * mag[0] + mag[1] * mag[1] + mag[2] * mag[2]); | ||
+ | |||
+ | const float epsilon = 1e-6; | ||
+ | if (magnitude < epsilon) { | ||
+ | current_compass_heading = 0; | ||
+ | |||
+ | } else { | ||
+ | float mag_xy = mag[1] / magnitude; | ||
+ | float mag_xx = mag[0] / magnitude; | ||
+ | current_compass_heading = (atan2(mag_xy, mag_xx)) * 180.0 / PI; | ||
+ | |||
+ | if (current_compass_heading < 0) { | ||
+ | current_compass_heading = 360 + current_compass_heading; | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ==== Haversine Algorithm ==== | ||
+ | |||
+ | In the provided function, we use the Haversine algorithm to calculate the shortest distance between two geographical points on Earth, identified by their latitude and longitude. We start by converting these coordinates from degrees to radians and then apply the Haversine formula to determine the distance. Additionally, we calculate the bearing and heading from the current location to the destination. | ||
+ | |||
+ | <syntaxhighlight lang = "c"> | ||
+ | void geo_logic__haversine_calculation(void) { | ||
+ | // Input: Latitude longitude, Output: heading, bearing, distance to destination | ||
+ | gps_coordinates_t current_gps = geo_sensors_gps__get_coordinates(); | ||
+ | float current_latitude = current_gps.latitude; | ||
+ | float current_longitude = current_gps.longitude; | ||
+ | |||
+ | gps_coordinates_t destination_gps = geo_msg_bank__get_gps_destination_location(); | ||
+ | float destination_latitude = destination_gps.latitude; | ||
+ | float destination_longitude = destination_gps.longitude; | ||
+ | |||
+ | // Convert latitudes and longitudes from degrees to radians | ||
+ | float phi1 = (float)(current_latitude * (float)PI_VAL / (float)180.0); | ||
+ | float phi2 = (float)(destination_latitude * PI_VAL / (float)180.0); | ||
+ | float delta_phi = (float)(destination_latitude - current_latitude) * PI_VAL / (float)180.0; | ||
+ | float delta_lambda = (float)(destination_longitude - current_longitude) * PI_VAL / (float)180.0; | ||
+ | |||
+ | // Haversine formula | ||
+ | float a = | ||
+ | sin(delta_phi / 2) * sin(delta_phi / 2) + cos(phi1) * cos(phi2) * sin(delta_lambda / 2) * sin(delta_lambda / 2); | ||
+ | float c = 2 * atan2(sqrt(a), sqrt(1 - a)); | ||
+ | distance_to_destination = RADIUS_EARTH_KM * c * 1000; | ||
+ | |||
+ | // Bearing calculation | ||
+ | float y = sin(delta_lambda) * cos(phi2); | ||
+ | float x = cos(phi1) * sin(phi2) - sin(phi1) * cos(phi2) * cos(delta_lambda); | ||
+ | float bearing_rad = atan2(y, x); | ||
+ | compass_bearing = fmod((bearing_rad * (float)180.0 / (float)PI_VAL + (float)360.0), 360.0); | ||
+ | |||
+ | compass_heading = geo_msg_bank__get_heading(); | ||
+ | |||
+ | current_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION = distance_to_destination; | ||
+ | current_geo_status.GEO_STATUS_COMPASS_BEARING = (uint8_t)(compass_bearing / 20); | ||
+ | current_geo_status.GEO_STATUS_COMPASS_HEADING = (uint8_t)(compass_heading); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ==== Checkpoint Algorithm ==== | ||
+ | The checkpoint algorithm is a very simple algo that provides the next "checkpoint" to drive to given the current location and destination coordinates. We first try to find the closest checkpoint, and if it brings us closer to the final destination, then travel to that checkpoint. We repeat this process until no checkpoint can bring us closer and the destination is the final "checkpoint." We use the haversine algorithm to determine how close we are to a checkpoint so that we know we reached it, otherwise we may circle back around to it. | ||
+ | |||
+ | If no checkpoints are provided in the list, then the car will attempt to navigate to the final destination directly which will likely be very challenging for large obstacles in the path. Initially, we used Euclidian distance to find the closest checkpoint, but raw distance calculated from that formula is not very easy to understand, so we switch to using haversine to get distance in meters. | ||
+ | |||
+ | <syntaxhighlight lang = "c"> | ||
+ | |||
+ | gps_coordinates_t find_next_point(gps_coordinates_t origin, gps_coordinates_t destination) { | ||
+ | gps_coordinates_t closest_point; | ||
+ | float min_distance = FLT_MAX; | ||
+ | float distance; | ||
+ | int checkpoint_idx = -1; | ||
+ | |||
+ | for (int i = 0; i < NUM_OF_CHECKPOINTS; i++) { | ||
+ | distance = get_distance_between_points(origin, locations_we_can_travel[i]); | ||
+ | if (distance < min_distance) { | ||
+ | if (get_distance_between_points(origin, locations_we_can_travel[i]) < 5) { | ||
+ | printf("reached checkpoint\n"); | ||
+ | continue; | ||
+ | } | ||
+ | // Check if point is actually closer to destincation | ||
+ | if (get_distance_between_points(locations_we_can_travel[i], destination) < | ||
+ | get_distance_between_points(origin, destination)) { | ||
+ | min_distance = distance; | ||
+ | checkpoint_idx = i; | ||
+ | printf("setting checkpoint\n"); | ||
+ | } else { | ||
+ | continue; | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | if (checkpoint_idx < 0) { | ||
+ | closest_point = destination; | ||
+ | printf("Going destination\n"); | ||
+ | } else { | ||
+ | printf("setting closest_point\n"); | ||
+ | closest_point = locations_we_can_travel[checkpoint_idx]; | ||
+ | } | ||
+ | printf("p: %f, %f", closest_point.latitude, closest_point.longitude); | ||
+ | return closest_point; | ||
+ | } | ||
+ | |||
+ | </syntaxhighlight> | ||
=== Technical Challenges === | === Technical Challenges === | ||
− | + | Most of our problems occurred due to an inaccurate compass reading. Mainly, the compass heading angles would not return as very stable values, which resulted in unstable driving behavior for the car. We initially thought it would resolve itself with some software calibration; however, we found that even with software calibration for the LSM, it would still be inaccurate and would not even give the full 360 degree heading range. As such, we resolved to simply buying a more expensive and more accurate magnetometer, which solved our issues. The new module returned more stable values, despite it still fluctuating, the angle changing was not enough to affect the driving behavior since we built our module with the intent of not needing the exact degree of the angles. We also found some trouble mounting the compass due to not wanting to have to handle any further offsets after mounting. Because of this, when mounting the compass, we identified where the compass was detecting north and faced the front of the car in that direction. Following that step, we mounted the compass so that it, along with the front of the car, was facing north. | |
+ | |||
+ | Additionally, we ran into some errors with the GPS module due to us receiving latitude and longitude values that were miles away from our current location. However, we identified an error on our end where we had misinterpreted the data returned from the GPS module and thus were calculating the wrong latitude and longitude values. Once we identified the error, we found the correct way to extract the correct latitude and longitude values for a more accurate location. | ||
<HR> | <HR> | ||
Line 379: | Line 988: | ||
== Driver and LCD Module == | == Driver and LCD Module == | ||
+ | [[File:LCDmodule.jpg|500px]] | ||
+ | |||
+ | |||
+ | [https://gitlab.com/ashley.n.ho/sjtwo-c/-/tree/master/projects/driver_node?ref_type=heads Gitlab Driver & LCD Node Link] | ||
− | + | The driver node utilized the 10Hz to handle message transmission and reception as well as setting the LCD display for status updates and motor commands. Meanwhile, the 100Hz periodics processed the inputs and transferred the data received to their respective local data structures (see Software Design for more details). | |
− | + | <syntaxhighlight lang="c"> | |
+ | void periodic_callbacks__10Hz(uint32_t callback_count) { | ||
+ | driver_msg_bank__handle_msg(); | ||
+ | driver_msg_bank__service_mia_10hz(); | ||
+ | driver_msg_bank__transmit_msg(); | ||
+ | i2c_lcd__clear(); | ||
+ | driver__lcd_display_data(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang="c"> | ||
+ | void periodic_callbacks__100Hz(uint32_t callback_count) { | ||
+ | driver__process_input(); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
=== Hardware Design === | === Hardware Design === | ||
+ | The driver node, aside from its connection to the CAN bus, is also connected the the LCD module through I2C. the SJ2 board provides the LCD with 3.3V power and sends data through SDA and SCL. | ||
+ | |||
+ | [[File:driverLCD.png|500px]] | ||
=== Software Design === | === Software Design === | ||
− | < | + | |
+ | ==== Driver Logic ==== | ||
+ | The driver logic came down to a basic logic (shown in table below) where 0 implies there is no obstacle, and 1 implies an obstacle is present. Depending on each combination of 1's and 0's, the car would determine whether to turn left or right and move forward or backward. | ||
+ | |||
+ | [[File:driverlogic.png|500px]] | ||
+ | |||
+ | <syntaxhighlight lang="c"> | ||
+ | dbc_MOTOR_CMD_s driver__get_motor_commands(void) { | ||
+ | driver__avoid_obstacle(); | ||
+ | return motor_commands;} | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | static void driver__avoid_obstacle(void) { | ||
+ | obstacle_below_threshold_s below_thresholds = driver__closest_obstacle(); | ||
+ | |||
+ | if (!(below_thresholds.MIDDLE) && !(below_thresholds.LEFT) && !(below_thresholds.RIGHT)) { | ||
+ | driver__go_to_destination(); | ||
+ | } else { | ||
+ | driver__steering(); | ||
+ | } | ||
+ | driver__led_indicators();} | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | dbc_MOTOR_CMD_s driver__get_motor_commands(void) { | ||
+ | driver__avoid_obstacle(); | ||
+ | return motor_commands; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | // slight turns for destination movement | ||
+ | static void driver__go_to_destination(void) { | ||
+ | int angle_difference = local_geo_status.GEO_STATUS_COMPASS_HEADING - local_geo_status.GEO_STATUS_COMPASS_BEARING; | ||
+ | if (local_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION > 0) { | ||
+ | if (angle_difference > 0) { | ||
+ | // go right | ||
+ | motor_commands.MOTOR_CMD_steer = 1; | ||
+ | motor_commands.MOTOR_CMD_forward = 3; | ||
+ | } else if (angle_difference < 0) { | ||
+ | // go left | ||
+ | motor_commands.MOTOR_CMD_steer = -1; | ||
+ | motor_commands.MOTOR_CMD_forward = 3; | ||
+ | } else { // go straight | ||
+ | motor_commands.MOTOR_CMD_steer = 0; | ||
+ | motor_commands.MOTOR_CMD_forward = 3; | ||
+ | } | ||
+ | } else { // reached destination | ||
+ | motor_commands.MOTOR_CMD_forward = 0; | ||
+ | motor_commands.MOTOR_CMD_steer = 0; | ||
+ | }} | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | ==== LCD Logic ==== | ||
+ | |||
+ | The LCD printout relied solely on the datasheet. However, some optimizations were made in order to simplify the LCD methods. Specifically the starting_position() function allowed for eash access to each line of the LCD's printout without needing to write data to the addresses every time we wanted to print onto a specific line. Additionally, the lcd__printf() was a minor optimization to allow for us to print a string rather than per character and calling the send_data() function for every character. | ||
+ | |||
+ | <syntaxhighlight lang="c"> | ||
+ | void driver__lcd_display_data(void) { | ||
+ | char debug_str[15]; | ||
+ | |||
+ | if (local_motor_stop.MOTOR_STOP_stop) { | ||
+ | i2c_lcd__clear(); | ||
+ | i2c_lcd__starting_position(0, 0); | ||
+ | i2c_lcd__printf(" MOTOR STOPPED!"); | ||
+ | i2c_lcd__starting_position(1, 0); | ||
+ | i2c_lcd__printf(" PLS RESTART BRIDGE"); | ||
+ | i2c_lcd__starting_position(1, 0); | ||
+ | i2c_lcd__printf(" TO CONTINUE"); | ||
+ | } else if (local_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION) { | ||
+ | sprintf(debug_str, "%.1lf", local_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION); | ||
+ | |||
+ | i2c_lcd__starting_position(0, 0); | ||
+ | i2c_lcd__printf(" PROJECT TEAM X"); | ||
+ | |||
+ | i2c_lcd__starting_position(1, 0); | ||
+ | i2c_lcd__printf("Distance:"); | ||
+ | i2c_lcd__starting_position(1, 10); | ||
+ | i2c_lcd__printf(debug_str); | ||
+ | |||
+ | sprintf(debug_str, "%d", (int)local_geo_status.GEO_STATUS_COMPASS_HEADING); | ||
+ | i2c_lcd__starting_position(2, 0); | ||
+ | i2c_lcd__printf(" Heading:"); | ||
+ | i2c_lcd__starting_position(2, 13); | ||
+ | i2c_lcd__printf(debug_str); | ||
+ | |||
+ | sprintf(debug_str, "%d", (int)local_geo_status.GEO_STATUS_COMPASS_BEARING); | ||
+ | i2c_lcd__starting_position(3, 0); | ||
+ | i2c_lcd__printf(" Bearing:"); | ||
+ | i2c_lcd__starting_position(3, 13); | ||
+ | i2c_lcd__printf(debug_str); | ||
+ | } else if (local_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION < 2) { | ||
+ | i2c_lcd__clear(); | ||
+ | i2c_lcd__starting_position(1, 0); | ||
+ | i2c_lcd__printf("DESTINATION REACHED!"); | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | void i2c_lcd__printf(char *line) { | ||
+ | while (*line) | ||
+ | i2c_lcd__send_data(*line++); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <syntaxhighlight lang="c"> | ||
+ | void i2c_lcd__starting_position(uint8_t y, uint8_t x) { | ||
+ | |||
+ | char Starting_Addr = 0x80; | ||
+ | switch (y) { | ||
+ | case 0: | ||
+ | Starting_Addr |= 0x00; | ||
+ | break; | ||
+ | case 1: | ||
+ | Starting_Addr |= 0x40; | ||
+ | break; | ||
+ | case 2: | ||
+ | Starting_Addr |= 0x14; | ||
+ | break; | ||
+ | case 3: | ||
+ | Starting_Addr |= 0x54; | ||
+ | break; | ||
+ | default:; | ||
+ | } | ||
+ | |||
+ | Starting_Addr += x; | ||
+ | |||
+ | i2c_lcd__send_command(0x80 | Starting_Addr); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
=== Technical Challenges === | === Technical Challenges === | ||
− | + | Most of the issues surrounding the driver node occurred after field testing. We found there were some issues regarding how soon the driver made the decision compared to when it received the sensor data. As such, we made adjustments so that, despite the delay, there would be time for the driver to receive the sensor data, identify the correct action to take, and then move the wheels. Overall, our driver node worked as expected once we started field testing due to the multitude of unit tests that were done to ensure proper logic. We also identified some minor issues when testing the reverse; however, this was easily fixed by modifying the sensor priorities so that the middle sensor's values, when below the threshold, had the most precedence. In this way, the car would not fluctuate between going forward and reverse when there was clearly an object in front of it. | |
+ | |||
+ | Additionally, we ran into issues integrating the LCD screen through I2C. The screen's slave address would not get detected, despite the device having the proper connections and power supply. However, it was found to have just been a hardware issue and worked with a different I2C LCD device. | ||
<HR> | <HR> | ||
Line 397: | Line 1,155: | ||
== Mobile Application == | == Mobile Application == | ||
− | < | + | [[File:App_flow.png]] |
+ | |||
+ | [https://gitlab.com/ashley.n.ho/sjtwo-c/-/tree/master/mobile_app?ref_type=heads Gitlab Mobile App Node Link ] | ||
+ | |||
+ | === Software Design === | ||
+ | The iOS Mobile App was designed using Swift. The primary purpose of the app was to connect to the Bridge Controller via bluetooth and send GPS destination and emergency stop message and to receive and display geo controller status heading and bearing data. | ||
+ | |||
+ | ==== Scan Bluetooth Devices ==== | ||
+ | |||
+ | |||
+ | <syntaxhighlight lang="swift"> | ||
+ | @IBAction func buttonPressed(_ sender: UIButton) { | ||
+ | print("Scan bluetooth devices Button pressed") | ||
+ | |||
+ | // Start scanning for Bluetooth devices if Bluetooth is turned on | ||
+ | if centralManager.state == .poweredOn { | ||
+ | centralManager.scanForPeripherals(withServices: nil, options: nil) | ||
+ | print("Scanning for Bluetooth devices...") | ||
+ | } else { | ||
+ | print("Bluetooth is not turned on") | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang="swift"> | ||
+ | extension ViewController: CBCentralManagerDelegate { | ||
+ | func centralManagerDidUpdateState(_ central: CBCentralManager) { | ||
+ | switch central.state { | ||
+ | case .poweredOn: | ||
+ | print("Bluetooth is On") | ||
+ | case .poweredOff: | ||
+ | print("Bluetooth is Off") | ||
+ | case .resetting: | ||
+ | print("Bluetooth is Resetting") | ||
+ | case .unauthorized: | ||
+ | print("Bluetooth not authorized") | ||
+ | case .unsupported: | ||
+ | print("Bluetooth not supported") | ||
+ | case .unknown: | ||
+ | print("Bluetooth unknown state") | ||
+ | @unknown default: | ||
+ | print("A new case was added that is not handled") | ||
+ | } | ||
+ | |||
+ | } | ||
+ | |||
+ | func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { | ||
+ | |||
+ | if let name = peripheral.name, name != "Unknown Device" { | ||
+ | // Avoid adding duplicates | ||
+ | if !discoveredDevices.contains(where: { $0.identifier == peripheral.identifier }) { | ||
+ | discoveredDevices.append(peripheral) | ||
+ | DispatchQueue.main.async { [weak self] in self?.displayContent.reloadData() | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | |||
+ | } | ||
+ | func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { | ||
+ | print("Connected to peripheral: \(peripheral)") | ||
+ | |||
+ | selectedPeripheral = peripheral // Make sure to store the reference to the connected didFailToConnectperipheral | ||
+ | peripheral.delegate = self // Set the delegate to self for handling peripheral events | ||
+ | peripheral.discoverServices(nil) | ||
+ | |||
+ | } | ||
+ | |||
+ | func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { | ||
+ | print("Disconnected from peripheral: \(peripheral)") | ||
+ | if let error = error { | ||
+ | print("Error: \(error.localizedDescription)") | ||
+ | } | ||
+ | } | ||
+ | |||
+ | func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { | ||
+ | print("Failed to connect to peripheral: \(peripheral), error: \(error?.localizedDescription ?? "Unknown error")") | ||
+ | |||
+ | // Present an alert to the user with the option to try connecting again | ||
+ | let alert = UIAlertController(title: "Connection Failed", message: "Failed to connect to the selected device. Would you like to try again?", preferredStyle: .alert) | ||
+ | |||
+ | // Add a "Try Again" action to the alert | ||
+ | alert.addAction(UIAlertAction(title: "Try Again", style: .default) { _ in | ||
+ | // Retry connecting to the selected peripheral | ||
+ | central.connect(peripheral, options: nil) | ||
+ | }) | ||
+ | |||
+ | // Add a "Cancel" action to the alert | ||
+ | alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) | ||
+ | |||
+ | // Present the alert | ||
+ | self.present(alert, animated: true, completion: nil) | ||
+ | } | ||
+ | } | ||
+ | |||
+ | </syntaxhighlight> | ||
+ | |||
+ | ==== Set GPS Desination ==== | ||
+ | <syntaxhighlight lang="swift"> | ||
+ | import UIKit | ||
+ | import MapKit | ||
+ | |||
+ | protocol MapViewControllerDelegate: AnyObject { | ||
+ | func didChooseLocation(latitude: Double, longitude: Double) | ||
+ | } | ||
+ | |||
+ | |||
+ | class CustomMapViewController: UIViewController, MKMapViewDelegate { | ||
+ | |||
+ | @IBOutlet weak var mapView: MKMapView! | ||
+ | weak var delegate: MapViewControllerDelegate? | ||
+ | |||
+ | var lastSelectedLatitude: Double? | ||
+ | var lastSelectedLongitude: Double? | ||
+ | |||
+ | override func viewDidLoad() { | ||
+ | super.viewDidLoad() | ||
+ | mapView.delegate = self | ||
− | + | print("Map View loaded!") | |
+ | // Add a tap gesture recognizer to the map view | ||
+ | let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleMapTap(_:))) | ||
+ | mapView.addGestureRecognizer(tapRecognizer) | ||
+ | |||
+ | // Define the center of the region your map should display | ||
+ | // 37.33919199814887, -121.88103575173972 | ||
+ | let center = CLLocationCoordinate2D(latitude: 37.33919199814887, longitude: -121.88103575173972) // SJSU parking lot | ||
+ | |||
+ | // Set the region of the map | ||
+ | let region = MKCoordinateRegion(center: center, span: span) | ||
+ | mapView.setRegion(region, animated: true) | ||
+ | } | ||
− | === | + | @objc func handleMapTap(_ gestureReconizer: UITapGestureRecognizer) { |
+ | let location = gestureReconizer.location(in: mapView) | ||
+ | let coordinate = mapView.convert(location, toCoordinateFrom: mapView) | ||
+ | |||
+ | // Remove all existing annotations | ||
+ | mapView.removeAnnotations(mapView.annotations) | ||
+ | |||
+ | // Add annotation: | ||
+ | let annotation = MKPointAnnotation() | ||
+ | annotation.coordinate = coordinate | ||
+ | mapView.addAnnotation(annotation) | ||
+ | |||
+ | lastSelectedLatitude = coordinate.latitude | ||
+ | lastSelectedLongitude = coordinate.longitude | ||
+ | |||
+ | print("Latitude: \(coordinate.latitude), Longitude: \(coordinate.longitude)") | ||
+ | |||
+ | } | ||
+ | |||
+ | @IBAction func buttonPressed(_ sender: UIButton) { | ||
+ | print("Sending GPS destination location to Bridge Controller!") | ||
+ | |||
+ | if let currentlatitude = lastSelectedLatitude, let currentlongitude = lastSelectedLongitude { | ||
+ | delegate?.didChooseLocation(latitude: currentlatitude, longitude: currentlongitude) | ||
+ | print("Coordinates sent: Latitude: \(currentlatitude), Longitude: \(currentlongitude)") | ||
+ | } else { | ||
+ | print("No location selected.") | ||
+ | } | ||
+ | } | ||
+ | |||
+ | } | ||
+ | |||
+ | </syntaxhighlight> | ||
+ | |||
+ | ==== Send Emergency Stop ==== | ||
+ | <syntaxhighlight lang="swift"> | ||
+ | @IBAction func buttonPressed2(_ sender: UIButton) { | ||
+ | print("STOP Button pressed") | ||
+ | |||
+ | sendStopToPeripheral() | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang="swift"> | ||
+ | extension ViewController { | ||
+ | func sendStopToPeripheral() { | ||
+ | guard let peripheral = selectedPeripheral, | ||
+ | let characteristic = writeCharacteristic, | ||
+ | characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse), | ||
+ | let stopData = "S".data(using: .utf8), | ||
+ | let stringRepresentation = String(data: stopData, encoding: .utf8) else { | ||
+ | print("Cannot send data: Peripheral or characteristic not set up correctly.") | ||
+ | return | ||
+ | |||
+ | } | ||
+ | |||
+ | |||
+ | peripheral.writeValue(stopData, for: characteristic, type: .withResponse) // or .withoutResponse | ||
+ | print("stopData sent: \(stringRepresentation)") | ||
+ | |||
+ | if characteristic.uuid == CBUUID(string: "6E400002-B5A3-F393-E0A9-E50E24DCCA9E") { | ||
+ | //writeCharacteristic = characteristic | ||
+ | print("Adafruit BLE write characteristic FOUND") | ||
+ | peripheral.writeValue(stopData, for: characteristic, type: .withResponse) // or .withoutResponse | ||
+ | print("stopData sent: \(stopData)") | ||
+ | print("stopData sent str: \(stringRepresentation)") | ||
+ | } | ||
+ | else{ | ||
+ | print("Adafruit BLE write characteristic NOT FOUND") | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
− | === | + | ==== Receive GEO Status ==== |
− | < | + | <syntaxhighlight lang="swift"> |
+ | func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { | ||
+ | if let error = error { | ||
+ | print("Error discovering characteristics: \(error.localizedDescription)") | ||
+ | } | ||
+ | guard let characteristics = service.characteristics else { | ||
+ | print("No characteristics discovered for service: \(service.uuid)") | ||
+ | return | ||
+ | } | ||
+ | |||
+ | for characteristic in characteristics { | ||
+ | print("Discovered characteristic: \(characteristic.uuid)") | ||
+ | |||
+ | // Check if this characteristic supports write operations | ||
+ | if characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) { | ||
+ | writeCharacteristic = characteristic | ||
+ | print("Write characteristic found: \(characteristic.uuid)") | ||
+ | |||
+ | } | ||
+ | |||
+ | if characteristic.uuid == CBUUID(string: "6E400003-B5A3-F393-E0A9-E50E24DCCA9E") { | ||
+ | readCharacteristic = characteristic | ||
+ | print("Read characteristic found: \(characteristic.uuid)") | ||
+ | |||
+ | // Now that we have the read characteristic, we can read data | ||
+ | peripheral.setNotifyValue(true, for: characteristic) // Enable notifications for this characteristic | ||
+ | peripheral.readValue(for: characteristic) // Read the initial value | ||
+ | print("Reading data...") | ||
+ | } | ||
+ | |||
+ | } | ||
+ | } | ||
+ | </syntaxhighlight> | ||
=== Technical Challenges === | === Technical Challenges === | ||
− | + | The first challenge we encountered involved identifying the read/write characteristics of the scanned peripherals. The UUIDs for the read and write characteristics weren't being detected when sifting through nearby Bluetooth devices. To resolve this, we used a different Bluetooth testing app that successfully parsed and identified all relevant UUIDs. Subsequently, we hardcoded these UUIDs into our Bluetooth module to enable data transmission and reception. | |
+ | The second issue arose with the transmission of latitude and longitude coordinates selected on the map view. Since the map view operated as a separate screen within the app, the latitude and longitude values from the dropped pin were not accessible from the main view controller screen. To address this, we implemented a singleton to store these coordinates globally, allowing them to be accessed and updated across different screens effectively. | ||
<BR/> | <BR/> | ||
Line 417: | Line 1,408: | ||
== Conclusion == | == Conclusion == | ||
− | + | Overall, through the course of this project, we learned a lot of different types of skills. Starting with the obvious, we learned better coding habits such as code modularization and code decoupling. We also understood how to utilize the CAN bus and messages in addition to PWM hacking for the RC car. In the scope of the project, we learned communication and group coordination and distribution skills. Although we had a bit of a rough start, as the project continued, we better understood how to organize weekly goals and tasks that needed to be done and properly distributed these tasks to each member. In addition, we learned how to collaborate with each other to build the RC car. | |
− | |||
− | |||
=== Project Video === | === Project Video === | ||
+ | [https://drive.google.com/file/d/1A88K5aRfS_7tnjLPoShG8fn4YsLxWrRU/view?usp=drive_link Demo] | ||
=== Project Source Code === | === Project Source Code === | ||
− | + | [https://gitlab.com/ashley.n.ho/sjtwo-c/-/tree/master?ref_type=heads Team X Gitlab Link ] | |
=== Advice for Future Students === | === Advice for Future Students === | ||
− | *Start early! Order things as soon as you have your team, and keep track of finances for reimbursements | + | * Start early! Order things as soon as you have your team, and keep track of finances for reimbursements |
+ | * Unit-testing lets you know the obstacle avoidance works the way you generally want it to and saves a lot of time when field testing | ||
+ | * Try to keep the logic simple, over-complicating the code modules makes your debugging time a lot harder since you won't know where things went wrong | ||
+ | * Avoid the LSM compass where possible: The heading angles are not stable, which caused issues for us when handling the "Going to Destination" logic | ||
+ | * Take advantage of the past reports! Because so many people have done this project, there are a lot of mistakes that have occurred that you can avoid by reading the past reports | ||
=== Acknowledgement === | === Acknowledgement === | ||
+ | |||
+ | Thank you Preet for the class and for guiding us through the process of building the RC car. | ||
=== References === | === References === | ||
+ | |||
+ | 1. [https://maxbotix.com/pages/lv-maxsonar-ez-datasheet Ultrasonic Sensors Datasheet] | ||
+ | <BR> | ||
+ | 2. [https://stackoverflow.com/questions/36254363/how-to-convert-latitude-and-longitude-of-nmea-format-data-to-decimal Convert NMEA to Latitude Longitude] | ||
+ | <BR> | ||
+ | 3. [https://stackoverflow.com/questions/48663880/gps-nmea-output-getting-valid-gpgsv-but-not-valid-gpgga-gprmc GPS Position Fixing] | ||
+ | <BR> | ||
+ | 4. [https://www.mouser.com/datasheet/2/783/BST-BMM150-DS001-01-786480.pdf BMM150 Datasheet] | ||
+ | <BR> | ||
+ | 5. [http://www.handsontec.com/dataspecs/I2C_2004_LCD.pdf LCD Datasheet] | ||
+ | <BR> | ||
+ | 6. [https://controllerstech.com/lcd-20x4-using-i2c-with-stm32/ LCD Display Initialization and Configuration Example Tutorial] | ||
+ | <BR> | ||
+ | 7. [http://socialledge.com/sjsu/index.php/Industrial_Application_using_CAN_Bus#Class_Project_Reports Previous Project Reports] |
Latest revision as of 03:52, 23 May 2024
Contents
Project Title
Team X
Abstract
Our main goal of this project was to utilize the knowledge acquired from the lectures in CMPE 243. The report summarizes the overall process taken to develop an autonomous driving RC car using FreeRTOS, various periodic tasks, and the CAN bus to combine and run the different code modules.
Introduction
The project was divided into 5 modules:
- Sensor Node
- Motor Node
- Driver Node
- Geo Node
- Mobile Application
Team Members & Responsibilities
Team Members | Task Responsibility |
---|---|
|
|
|
|
|
|
|
|
Schedule
Week# | Start Date | End Date | Task | Status |
---|---|---|---|---|
1 | 02/19/2024 | 02/25/2024 |
|
|
2 | 02/26/2024 | 03/03/2024 |
|
|
3 | 03/04/2024 | 03/11/2024 |
|
|
4 | 03/18/2024 | 03/24/2024 |
|
|
5 | 03/25/2024 | 03/31/2024 |
|
|
6 | 04/01/2024 | 04/07/2024 |
|
|
7 | 04/08/2024 | 04/14/2024 |
|
|
8 | 04/15/2024 | 04/21/2024 |
|
|
9 | 04/22/2024 | 04/28/2024 |
|
|
10 | 04/29/2024 | 05/05/2024 |
|
|
11 | 05/06/2024 | 05/12/2024 |
|
|
12 | 05/06/2024 | 05/12/2024 |
|
|
13 | 05/13/2024 | 05/19/2024 |
|
|
14 | 05/20/2024 | 05/26/2024 |
|
|
Parts List & Cost
Item# | Part Desciption | Vendor | Qty | Cost |
---|---|---|---|---|
1 | RC Car | Traxxas | 1 | $250.00 |
2 | RC Car Battery | Traxxus | 1 | $110 |
3 | CAN Transceivers MCP2551-I/P | Microchip | 8 | Free Samples |
4 | MB1010 LV-MaxSonar | MaxBotix | 4 | $29.95 |
5 | GPS Module | Amazon | 1 | $18.99 |
6 | BMM150 Magnetometer | Amazon | 1 | $12.49 |
7 | LCD | Amazon | 1 | $11.69 |
8 | BLE Module | [1] | 1 | $17.50 |
CAN Communication
Each node is connected to a CAN transceiver that are connected to a bus with a 120 Ohm resistor on each end. We handled each message on the 10Hz, with the sensor and motor messages having the highest priority.
Specifically, we classified each node with these (see table below) message IDs.
Node | Message ID Range | |
---|---|---|
1 | MOTOR | 300 - 310 |
2 | SENSOR | 200 |
3 | GEO | 400 - 450 |
4 | DEBUG | 600 - 700 |
Hardware Design
DBC File
Shown below are the messages utilized in our DBC file:
BO_ 200 SENSOR_SONARS: 4 SENSOR SG_ SENSOR_SONARS_left : 0|10@1+ (1,0) [6|254] "inch" DRIVER SG_ SENSOR_SONARS_right : 10|10@1+ (1,0) [6|254] "inch" DRIVER SG_ SENSOR_SONARS_middle : 20|10@1+ (1,0) [6|254] "inch" DRIVER
BO_ 300 MOTOR_CMD: 1 DRIVER SG_ MOTOR_CMD_steer: 0|4@1- (1,0) [-2|2] "" MOTOR SG_ MOTOR_CMD_forward: 4|4@1- (1,0) [-5|5] "" MOTOR
BO_ 310 MOTOR_STOP: 1 SENSOR SG_ MOTOR_STOP_stop: 0|1@1+ (1,0) [0|0] "" MOTOR
BO_ 400 GPS_NAV: 2 GEO SG_ GPS_NAV_latitude : 0|8@1- (1,0) [-90|90] "" DRIVER SG_ GPS_NAV_longitude : 8|8@1- (1,0) [-180|180] "" DRIVER
BO_ 420 GPS_HEADING: 4 SENSOR SG_ GPS_HEADING_RAW_DEGREES: 0|16@1+ (1,0) [0|0] "Degrees" GEO
BO_ 430 GEO_STATUS: 4 GEO SG_ GEO_STATUS_COMPASS_HEADING : 0|5@1+ (1,0) [0|18] "Degrees" DRIVER SG_ GEO_STATUS_COMPASS_BEARING : 5|5@1+ (1,0) [0|18] "Degrees" DRIVER SG_ GEO_STATUS_DISTANCE_TO_DESTINATION : 10|16@1+ (0.1,0) [0|0] "Meters" DRIVER
BO_ 450 GPS_DESTINATION_LOCATION: 8 DRIVER SG_ GPS_DEST_LATITUDE_SCALED_100000 : 0|32@1- (1,0) [0|0] "Degrees" GEO SG_ GPS_DEST_LONGITUDE_SCALED_100000 : 32|32@1- (1,0) [0|0] "Degrees" GEO
BO_ 600 DBG_MSG_MOTOR: 4 MOTOR SG_ SPEED_M_PER_S : 0|32@1+ (0.001,-100) [0|0] "" SENSOR
BO_ 700 DBG_MSG_GPS: 3 GEO SG_ DBG_GPS_latitude : 0|8@1- (1,0) [-90|90] "" DBG SG_ DBG_GPS_longitude : 8|8@1- (1,0) [-180|180] "" DBG SG_ DBG_GPS_lock : 16|1@1+ (1,0) [0|0] "" DBG
Sensor and Bridge Controller ECU
Gitlab Sensor and Bridge Controller Node Link
The sensor node utilized the 10Hz to handle message transmission and reception. Meanwhile, the 1Hz periodics receives the sensor data directly from the utrasonic sensor modules. (see Software Design for more details)
void periodic_callbacks__1Hz(uint32_t callback_count) {
if (callback_count == 0) {
delay__us(450000); // start up delay
return;
}
ultra_sonic_sensor_data_s data;
ultrasonic_sensor__run_once();
}
void periodic_callbacks__10Hz(uint32_t callback_count) {
sensors__transmit_once();
bridge_get_data();
sensor_msg_bank__handle_msg();
heading_sensor_run_once();
}
Hardware Design
Software Design
The ultrasonic get sensor data task occurs in the 1hz, but we range 8 times in the 1hz function. The 3 ultrasonic sensors are chained together to prevent crosstalk. The SJ2 board will send a trigger signal to the left sensor which will then trigger the middle sensor, then the left. This process repeats 8 times in 1 second. Due to the chaining, the sample rate is significantly reduced, but the incoming data for each sensor is more accurate. Without the chaining, the sensor readings appear to be unstable.
The bridge task is responsible for receiving data from the APP via bluetooth. We utilize a Adafruit module (see above for part) which acts as a uart-bluetooth bridge making it extremely easy to integrate into our system without diving too deep into making bluetooth drivers. The main messages we receive are the GPS destination coordinates, and an emergency stop request.
The emergency stop task is a task that is constantly sending a "stop" flag. This flag is false by default and only set true if received from the APP. Once the vehicle stops, our the sensor node must be manually reset to continue operation.
Sensor Modules
void ultrasonic_sensor__run_once() {
// left, middle, right respectively
for (int i = 0; i < 8; i++) {
uint16_t adc_raw[3];
// start range and wait till all sensors are done
ultrasonic_range_once();
adc_raw[0] = adc__get_adc_value(ADC__CHANNEL_2);
adc_raw[1] = adc__get_adc_value(ADC__CHANNEL_4);
adc_raw[2] = adc__get_adc_value(ADC__CHANNEL_5);
// printf("adc2: %d\n", adc_raw[0]);
sensor_data.left = ((float)adc_raw[0] * SCALE_FACTOR); // / 2.0;
sensor_data.middle = ((float)adc_raw[1] * SCALE_FACTOR); // / 2.0;
sensor_data.right = ((float)adc_raw[2] * SCALE_FACTOR); // / 2.0;
if (sensor_data.left < 36) {
gpio__reset(board_io__get_led3());
} else {
gpio__set(board_io__get_led3());
}
if (sensor_data.middle < 36) {
gpio__reset(board_io__get_led2());
} else {
gpio__set(board_io__get_led2());
}
if (sensor_data.right < 36) {
gpio__reset(board_io__get_led1());
} else {
gpio__set(board_io__get_led1());
}
}
}
Bridge Controller
void bridge_get_data(void) {
char byte;
const uint32_t zero_timeout = 0;
while (uart__get(bridge_uart, &byte, zero_timeout)) {
printf("received byte: %c\n", byte);
}
}
void bridge_send_data(void *buf, uint8_t buf_size, uint8_t msg_id) {
// Format the float value from the buffer
char tx_buf[30];
if (msg_id == 0) {
float speed = *(float *)buf;
snprintf(tx_buf, sizeof(tx_buf), "spd: %f\n", (double)speed);
} else if (msg_id == 1) {
dbc_GEO_STATUS_s *msg = (dbc_GEO_STATUS_s *)buf;
snprintf(tx_buf, sizeof(tx_buf), "hd: %d, br: %d\n", msg->GEO_STATUS_COMPASS_HEADING,
msg->GEO_STATUS_COMPASS_BEARING);
}
uart_printf(bridge_uart, "%s", tx_buf);
// printf("sent: %s\n", tx_buf);
}
static void process_uart_data_buf(void) {
int temp;
char *token;
int coord_received = 0;
token = strtok(uart_rx_buf, ",");
temp = atoi(token);
if (temp != 0) {
dest_latitude = temp / 1000000.0f;
printf("la: %f ", (double)dest_latitude);
coord_received++;
}
token = strtok(NULL, ",");
temp = atoi(token);
if (temp != 0) {
dest_longitude = temp / 1000000.0f;
printf("lo: %f\n", (double)dest_longitude);
coord_received++;
}
if (coord_received == 2) {
dbc_GPS_DESTINATION_LOCATION_s dest_location;
dest_location.GPS_DEST_LATITUDE_SCALED_100000 = dest_latitude * 100000;
dest_location.GPS_DEST_LONGITUDE_SCALED_100000 = dest_longitude * 100000;
can__msg_t can_msg = {};
dbc_message_header_t header;
header = dbc_encode_GPS_DESTINATION_LOCATION(can_msg.data.bytes, &dest_location);
can_msg.msg_id = header.message_id;
can_msg.frame_fields.data_len = header.message_dlc;
can__tx(can1, &can_msg, 0);
}
}
Technical Challenges
Our main problems with the sensors occurred once we began outdoor testing. When testing indoors, we encountered no issues with the sensors incorrectly detecting obstacles. However, when moving outdoors, the sensors would detect the ground; thus, we resolved the issue by re-mounting the sensors at an angle in order to avoid detecting the ground. Additionally, we found that when initially calibrating the sensors on startup, there must not be any objects in its way for proper calibration, otherwise we would run into undefined behavior.
Motor ECU
The motor node utilized the 10Hz to handle message transmission and reception as well as for setting the PWM value. Meanwhile, the 100Hz periodics processed the inputs and transferred the data received to their respective local data structures (see Software Design for more details).
void periodic_callbacks__10Hz(uint32_t callback_count) {
motor_msg_bank__handle_msg();
motor_msg_bank__service_mia_10hz();
motor_pwm__set_pwm();
if (callback_count % 7 == 0) {
motor_rpm_driver_calc_speed();
}
motor_speed_pid_run_once();
}
void periodic_callbacks__100Hz(uint32_t callback_count) {
motor_pwm__process_input();
}
Hardware Design
The motor is directly connected to the RC car's ESC device, which is what initially controlled the car's PWMs prior to hijacking. The SJ2 now becomes the PWM transmitter as opposed to the remote and sends the corresponding PWMs based on driver signals (see Software Design for more details)
Software Design
The motor software takes in driver-motor commands through the CAN bus and based on those commands, modifies the PWMs of the motor and the servo to move the wheels forward, backward, left, or right. We mapped the PWM values (See tables below).
Motor PWM | Direction | |
---|---|---|
1 | 16.2 | Forward |
2 | 14.5 | Backward |
3 | 15.02 | Idle |
Servo PWM | Direction | |
---|---|---|
1 | 11.0 | Hard Left |
2 | 13.0 | Slight Left |
3 | 15.48 | Straight |
4 | 17.0 | Slight Right |
5 | 19.0 | Hard Right |
Additionally, we utilized a general state machine that allowed for fluid transitions between forward and reverse (see diagram below). Without a delay in a neutral state, the car's motor would not be able to easily transition from forward to reverse and vice versa, but would rather just stop. As such, we implemented the diagram in the code below and thus allowed for the car to easily transition between the states of forward and reverse.
void motor_pwm__set_pwm(void) {
motor_pwm__set_motor_pwm();
motor_pwm__set_servo_pwm();
}
static void motor_pwm__set_servo_pwm(void) {
static float set_servo_duty_cycle = servo_pwm_idle_duty_cycle;
if (motor_cmd_local.MOTOR_CMD_steer == 0) {
// idle
set_servo_duty_cycle = servo_pwm_idle_duty_cycle;
} else if (motor_cmd_local.MOTOR_CMD_steer == 1) {
// slightly right
set_servo_duty_cycle = 17.00;
} else if (motor_cmd_local.MOTOR_CMD_steer == 2) {
// max right
set_servo_duty_cycle = 19.00;
} else if (motor_cmd_local.MOTOR_CMD_steer == -1) {
// slightly left
set_servo_duty_cycle = 13.00;
} else if (motor_cmd_local.MOTOR_CMD_steer == -2) {
// max left
set_servo_duty_cycle = 11.00;
}
pwm1__set_duty_cycle(servo_pwm, set_servo_duty_cycle);
}
static void motor_pwm__set_motor_pwm(void) {
static float set_motor_duty_cycle = motor_pwm_idle_duty_cycle;
if (motor_stop_local.MOTOR_STOP_stop) {
motor_speed_pid_set_target_pwm(motor_pwm_idle_duty_cycle);
} else {
if (!ignore_cmds) {
if (motor_cmd_local.MOTOR_CMD_forward == -1) { // Reverse
set_motor_duty_cycle = 14.50;
if (reverse_flag == false) {
motor_speed_pid_set_target_pwm(motor_pwm_idle_duty_cycle);
ignore_cmds = true;
start_time = sys_time__get_uptime_ms();
reverse_flag = true;
return;
}
} else if (motor_cmd_local.MOTOR_CMD_forward == 0) { // Stop
set_motor_duty_cycle = motor_pwm_idle_duty_cycle;
} else if (motor_cmd_local.MOTOR_CMD_forward == 3) { // Forward
set_motor_duty_cycle = 16.2; // 15.7 originally?, 16.2
if (reverse_flag == true) {
motor_speed_pid_set_target_pwm(motor_pwm_idle_duty_cycle);
ignore_cmds = true;
start_time = sys_time__get_uptime_ms();
reverse_flag = false;
return;
}
}
motor_speed_pid_set_target_pwm(set_motor_duty_cycle);
} else if (sys_time__get_uptime_ms() - start_time >= DIRECTION_CHANGE_DELAY) {
ignore_cmds = false;
} else {
}
}
}
Technical Challenges
The main issue we had with the motor controller occurred during PWM hacking because we did not want the motor running the car too fast. As such, we had to guess and check a good PWM value to run the motor so that the car would move at the slowest speed possible without running into issues where it could not move. However, with continual tests, we managed to identify the ideal range we wanted to run the motor.
Additionally, we encountered minor issues where, when transitioning from reverse to forward and vice versa, the car would go into neutral and never exit from the neutral state. We found that this issue occurred due to the delay being too small, and so the motor would not have enough time to truly go into neutral and thus would remain in that state. To counter this, we increased the delay and also slightly increased the forward PWM in order to combat the potential that it was stopping due to having too low of a PWM value.
Geographical Controller
The Geo node utilized the 10Hz to handle message transmission and reception as well as receiving the compass and GPS data directly from the hardware modules. Meanwhile, the 1Hz periodics processed the GPS lock and would toggle the LED on the SJ2 board accordingly (see Software Design for more details).
void periodic_callbacks__1Hz(uint32_t callback_count) {
int gps_lock_status = geo_sensors_gps__get_gps_lock_status();
// printf("GPS lock status: %d\n", gps_lock_status);
if (!gps_lock_status) {
gpio__toggle(board_io__get_led0());
} else {
gpio__reset(board_io__get_led0());
}
}
void periodic_callbacks__10Hz(uint32_t callback_count) {
geo_msg_bank__handle_msg();
geo_msg_bank__service_mia_10hz();
geo_msg_bank__transmit_msg();
geo_sensors_gps__run_once();
// geo_sensors_compass_lsm__run_once();
}
Hardware Design
Software Design
GPS
bool geo_sensors_gps__run_once(void) {
bool gps_transfer_success = false;
gps_transfer_success = geo_sensors_gps__transfer_data_from_uart_driver_to_line_buffer();
gps__parse_coordinates_from_line();
return gps_transfer_success;
}
bool geo_sensors_gps__transfer_data_from_uart_driver_to_line_buffer(void) {
char byte_read;
const uint32_t zero_timeout = 0;
bool gps_status_reading = false;
while (uart__get(uart_gps, &byte_read, zero_timeout)) {
gps_status_reading = true;
line_buffer__add_byte(&line, byte_read);
}
return gps_status_reading;
}
static void gps__parse_coordinates_from_line(void) {
char gps_line[1000];
if (line_buffer__remove_line(&line, gps_line, sizeof(gps_line))) {
// Check if the line is a GPGGA stream
if (strncmp(gps_line, "$GPGGA,", 7) == 0) {
char *token;
int field_idx = 0;
int latitude_flag = 1;
int longitude_flag = 1;
float latitude = 0.0;
float longitude = 0.0;
token = strtok(gps_line, ",");
while (token != NULL) {
token = strtok(NULL, ",");
field_idx++;
if (field_idx == 2) { // Latitude is field 2 in GPGGA
latitude = atof(token);
} else if (field_idx == 3) { // N/S direction is field 3 in GPGGA
char c = token[0];
if (c == 'S') {
latitude_flag *= -1;
}
} else if (field_idx == 4) { // Longitude is field 4 in GPGGA
longitude = atof(token);
} else if (field_idx == 5) { // E/W direction is field 5 in GPGGA
char c = token[0];
if (c == 'W') {
longitude_flag *= -1;
}
} else if (field_idx == 6) {
char c = token[0];
// printf("GPS QUALITY: %c\n", c);
if (c == '0') {
gps_quality = 0;
} else if (c == '1') {
gps_quality = 1;
// printf("GPS lock successful\n");
} else {
// printf("Trying to acquire GPS fix\n");
}
} else if (field_idx > 6) {
break;
}
}
int latitude_days = latitude / 100;
int longitude_days = longitude / 100;
float latitude_minutes = latitude - 3700.00;
float longitude_minutes = longitude - 12100.00;
latitude_minutes /= 60;
longitude_minutes /= 60;
parsed_coordinates.latitude = ((1.0 * latitude_days) + latitude_minutes) * latitude_flag;
parsed_coordinates.longitude = ((1.0 * longitude_days) + longitude_minutes) * longitude_flag;
}
}
Compass Module
void geo_sensors_compass_lsm__run_once(void) { geo_sensors_compass__read(); }
void geo_sensors_compass__read(void) {
uint8_t buffer[6];
float mag[3];
i2c__read_slave_data(current_i2c, magnetometer_read, LSM303AGR_MAG_OUTX_L_REG, buffer, 6);
mag[0] = (int16_t)(buffer[1] << 8 | buffer[0]);
mag[1] = (int16_t)(buffer[3] << 8 | buffer[2]);
mag[2] = (int16_t)(buffer[5] << 8 | buffer[4]);
geo_sensors_compass__calculate_heading(mag);
}
static void geo_sensors_compass__calculate_heading(float mag[3]) {
float magnitude = sqrtf(mag[0] * mag[0] + mag[1] * mag[1] + mag[2] * mag[2]);
const float epsilon = 1e-6;
if (magnitude < epsilon) {
current_compass_heading = 0;
} else {
float mag_xy = mag[1] / magnitude;
float mag_xx = mag[0] / magnitude;
current_compass_heading = (atan2(mag_xy, mag_xx)) * 180.0 / PI;
if (current_compass_heading < 0) {
current_compass_heading = 360 + current_compass_heading;
}
}
}
Haversine Algorithm
In the provided function, we use the Haversine algorithm to calculate the shortest distance between two geographical points on Earth, identified by their latitude and longitude. We start by converting these coordinates from degrees to radians and then apply the Haversine formula to determine the distance. Additionally, we calculate the bearing and heading from the current location to the destination.
void geo_logic__haversine_calculation(void) {
// Input: Latitude longitude, Output: heading, bearing, distance to destination
gps_coordinates_t current_gps = geo_sensors_gps__get_coordinates();
float current_latitude = current_gps.latitude;
float current_longitude = current_gps.longitude;
gps_coordinates_t destination_gps = geo_msg_bank__get_gps_destination_location();
float destination_latitude = destination_gps.latitude;
float destination_longitude = destination_gps.longitude;
// Convert latitudes and longitudes from degrees to radians
float phi1 = (float)(current_latitude * (float)PI_VAL / (float)180.0);
float phi2 = (float)(destination_latitude * PI_VAL / (float)180.0);
float delta_phi = (float)(destination_latitude - current_latitude) * PI_VAL / (float)180.0;
float delta_lambda = (float)(destination_longitude - current_longitude) * PI_VAL / (float)180.0;
// Haversine formula
float a =
sin(delta_phi / 2) * sin(delta_phi / 2) + cos(phi1) * cos(phi2) * sin(delta_lambda / 2) * sin(delta_lambda / 2);
float c = 2 * atan2(sqrt(a), sqrt(1 - a));
distance_to_destination = RADIUS_EARTH_KM * c * 1000;
// Bearing calculation
float y = sin(delta_lambda) * cos(phi2);
float x = cos(phi1) * sin(phi2) - sin(phi1) * cos(phi2) * cos(delta_lambda);
float bearing_rad = atan2(y, x);
compass_bearing = fmod((bearing_rad * (float)180.0 / (float)PI_VAL + (float)360.0), 360.0);
compass_heading = geo_msg_bank__get_heading();
current_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION = distance_to_destination;
current_geo_status.GEO_STATUS_COMPASS_BEARING = (uint8_t)(compass_bearing / 20);
current_geo_status.GEO_STATUS_COMPASS_HEADING = (uint8_t)(compass_heading);
}
Checkpoint Algorithm
The checkpoint algorithm is a very simple algo that provides the next "checkpoint" to drive to given the current location and destination coordinates. We first try to find the closest checkpoint, and if it brings us closer to the final destination, then travel to that checkpoint. We repeat this process until no checkpoint can bring us closer and the destination is the final "checkpoint." We use the haversine algorithm to determine how close we are to a checkpoint so that we know we reached it, otherwise we may circle back around to it.
If no checkpoints are provided in the list, then the car will attempt to navigate to the final destination directly which will likely be very challenging for large obstacles in the path. Initially, we used Euclidian distance to find the closest checkpoint, but raw distance calculated from that formula is not very easy to understand, so we switch to using haversine to get distance in meters.
gps_coordinates_t find_next_point(gps_coordinates_t origin, gps_coordinates_t destination) {
gps_coordinates_t closest_point;
float min_distance = FLT_MAX;
float distance;
int checkpoint_idx = -1;
for (int i = 0; i < NUM_OF_CHECKPOINTS; i++) {
distance = get_distance_between_points(origin, locations_we_can_travel[i]);
if (distance < min_distance) {
if (get_distance_between_points(origin, locations_we_can_travel[i]) < 5) {
printf("reached checkpoint\n");
continue;
}
// Check if point is actually closer to destincation
if (get_distance_between_points(locations_we_can_travel[i], destination) <
get_distance_between_points(origin, destination)) {
min_distance = distance;
checkpoint_idx = i;
printf("setting checkpoint\n");
} else {
continue;
}
}
}
if (checkpoint_idx < 0) {
closest_point = destination;
printf("Going destination\n");
} else {
printf("setting closest_point\n");
closest_point = locations_we_can_travel[checkpoint_idx];
}
printf("p: %f, %f", closest_point.latitude, closest_point.longitude);
return closest_point;
}
Technical Challenges
Most of our problems occurred due to an inaccurate compass reading. Mainly, the compass heading angles would not return as very stable values, which resulted in unstable driving behavior for the car. We initially thought it would resolve itself with some software calibration; however, we found that even with software calibration for the LSM, it would still be inaccurate and would not even give the full 360 degree heading range. As such, we resolved to simply buying a more expensive and more accurate magnetometer, which solved our issues. The new module returned more stable values, despite it still fluctuating, the angle changing was not enough to affect the driving behavior since we built our module with the intent of not needing the exact degree of the angles. We also found some trouble mounting the compass due to not wanting to have to handle any further offsets after mounting. Because of this, when mounting the compass, we identified where the compass was detecting north and faced the front of the car in that direction. Following that step, we mounted the compass so that it, along with the front of the car, was facing north.
Additionally, we ran into some errors with the GPS module due to us receiving latitude and longitude values that were miles away from our current location. However, we identified an error on our end where we had misinterpreted the data returned from the GPS module and thus were calculating the wrong latitude and longitude values. Once we identified the error, we found the correct way to extract the correct latitude and longitude values for a more accurate location.
Driver and LCD Module
The driver node utilized the 10Hz to handle message transmission and reception as well as setting the LCD display for status updates and motor commands. Meanwhile, the 100Hz periodics processed the inputs and transferred the data received to their respective local data structures (see Software Design for more details).
void periodic_callbacks__10Hz(uint32_t callback_count) {
driver_msg_bank__handle_msg();
driver_msg_bank__service_mia_10hz();
driver_msg_bank__transmit_msg();
i2c_lcd__clear();
driver__lcd_display_data();
}
void periodic_callbacks__100Hz(uint32_t callback_count) {
driver__process_input();
}
Hardware Design
The driver node, aside from its connection to the CAN bus, is also connected the the LCD module through I2C. the SJ2 board provides the LCD with 3.3V power and sends data through SDA and SCL.
Software Design
Driver Logic
The driver logic came down to a basic logic (shown in table below) where 0 implies there is no obstacle, and 1 implies an obstacle is present. Depending on each combination of 1's and 0's, the car would determine whether to turn left or right and move forward or backward.
dbc_MOTOR_CMD_s driver__get_motor_commands(void) {
driver__avoid_obstacle();
return motor_commands;}
static void driver__avoid_obstacle(void) {
obstacle_below_threshold_s below_thresholds = driver__closest_obstacle();
if (!(below_thresholds.MIDDLE) && !(below_thresholds.LEFT) && !(below_thresholds.RIGHT)) {
driver__go_to_destination();
} else {
driver__steering();
}
driver__led_indicators();}
dbc_MOTOR_CMD_s driver__get_motor_commands(void) {
driver__avoid_obstacle();
return motor_commands;
}
// slight turns for destination movement
static void driver__go_to_destination(void) {
int angle_difference = local_geo_status.GEO_STATUS_COMPASS_HEADING - local_geo_status.GEO_STATUS_COMPASS_BEARING;
if (local_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION > 0) {
if (angle_difference > 0) {
// go right
motor_commands.MOTOR_CMD_steer = 1;
motor_commands.MOTOR_CMD_forward = 3;
} else if (angle_difference < 0) {
// go left
motor_commands.MOTOR_CMD_steer = -1;
motor_commands.MOTOR_CMD_forward = 3;
} else { // go straight
motor_commands.MOTOR_CMD_steer = 0;
motor_commands.MOTOR_CMD_forward = 3;
}
} else { // reached destination
motor_commands.MOTOR_CMD_forward = 0;
motor_commands.MOTOR_CMD_steer = 0;
}}
LCD Logic
The LCD printout relied solely on the datasheet. However, some optimizations were made in order to simplify the LCD methods. Specifically the starting_position() function allowed for eash access to each line of the LCD's printout without needing to write data to the addresses every time we wanted to print onto a specific line. Additionally, the lcd__printf() was a minor optimization to allow for us to print a string rather than per character and calling the send_data() function for every character.
void driver__lcd_display_data(void) {
char debug_str[15];
if (local_motor_stop.MOTOR_STOP_stop) {
i2c_lcd__clear();
i2c_lcd__starting_position(0, 0);
i2c_lcd__printf(" MOTOR STOPPED!");
i2c_lcd__starting_position(1, 0);
i2c_lcd__printf(" PLS RESTART BRIDGE");
i2c_lcd__starting_position(1, 0);
i2c_lcd__printf(" TO CONTINUE");
} else if (local_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION) {
sprintf(debug_str, "%.1lf", local_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION);
i2c_lcd__starting_position(0, 0);
i2c_lcd__printf(" PROJECT TEAM X");
i2c_lcd__starting_position(1, 0);
i2c_lcd__printf("Distance:");
i2c_lcd__starting_position(1, 10);
i2c_lcd__printf(debug_str);
sprintf(debug_str, "%d", (int)local_geo_status.GEO_STATUS_COMPASS_HEADING);
i2c_lcd__starting_position(2, 0);
i2c_lcd__printf(" Heading:");
i2c_lcd__starting_position(2, 13);
i2c_lcd__printf(debug_str);
sprintf(debug_str, "%d", (int)local_geo_status.GEO_STATUS_COMPASS_BEARING);
i2c_lcd__starting_position(3, 0);
i2c_lcd__printf(" Bearing:");
i2c_lcd__starting_position(3, 13);
i2c_lcd__printf(debug_str);
} else if (local_geo_status.GEO_STATUS_DISTANCE_TO_DESTINATION < 2) {
i2c_lcd__clear();
i2c_lcd__starting_position(1, 0);
i2c_lcd__printf("DESTINATION REACHED!");
}
}
void i2c_lcd__printf(char *line) {
while (*line)
i2c_lcd__send_data(*line++);
}
void i2c_lcd__starting_position(uint8_t y, uint8_t x) {
char Starting_Addr = 0x80;
switch (y) {
case 0:
Starting_Addr |= 0x00;
break;
case 1:
Starting_Addr |= 0x40;
break;
case 2:
Starting_Addr |= 0x14;
break;
case 3:
Starting_Addr |= 0x54;
break;
default:;
}
Starting_Addr += x;
i2c_lcd__send_command(0x80 | Starting_Addr);
}
Technical Challenges
Most of the issues surrounding the driver node occurred after field testing. We found there were some issues regarding how soon the driver made the decision compared to when it received the sensor data. As such, we made adjustments so that, despite the delay, there would be time for the driver to receive the sensor data, identify the correct action to take, and then move the wheels. Overall, our driver node worked as expected once we started field testing due to the multitude of unit tests that were done to ensure proper logic. We also identified some minor issues when testing the reverse; however, this was easily fixed by modifying the sensor priorities so that the middle sensor's values, when below the threshold, had the most precedence. In this way, the car would not fluctuate between going forward and reverse when there was clearly an object in front of it.
Additionally, we ran into issues integrating the LCD screen through I2C. The screen's slave address would not get detected, despite the device having the proper connections and power supply. However, it was found to have just been a hardware issue and worked with a different I2C LCD device.
Mobile Application
Software Design
The iOS Mobile App was designed using Swift. The primary purpose of the app was to connect to the Bridge Controller via bluetooth and send GPS destination and emergency stop message and to receive and display geo controller status heading and bearing data.
Scan Bluetooth Devices
@IBAction func buttonPressed(_ sender: UIButton) {
print("Scan bluetooth devices Button pressed")
// Start scanning for Bluetooth devices if Bluetooth is turned on
if centralManager.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil, options: nil)
print("Scanning for Bluetooth devices...")
} else {
print("Bluetooth is not turned on")
}
}
extension ViewController: CBCentralManagerDelegate {
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn:
print("Bluetooth is On")
case .poweredOff:
print("Bluetooth is Off")
case .resetting:
print("Bluetooth is Resetting")
case .unauthorized:
print("Bluetooth not authorized")
case .unsupported:
print("Bluetooth not supported")
case .unknown:
print("Bluetooth unknown state")
@unknown default:
print("A new case was added that is not handled")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let name = peripheral.name, name != "Unknown Device" {
// Avoid adding duplicates
if !discoveredDevices.contains(where: { $0.identifier == peripheral.identifier }) {
discoveredDevices.append(peripheral)
DispatchQueue.main.async { [weak self] in self?.displayContent.reloadData()
}
}
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Connected to peripheral: \(peripheral)")
selectedPeripheral = peripheral // Make sure to store the reference to the connected didFailToConnectperipheral
peripheral.delegate = self // Set the delegate to self for handling peripheral events
peripheral.discoverServices(nil)
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("Disconnected from peripheral: \(peripheral)")
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("Failed to connect to peripheral: \(peripheral), error: \(error?.localizedDescription ?? "Unknown error")")
// Present an alert to the user with the option to try connecting again
let alert = UIAlertController(title: "Connection Failed", message: "Failed to connect to the selected device. Would you like to try again?", preferredStyle: .alert)
// Add a "Try Again" action to the alert
alert.addAction(UIAlertAction(title: "Try Again", style: .default) { _ in
// Retry connecting to the selected peripheral
central.connect(peripheral, options: nil)
})
// Add a "Cancel" action to the alert
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
// Present the alert
self.present(alert, animated: true, completion: nil)
}
}
Set GPS Desination
import UIKit
import MapKit
protocol MapViewControllerDelegate: AnyObject {
func didChooseLocation(latitude: Double, longitude: Double)
}
class CustomMapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
weak var delegate: MapViewControllerDelegate?
var lastSelectedLatitude: Double?
var lastSelectedLongitude: Double?
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
print("Map View loaded!")
// Add a tap gesture recognizer to the map view
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleMapTap(_:)))
mapView.addGestureRecognizer(tapRecognizer)
// Define the center of the region your map should display
// 37.33919199814887, -121.88103575173972
let center = CLLocationCoordinate2D(latitude: 37.33919199814887, longitude: -121.88103575173972) // SJSU parking lot
// Set the region of the map
let region = MKCoordinateRegion(center: center, span: span)
mapView.setRegion(region, animated: true)
}
@objc func handleMapTap(_ gestureReconizer: UITapGestureRecognizer) {
let location = gestureReconizer.location(in: mapView)
let coordinate = mapView.convert(location, toCoordinateFrom: mapView)
// Remove all existing annotations
mapView.removeAnnotations(mapView.annotations)
// Add annotation:
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
mapView.addAnnotation(annotation)
lastSelectedLatitude = coordinate.latitude
lastSelectedLongitude = coordinate.longitude
print("Latitude: \(coordinate.latitude), Longitude: \(coordinate.longitude)")
}
@IBAction func buttonPressed(_ sender: UIButton) {
print("Sending GPS destination location to Bridge Controller!")
if let currentlatitude = lastSelectedLatitude, let currentlongitude = lastSelectedLongitude {
delegate?.didChooseLocation(latitude: currentlatitude, longitude: currentlongitude)
print("Coordinates sent: Latitude: \(currentlatitude), Longitude: \(currentlongitude)")
} else {
print("No location selected.")
}
}
}
Send Emergency Stop
@IBAction func buttonPressed2(_ sender: UIButton) {
print("STOP Button pressed")
sendStopToPeripheral()
}
extension ViewController {
func sendStopToPeripheral() {
guard let peripheral = selectedPeripheral,
let characteristic = writeCharacteristic,
characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse),
let stopData = "S".data(using: .utf8),
let stringRepresentation = String(data: stopData, encoding: .utf8) else {
print("Cannot send data: Peripheral or characteristic not set up correctly.")
return
}
peripheral.writeValue(stopData, for: characteristic, type: .withResponse) // or .withoutResponse
print("stopData sent: \(stringRepresentation)")
if characteristic.uuid == CBUUID(string: "6E400002-B5A3-F393-E0A9-E50E24DCCA9E") {
//writeCharacteristic = characteristic
print("Adafruit BLE write characteristic FOUND")
peripheral.writeValue(stopData, for: characteristic, type: .withResponse) // or .withoutResponse
print("stopData sent: \(stopData)")
print("stopData sent str: \(stringRepresentation)")
}
else{
print("Adafruit BLE write characteristic NOT FOUND")
}
}
}
Receive GEO Status
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let error = error {
print("Error discovering characteristics: \(error.localizedDescription)")
}
guard let characteristics = service.characteristics else {
print("No characteristics discovered for service: \(service.uuid)")
return
}
for characteristic in characteristics {
print("Discovered characteristic: \(characteristic.uuid)")
// Check if this characteristic supports write operations
if characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) {
writeCharacteristic = characteristic
print("Write characteristic found: \(characteristic.uuid)")
}
if characteristic.uuid == CBUUID(string: "6E400003-B5A3-F393-E0A9-E50E24DCCA9E") {
readCharacteristic = characteristic
print("Read characteristic found: \(characteristic.uuid)")
// Now that we have the read characteristic, we can read data
peripheral.setNotifyValue(true, for: characteristic) // Enable notifications for this characteristic
peripheral.readValue(for: characteristic) // Read the initial value
print("Reading data...")
}
}
}
Technical Challenges
The first challenge we encountered involved identifying the read/write characteristics of the scanned peripherals. The UUIDs for the read and write characteristics weren't being detected when sifting through nearby Bluetooth devices. To resolve this, we used a different Bluetooth testing app that successfully parsed and identified all relevant UUIDs. Subsequently, we hardcoded these UUIDs into our Bluetooth module to enable data transmission and reception.
The second issue arose with the transmission of latitude and longitude coordinates selected on the map view. Since the map view operated as a separate screen within the app, the latitude and longitude values from the dropped pin were not accessible from the main view controller screen. To address this, we implemented a singleton to store these coordinates globally, allowing them to be accessed and updated across different screens effectively.
Conclusion
Overall, through the course of this project, we learned a lot of different types of skills. Starting with the obvious, we learned better coding habits such as code modularization and code decoupling. We also understood how to utilize the CAN bus and messages in addition to PWM hacking for the RC car. In the scope of the project, we learned communication and group coordination and distribution skills. Although we had a bit of a rough start, as the project continued, we better understood how to organize weekly goals and tasks that needed to be done and properly distributed these tasks to each member. In addition, we learned how to collaborate with each other to build the RC car.
Project Video
Project Source Code
Advice for Future Students
- Start early! Order things as soon as you have your team, and keep track of finances for reimbursements
- Unit-testing lets you know the obstacle avoidance works the way you generally want it to and saves a lot of time when field testing
- Try to keep the logic simple, over-complicating the code modules makes your debugging time a lot harder since you won't know where things went wrong
- Avoid the LSM compass where possible: The heading angles are not stable, which caused issues for us when handling the "Going to Destination" logic
- Take advantage of the past reports! Because so many people have done this project, there are a lot of mistakes that have occurred that you can avoid by reading the past reports
Acknowledgement
Thank you Preet for the class and for guiding us through the process of building the RC car.
References
1. Ultrasonic Sensors Datasheet
2. Convert NMEA to Latitude Longitude
3. GPS Position Fixing
4. BMM150 Datasheet
5. LCD Datasheet
6. LCD Display Initialization and Configuration Example Tutorial
7. Previous Project Reports