1

我正在创建一个从力传感器接收输入的iOS应用程序。Arduino 连接到 BLE蓝牙发射器,该发射器将信息数据流发送到应用程序。

下面是我的代码:

-(void) bleDidReceiveData:(unsigned char *)data length:(int)length
{
    NSData *d = [NSData dataWithBytes:data length:length];
    NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
    self.label.text = s;

    if (s>150){
        [UIImageView beginAnimations:NULL context:nil];
        [UIImageView setAnimationDuration:0.01];
        [ImageView setAlpha:1];
        [UIImageView commitAnimations];
    }
    else {
        //remove red
        [UIImageView beginAnimations:NULL context:nil];
        [UIImageView setAnimationDuration:1.0];
        [ImageView setAlpha:0];
        [UIImageView commitAnimations];
    }
}

我有两个问题:

  • 蓝牙子系统发送数据流 (d),它是一组数字,表示力对力传感器的影响。有什么方法可以让我进入 d 的每个元素或转换后的字符串,s以便我可以在 if 语句中使用它?if如果字符串中的任何数字高于阈值(语句),我需要显示图像。或者我可以直接使用if语句中的字符串吗?我想这将需要一个 for 循环。我只是不确定如何设置它。

  • 要获得阈值,我需要校准力传感器。有没有办法获得数据流或字符串的模式或平均值?

4

1 回答 1

0

如果数据流之间存在间隙或某种分隔符(例如“-”或“/”):

  • use [NSString componentsSeparatedByString] to split the string into it's constituent parts
  • then use [NSString floatValue] on each separated string to get the number
  • compare this value to your threshold in your if statement, show your image if necessary.

If there is no separator in your data stream then there are two options:

1) convert to NSString as you do already, then use characteratIndex[n] inside a for loop to get each character. To convert each returned unichar to a number, you'll need to do some jiggerypokery. See these two threads:

Objective-C NSString for loop with characterAtIndex

Converting Unichar to Int Problem

2) if you know how many bytes are taken up by each value you may be able to skip the NSString completey and use [NSData subDataWithRange:] (inside a for loop) to extract the data and convert to a value.

Good luck!

于 2013-04-07T22:41:47.750 回答