当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Serial Monitor Input for the Arduino?

问题描述:

This is just a simple test program. I'm trying to have the Arduino print "received" on an LCD screen attached to it. I think it's my if statement causing the error, any ideas?

Currently when "send" is put in the serial monitor nothing happens.

Here is the code:

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

char serialinput; // for incoming serial data

void setup() {

Serial.begin(9600); // opens serial port, sets data rate to 9600 bps

}

void loop() {

// send data only when you receive data:

if (Serial.available() > 0) {

// read the incoming byte:

serialinput = Serial.read();

if (serialinput == 'send')

{

lcd.print("received");

}

}

}

网友答案:

You're reading a byte (a char in C) from your serial port, but you try to compare it to a string:

If you want to read 4 char and compare it to "send" then you would have to do something like:

#include <LiquidCrystal.h>
#include <string.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

char serialinput [5] = {0};   // for incoming serial data
                              // 4 char + ending null char

void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {
    // send data only when you receive data:
    if (Serial.available() > 0) {
        memmove (serialinput, &serialinput[1], 3); // Move 3 previous char in the buffer
        serialinput [3] = Serial.read(); // read char at the end of input buffer

        if (0 == strcmp(serialinput, "send")) // Compare buffer content to "send"
        {
            lcd.print("received");
        }
    }
}

Assuming that <string.h> header is valid within the Arduino SDK

PS : litteral strings in C code are written between " (double quotation marks). ' is for characters.

网友答案:

What errors did you have when uploading to the arduino ?

分享给朋友:
您可能感兴趣的文章:
随机阅读: