HAOHENG TANG'S PROJECTS

HTMAA23

Final Project
...
Demo!
Electronic Part
... Circuit's schematic design ... PCB design PCB CNC Milling ... My final PCB ... My final PCB ... Packaging- Front View ... Packaging- Back View ... Packaging- on board ... Packaging- on board
Networking Part
Server Setup

Though the ideal case is that I could host a server in the cloud, but for testing, I would like to host an Apache and MySQL server locally using XAMPP.

... Local Apache & MySQL Service


Next, I create a database called mapping in phpMyAdmin and a table called bikelane in the database.

... XAMPP dashboard ... Create a database and a table
Modifying Database

The simplest operation of modifying a database with SQL is to 1.INSERT 2.SELECT data. For this week's assignment, I just need to use the INSERT operation. SELECT will be useful for my Week12 assignment.

php provides us with a fast way to make changes in database with SQL syntax. I created a file called mapping_data.php at `F:\xampp\htdocs\bikelane_project`

                  
                    
                      
      <?php
      
      $hostname = "localhost";
      $username = "root";
      $password = "";
      $database = "mapping";
      
      $conn = mysqli_connect($hostname, $username, $password, $database);
      
      if (!$conn){
      die("Connection failed: " . mysqli_connect_error());
      }
      
      echo "Database connection is OK
"; if(isset($_POST["latitude"]) && isset($_POST["longitude"]) && isset($_POST["dx"]) && isset($_POST["dy"]) && isset($_POST["dz"])){ $lat = $_POST["latitude"]; $lng = $_POST["longitude"]; $dx = $_POST["dx"]; $dy = $_POST["dy"]; $dz = $_POST["dz"]; $sql = "INSERT INTO bikelane (lat, lng, dx, dy, dz) VALUES (" .$lat.", " .$lng.", " .$dx.", " .$dy.", " .$dz.")"; if(mysqli_query($conn, $sql)){ echo "\nNew record created successfully"; }else{ echo "Error: " .$sql . "
" . mysqli_error($conn); } } ?>
Communication between ESP32S3 and localhost server

WiFi module in Arduino makes it possible to connect ESP32 to any WiFi. All we need to provide are just SSID and password.

I wrote an Arduino code that asks the microcontroller to post data to the database each time it senses motion. It's done by modifying variables in the .php file mentioned above, which helps INSERT data to the bikelane database.

                  
      //MPU6050
      #include 
      #include 
      #include 
      Adafruit_MPU6050 mpu;
      
      
      //WiFi
      #include 
      #include 
      
      String URL = "http://192.168.2.110/bikelane_project/mapping_data.php"; //"http://computer_ip/project_folder/project_file.php";
      
      const char* ssid = "LEGION_TANG 0522";
      const char* password = "V1655-w8";
      
      float lat = 42.3601;
      float lng = 71.0589;
      
      void setup() {
      //------------------------WiFi---------------------------
      Serial.begin(115200);
      connectWiFi();
      
      //-----------------------MPU6050-------------------------
      Serial.begin(115200);
      while (!Serial)
      delay(10); // will pause Zero, Leonardo, etc until serial console opens
      
      Serial.println("Adafruit MPU6050 test!");
      
      // Try to initialize!
      if (!mpu.begin()) {
      Serial.println("Failed to find MPU6050 chip");
      while (1) {
        delay(10);
      }
      }
      Serial.println("MPU6050 Found!");
      
      //setupt motion detection
      mpu.setHighPassFilter(MPU6050_HIGHPASS_0_63_HZ);
      mpu.setMotionDetectionThreshold(1);
      mpu.setMotionDetectionDuration(20);
      mpu.setInterruptPinLatch(true);	// Keep it latched.  Will turn off when reinitialized.
      mpu.setInterruptPinPolarity(true);
      mpu.setMotionInterrupt(true);
      
      Serial.println("");
      delay(100);
      }
      
      void loop() {
      //-----------------------WiFi--------------------------
      if(WiFi.status() != WL_CONNECTED){
      connectWiFi();
      }
      
      
      //---------------------MPU6050-------------------------
      if(mpu.getMotionInterruptStatus()) {
      /* Get new sensor events with the readings */
      sensors_event_t a, g, temp;
      mpu.getEvent(&a, &g, &temp);
      
      /* Print out the values */
      Serial.print("AccelX:");
      Serial.print(a.acceleration.x);
      Serial.print(",");
      Serial.print("AccelY:");
      Serial.print(a.acceleration.y);
      Serial.print(",");
      Serial.print("AccelZ:");
      Serial.print(a.acceleration.z);
      Serial.print(", ");
      Serial.print("GyroX:");
      Serial.print(g.gyro.x);
      Serial.print(",");
      Serial.print("GyroY:");
      Serial.print(g.gyro.y);
      Serial.print(",");
      Serial.print("GyroZ:");
      Serial.print(g.gyro.z);
      Serial.println("");
      
      
      /*Send the data to database*/
      String postData = "latitude=" + String(lat) + "&longitude=" + String(lng) + "&dx=" +String(a.acceleration.x) + "&dy=" +String(a.acceleration.y) + "&dz=" +String(a.acceleration.z);
      
      HTTPClient http;
      http.begin(URL);
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");
      int httpCode = http.POST(postData);
      String payload = http.getString();
      
      
      Serial.print("URL: "); Serial.println(URL);
      Serial.print("Data: "); Serial.println(postData);
      Serial.print("httpCode: "); Serial.println(httpCode);
      Serial.print("payload: "); Serial.println(payload);
      Serial.println("------------------------------------------");
      }
      
      delay(10);
      }
      
      void connectWiFi(){
      WiFi.mode(WIFI_OFF);
      delay(1000);
      
      Serial.print("Try to connect to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);
      
      while (WiFi.status() != WL_CONNECTED){
      delay(500);
      Serial.print(".");
      }
      Serial.print("Connected to : "); Serial.println(ssid);
      Serial.print("IP address: "); Serial.println(WiFi.localIP());
      }
                                         
      
                    

To be noticed, you have to get the IP address and put it into the above code. To get your IP address, simply run ipconfig in your cmd.exe.

... IPv4 address
Testing!

The ESP32S3 is connecting a hotspot shared by my laptop (don't forget to change the bend to 2.4GHz, otherwise the ESP32S3 will not be able to connect to the WiFi). Though there is a cable connecting ESP32S3 and my laptop, it is just for reading message from Serial port to debug. Once I move the PCB, the accelerametor senses the motion and the microcontroller posts data through WiFi automatically.

... Serial port messages ... New data posted from ESP32S3
Interfacing part
MySQL database

As discussed in Week11, we host a database in MySQL server with the use of XAMPP

...

The only challenge this week is to build a responsive frontend to present the data.

Flask as a back end

It is impossible for a front-edn to fetch data directly from the database. We need flask as a backend to bridge the gap between these two.

... image source: link


We use mysql.connector to make connection to the MySQL database and use SQL syntax to select the data we want.

                  
                
  from flask import Flask, render_template, jsonify
  import mysql.connector
  from flask_cors import CORS  # Import the CORS module
  
  app = Flask(__name__)
  CORS(app)  # Enable CORS for all routes in your Flask app
  
  # Configure MySQL connection
  db = mysql.connector.connect(
      host="localhost",
      user="root",
      password="",
      database="mapping"
  )
  
  # Create a cursor to interact with the database
  cursor = db.cursor()
  
  @app.route('/')
  def index():
      # Example query to fetch data
      query = "SELECT * FROM bikelane"
      cursor.execute(query)
  
      # Fetch all the results
      data = cursor.fetchall()
  
      # Close the cursor and database connection
      cursor.close()
      db.close()
  
      # Render the template with the fetched data
      return render_template('index.html', data=data)
  
  @app.route('/api/data', methods=['GET'])
  def get_data():
      # Example query to fetch data
      query = "SELECT * FROM bikelane"
      cursor.execute(query)
  
      # Fetch all the results
      data = cursor.fetchall()
  
      # Close the cursor and database connection
      cursor.close()
      db.close()
      return jsonify({"data": data})
  
  if __name__ == '__main__':
      app.run(debug=True)
  
                
                
HTML CSS & JavaScript as a frontend

Flask provides html_template which is a perfect tool to enable us to integrate frontend into the flask app with a simple line of code return render_template('index.html', data=data)

To be noticed, the files should be placed in a specific structure. The index.html must be placed in a folder named "templates"

...

Then, we are able to get a simple web page presenting all the data we have in the MySQL database

...

After working on the HTML, CSS and JavaScript for a while, we finally got this satisfying interface!

...

All the data with geolocation will pop up on the interactive map. Every time a user refresh the web page, it will synchronize with the MySQL database.

Physical Part
Molding
CAD ... CADing mold in fusion360 ... Import it into Rhino model to delete the vertical surfaces and organize layers following the instructions of GSD's fab lab.
CAM ...

Merge rhino file into MasterCAM2020. Use GSD Fab lab template file. Set the stock size. Set the toolpath.

Once setting up the parameter and geometry, we can check the CNC process with the help of MasterCAM simulator.

Milling ...

Woodshop staffs checked the masterCAM file and helped me set up the CNC milling machine.

Step 1: Surface rough parallel

In the first step, the machine uses a 0.5 flat endmill to create a rough curved shape, running in a straight way. This step doesn't take much time.

CNC process Corresponding CAM simulation
Step 2: Surface finish parallel

In the second step, the machine uses a 0.5 ball-nose endmill to create a smooth shape, running in a spherical way. This step lasts much longer than the previous one.

CNC process CNC process CNC process CNC process CNC process Corresponding CAM simulation
Step 3: Contour 2D

In the third step, the machine uses a 0.5 flat endmill to cut through the stock but leave some tabs on it.

CNC process Corresponding CAM simulation
Finished! ... Cleaning fragments in the gap. ... Finished pieces ... Finished pieces ... Finished pieces ... Finished pieces
Preparation

Though it looks like a single piece of wood, the longboard deck is actually made by 7 layers (in my case) of wood veneers.

High-quality rock maple wood veneers can be purchased on Woodcraft. This skateboard veneer pack contains 7 plys or layers that measure 12" × 48" including:
Face Grade: Layers 1 and 7
Core Grade: Layers 2, 4, and 6, same grain
direction as Face Grade for flexibility
Crossband Grade:
Layers 3 and 5, grain goes across direction of the other two layers for dimensional stability.

The wood veneer is too big so I need to trim it to a proper size and a shape close to my longboard deck.

Zund cut
Laminating & Vacuuming

The wood veneers are soft and easy to bend. Alfonso helped me laminate the 7 layers of wood veneers.

Laminating

Then, we vacuumed the mold and the wood to make the use of atmosphere pressure to press on the wood and form the shape we want.

Vacuuming process ... Vacuum bag

...
...
24 hours later...
We got this nice piece of longboard deck with a subtle but smooth curvature surface.

... Front view ... Composite board
Trimming

The longboard deck is a bit larger than the shape I want so I have to trim it to get the perfect shape.

However, the shape of the longboard deck is so complicated that it cannot be perfectly trimed with the machine. I ended up cutting it with a saw by myself... It took me three and a half hours.

Trimming by hand
Sanding

The contour of the longboard deck is not cut perfectly and the surface is still rough, so I have to sand it.

I first use coarse sandpaper (180) to sand the contour to make it exactly the shape that I want

... 180

Then I use finer sandpaper to create fillet on the edges and remove some stains on the board.

...

Finally, I used a piece of fine sandpaer with a sponge in-between to polish the wood surface.

...

Assembly ... I got all the pieces I want! Drill holes on the board to according to the location of the screws on the truck. Before assembling the wheels and trucks to the longboard deck, I have to get rid of the 3D printed part which is sticked to the wood veneer surface and is just for locating. ... I paste a transparent skateboard tape on top of the deck. Use driling to insert screws ...

Finally, the longboard is done! I really like it and can't waiting skateboarding on the road!

Last but not least, I wanna give a big thanks to Alfonso!!!! He helped so much during this process of making.

Concepts
Cycling Sensors
Background

Last week, I came across a brochure attached to my bike, advocating for our rights to ride bikes safely in Cambridge and for the improvement of bike lanes. At times, I feel uneasy while biking in Cambridge, particularly when navigating through narrow spaces between parked cars on my right and passing vehicles on my left. I often prefer using pathways to reduce the risk of being in close proximity to traffic, even though it can lead to other inconveniences as I try to navigate around pedestrians.

The condition of the roads and pathways also discourages many from biking or using scooters. A friend of mine recently had a fall from her scooter and sustained an injury while traversing through rugged areas.

Despite the frequency of such incidents, there is often a lack of concrete evidence. This has prompted me to consider creating a sensor for scooters and bike shares, designed to detect and record such inconveniences experienced by cyclists in Cambridge.

Solutions

Device

  • A tiny device integrated with sensors and microcontroller. It has the ability to sense and analyze data, send it to the cloud and can be easily attahced to city bike share or scooters.

Data to get:

  • Acceleration: Curves, shows when the bike accelarte and brake. The data can be used for machine learning and prediction.
  • GPS: provide geographical information for each data point
  • Signal processing!!

Power supply:

  • Scooters: Using its own electronics power.
  • Bluebikes: Charged when the bike in in dock.

Advantages:

  • Low cost: It helps collect data without much effort. People ride bikes and scooters everyday!
  • Large covering area: Though the number of the cycling devices is limited. The mobility of bicycles and scooters helps it cover most areas in the cities.
Related Project
...

...
MIT Senseable City Lab- Copenhagen Wheel

Smart, responsive and elegant, the Copenhagen Wheel is a new emblem for urban mobility. It transforms ordinary bicycles quickly into hybrid e-bikes that also function as mobile sensing units. The Copenhagen Wheel allows you to capture the energy dissipated while cycling and braking and save it for when you need a bit of a boost. It also maps pollution levels, traffic congestion, and road conditions in real-time.

Controlled through your smart phone, the Copenhagen Wheel becomes a natural extension of your everyday life. You can use your phone to unlock and lock your bike, change gears and select how much the motor assists you. As you cycle, the wheel’s sensing unit is also capturing your effort level and information about your surroundings, including road conditions, carbon monoxide, NOx, noise, ambient temperature and relative humidity. Access this data through your phone or the web and use it to plan healthier bike routes, to achieve your exercise goals or to meet up with friends on the go. You can also share your data with friends, or with your city - anonymously if you wish – thereby contributing to a fine-grained database of environmental information from which we can all benefit.

...

...

...
My previous project -Trees' Breath

Having seen more and more old banyan trees being cut by the government, citizens in Guangzhou engaged in an event tagged by “Hug the Banyan Trees in Guangzhou” on Weibo (social media similar to Twitter) in May 2021, which asks people to take photos of themselves hugging the banyan trees to show their love to them.

For centuries, banyan tree has become a symbol of Guangzhou culture. As the climate in Guangzhou is hot all year, people like staying under the shadows of banyan trees and have a strong bond with the trees.

The government cut banyan trees because they assumed the banyan trees are not so important to citizens and could be replaced by other kind of trees that look nicer. However, once the banyan trees at a place are cut, citizens cannot enjoy the shading by them and spend substantially less time at the place.

...
MIT Senseable City Lab - trash tags

The trash tag periodically measures its location and reports that data to the server via the cellular network. The first generation of trash tags (shown in photo 1) was based on GSM cellular phone technology that estimates the tag position by measuring signal strength from each cell tower in sight of the device and comparing it to a map of cell phone towers – a technique known as CellID triangulation. The location accuracy is not as good as GPS but tends to be more robust, as cellular signals can be picked up inside buildings and from within piles of trash, not requiring an unobstructed sky view. Our second generation of tracking tags use the best of both worlds – GPS and CDMA cell-tower trilateration based on the Qualcomm inGeo™ platform (device shown in photo 2) in combination with Sprint's cell phone network, utilizing Qualcomm’s gpsOne® technology to provide both accuracy and availability for position tracking applications like ours. Future generations of devices will work seamlessly across CDMA/GSM/UMTS networks, a feature that will allow tracking items across international borders.

In order to ensure a long enough lifetime to track the trash to its final destination, we developed ‘duty cycling’ algorithms, which we use along with inGeo™‘s “Low Duty Cycle” technology which provides hibernation capability that keep the tag off most of the time, turning it on only every few hours to sense and report its position. The tag also uses a motion sensor, which allows it to continue being in hibernation mode if no movement has been detected, thus further extending the battery life. If movement has been detected, the motion sensor wakes up the device to check and report its new position. Our algorithms vary the sampling rate in response to conditions sensed by the tag. In particular, the tag uses a set of orientation sensors to sense changes in position to increase the location sampling rate when the tag is apparently moving, and whenever previously unseen cell tower IDs are observed.

All of the components used in the tags are RoHS compliant, which means that toxic material levels are below both U.S. and European Union standards for electronics products for which the Trash Track tags can be legally introduced into waste streams.

...
MIT Responsive Environment Lab - Responsive Roadways

"We have built a prototype infrastructure for the real-time collection and distribution of comprehensive information about road traffic and conditions on a network of streets. Small (2 cm diameter) cylinders placed just under the road surface count passing vehicles by detecting magnetic-field disturbances. Periodically, these sensors transmit an updated count by radio to a regional repeater, which relays them to a central processing station. The package, powered by a single lithium battery, costs about $40, and can be installed in a few minutes without tearing up the road.

The central station uses the sensor data to compute queue-length and departure rate statistics for each road segment, and uses Little's Formula to assign a time in seconds to each road link. This database is published once a minute on the Internet. Vehicles will use CDPD or a similar wireless network standard to download the relevant sections of the database, and plan optimum (shortest time or least fuel) routes through the road network, informing the driver of suggested route changes in real time. We have also explored adding other minimally expensive sensors to this package, such as piezo pickups for detecting road vibration and perhaps accident signatures, and temperature and humidity sensors to determine local road conditions."

Car-counting data wirelessly uploaded from the above Vassar St. pothole, showing traffic building during the morning Cambridge rush hour, then abrubtly slowing as a traffic jam developed at peak commuting time (8 AM).

...

...
Potential Problems

Water Rsistance



Image Source

https://www.treehugger.com/best-e-bike-conversion-kits-5188910
https://senseable.mit.edu/copenhagenwheel/
https://resenv.media.mit.edu/vehicles.html
https://senseable.mit.edu/trashtrack/