当我从Arduino收到整条消息时,这里有一个while循环,要满足一个条件。问题是:我不知道如何改变这种情况
do
{
read_result = arduino.readSerialPort(incomingData, MAX_DATA_LENGTH);
//prints out data
if (read_result > 0)
cout << incomingData;
//puts(incomingData);
} while (true);
我从Here启发了我所有的项目
但是我改变了主要功能和我的arduino文件。这是我的主要功能:
//This code snippet will help you to read and write data from arduino
//#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "SerialClass.h"
#include <fstream>
//using namespace std;
using std::cin;
using std::cout;
using std::endl;
//String for getting the Output from Arduino
char outputData[MAX_DATA_LENGTH];
//String for incoming data
char incomingData[MAX_DATA_LENGTH];
//Portname must contain these backslashes
char *port_name = "\\\\.\\COM5";
const unsigned int bufSize =255;
int main()
{
SerialPort arduino(port_name);
if (arduino.isConnected())
std::cout << "Connection Established! \n" << std::endl;
else
std::cout << "ERROR, check port!";
while (arduino.isConnected()) {
std::string input_string ;
//cout << "Write something: \n";
getline(cin, input_string);
//Creating a c string
char *c_string = new char[input_string.size() + 1];
//copying the std::string to c string
std::copy(input_string.begin(), input_string.end(), c_string);
//Adding the delimeter
c_string[input_string.size()] = '\n';
//Writing string to arduino
arduino.writeSerialPort(c_string, MAX_DATA_LENGTH);
//Getting reply from arduino
arduino.readSerialPort(outputData, MAX_DATA_LENGTH);
//printing the output
//puts(outputData);
//freeing c_string memory
delete[] c_string;
//Check if data has been read or not
int read_result;
do
{
read_result = arduino.readSerialPort(incomingData, MAX_DATA_LENGTH);
//prints out data
if (read_result > 0)
cout << incomingData;
//puts(incomingData);
} while (true);
//wait a bit
//Sleep(100000);
}
}
这是我的arduino文件:
int PButton=2;
int Led=13;
unsigned long start,finished,elapsed;
void setup() {
Serial.begin(9600); //begins the Serial Connection.
pinMode(PButton, INPUT_PULLUP);
pinMode(Led,OUTPUT);
digitalWrite(Led,LOW);
Serial.println("Is the video already started? ""yes/no""...\n");
start=millis();
String ans;
while(Serial.available()<=0)
{
}
ans=Serial.readStringUntil('\n');
if(ans.equals("yes")){
digitalWrite(13,HIGH);
Serial.println("The video is started!\n\nplease Press the Pushbutton when the task is fullfilled!\n");
}
else if(ans.equals("no")){
digitalWrite(13,LOW);
Serial.println("The Video is still not started! \n");
}
}
void loop() {
int buttonState=digitalRead(PButton); //read the input pin
if(buttonState==LOW)
{
Serial.print("The pushbutton is pressed after ");
finished=millis();
elapsed=finished-start;
Serial.println(elapsed);
delay(3000);
}
}