Arduino零基础实践2——串口通信

具体的原理已经在之前的微机原理中提到过了,所以下面直接使用arduinoIDE对Arduino开发板进行编程,使用串口。

#include 

SoftwareSerial mySerial(2, 3); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only
  }


  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(38400);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

更简单的方案还可以这样:

char var;
void setup() {
  pinMode(13, OUTPUT);  //设置IO口13输出模式
  Serial.begin(9600);  //设置波特率
  Serial.println("Hello!PC,I'm arduino!"); //发送数据到串口
}
void loop() {
  if (Serial.available())
  {
      var = Serial.read(); //从串口接收数据
      if (var == '1') {
        digitalWrite(13, HIGH);
        Serial.println("LED is on!"); 
      }
      if (var == '0') {
        digitalWrite(13, LOW);
        Serial.println("LED is off");
      }
  }
}

你可能感兴趣的:(嵌入式)