Mobile Tape Measure (using IOS + Arduino)
Today we take a little departure from our usual pure code project and get our hands dirty with a very popular hardware called Arduino. Arduino is a highly popular open source hardware prototyping platform. In geek's term, it's a microcontroller that you can use to interface with other hardware, which you can then program to get you the desirable behavior. You already know how to program your phone, knowing how to create custom hardware that interfaces with your phone can take the value of your software skills to the next level, allowing you to do things that's otherwise impossible with computer alone. As such, knowing how to use something like Arduino gives you the ability to extend your computer or mobile hardware and make it do things that's outside of its current capabilities. In this post, we are going to do exactly that by creating a tape measure gadget and recording the distance data on our iPhone.
You can download the code for this project here.
Goal
The goal of this project is to detect the distance between you and the object in a place you can’t see, and display the distance on your iPhone's display.
Usages
- Measure distance between the sensor and the object in front of it.
- You can put the device on the back of your car to keep yourself from running into another car when you parallel park.
- You can put it on your pocket, if someone is too close to your pocket, the alarm will sound.
Ultrasonic Ranger
I use HC-SR04 as my ultrasonic range finder. It is a very popular on the market with stable performance and high accuracy. You can buy it from Amazon for $9.49.

Specifications:
- Ranging: 3 cm to 400 cm
- Resolution: 0.3 cm
HC-SR04 Datasheet
There are 4 pins out of this module from left to right, they are: VCC, Trig, Echo, GND.
The basic idea is that VCC connects to 5V, GND to ground to provide power. This creates an electrical potential difference, which causes electrons to flow, thereby giving you current. Trig is a trigger pin to tell the board to start working. When the Trig pin is set to high for more than 10-microsecond impulse, the module starts ranging. The Echo pin returns different duration of high level based on distance .
Distance = ((Duration of high level) * (Sonic:340m/s))/2
Connect HC-SR04 to Arduino

From left to right wire Red, Yellow, Green, Blue

Display on Arduino IDE serial monitor
/* HC-SR04 Ultrasonic module results to Arduino serial monitor
#define ECHOPIN // Pin to receive echo pulse
#define TRIGPIN // Pin to send trigger pulse
void setup()
{
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
void loop() {
// Trigger Trig pin to Start Ranging
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
// Compute distance
float distance = pulseIn(ECHOPIN, HIGH);
//pulseIn(pin,value) reads a pulse length of the value.(μs - microseconds)
distance = distance / 58;
// From datasheet: pluse width(μs)/58 = distance (cm)
// pluse width(uS)/148 = distance (inch)
Serial.println(distance);
delay(1000); // return distance per second.
}
Connect Arduino to iPhone through Redpark Serial

Based on Apple’s MFI licensing program, you must be an MFi licensee to develop hardware accessories that connect to your iDevice. But becoming a member of the MFi program is a long process. So I just buy “The Redpark Serial Cable” to connect to iPhone and a “P4B RS232 to TTL Serial Adapter” to do away with the hassles since we are just building a prototype.
Connections
- iPhone to Redpark (20pin)
- Redpark to P4b (Serial connection)
- P4b to Arduino (Wire)
- Download Redpark SDK from here
- Drag and drop redparkSerial.h, rscMgr.h header files from inc/folder and libRscMgrUniv.a from lib/folder into your project.
- Add External Accessory Framework from Build Phases tab.
- In your project's plist file. Add a new row named "Supported external accessory protocols", type "com.redpark.hobdb9" into Item0.
- Compile and Run to check if any errors.


Interface on iPhone

Declare three components in .h file
@property (weak, nonatomic) IBOutlet UITextField *inputText; @property (weak, nonatomic) IBOutlet UITextView *outputResult; - (IBAction)sendClick:(id)sender;
Add Redpark Serial Library
Add codes in your project
In your viewController’s header file, add these lines:
#import
#import "RscMgr.h"
#define BUFFER_LEN 1024
@interface ViewController : UIViewController {
RscMgr *rscMgr;
UInt8 rxBuffer[BUFFER_LEN];
UInt8 txBuffer[BUFFER_LEN];
}
@property (weak, nonatomic) IBOutlet UITextField *inputText;
@property (weak, nonatomic) IBOutlet UITextView *outputResult;
- (IBAction)sendClick:(id)sender;
@end
Then in ViewController.m file, inside viewDidLoad method add these two lines:
rscMgr = [[RscMgr alloc] init]; [rscMgr setDelegate:self];
After you init a instance of RscMgr and setup the delegate method to itself, it’s time to implement the delegate callbacks.
#pragma mark - RscMgrDelegate methods
- (void) cableConnected:(NSString *)protocol {
[rscMgr setBaud:9600];
[rscMgr open];
}
- (void) cableDisconnected { }
- (void) portStatusChanged { }
- (void) readBytesAvailable:(UInt32)numBytes {
int bytesRead = [rscMgr read:rxBuffer Length:numBytes];
NSLog( @"Read %d bytes from serial cable.", bytesRead );
for (int i = 0; i < numBytes;++i) {
self.outputResult.text = [NSString stringWithFormat:@"%@%c",self.outputResult.text,((char *)rxBuffer)[i]];
}
[self.outputResult scrollRangeToVisible:NSMakeRange([self.outputResult.text length], 0)];
}
cableConnected:protocol method setup the bit rate to 9600
readBytesAvaliable:numBytes method reads bytes from buffer and added them to Result display.
The last line: [self.outputResult scrollRangeToVisible:NSMakeRange([self.outputResult.text length], 0)];
The purpose of this line is to autoscroll Result display, so that the newest results always show on the bottom of the screen. At this point, if you run your application on iPhone and connect it to Arduino board, your iPhone will get the same output as Arduino IDE’s serial monitor.
One last thing
We did not implement the send button method yet. We don't really need it if we just want to display Ultrasonic Result on iPhone screen but it is still good to know how to do it for future use (say if you want persist the data).
- (IBAction)sendClick:(id)sender {
[self.inputText resignFirstResponder];
NSString *text = self.inputText.text;
int bytesToWrite = text.length;
for ( int i = 0; i < bytesToWrite; i++ ) {
txBuffer[i] = (int)[text characterAtIndex:i];
}
[rscMgr write:txBuffer Length:bytesToWrite];
}
Now when you click send button, it will send all bytes of what’s in inputText field to txBuffer one by one.
Mobile Tape Measure (side view)

Mobile Tape Measure (top view)

You can download the code for this project here.
arduino,
experiments,
iOS,
idevblogaday in
idevblogaday 


Reader Comments