4 DOF Arduino Robot Arm – Full Tutorial

Intro

In this tutorial, I will cover how to build this 4 DOF Arduino robot arm you can order under $40. The tutorial contains 4 parts: 0. Unboxing; 1. Assembly; 2. Electronics; 3. Codes

You can order it here: https://www.banggood.com/custlink/KGvvDNs7RV

Part 0: Unboxing

Part 1: Assembly

Part 2: Electronics

Part 3: Codes


#include "VarSpeedServo.h"
#include <EEPROM.h>
//120a120b120c120d
//90a90b90c90d

//120A120B120C120D
//90a90b90c90d

VarSpeedServo servo1;
VarSpeedServo servo2;
VarSpeedServo servo3;
VarSpeedServo servo4;

int potpin1 = 0;//Define the Jaw servo potentiometer to A0
int potpin2 = 1;//Define the Front Arm servo potentiometer to A1
int potpin3 = 2;//Define the Back Arm servo potentiometer to A2
int potpin4 = 3;//Define the Base servo potentiometer to A3


int val1;
int val2;
int val3;
int val4;

byte  mode ;
void setup()
{

  servo1.attach(11);               
  servo2.attach(10);  
  servo3.attach(9);                
  servo4.attach(6);


  Serial.begin(9600);
  Serial.write("begin");
}
void loop()
{
  static int v = 0;
  

  if ( Serial.available()) 

  {

    char ch = Serial.read();      
    switch(ch) {
    case '0'...'9':
      v = v * 10 + ch - '0'; 
      Serial.println(v);

      break;
    case 'a':             
      {
        if(mode==1)
          servo1.write(v,10);
      }
      v = 0;
      Serial.println(v);
      break;
    case 'b':             
      {  
        if(mode==1)
          servo2.write(v,10);
      }
      v = 0;
      Serial.println(v);
      break;   
    case 'c':             

      {
        if(mode==1)
          servo3.write(v,10);

      }
      v = 0;
      Serial.println(v);
      break;   
    case 'd':             
      {
        if(mode==1)
          servo4.write(v,10);

      }
      v = 0;
      Serial.println(v);
      break; 

      case 'A':             
      {
        if(mode==1)
          servo1.write(v,10,1);
      }
      v = 0;
      Serial.println(v);
      break;
    case 'B':             
      {  
        if(mode==1)
          servo2.write(v,10,1);
      }
      v = 0;
      Serial.println(v);
      break;   
    case 'C':             

      {
        if(mode==1)
          servo3.write(v,10,1);

      }
      v = 0;
      Serial.println(v);
      break;   
    case 'D':             
      {
        if(mode==1)
          servo4.write(v,10,1);

      }
      v = 0;
      Serial.println(v);
      break; 

    case 'W':
      { delay(2000);
        }
        break;
    case 'm':             
      {

        Serial.print("Mode = pot  ");
        EEPROM.write( 1001, 0);
        mode = EEPROM.read(1001);
        Serial.println(mode);
      }
      break; 
      v = 0;

    case 'n':             
      {

        Serial.print("Mode = pc   ");
        EEPROM.write( 1001, 1);
        mode = EEPROM.read(1001);
        Serial.println(mode);
      }
      break;
      v = 0;
    }
  }

  if(mode==0)

  {
    /////Jaw Servo Control///////
    val1 = analogRead(potpin1);
    Serial.println(val1);
    val1 = map (val1, 0, 1023, 0, 179);
    Serial.println(val1);
    servo1.write(val1);
    delay(10);


    //////Front Arm Servo Control///////
    val2 = analogRead(potpin2);
    val2 = map (val2, 0, 1023, 0, 179);
    servo2.write(val2);
    delay(10);  

    //////Back Arm Servo Control///////
    val3 = analogRead(potpin3);
    val3 = map (val3, 0, 1023, 0, 179);
    servo3.write(val3);
    delay(10);

    //////Base Servo Control/////// 
    val4 = analogRead(potpin4);
    val4 = map (val4, 0, 1023, 0, 179);
    servo4.write(val4);
    delay(10);






  }



}

Download the codes here:

Robot Arm Code

24 in 1 Clock – tells time of 24 time zones. Make your own at home from paper

The world is getting smaller and smaller, you might have a family member or friend that lives in a different time zone. Sometimes it can be confusing what time it is in another side of the earth. So I designed this 24 in 1 clock, that you can see all 24 times at one time.

Step 1: Parts and Tools:

Parts:

2 x page of 110 lb (199 g/m²), letter sized index paper

1 x clock mechanism ~ $1.5

1 x AA Battery

Tools:

A pair of scissors

Paper knife

Printer

Tape

Ruler for cutting and scoring

 

 

Step 2: How to Read the Clock

The major innovation of this clock is how to read the hours. Instead of the hour handle, I replaced it with a disc with a red spiral. The front clock face has numbers of slots that matches 24 time zones. So at where the red line meet the slot, you can read the current hour of that time zone.

The minute just works as a normal clock, since all the minutes in 24 time zones are the same 😀

 

Step 3: Print the Patterns

There are 2 options of patterns you can download, the major difference is the clock faces:

1. Full clock face with 24 time zones and cities.

2. Full clock face with 24 time zones with no cities.

Of course you can customize the clock face with only the time zones and cities you care about. An ai file is here so you can use adobe illustrator or Inkscape (free) to edit it. You can also mark the slots where you have family and friends.

Make sure to print it out with 100% scale.

The graphic files are here:

24 in 1 Clock 1.0 072018.ai

24 in 1 Clock 1.0 072018

Step 4: Cut and Score the Patterns

Cut all the patterns perimeter and inside cutouts with a knife.

 

Picture of Cut and Score the Patterns

 

Step 5: Fold the Pieces

 

1. Fold the two rectangular pieces as holders for the clock front. Use small pieces of tape to hold the folds on the ends.

2. Fold the spacer.

3. Fold the 4 “feet” of the clock face.

4.Fold the minute handle: Make sure to score the center line, fold it, then cut the rest of the white flaps, they are there for easier folding. (You don’t have to use this minute handle if you are happy with the one come with the clock mechanism).

Step 6: Stack Them Up

 

1. Disassemble the clock mechanism. Make sure to unscrew the nut on the clock screw.

2. Put 2 holder pieces on the clock screw, then secure it with the clock nut.

3. Add the spiral disc on to the hour cylinder of the clock.

4. Add spacer piece.

5. Put the clock face, and tackle the “feet” in the folded slots of the holder.

6. Install minute handle on to the minute cylinder.

7. Add the second handle if you like. In my design, I replaced it with a small disc just to show if the clock is running.

Step 7: Hang the Clock

 

Wrap the hanger piece around the AA battery, insert it to the clock and it should start ticking.

You can adjust the clock either use the clock knob, or just gently turn the disc.

Hang the clock to your wall with any nail and that’s all done!

Thanks for watching and see you next time!

How to Find Synced Typekit Fonts on Your Computer

http://dylanvalade.tumblr.com/post/74649521957/how-to-find-synced-typekit-fonts-on-your-computer

Chen: Make sure you restart Finder after the terminal line, Hold Option + right click on finder and then relaunch

Are you using Adobe CC and syncing fonts from Typekit to your desktop? If you’re on OSX you can follow these steps to see where those fonts live.

Occasionally Typekit takes my desktop fonts away which is scary in the middle of a project or en route to a design presentation. I then have to open the Creative Cloud app and re-sync the fonts. That’s an understandable workaround but I needed a viable game plan to meet a deadline even if Typekit or my connectivity is unreliable for a matter of hours. Now I sleep better knowing that I can still complete a project without worrying about the mystery sync bugs.

We’re going to use Terminal and Finder to locate these files. First you’ll need to enable viewing hidden files.

Open Terminal. Paste this command without the $ sign and click enter:
$ defaults write com.apple.finder AppleShowAllFiles TRUE
Now Finder displays hidden folders and files on your computer. “Hidden” files are now distinguished from normal files by being slightly transparent.
Open Finder. Go to Macintosh HD/Users/YOURNAME/Library/Application Support/Adobe/CoreSync/plugins/livetype/.r/
Your fonts are in this .r folder named FONTID.otf
My terminal below shows the list of files in .r by running ls -la
Finder below displays the font files copied to a normal folder

image

Finder won’t let you change the folder or file names prefixed with a dot like a normal file.

After you copy the .r folder to a safe place on your computer, right click the copy of .r and select Get Info. Change the copied .r folder name to TypeKit by expanding the Filename & Extension option. Use Get Info for each font you need to use offline. This image explains how to do it.

image

The fonts are open type files named with a dot prefix and font id like .70.otf. If you want to play with the files and not mess with your CC configuration you can use Finder (or Terminal) to copy them and paste the files somewhere else.

Terminal Option: Open Terminal and “move” the files while simultaneously changing their names, which renames them. Example:

$ mv .70.otf Bree-Bold.otf

There is an XML file in …/livetype/.c/entitlements.xml with the list of fonts that correlate to each font id. But if you open the Get Info window for each font you can see the Full Name field without needing to look at the XML.

If you want Finder to hide the hidden files and folders again paste this in Terminal and click enter:
$ defaults write com.apple.finder AppleShowAllFiles FALSE

Robot Car Part 3 Code Preview

Update: If you want to control the motor speeds, please swap pin 11 and pin 13 connections, as well as update the define section in the code. Pin 13 is not PWM pin but pin 11 is. sorry for the mistake.

This is the code preview for the smart robot car tutorial. Load it to your arduino board then it should work. Please let me know down below if you running to any problems.

#include <Servo.h>

// Pins
#define TRIG_PIN A0
#define ECHO_PIN A1

//Define all the connections maps to the L298N
#define enA 13
#define in1 12
#define in2 11
#define in3 7
#define in4 6
#define enB 5
#define servoPin 2

class Motor{

int enablePin;
int directionPin1;
int directionPin2;

public:

//Method to define the motor pins
Motor(int ENPin,int dPin1,int dPin2){
enablePin = ENPin;
directionPin1 = dPin1;
directionPin2 = dPin2;
};

//Method to drive the motor 0~255 driving forward. -1~-255 driving backward
void Drive(int speed){
if(speed>=0){
digitalWrite(directionPin1, LOW);
digitalWrite(directionPin2, HIGH);
}
else{
digitalWrite(directionPin1, HIGH);
digitalWrite(directionPin2, LOW);
speed = - speed;
}
analogWrite(enablePin, speed);
}
};

Motor leftMotor = Motor(enA, in1, in2);
Motor rightMotor = Motor(enB, in3, in4);
Servo myservo; // create servo object to control a servo

void motorInitiation(){
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
// Set initial direction and speed
digitalWrite(enA, LOW);
digitalWrite(enB, LOW);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
}

//Variables--------------------------------------------------------------------------
// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;
bool ObsticalAhead = false;
int servoPos = 90;

enum Directions { Forward, TurnLeft, TurnRight, TurnAround,Brake};

Directions nextStep = Forward;

unsigned long t1;
unsigned long t2;
unsigned long pulse_width;
float cm;
float inches;

//SETUP--------------------------------------------------------------------------
void setup() {

// The Trigger pin will tell the sensor to range find
pinMode(TRIG_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);

// We'll use the serial monitor to view the sensor output
Serial.begin(9600);
myservo.attach(servoPin);
motorInitiation();
Directions nextStep = Forward;
}

void loop() {

checkDistance();
checkDirection();
drive();
}

void checkDistance(){

// Hold the trigger pin high for at least 10 us
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// Wait for pulse on echo pin
while ( digitalRead(ECHO_PIN) == 0 );

// Measure how long the echo pin was held high (pulse width)
// Note: the micros() counter will overflow after ~70 min
t1 = micros();
while ( digitalRead(ECHO_PIN) == 1);
t2 = micros();
pulse_width = t2 - t1;

// Calculate distance in centimeters and inches. The constants
// are found in the datasheet, and calculated from the assumed speed
//of sound in air at sea level (~340 m/s).
cm = pulse_width / 58.0;
inches = pulse_width / 148.0;

// Print out results
if ( pulse_width > MAX_DIST ) {
//Serial.println("Out of range");
} else {
//Serial.print(cm);
//Serial.print(" cm \t");
//Serial.print(inches);
//Serial.println(" in");
}

// Wait at least 60ms before next measurement
delay(60);

if(cm<= 20){
ObsticalAhead = true;
Serial.println("Problem Ahead");

}
else{ ObsticalAhead = false;}

}
void checkDirection(){
Serial.println("checking direction");
if(ObsticalAhead ==true){
nextStep = Brake;
drive();
myservo.write(180); // tell servo to go to position in variable 'pos'
delay(400); // waits 15ms for the servo to reach the position
checkDistance();
if(ObsticalAhead ==false){//if left side is open
nextStep = TurnLeft;
Serial.println("Next step is TurnLeft");
myservo.write(90);//reset servo position
delay(400);
}
else{// left is blocked, now need to look at right
myservo.write(0); // tell servo to go to position in variable 'pos'
delay(800); // waits 15ms for the servo to reach the position
checkDistance();
if(ObsticalAhead ==false){//if right side is open
nextStep = TurnRight;
Serial.println("Next step is TurnRight");
myservo.write(90);//reset servo position
delay(400);
}
else{//right is blocked as well, need to turn around
nextStep = TurnAround;
myservo.write(90);//reset servo position
delay(300);
Serial.println("Next step is TurnAround");
}
}

}
else{nextStep = Forward;}//No obstical ahead
}

void drive(){
switch (nextStep){
case Forward:
leftMotor.Drive(255);
rightMotor.Drive(255);
Serial.println("Forward");

break;
case TurnLeft:
leftMotor.Drive(-255);
rightMotor.Drive(255);
Serial.println(" TurnLeft");
delay(400);

break;
case TurnRight:
leftMotor.Drive(255);
rightMotor.Drive(-255);
Serial.println(" TurnRight");
delay(400);
break;
case TurnAround:
leftMotor.Drive(255);
rightMotor.Drive(-255);
Serial.println(" TurnAround");
delay(600);
break;

case Brake:
leftMotor.Drive(0);
rightMotor.Drive(0);
Serial.println(" stopped");
}

}

11,948 total views, 0 views today

Unity Touch keyboard on win10

https://answers.unity.com/questions/1134775/on-screen-keyboard-pc-and-console-best-practices.html

 

First you need to create VirtualKeyboard.cs script

  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Diagnostics;
  5. using System.Runtime.InteropServices;
  6. public class VirtualKeyboard
  7. {
  8. [DllImport("user32")]
  9. static extern IntPtr FindWindow(String sClassName, String sAppName);
  10. [DllImport("user32")]
  11. static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
  12. private static Process _onScreenKeyboardProcess = null;
  13. /// <summary>
  14. /// Show the touch keyboard (tabtip.exe).
  15. /// </summary>
  16. public void ShowTouchKeyboard()
  17. {
  18. ExternalCall("C:\\Program Files\\Common Files\\Microsoft Shared\\ink\\tabtip.exe", null, false);
  19. //ExternalCall("TABTIP", null, false);
  20. }
  21. /// <summary>
  22. /// Hide the touch keyboard (tabtip.exe).
  23. /// </summary>
  24. public void HideTouchKeyboard()
  25. {
  26. uint WM_SYSCOMMAND = 274;
  27. int SC_CLOSE = 61536;
  28. IntPtr ptr = FindWindow("IPTip_Main_Window", null);
  29. PostMessage(ptr, WM_SYSCOMMAND, SC_CLOSE, 0);
  30. }
  31. /// <summary>
  32. /// Show the on screen keyboard (osk.exe).
  33. /// </summary>
  34. public void ShowOnScreenKeyboard()
  35. {
  36. //ExternalCall("C:\\Windows\\system32\\osk.exe", null, false);
  37. if (_onScreenKeyboardProcess == null || _onScreenKeyboardProcess.HasExited)
  38. _onScreenKeyboardProcess = ExternalCall("OSK", null, false);
  39. }
  40. /// <summary>
  41. /// Hide the on screen keyboard (osk.exe).
  42. /// </summary>
  43. public void HideOnScreenKeyboard()
  44. {
  45. if (_onScreenKeyboardProcess != null && !_onScreenKeyboardProcess.HasExited)
  46. _onScreenKeyboardProcess.Kill();
  47. }
  48. /// <summary>
  49. /// Set size and location of the OSK.exe keyboard, via registry changes. Messy, but only known method.
  50. /// </summary>
  51. /// <param name='rect'>
  52. /// Rect.
  53. /// </param>
  54. public void RepositionOnScreenKeyboard(Rect rect)
  55. {
  56. ExternalCall("REG", @"ADD HKCU\Software\Microsoft\Osk /v WindowLeft /t REG_DWORD /d " + (int)rect.x + " /f", true);
  57. ExternalCall("REG", @"ADD HKCU\Software\Microsoft\Osk /v WindowTop /t REG_DWORD /d " + (int)rect.y + " /f", true);
  58. ExternalCall("REG", @"ADD HKCU\Software\Microsoft\Osk /v WindowWidth /t REG_DWORD /d " + (int)rect.width + " /f", true);
  59. ExternalCall("REG", @"ADD HKCU\Software\Microsoft\Osk /v WindowHeight /t REG_DWORD /d " + (int)rect.height + " /f", true);
  60. }
  61. private static Process ExternalCall(string filename, string arguments, bool hideWindow)
  62. {
  63. ProcessStartInfo startInfo = new ProcessStartInfo();
  64. startInfo.FileName = filename;
  65. startInfo.Arguments = arguments;
  66. // if just command, we don't want to see the console displayed
  67. if (hideWindow)
  68. {
  69. startInfo.RedirectStandardOutput = true;
  70. startInfo.RedirectStandardError = true;
  71. startInfo.UseShellExecute = false;
  72. startInfo.CreateNoWindow = true;
  73. }
  74. Process process = new Process();
  75. process.StartInfo = startInfo;
  76. process.Start();
  77. return process;
  78. }
  79. }

then call from your script like below

  1. VirtualKeyboard vk = new VirtualKeyboard();
  2. public void OpenKeyboard()
  3. {
  4. {
  5. vk.ShowTouchKeyboard();
  6. }
  7. }
  8. public void CloseKeyboard()
  9. {
  10. {
  11. vk.HideTouchKeyboard();
  12. }
  13. }

 

 

Resizing

http://forum.tabletpcreview.com/threads/how-to-resize-on-screen-keyboard.70030/

 

The gigantic On-Screen keyboard covers up half of the screen
and program window on my Surface Pro 3. using Windows 8.1
I have been using the M.S. Accessibility keyboard as you can resize it, but it
has the huge sidebars, etc. and you can not write out text input.

A friend showed me a Registry hack that resizes the OnScreen Keyboard.
(As always, back up your registry, use at your own risk)

1) Go to RUN–
Type :
regedit

2) Browse to:
HKLM(Local Machine)>Software>Microsoft>Windows>CurrentVersion>Explorer

3) Once at Explorer> Rt Click on Explorer folder and Add New Key
Type:
Scaling
(This adds a new folder titled ‘Scaling’ under Explorer)

4) Rt Click on Scaling folder:
Add– New String Value
Type:
Monitorsize

5) Double Click on MoniterSize:
Enter String Value “25”
(For a half screen-width keyboard)

6) Restart or Shut down/Restart
Keyboard will now pop up much smaller

Smaller numbers results in larger keyboard.
20=2/3 screen width
Experiment for your desired size.

So far I have not experienced any abnormalities, in other programs
I use Internet Explorer for web browsing.

I understand it also works in Windows 10,
but I don’t have Windows 10 to test it.

Arduino Smart Robot Car-Part 2

This is the second part tutorial of the smart robot car from banggood. In this video, I gonna cover all the electronic connections and test codes to make sure everything works.

Connections

Updates: please watch the part 3 tutorial for some of the connection updates here: Arduino Smart Robot Car from Banggood: PART3 Updates for the full CodesBasically you need to connect the servo pins from pin 0 tp pin 2 if you want to read ultrasonic data through serial monitor. The digital pin 0 and 1 need to be blank for serial monitor.Also the L298N controlling pins we were using(5 to 10) has conflict with the servo.h library. The library explicily mentioned the pin 9 and 10 need to be blank. So we have to mov e the pins on 8,9,10 to 11,12,13.

Smart Car Motor Test

/* Arduino DC Motor L298N Module H-bridge DC Motor Test
By Chen The Design Maker chenthedesignmaker.com
*/

//Define all the connections maps to the L298N
#define enA 10
#define in1 9
#define in2 8
#define in3 7
#define in4 6
#define enB 5

class Motor{

int enablePin;
int directionPin1;
int directionPin2;
public:

//Method to define the motor pins
Motor(int ENPin,int dPin1,int dPin2){
enablePin = ENPin;
directionPin1 = dPin1;
directionPin2 = dPin2;
};

//Method to drive the motor 0~255 driving forward. -1~-255 driving backward
Drive(int speed){
if(speed>=0){
digitalWrite(directionPin1, LOW);
digitalWrite(directionPin2, HIGH);
}
else{
digitalWrite(directionPin1, HIGH);
digitalWrite(directionPin2, LOW);
speed = - speed;
}
analogWrite(enablePin, speed);
}
};
Motor leftMotor = Motor(enA, in1, in2);
Motor rightMotor = Motor(enB, in3, in4);

void setup() {
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
// Set initial direction and speed
digitalWrite(enA, LOW);
digitalWrite(enB, LOW);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
}

void loop() {

leftMotor.Drive(200);
rightMotor.Drive(200);

delay(500);

leftMotor.Drive(0);
rightMotor.Drive(0);

delay(250);

leftMotor.Drive(150);
rightMotor.Drive(-150);

delay(500);

leftMotor.Drive(0);
rightMotor.Drive(0);

delay(250);

}

Servo Test:

/* Sweep
by BARRAGAN <http://barraganstudio.com>
This example code is in the public domain.

modified 8 Nov 2013
by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0; // variable to store the servo position

void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

/**
* HC-SR04 Demo
* Demonstration of the HC-SR04 Ultrasonic Sensor
* Date: August 3, 2016
*
* Description:
* Connect the ultrasonic sensor to the Arduino as per the
* hardware connections below. Run the sketch and open a serial
* monitor. The distance read from the sensor will be displayed
* in centimeters and inches.
*
* Hardware Connections:
* Arduino | HC-SR04
* -------------------
* 5V | VCC
* A0 | Trig
* A1 | Echo
* GND | GND
*
* License:
* Public Domain
*/

// Pins
const int TRIG_PIN = A0;
const int ECHO_PIN = A1;

// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;

void setup() {

// The Trigger pin will tell the sensor to range find
pinMode(TRIG_PIN, OUTPUT);
digitalWrite(TRIG_PIN, LOW);

// We'll use the serial monitor to view the sensor output
Serial.begin(9600);
}

void loop() {

unsigned long t1;
unsigned long t2;
unsigned long pulse_width;
float cm;
float inches;

// Hold the trigger pin high for at least 10 us
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// Wait for pulse on echo pin
while ( digitalRead(ECHO_PIN) == 0 );

// Measure how long the echo pin was held high (pulse width)
// Note: the micros() counter will overflow after ~70 min
t1 = micros();
while ( digitalRead(ECHO_PIN) == 1);
t2 = micros();
pulse_width = t2 - t1;

// Calculate distance in centimeters and inches. The constants
// are found in the datasheet, and calculated from the assumed speed
//of sound in air at sea level (~340 m/s).
cm = pulse_width / 58.0;
inches = pulse_width / 148.0;

// Print out results
if ( pulse_width > MAX_DIST ) {
Serial.println("Out of range");
} else {
Serial.print(cm);
Serial.print(" cm \t");
Serial.print(inches);
Serial.println(" in");
}

// Wait at least 60ms before next measurement
delay(60);
}

Parts list:

Smart Robot Car kit:

https://www.banggood.com/DIY-L298N-2WD-Ultrasonic-Smart-Tracking-Moteur-Robot-Car-Kit-For-Arduino-p-1155139.html?p=JH2514288496201309O3

M3 *10mm Standoffs:

https://www.banggood.com/50pcs-M3-10mm-Brass-Female-Threaded-Hex-Standoffs-Spacer-Nut-DIY-PCB-Parts-p-1007519.html?p=JH2514288496201309O3
Amazon: http://amzn.to/2Auwbzq

Extra servo for pan and tilt camera mount:

https://www.banggood.com/TowerPro-SG90-Mini-Gear-Micro-Servo-9g-For-RC-Airplane-Helicopter-p-1009914.html?p=JH2514288496201309O3
Amazon: http://amzn.to/2jO7BBE

Speed encoder kit(Will cover in later video):

https://www.banggood.com/HC-020K-Double-Speed-Measuring-Module-With-Speed-Encoder-Kit-p-970327.html?p=JH2514288496201309O3
Amazon: http://amzn.to/2kq7H6J

3 in 1 Jumper cable set:

https://www.banggood.com/3-IN-1-120pcs-10cm-Male-To-Female-Female-To-Female-Male-To-Male-Jumper-Cable-Dupont-Wire-For-Arduino-p-1054670.html?p=JH2514288496201309O3
Amazon: http://amzn.to/2D5QYuw

Let me know if you have any kit that need help with!

My Website: http://chenludesign.com
My Instagram:https://www.instagram.com/friedlc/
My Dribbble: https://dribbble.com/chenludesign
My Instructable: https://www.instructables.com/member/Friedlc/

DISCLAIMER: This video and description contains affiliate links, which means that if you click on one of the product links, I’ll receive a small commission. This help support the channel and allows us to continue to make videos like this. Thank you for the support!

DISCLAIMER: This post contains affiliate links, which means that if you click on one of the product links, I’ll receive a small commission. This help support the channel and allows us to continue to make videos like this. Thank you for the support!