How to connect iPhone to Arduino

how to control arduino iphone and how to use iphone with arduino and how to connect a cell phone to arduino and how to connect android phone to arduino uno
Dr.KiranArora Profile Pic
Published Date:27-10-2017
Your Website URL(Optional)
CHAPTER 2 Connecting the iPhone to the Arduino The arrival of the External Accessory framework with iOS 3 was seen, initially at least, as having the potential to open the iOS platform up to a host of external accessories and additional sensors. Sadly, little of the innovation people were expecting actually occurred, and while there are finally starting to be some interesting products arriving on the market, for the most part the External Accessory framework is being used to support a fairly predictable range of audio and video accessories from big-name manufacturers. The Apple MFi Program The reason for this lack of innovation is usually laid at the feet of Apple’s Made for iPod (MFi) licensing program. The MFi Program is entirely separate from the Apple Developer Program. Being a registered Apple Developer or a member of the iOS De- veloper Program does not automatically admit you to the MFi Program. However, to develop hardware accessories that connect to the iPod, iPhone, or iPad, you must be an MFi licensee. If you are interested in developing your own hardware, more informa- tion about the MFi licensing program can be found at http://developer Licensed developers gain access to technical documentation, hardware components, and technical support that will allow them to build external hardware that can connect to the iPod, iPhone, or iPad. Unfortunately, becoming a member of the MFi program is not as simple as signing up as an Apple Developer, and it is a fairly lengthy process. From personal experience I can confirm that the process of becoming an MFi licensee is not for the faint-hearted. And once you’re a member of the program, getting your hardware out of prototype stage and approved by Apple for distribution and sale is not necessarily a simple process. 15 Redpark Serial Cable Until recently, the restrictions placed on developers by the existence of the MFi program meant that if you were an independent developer, or even a small company, you prob- ably couldn’t get access to the documentation and components you needed to connect your iOS device to an arbitrary piece of existing hardware. Since many of those pieces of existing hardware have serial (RS-232) interfaces, the arrival of the Redpark Serial Cable makes connecting to such hardware fairly easy. The cable arrives in a plain white box; inside is the cable itself (Apple Dock Connector to male 9-pin RS-232 serial) and a loopback test adaptor that allows you to test the cable (see Figure 2-1). Figure 2-1. The Redpark Serial Cable (left) and loopback adaptor (right) The Redpark cable is available in the Maker Shed as the “Redpark iPhone Breakout Pack for Arduino” or directly from the manufacturer. The Redpark Serial Cable SDK comes as a .dmg file. You can download the latest version of the SDK from _Downloads.html. 16 Chapter 2: Connecting the iPhone to the Arduino the Cable There are two ways to test that your cable works correctly before we go ahead and start writing code to use it. First, when the cable is plugged in, there should be a new entry in the Settings application; if you go to General→About→Serial Cable, you should see something like Figure 2-2. If the cable is plugged into your iOS device and you do not see this settings entry, or there seems to be something wrong with it, there may be something wrong with your cable. Figure 2-2. Checking the cable in the Settings application Additionally, the Redpark Serial Cable ships with a loopback adaptor (see Figure 2-3) and a demo application called Rsc Demo. If you open the demo application in Xcode and then build and deploy it onto your device, you should be able to perform a loopback test using this adaptor. Plug the adaptor into the RS-232 end of the cable, and then plug the cable into the dock connector. Run the Rsc Demo application and tap on the Loop Test button. If you do not see a UIAlertView, as in Figure 2-3, informing you that the loopback test has been successful, then, again, there may be something wrong with your cable. Assuming your new cable passes both of these tests, however, you should assume that all is well, and we can now go ahead and write some code. The Redpark Serial Cable 17 2-3. Performing a loopback test in the Rsc Demo Application Connecting to the Arduino While the original Arduino board used RS-232 serial to connect to the development machine, more recent models use USB. We therefore need an adaptor to translate from RS-232 serial used by the Redpark cable to the TTL serial that we can easily connect to the Arduino transmit/receive (TX/RX) pins (pin 1 and 0, respectively). To do this conversion I’m using the SparkFun RS-232 Shifter (see Figure 2-4; http://; 13.95), although any equivalent unit would suffice. For instance, the Maker Shed carries the equally effective but slightly cheaper (7) P4 Adapter Kit. As you can see from Figure 2-4, the TTL end has four wires: RX, TX, GND, and VCC (5V). The easiest way to connect this to our Arduino is to solder some snapable header pins to four lengths of single core wire (see Figure 2-5) and build a custom jumper cable (see Figure 2-6). You can, of course, just make use of premade jumper cables; the Maker Shed, for instance, sells a set of Breadboard Jumper Wires that you could use instead of soldering up your own cable. 18 Chapter 2: Connecting the iPhone to the Arduino 2-4. The SparkFun RS-232 Shifter SMD (sku: PRT-00449) Figure 2-5. Single core wire (top) and snapable header pins (bottom) Connecting to the Arduino 19 2-6. The completed jumper cable Once you have bought or built your jumper cable, connect the Redpark Serial Cable to your RS-232 to TTL serial adaptor, and that in turn (using your jumper cable) to your Arduino board, as shown in Figure 2-7. To do so, connect the VCC pin of your adaptor to the 5V pin on the Arduino, the GND pin to one of the available GND pins on the Arduino, the RX pin on the adaptor to the TX pin on the Arduino, and the TX pin on the adaptor to the RX pin on the Arduino. The receive (RX) pin on your Arduino board (pin 0) must be routed to the transmit (TX) pin on your adaptor, and the transmit (TX) pin on the Arduino board (pin 1) must in turn be connected to the receive (RX) pin on your adaptor. If these are not correctly connected, your applications will not work. Do not connect RX to RX and TX to TX. You can power the Arduino board either via a USB cable, plugged into your Mac or a wall adaptor, or via a battery pack. Since I had one lying around, I used a battery pack, but it’s entirely up to you. 20 Chapter 2: Connecting the iPhone to the Arduino 2-7. Connecting the cable to the Arduino Connecting to an iOS Device Once you’ve powered your Arduino, and hence the RS-232 to TTL serial adaptor, the only thing left to do is plug the Redpark Serial Cable into your iOS device (Figure 2-8). Unfortunately, we’re going to spend a lot of time plugging and unplugging our iPhone or iPad from the Redpark cable, as we’ll need to plug the device into our Mac to deploy our development code to it. For now, however, we’re good to go. Let’s go ahead and write some code to demonstrate the cable. A Simple Serial Application Our first application making use of the serial cable will be a simple serial terminal, replicating the functionality of the serial console in the Arduino development environ- ment. Open Xcode, choose to create a new project, select a View-based Application for the iPhone, and when prompted name it “SerialConsole” and save it to the Desktop. Let’s start by building our interface. Click on the SerialConsoleViewController.xib file to open it in Interface Builder. Open up the Utilities pane and then drag and drop a UINavigationBar, UITextField, UIButton, and a UITextView into the View from the Ob- ject library. Arrange them in a fashion similar to Figure 2-9. A Simple Serial Application 21 2-8. Powering the Arduino, and connecting the cable to the iPhone Figure 2-9. Building the SerialConsole app’s user interface 22 Chapter 2: Connecting the iPhone to the Arduino’re going to make use of the real estate offered by the navigation bar later in the chapter to add a UIBarButtonItem. But for now, change the title text to read “Serial Console,” and we’ll come back to it later on. Finally, select and delete the Lorem ipsum text from the UITextView, and uncheck the Editable checkbox in the Attributes tab of the Utilities pane so that users won’t be able to obscure the view of the text window by accidentally popping up the keyboard. Close the Utilities pane and open the Assistant Editor, making sure it’s set to Automatic and is displaying the SerialConsoleViewController.h file. Then Ctrl-click and drag from the UITextField, UIButton, and UITextView to the editor window to create an IBOutlet property for each item, named textEntry, sendButton, and serialView, respectively. Then Ctrl-click and drag once again from the UIButton to create an IBAction called sendString: (see Figure 2-10). Finally, right-click on the UITextField to bring up the Text Fields outlets, events, and actions pane and click and drag to connect the Did End on Exit event to the same sendString: method. Doing this means that the same send String: method is called either when you tap on the Send button or tap on Return when entering characters into the text entry field itself. Figure 2-10. Connecting the outlets and actions A Simple Serial Application 23 connecting your UI elements to the interface file, your SerialConsoleViewCon- troller.h header file should look something like this: import UIKit/UIKit.h interface SerialConsoleViewController : UIViewController UITextField textEntry; UIButton sendButton; UITextView serialView; property (nonatomic, retain) IBOutlet UITextField textEntry; property (nonatomic, retain) IBOutlet UIButton sendButton; property (nonatomic, retain) IBOutlet UITextView serialView; - (IBAction)sendString:(id)sender; end with corresponding changes in the implementation file. Now click on the SerialCon- soleViewController.m implementation file, and add the following line to the send String: method: - (IBAction)sendString:(id)sender self.textEntry resignFirstResponder; // Add code here This will ensure that the keyboard is dismissed when the user presses the Send button to send a string of characters. We’ll come back to this later in the chapter. Adding the Redpark Serial Library Now we’ve got the bare bones of a user interface; let’s go ahead and start filling in behind the scenes. Open up your copy of the Redpark Serial SDK and grab the red- parkSerial.h and rscMgr.h header files from the inc/ folder, and the libRscMgrUniv.a static library from lib/ (see Figure 2-11). The libRscMgrUniv.a library is a universal (fat) library supporting the x86 architecture for use in the Simulator as well as the armv6 and armv7 architectures for use on the device hardware itself. Drag and drop them into your SerialConsole project, remembering to tick the “Copy items into destination group’s folder (if needed)” checkbox when prompted. Since the SDK makes use of the External Accessory framework, we also need to add this to the project at this stage. Click on the project icon at the top of the Project pane in Xcode, then click on the SerialConsole Target, and then on the Build Phases tab. Finally, click on the Link Binary with Libraries item to open up the list of linked frame- works, and click on the + symbol to add a new framework. Select the External Accessory framework from the drop-down list and click the Add button (as in Figure 2-12). 24 Chapter 2: Connecting the iPhone to the Arduino 2-11. The Redpark Serial SDK Figure 2-12. Adding the External Accessory framework to the project A Simple Serial Application 25, we need to declare support for the cable in our application’s Info.plist file. If we don’t do this, we’ll get something that looks like Figure 2-13 every time we plug the cable into the device. Figure 2-13. The unsupported External Accessory window Click on the SerialConsole-Info.plist file to open it in the editor. Right-click on the bottommost row of the list and select Add Row from the menu. An extra row will be added to the table, and you’ll be presented with a drop-down menu. Type UISupportedExternalAccessoryProtocols into the box. This will change to the human- readable text “Supported external accessory protocols.” Type the string com.redpark.hobdb9 into Item 0, as in Figure 2-14. Now that we’ve added the necessary files to our project and configured our application to support the cable, click on the SerialConsoleViewController.h header file and add the code highlighted below to the file: 26 Chapter 2: Connecting the iPhone to the Arduino 2-14. Declaring support for the cable in the Info.plist file import UIKit/UIKit.h import "RscMgr.h" define BUFFER_LEN 1024 interface SerialConsoleViewController : UIViewController RscMgrDelegate RscMgr rscMgr; UInt8 rxBufferBUFFER_LEN; UInt8 txBufferBUFFER_LEN; UITextField textEntry; UIButton sendButton; UITextView serialView; property (nonatomic, retain) IBOutlet UITextField textEntry; property (nonatomic, retain) IBOutlet UIButton sendButton; property (nonatomic, retain) IBOutlet UITextView serialView; - (IBAction)sendString:(id)sender; end Then, in the corresponding SerialConsoleViewController.m implementation file, un- comment the viewDidLoad method and add the following highlighted lines: - (void)viewDidLoad super viewDidLoad; rscMgr = RscMgr alloc init; rscMgr setDelegate:self; A Simple Serial Application 27 will initialize the Redpark Serial Cable Manager and set its delegate to be this class. After doing so, we need to add the mandatory 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.serialView.text = NSString stringWithFormat:"%%c", self.serialView.text, ((char )rxBuffer)i; - (BOOL) rscMessageReceived:(UInt8 )msg TotalLength:(int)len return FALSE; - (void) didReceivePortConfig Here we pass the rxBuffer instance variable by reference into the rscMgr’s read:Length: method, which will modify it in-place. This isn’t normal behavior for an Objective-C method, so be careful. Here we’re appending the characters in the newly populated rxBuffer array to the text already in the UITextView. Although we have to implement all of the mandatory methods, in our bare-bones im- plementation we’re really only interested in the cableConnected: and readBytesAvaila ble: callbacks. Connecting the Arduino We’ve reached a good point to stop and test the code; click on the Run button in the Xcode toolbar to build and deploy the code onto your iPhone. Once the application 28 Chapter 2: Connecting the iPhone to the Arduino been put onto the iPhone, click on the Stop button to stop it running and unplug your phone from your Mac. To test the code, we can use the simple serial sketch we used in the previous chapter: void setup() Serial.begin(9600); void loop() while (Serial.available() = 0) Serial.println("Hello world"); delay(300); Serial.println("Goodbye world"); while(1) If you don’t already have the sketch loaded onto an Arduino, open up the Arduino development environment and load the sketch. Then connect the Arduino to the Red- park cable, and the Redpark cable to your iPhone. Then tap on the SerialConsole app to resume execution. If you’ve plumbed everything together correctly, you should get something that looks very much like Figure 2-15. Just like the serial console on your Mac, the Arduino says “Hello World.” Figure 2-15. The SerialConsole app connected to an Arduino A Simple Serial Application 29 Data Back to the Arduino While your iPhone can now receive data from the Arduino, we can’t yet send data. Don’t worry; this is actually a lot easier than receiving data. Click on the SerialConso- leViewController.m implementation file and scroll down until you find the send String: method. Add the following lines: - (IBAction)sendString:(id)sender self.textEntry resignFirstResponder; NSString text = self.textEntry.text; int bytesToWrite = text.length; for ( int i = 0; i bytesToWrite; i++ ) txBufferi = (int)text characterAtIndex:i; int bytesWritten = rscMgr write:txBuffer Length:bytesToWrite; Here we take the text in the UITextField widget and pack the string into the txBuffer one byte at a time. We then use the rscMgr and write the buffer to the serial port. Go ahead and unplug your iPhone from the Redpark cable, and plug it back into your Mac. Once it’s visible again to Xcode, click on the Run button in Xcode to build and deploy the application to your iPhone once again. After it starts up, click on the Stop button and disconnect the iPhone from your Mac and reconnect the Redpark cable. Tap on the SerialConsole application to resume execution. When you see the “Hello World” messages scroll up the text view, tap on the text entry widget and type a few characters. Then tap the Send button. You should see something like Figure 2-16, and the “Goodbye World” message. If you want to add a blinking light at this point, you could insert an LED into pin 13, as we did in the previous chapter, and add the following familiar code to our sketch: void setup() Serial.begin(9600); pinMode(13, OUTPUT); void loop() while (Serial.available() = 0) Serial.println("Hello world"); delay(300); Serial.println("Goodbye world"); while(1) digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); 30 Chapter 2: Connecting the iPhone to the Arduino 2-16. Application connected to the Arduino (left), entering characters (middle), which have been received by the Arduino (right) If you upload this modified sketch to your Arduino board, as well as printing “Goodbye world” when it receives bytes over the serial port, the Arduino will begin to blink the LED on pin 13 on and off once a second. See Figure 2-17. Log Messages One of the things that’s going to start to irritate you fairly quickly is how hard it is to debug applications using the Redpark cable. With the cable plugged in, you’re going to be unable to see output to the debug console: for instance, log messages you might normally print to the console using the NSLog method. Fortunately, there is a way around this. We can actually redirect the stderr output that would normally appear in the Debug area to a file, which we can then view inside our application itself. Open up the SerialConsole project in Xcode and click on the main.m file, which is located in the Supporting Files group in the Project pane, and add the highlighted lines below to it: Log Messages 31 2-17. The SerialConsole application, cabling, and the Arduino import UIKit/UIKit.h int main(int argc, char argv) NSAutoreleasePool pool = NSAutoreleasePool alloc init; NSArray paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString log = paths objectAtIndex:0 stringByAppendingPathComponent: "ns.log"; NSFileManager fileMgr = NSFileManager defaultManager; fileMgr removeItemAtPath:log error:nil; freopen(log fileSystemRepresentation, "a", stderr); int retVal = UIApplicationMain(argc, argv, nil, nil); pool release; return retVal; This will redirect the stderr output to a file called ns.log inside the application’s Docu- ments directory. The file will be deleted and recreated each time the application is started. Now that we’ve done this, we need to create a view controller to allow us to look at the log. Right-click on the Project pane and select New File..., select a UIViewController subclass from the drop-down list, which is a subclass of UIViewController itself, and 32 Chapter 2: Connecting the iPhone to the Arduino sure the “With XIB for user interface” checkbox is checked. Name the new class LogController when prompted. Click on the LogController.xib file to open it in Interface Build, and drag a UINaviga tionBar and a UIBarButtonItem from the Object library into your view. Position the bar button item on the left of the navigation bar and change the text to be “Done.” Then in the Attributes inspector, change the button style to Done rather than Plain. You should also change the title of the navigation bar to “NSLog.” Now drag a UITextView from the Object library into the view to fill the remaining space. Delete the Lorem ipsum text, and in the Attributes inspector, uncheck the Editable checkbox. Next, close the Utilities pane and open the Assistant Editor. Make sure it’s on Auto- matic, and Ctrl-click and drag from the UITextView to the displayed LogController.h interface file to create a property and IBOutlet called logWindow. Then, similarly, Ctrl- click and drag from the Done button the interface file to create an IBAction called done:; see Figure 2-18. Figure 2-18. Connecting the outlets and actions to the user interface Log Messages 33 your changes, return to the Standard Editor, and click on the LogController.h interface file to open it in the Xcode editor. Add the highlighted lines below: import UIKit/UIKit.h interface LogController : UIViewController UITextView logWindow; BOOL firstOpen; property (nonatomic, retain) IBOutlet UITextView logWindow; - (IBAction)done:(id)sender; - (void)setWindowScrollToVisible; end Then, click on the corresponding LogController.m implementation file. The first thing we need to do is modify the initWithNibName: method as follows: - (id)initWithNibName:(NSString )nibNameOrNil bundle:(NSBundle )nibBundleOrNil self = super initWithNibName:nibNameOrNil bundle:nibBundleOrNil; if (self) NSArray paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES); NSString log = paths objectAtIndex:0 stringByAppendingPathComponent: "ns.log"; NSFileHandle fh = NSFileHandle fileHandleForReadingAtPath:log; fh seekToEndOfFile; NSNotificationCenter defaultCenter addObserver:self selector:selector(getData:) name:"NSFileHandleReadCompletionNotification" object:fh; fh readInBackgroundAndNotify; firstOpen = YES; return self; From there we need to add the viewDidAppear: method: - (void)viewDidAppear:(BOOL)animated super viewDidAppear:animated; NSArray paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString log = paths objectAtIndex:0 stringByAppendingPathComponent: "ns.log"; if ( firstOpen ) NSString content = NSString stringWithContentsOfFile:log encoding:NSUTF8StringEncoding error:NULL; logWindow.editable = TRUE; 34 Chapter 2: Connecting the iPhone to the Arduino

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.