I am trying to send a three digit number from an XCode foundation command-line tool to an arduino over USB as a proof of concept for sending a data stream. The arduino code is supposed to flash a light the number of times that the number in the incoming data is. It works perfectly using the serial monitor in the arduino IDE, but when I try using the Objective-C program, which uses ORSSerialPort, the Rx light flashes on the arduino, indicating that it has received data, but nothing else happens.
Here is the Objective-C code:
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import "ORSSerialPort.h"
#import "ORSSerialPortManager.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
ORSSerialPort *arduino = [ORSSerialPort serialPortWithPath:@"/dev/tty.usbmodem26231"];
//initalizes ORSSerialPort instance
NSString *string = @"012"; //creates string from the 3-digit number
NSData *outgoingdata = [string dataUsingEncoding:NSASCIIStringEncoding];
//encodes string using ASCII
int number = 1200;
NSNumber *baudrate = [[NSNumber alloc] initWithInt:number];
//initializes an NSNumber for the baud rate
[arduino open]; //opens port
baudrate = arduino.baudRate; //sets baud rate
[arduino sendData:outgoingdata]; //sends data
[arduino close]; //closes port
NSLog(@"%@ sent", string); //logs the number
}
return 0;
}
Here is the arduino code:
#include <SoftwareSerial.h>
int i100;
int i10;
int i1;
int total;
void setup() {
Serial.begin(1200);
pinMode(2, OUTPUT);
}
void loop() {
int mail = Serial.available(); //reads number of available bytes
if(mail >= 3) {
int i100raw = Serial.read()-48; //reads 3 bytes and decodes from ASCII by subtracting 48
int i10raw = Serial.read()-48;
int i1raw = Serial.read()-48;
if(i1raw >= 0) { //checks if each byte is a valid input
i100 = i100raw;
}
if(i10raw >= 0) {
i10 = i10raw;
}
if(i1raw >= 0) {
i1 = i1raw;
}
total = (i100*100)+(i10*10)+(i1); //puts together 3 digit number from 3 bytes
while(total > 0) { //flashes light
digitalWrite(2, HIGH);
delay(50);
digitalWrite(2, LOW);
delay(50);
total--;
}
}
}