开发者

How could I communicate with an RS232 device in Objective-C?

开发者 https://www.devze.com 2023-02-15 02:06 出处:网络
I\'m trying to write a command-line, Foundation Objective-C program and I need to communicate to an RS232 serial device.

I'm trying to write a command-line, Foundation Objective-C program and I need to communicate to an RS232 serial device.

Any ideas on how to do this?

EDIT - This is NOT for iPhone! 开发者_JAVA百科This is a DESKTOP APPLICATION.


I'm assuming you are using an RS-232/USB adapter. If I were doing it, I'd figure out which device it shows up on, and just open it using the open("/dev/ttyS0", etc) function. You can then wrap up the file descriptor and the access functions in an object.

Here is a page on playing with serial ports in POSIX environments: http://www.easysw.com/~mike/serial/serial.html


I used so-called "Serial Device Server" from moxa and it worked like a charm.

Advantages over USB-Serial converter:

  • The device can be integrated anywhere in the network
  • on application side it is just well-documented network programming

Device Server in general allow you to connect to a serial device by using networks like LAN or WiFi.

Software side it would be quite easy network/socket programming, like:

(Using GCDAsyncSocket)

Preparing data

static u_int8_t cmd1[] = { 0x1a, 0x73, 0x10 }; //defined by the serial device's protocol
static u_int8_t cmd2[] = { 0x1b, 0x51, 0x01 };

self.data = [NSMutableData dataWithBytes:&cmd1 length:sizeof(cmd1)];
[self.data appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
[self.data appendBytes:&cmd2 length:sizeof(cmd2)];

sending data

-(IBAction)buttonAction:(id)sender
{
    NSError *error = nil;
    [self.socket connectToHost:@"192.168.1.9" onPort:1234 withTimeout:-1 error:&error];
    if (error) {
        NSLog(@"error: %@", error);
    }
}


-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    [self.socket writeData:self.data withTimeout:-1 tag:23];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消