与jSerialComm的串行通信未发送任何内容

时间:2020-02-10 11:42:49

标签: scala arduino

我构建了一个简单的Scala应用程序和一个简单的Arduino脚本来测试jSerialComm库上的串行通信。该程序仅找到一个活动端口(与Arduino连接的端口),该端口和Arduino上的波特率相同,并且代码在编写时不会引发异常。但是,Arduino却什么也没收到(RX led已关闭)。

Scala代码:

import com.fazecast.jSerialComm._

object Test extends App {
  val ports = SerialPort.getCommPorts
  ports.foreach(println(_))
  val port: SerialPort = ports(0)

  var bytes = Array[Byte]()
  val toWrite: Long = 3
  var a = 0
  var b = 0
  var c = 0

  println(port.getBaudRate)

  while (true) {
    if (a < 3) a += 1 else a = 0
    bytes = Array[Byte](a.toByte, a.toByte, a.toByte)
    port.writeBytes(bytes, toWrite)
    println("Sent " + bytes(0) + " to " + port.toString)
    Thread.sleep(1000)
  }
}

Arduino代码:

const int R = 12;
const int G = 13;
const int B = 11;

void setup() {
  pinMode(R, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(B, OUTPUT);
  Serial.begin(9600);
  while(!Serial);
}

void loop() {
  byte buff[3] = {0, 0, 0};
  int numR = 0;

  bool cont1 = false;
  bool cont2 = false;
  bool cont3 = false;

  if(Serial.available()){
    Serial.print("Found stuff");
    Serial.readBytes(buff,3);
  }

  for(int i = 0; i < 3; i++){
    if(buff[i] == 1){
      cont1 = true;
    }
    if(buff[i] == 2){
      cont2 = true;
    }
    if(buff[i] == 3){
      cont3 = true;
    }
  }

  if(cont1) digitalWrite(R, HIGH); else digitalWrite(R, LOW);
  if(cont2) digitalWrite(G, HIGH); else digitalWrite(G, LOW);
  if(cont3) digitalWrite(B, HIGH); else digitalWrite(B, LOW);
  if(cont1 || cont2 || cont3) delay(1000);
}

1 个答案:

答案 0 :(得分:0)

我忘了打开端口

port.openPort()

现在它可以正常工作