Ojakokko
Ojakokko

Reputation: 41

Serial communication with jSerialComm not sending anything

I built a simple Scala application and a simple Arduino script to test serial communication on the jSerialComm library. The program only finds one active port (the one the Arduino connected to), the baud rates are the same on the port and the Arduino and the code throws no exceptions while writing. The Arduino, however, receives nothing (the RX led is off).

The Scala code:

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)
  }
}

The Arduino code:

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);
}

Upvotes: 2

Views: 614

Answers (1)

Ojakokko
Ojakokko

Reputation: 41

I had forgotten to open the port with

port.openPort()

Now it works just fine

Upvotes: 1

Related Questions