简体   繁体   中英

Send a signed integer as a byte via serial in c++ and Arduino read it

I could send a String via serial, but Arduino reads String very slow. Therefore, I use reading byte in Arduino, but the problem is I don't know how to send a number (<256) as a byte via Serial Port in C++.

If you open up the Arduino IDE, under the menu, look at:

File > Examples > 08.Strings > CharacterAnalysis

Here I think you'll find something very close what you're looking for. To sum up, it opens a Serial connection (USB) and reads input from the computer. (You'll need to make sure you match the baud rate and use the "send" button.) It's up to you do program the Arduino as you'd like. In the example's case, it simply sends feedback back to the the Serial Monitor. Run it for yourself and see what happens :)

A [MCVE] snippet from the example:

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }

    // send an intro:
    Serial.println("send any byte and I'll tell you everything I can about it");
    Serial.println();
}

void loop() {
    // get any incoming bytes:
    if (Serial.available() > 0) {
        int thisChar = Serial.read();

        // say what was sent:
        Serial.print("You sent me: \'");
        Serial.write(thisChar);
}

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