cocoa - 如何通过popen发送整数?

标签 cocoa arduino popen

我需要能够将一个整数从 cocoa 发送到 arduino。

发送字符(即个位数整数)很容易,但我似乎找不到发送两位和三位数整数的方法。

这样做的目的是在 0 到 255 之间连续控制 LED 的亮度。

到目前为止,我可以使用以下代码打开和关闭它:

int ledPin =  9;    // LED connected to digital pin 9
int incomingByte = 0;   // for incoming serial data


void setup()   {                
  // initialize the digital pin as an output:
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop()                     
{

  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.read();
    if(incomingByte == 105){         //105 corresponds to i and is programmed in cocoa to turn the LED on
      digitalWrite(ledPin, HIGH);
    }
    else if(incomingByte == 111){    //111 corresponds to o and is programmed in cocoa to turn the LED on
      digitalWrite(ledPin, LOW);
    }
  }
}

但是,我不知道如何设置 0 到 255 之间的值。我会使用“AnalogWrite”而不是“digitalWrite”,但是,我不知道如何将传入字节发送为介于 0 和 255 之间的值0 和 255。

这是 cocoa 代码:

#import "MainController.h"

@implementation MainController


-(IBAction)ledOn:(id)sender{
        popen("echo i > /dev/cu.usbmodem1411", "r");

}

-(IBAction)ledOff:(id)sender{
        popen("echo o > /dev/cu.usbmodem1411", "r");
}


@end

谢谢。

最佳答案

您可以在arduino代码中将多于一位的整数视为cstring,然后通过atoi()将它们转换为整数。

以下代码将从串行缓冲区捕获字节作为 cstring:

char buffer[MAX_BUFFER_SIZE]; // global c character array variable

boolean inputReady()
{
  byte index = 0;
  byte avail = Serial.available();
  if(avail > 0)
  {
    while(index < avail)
    {
      byte val;
      do
      {
        val = Serial.read();
      }
      while (val == -1); // if value is no longer -1, bytes are captured
      buffer[index] = val;
      index++;
    }
    buffer[index] = 0; //terminate the character array
    return true;
  }
  return false;
}

注意: 与 arduino IDE 中内置的 String 类相比,我更喜欢 cstrings,因为它使用更多内存,但要小心使用 cstrings,因为如果管理不当,它们很容易出现内存泄漏。

这就是你的 loop() block 的样子:

void loop()
{
  if(inputReady())
  {
    int pwmValue = atoi(buffer); // convert ascii buffer to integer.
    if(pwmValue >= 0 && pwmValue <= 255) // filter values from 0-255
       analogWrite(ledPin, pwmValue);
    else
       digitalWrite(ledPin, LOW); // turn off if pwmValue is more than 255
  }
  delay(100);
}

然后,您可以通过 popen() 从 cocoa 代码中以字符串形式发送 pwm 值。

#import "MainController.h"

@implementation MainController


-(IBAction)ledPWMValue:(id)sender{
        popen("echo 254 > /dev/cu.usbmodem1411", "r");

}

@end

我已经在我的 Arduino Uno 上测试了这个,并且可能适用于其他变体。我希望这对您的项目有所帮助,祝您好运!

关于cocoa - 如何通过popen发送整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23741024/

相关文章:

ios - 基于一个订购两个 NSMutableArrays

ios - NSHashTable 计数错误地报告非空

我可以使用列表重置数组值吗?

python - 所有 os.popen() 方法之间有什么区别?

python - 为什么矢量化的 numpy 方法在 python ssh 子进程中只使用一个核心

python - 如何使用 subprocess.POPEN 获取异步输入和输出

iphone - Objective-C++ 支持多少 C++

objective-c - 实现自定义 View 的最佳方式

android - Android 上的蓝牙控制信号(DTR、DSR、RTS、CTS)

android - 设置主机卡仿真