简体   繁体   中英

Return null result from read data from Arduino in to processing

I want to read data from Arduino. My arduino cod is simple

void setup() 
{
//initialize serial communications at a 9600 baud rate
Serial.begin(9600);
}

void loop()
{
//send 'Hello, world!' over the serial port
Serial.println("Hello, world!");
//wait 100 milliseconds so we don't drive ourselves crazy
delay(100);
}

In Processing i have following cod

import processing.serial.*;

Serial  myPort;
String val;


void setup()  { 

  String portName = Serial.list()[1];
  myPort = new Serial(this, portName, 9600);

} 

void draw()  { 
  if ( myPort.available() > 0) 
  {  // If data is available,
  val = myPort.readStringUntil('\n');        
  } 
println(val); //pr

} 

But

val

always is Null. I don't understand why it everytime returns this valu. The port is available

In Processing, if you put in:

if (val == null) {
val = "0";
}

it should work. It'll keep printing 'val' without halting the program, but it'll return a value of "0" instead of "null".

Basically, you have to tell Processing to run even if it receives a "null" value.

The code posted should work. The things to check here are whether you are using the correct serial port. Try printing out the list of serial ports in setup:

println( Serial.list() );

If your code is correct, the port you want will be the second one. If that's not correct, change the number of the array index when you specify portName.

The other thing to check is whether the Arduino is actually printing what you think it's printing. When you open up the Serial Monitor, is it actually printing "Hello, world!" a bunch of times?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM