我需要在计算机和arduino之间建立串行连接。我发现了一个使串行连接的类没有任何错误。我已经在arduino中编写了我的代码(从端口2读取到arduino并将其写入输出并从C ++接收字符),这是:
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? ""y/n""...\n");
start=millis();
}
void loop() {
if(Serial.available()>0){
char letter=Serial.read();
if(letter=='y'){
digitalWrite(13,HIGH);
Serial.println("The video is started!\n");
}
else if(letter=='n'){
digitalWrite(13,LOW);
Serial.println("The Video is still not started! \n");
}
else
Serial.println("Enter a valid Answer please!\n");
}
int buttonState=digitalRead(PButton); //read the input pin
if(buttonState==LOW){
Serial.println(" the pushbutton is pressed!");
finished=millis();
elapsed=finished-start;
Serial.print(elapsed);
}
}
代码可以作为独立代码使用,它可以在串行监视器中输出正确的代码。问题是我在C ++方面不是很有经验,我很困惑如何编写主函数来读写C ++到arduino,反之亦然。我在stackoverflow中找到了一些代码,但我无法根据需要调整它们。
这是我的C ++代码(我已经有了串行连接类)。我不确定要评论哪一行,以及它是否合乎逻辑!
// SerialCommunication.cpp : Definiert den Einstiegspunkt für die
Konsolenanwendung.
//This code snippet will help you to read data from arduino
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "SerialPort.h"
//using namespace std;
//using std::cin;
//using std::cout;
//using std::endl;
//String for getting the Output from Arduino
char output[MAX_DATA_LENGTH];
//Portname must contain these backslashes
char *port_name = "\\\\.\\COM5";
//const unsigned int bufSize =255;
//String for incoming data
char incomingData[MAX_DATA_LENGTH];
int main()
{
SerialPort arduino(port_name);
if (arduino.isConnected())
std::cout << "Connection Established" << std::endl;
else
std::cout << "ERROR, check port!";
while (arduino.isConnected()) {
//std::cout << "Is the video Started?Yes or No: \n";
//std::string input_string = "Blabla\n";
char answer;
std::cin >> answer;
//Writing answer to arduino
arduino.writeSerialPort( (answer* ), MAX_DATA_LENGTH);
//Getting reply from arduino
arduino.readSerialPort(output, MAX_DATA_LENGTH);
//printing the output
puts(output);
}
/*while (arduino.isConnected()) {
//Check if data has been read or not
int read_result = arduino.readSerialPort(incomingData, bufSize);
//prints out data
puts(incomingData);
//wait a bit
Sleep(10);
}*/
}