Converting Serial.Read() to var?

Hello, The below code prints data from a sensor. I'd like it, however, to be sent to a string variable (where it will be transmitted via WiFi)

if (ops241Serial.available())
{
  Serial.write(ops241Serial.read());
  }

I have tried:

  Udp.write(ops241Serial.read());

However, my Server gets "-1", instead of the sensor data.

Can anyone assist? Thanks

However, my Server gets "-1", instead of the sensor data.

The read() returns -1 if nothing is available to be read, hence the need to use the available() function first. Try reading the value into a variable and printing the variable to see exactly what you are reading from serial.

Thanks for your response. Reading the value into a variable is something I don’t know how to do, which is what I was asking. For what it’s worth, when I do:

Serial.write(ops241Serial.read());

It prints the correct data to the screen?

Simple serial test code that captures a string of characters sent from the serial monitor in a String variable, then sends those characters back to the serial monitor.

//zoomkat 6-29-14 Simple serial echo test
//type or paste text in serial monitor and send

String readString;

void setup() {
  Serial.begin(9600);
  Serial.println("Simple serial echo test"); // so I can keep track of what is loaded
}

void loop() {

  while (Serial.available()) {
    char c = Serial.read();  //gets one byte from serial buffer
    readString += c; //makes the String readString
    delay(3);  //slow looping to allow buffer to fill with next character
  }

  if (readString.length() > 0) {
    Serial.println(readString);  //so you can see the captured String
    readString = "";
  }
}
char aChar = ops241Serial.read();

Quoting the following lines from your post:

if (ops241Serial.available())
{
  Serial.write(ops241Serial.read());
}

Expanded form:

byte n = ops241Serial.available();   //checking if a character byte (in ASCII form) or a data byte (in natural binary) has arrived from your device represented by the object: ops241Serial
if(n != 0)  //assume that a character byte (ASCII formatted data) has arrived and get stored in FIFO Buffer
{
    char aChar = ops241Serial.read(); //get the character byte from FIFO Buffer and save in variable: aChar.
}

Now, send the aChar data item (it is in ASCII format) to your destination using WiFi.

Golam, Works like a charm. Thank you, and thank you to zoomkat and UKHeliBob as well.