c_cpp 使用arduino数字引脚与外界联系。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 使用arduino数字引脚与外界联系。相关的知识,希望对你有一定的参考价值。

// Arduino digital pin serial control
// Ben Fasoli
//
// Takes input strings over a standard serial connection and sets
// digital pins high/low.
//
// Input:
//   Set pin# to 0,1 (LOW, HIGH)
//   [pin#].[0,1]\n
//   2.1\n
//   3.0\n
//
// Warning: if changing multiple pins at the same time, add some slight delay
// between sending the serial commands to avoid overloading the serial buffer.

#include <math.h>

// declare variables
boolean debug = false;
boolean readComplete = false;
String inputString = "";

// runs on initiation
void setup() {
  // initialize serial interface
  Serial.begin(9600);
  // reserve 200 bytes for the serial buffer
  inputString.reserve(200);
  // initialize pins 2 to 13 high
  for (int i = 2; i <= 13; i++) {
    pinMode(i, OUTPUT);
    digitalWrite(i, HIGH);
  }
}

// continually loops
void loop() {
  readSerialBuffer();

  // print the string when readSerialBuffer() sets readComplete to true
  if (readComplete) {
    // split incoming number 2.1 into setting 1 on pin 2
    float inNum = inputString.toFloat();
    int pin = floor(inNum);
    int setto = round(10 * (inNum - pin));

    // print setting to serial window - floating point number received, 
    // extracted pin number, extracted pin setting
    if (debug) {
      Serial.print(inNum);
      Serial.print('\t');
      Serial.print(pin);
      Serial.print('\t');
      Serial.println(setto);
    }

    // set desired pin to desired state
    digitalWrite(pin, setto);

    // clear the string buffer
    inputString = "";
    readComplete = false;
  }

    delay(50);
}

// dumps available serial data when new bytes are found
void readSerialBuffer() {
  while (readComplete == false & Serial.available()) {
    // get a single new byte and add to inputString
    char inChar = (char)Serial.read();
    inputString += inChar;

    // tell loop that the read is complete
    if (inChar == '\n') {
      readComplete = true;
    }
  }
}

以上是关于c_cpp 使用arduino数字引脚与外界联系。的主要内容,如果未能解决你的问题,请参考以下文章

求大神指导,arduino模拟引脚能当数字引脚用么

c_cpp 与arduino联系

Arduino可以把A0和数字信号引脚相连吗

如何防止 Arduino 数字引脚在启动时变高?

Arduino开发_数字IO操作

Arduino数字引脚