各位大神看看,我用arduino驱动步进电机,上位机和下位机的程序,现在就是上位机发送数据包到下位机,下位机接收执行,text之后OK出现好多,应该每动一次返回一个OK才对,求指导
//下面是main.cpp
#include
#include
#include "SerialClass.h" // Library described above
#include
#include "package.h"
#include
#include
// application reads from the specified serial port and reports the collected data
int main(int argc, _TCHAR* argv[])
{
printf("Welcome to the serial test app!\n\n");
Serial* SP = new Serial("COM3"); // adjust as needed
if (SP->IsConnected())
printf("We're connected");
char incomingData[256] = ""; // don't forget to pre-allocate memory
//printf("%s\n",incomingData);
int dataLength = 255;
int readResult = 0;
for(int i=0;i<45;i++){
package a;
trans(a, 90, 1);
std::cout << a;
/*std::stringstream ss;
ss << a;
char *outBuf;
ss >> outBuf;*/
//SP->WriteData(outBuf,sizeof(outBuf));
//char *out = "123456";
SP->WriteData(a.toChar(),strlen(a.toChar()));
/*readResult = */
/*printf("Bytes read: (0 means no data available) %i\n",readResult);
package b(0, 0, 0, 2, 0);
SP->WriteData(b.toChar(), strlen(b.toChar()));*/
//incomingData[readResult] = 0;
while (!SP->ReadData(incomingData, dataLength)) {
}
Sleep(1500);
std::cout << "test";
std::cout<<std::endl << incomingData;
}
//Sleep(500);
return 0;
}
//下面是package.cpp
#include "package.h"
#include <sstream>
std::ostream & operator<<(std::ostream & os, const package & o)
{
std::cout << " a: " << o.a << " b: " << o.b << " c: " << o.c << " d: "<< o.d<<" direction: "<<o.direction;
return os;
// TODO: 在此处插入 return 语句
}
char * package::toChar()
{
char *out1=new char[1];
itoa(a, out1, 10);
char *out2 = new char[1];
itoa(b, out2, 10);
char *out3 = new char[1];
itoa(c, out3, 10);
char *out4 = new char[1];
itoa(d, out4, 10);
char *out5 = new char[1];
itoa(direction, out5, 10);
char *out = new char[strlen(out1) + strlen(out2) + strlen(out3) + strlen(out4) + strlen(out5) + 1];
strcpy(out, out1);
strcat(out, out2);
strcat(out, out3);
strcat(out, out4);
strcat(out, out5);
return out;
}
void trans(package & output, int degree,bool direction)
{
int n = 360 / degree;
output.a = n / 512;
n =n % 512;
output.b = n / 64;
n =n % 64;
output.c = n / 8;
output.d = n % 8;
output.direction = direction;
}
//下面是serial.cpp
#include "SerialClass.h"
#include
Serial::Serial(std::string portName)
{
//We're not yet connected
this->connected = false;
//Try to connect to the given port throuh CreateFile
this->hSerial = CreateFile(TEXT("COM3"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
//Check if the connection was successfull
if (this->hSerial == INVALID_HANDLE_VALUE)
{
//If not success full display an Error
if (GetLastError() == ERROR_FILE_NOT_FOUND) {
//Print Error if neccessary
printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);
}
else
{
printf("ERROR!!!");
}
}
else
{
//If connected we try to set the comm parameters
DCB dcbSerialParams = { 0 };
//Try to get the current
if (!GetCommState(this->hSerial, &dcbSerialParams))
{
//If impossible, show an error
printf("failed to get current serial parameters!");
}
else
{
//Define serial connection parameters for the arduino board
dcbSerialParams.BaudRate = CBR_9600;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
//Setting the DTR to Control_Enable ensures that the Arduino is properly
//reset upon establishing a connection
dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE;
//Set the parameters and check for their proper application
if (!SetCommState(hSerial, &dcbSerialParams))
{
printf("ALERT: Could not set Serial Port parameters");
}
else
{
//If everything went fine we're connected
this->connected = true;
//Flush any remaining characters in the buffers
PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR);
//We wait 2s as the arduino board will be reseting
Sleep(ARDUINO_WAIT_TIME);
}
}
}
}
Serial::~Serial()
{
//Check if we are connected before trying to disconnect
if (this->connected)
{
//We're no longer connected
this->connected = false;
//Close the serial handler
CloseHandle(this->hSerial);
}
}
int Serial::ReadData(char *buffer, unsigned int nbChar)
{
//Number of bytes we'll have read
DWORD bytesRead;
//Number of bytes we'll really ask to read
unsigned int toRead;
//Use the ClearCommError function to get status info on the Serial port
ClearCommError(this->hSerial, &this->errors, &this->status);
//Check if there is something to read
if (this->status.cbInQue>0)
{
//If there is we check if there is enough data to read the required number
//of characters, if not we'll read only the available characters to prevent
//locking of the application.
if (this->status.cbInQue>nbChar)
{
toRead = nbChar;
}
else
{
toRead = this->status.cbInQue;
}
//Try to read the require number of chars, and return the number of read bytes on success
if (ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL))
{
return bytesRead;
}
}
//If nothing has been read, or that an error was detected return 0
return 0;
}
bool Serial::WriteData(char *buffer, unsigned int nbChar)
{
DWORD bytesSend;
//Try to write the buffer on the Serial port
if (!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
{
//In case it don't work get comm error and return false
ClearCommError(this->hSerial, &this->errors, &this->status);
return false;
}
else
return true;
}
bool Serial::IsConnected()
{
//Simply return the connection status
return this->connected;
}
//下面是package.h
#pragma once
#include
class package {
public:
int a;
int b;
int c;
int d;
int direction;
package(int a_=1, int b_=2, int c_=3,int d_=8,int direction_=1) :
a(a_), b(b_), c(c_),d(d_) ,direction(direction_){}
char *toChar();
friend std::ostream & operator<<(std::ostream & os, const package & o);
};
std::ostream & operator<<(std::ostream & os, const package & o);
void trans(package &, int,bool);
//下面是SerialClass.h
#ifndef SERIALCLASS_H_INCLUDED
#define SERIALCLASS_H_INCLUDED
#define ARDUINO_WAIT_TIME 2000
#include
#include
#include
#include
class Serial
{
private:
//Serial comm handler
HANDLE hSerial;
//Connection status
bool connected;
//Get various information about the connection
COMSTAT status;
//Keep track of last error
DWORD errors;
public:
//Initialize Serial communication with the given COM port
Serial(std::string portName);
//Close the connection
~Serial();
//Read data in a buffer, if nbChar is greater than the
//maximum number of bytes available, it will return only the
//bytes available. The function return -1 when nothing could
//be read, the number of bytes actually read.
int ReadData(char *buffer, unsigned int nbChar);
//Writes data from a buffer through the Serial connection
//return true on success.
bool WriteData(char *buffer, unsigned int nbChar);
//Check if we are actually connected
bool IsConnected();
};
#endif // SERIALCLASS_H_INCLUDED
//下面是下位机Arduino中的程序
int x;
int i=9;
class package {
public:
int count=0;
int a[5];
void push_back(int u){
a[count]=u;
count++;
}
};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(5,OUTPUT); // Step
pinMode(4,OUTPUT); // Dir
}
void loop() {
package a;
while(true){
i=Serial.read();
if(i!=9){
a.push_back(i-48);
i=9;
}
if (a.count==5){
break;
}
}
int degree=a.a[0]*512+a.a[1]*64+a.a[2]*8+a.a[3];
int step=3200/degree;
// put your main code here, to run repeatedly:
if(a.a[4]==1){
digitalWrite(4,HIGH); // Set Dir high
}
else{
digitalWrite(4,LOW);
}
for(x = 0; x < step; x++) // Loop 3200 times
{
digitalWrite(5,HIGH); // Output high
delayMicroseconds(400);
digitalWrite(5,LOW); // Output low
delayMicroseconds(400);
}
Serial.println("ok");
// pause one second
delay(1000);