0
votes

I'm just trying to get the very basics of serial communication started; I'm trying to use this example I found, from what I understand it should be working. I just want what I type into the serial monitor to be output back, so I can see how it works. I also tried removing the while serial.available in case the serial monitor doesn't trigger that condition. Here is my code:

// Buffer to store incoming commands from serial port
String inData;

void setup() {
Serial.begin(9600);
Serial.println("Initialized\n");
 }

   void loop() {
     while (Serial.available() > 0)
 {
    char recieved = Serial.read();
    inData += recieved; 

    // Process message when new line character is recieved
    if (recieved == '\n')
    {
        Serial.println("Arduino Received: ");
        Serial.println(inData);

        inData = ""; // Clear recieved buffer
        }
    }
}

It currently uploads fine, and prints "initialized" but doesn't work if i try to "send" any data.

2
Have you tried just printing received as soon as you read it?Dan12-16

2 Answers

1
votes

Serial.read() returns and int. You need to cast (char) in order to store it as a char.

char recieved = (char)Serial.read();

BTW: variable name should be received :)

EDIT:

Maybe you are never receiving any data for some reason. Let's try something super simple, use serialEvent() as suggested by @sohnryang and then print some text as soon as Serial.available() triggers:

    while (Serial.available() > 0) {
        Serial.println("Something has been received");
    }

You should see this message every time you send something to Arduino.

0
votes

Use SerialEvent. So the code will look like this.

String inData;

void setup() {
    Serial.begin(9600);
    Serial.println("Initialized\n");
}

void loop() {
}

void serialEvent() {
    while (Serial.available()) {
        char inChar = (char)Serial.read();
        inData += inChar;
        if (inChar == '\n') {
            Serial.println("Arduino Recieved : ");
            Serial.println("inData");
            inData = "";
        }
    }
}