本文整理汇总了C++中Serial::IsConnected方法的典型用法代码示例。如果您正苦于以下问题:C++ Serial::IsConnected方法的具体用法?C++ Serial::IsConnected怎么用?C++ Serial::IsConnected使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Serial
的用法示例。
在下文中一共展示了Serial::IsConnected方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: _tmain
//-----------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
Serial* SP = new Serial(COM_PORT); // Инициализация соединения
if (SP->IsConnected())
printf("We're connected\n\n");
else
printf("Connection refused\n\n");
char incomingData[BUF_SIZE] = ""; // Строка для посылки (данных)
int readResult = 0; // Каков размер нашей посылки
while (SP->IsConnected())
{
readResult = SP->ReadData(incomingData, BUF_SIZE-1);
// Если ничего нет readResult будет равно -1
if (DEBUG) printf("Bytes read: %i\n",readResult);
// Выводим для отладки кол-во байт переданных данных (или -1)
incomingData[readResult] = 0;
// Записываем конец строки после всех нужных данных
if (readResult > 0) printf("%s",incomingData);
// Eсли в посылке что-то было (и она была), то выводим ее
Sleep(UPD_TIME);
// Подождем пока, чтобы не вывести одно и тоже несколько раз
}
delete SP;
Sleep(2000);
return 0;
} // By SnipGhost 06.08.2016
示例2: _tmain
// application reads from the specified serial port and reports the collected data
int _tmain(int argc, _TCHAR* argv[])
{
printf("Welcome to the serial test app!\n\n");
Serial* SP = new Serial("\\\\.\\COM13"); // adjust as needed
if (SP->IsConnected())
printf("We're connected");
char incomingData[2000] = ""; // don't forget to pre-allocate memory
//printf("%s\n",incomingData);
int dataLength = 1500;
int readResult = 0;
while(SP->IsConnected())
{
readResult = SP->ReadData(incomingData,dataLength);
// printf("Bytes read: (-1 means no data available) %i\n",readResult);
if (readResult == -1) continue;
std::string test(incomingData);
for (int i = 0; i < readResult; i++)
{
printf("%c", incomingData[i]);
}
// printf("%s",incomingData);
test = "";
Sleep(50);
}
return 0;
}
示例3: _tmain
// application reads from the specified serial port and reports the collected data
int _tmain(int argc, _TCHAR* argv[])
{
printf("Welcome to the serial test app!\n\n");
Serial* SP = new Serial("COM4"); // adjust as needed
if (SP->IsConnected())
printf("We're connected\n");
char incomingData[256] = ""; // don't forget to pre-allocate memory
//printf("%s\n",incomingData);
int dataLength = 256;
int readResult = 0;
while(SP->IsConnected())
{
readResult = SP->ReadData(incomingData,dataLength);
// printf("Bytes read: (-1 means no data available) %i\n",readResult);
std::string test(incomingData);
printf("%s",incomingData);
test = "";
Sleep(500);
}
return 0;
}
示例4: _tmain
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Connecting to arduino..." << endl;
Serial* SP = new Serial("\\\\.\\COM7"); // adjust as needed
if (SP->IsConnected())
cout << "Connection established with Arduino!!" << endl; // Let us know the serial is connected
char incomingData[256] = ""; // don't forget to pre-allocate memory
int dataLength = 256;
int readResult = 0;
while(SP->IsConnected())
{
readResult = SP->ReadData(incomingData,dataLength);
//cout << "Bytes read: " << readResult << endl;
string test(incomingData);
if (readResult > 0) {
cout << incomingData << endl;
test = "";
}
Sleep(300);
}
cin >> argc;
return 0;
}
示例5: main
int main(int argc, char* argv[])
{
Serial * Arduino = new Serial("COM8");
cout << "Communicating with COM7 enter data to be sent\n";
char data[256] = "";
int nchar = 256;
char incomingData[256] = "";
while (Arduino->IsConnected())
{
cin >> data;
Arduino->WriteData(data, nchar);
Arduino->ReadData(incomingData, nchar);
cout << incomingData << endl;
}
return 0;
}
示例6: main
int main() {
Serial* port = new Serial("COM4");
if (port->IsConnected()) cout << "Connection established!!!" << endl;
int tempX = 1111;
int tempY = 1111;
bool automatic = true;
sendCommandToArduino(port, automatic, 'w', tempX, tempY);
//char data[256] = "";
//int datalength = 256;
//int readResult = 0;
//for (int i = 0; i < 256; ++i) { data[i] = 0; }
//string str;
//char command[] = "i";
/*char sendMe[1];
sendMe[0] = '1';
sendMe[0] = '0';
int msglen = strlen(sendMe);
while(true){
port->WriteData(sendMe, 2);
cout << "Please write two digit number (00 = turn off, 01 = turn on, 11 = blink): ";
cin >> sendMe[0];
cin >> sendMe[1];
system("pause");
if(sendMe[0] == '1')
sendMe[0] = '0';
else
sendMe[0] = '1';
}
//while (1) {
// while (port->ReadData(data, 256) != -1) {
// printf("%s", data);
// }
//} */
system("pause");
return 0;
}
示例7: connectToPort
Serial* connectToPort(){
string lPort;
cout << "Port: ";
cin >> lPort;
#ifdef __WIN32__
string lfilePath = "\\\\.\\COM"+ lPort;
#endif
#ifdef __linux__
string lfilePath = "/dev/"+ lPort;
#endif
Serial * pSerial = new Serial(lfilePath.c_str());
if(!pSerial->IsConnected()){
cout << "Unable to connect to Serial Port :" + lPort << endl;
return NULL;
}
else{
cout << "Connection established" << endl;
return pSerial;
}
}
示例8: Serial
int *LedAmountTest(char *Comm)
{
Serial* SP = new Serial(Comm);
if (SP->IsConnected())
std::cout << "Connected with COM5" << std::endl;
bool exit = false;
//je kan hier op escape drukken om het programma af ste sluiten hier
std::cout << "Waiting for Arduino. Press ESC to quit" << std::endl;
char Rx_buffer[2] = "";
while (Rx_buffer[0] != '0') //blijf hier hangen tot de arduino klaar is
{
Sleep(100);
SP->ReadData(Rx_buffer, 2);
if (GetAsyncKeyState(VK_ESCAPE))
{
exit = true;
}
if (exit == true)
{
std::cout << "Something went wrong with communication. Check baudrate settings and COM port" << std::endl;
}
}
Rx_buffer[0] = '0';
std::cout << "Got response from arduino sending amount of leds" << std::endl;
//Stuur de hoeveelheid leds naar de arduino
UINT8 Tx_buffer[600 * 3];
ZeroMemory(Tx_buffer, 600 * 3);
Tx_buffer[0] = 600 >> 8 & 0x00FF;
Tx_buffer[1] = 600 & 0x00FF;
SP->WriteData((char*)Tx_buffer, 2);
std::cout << "Press up to add a LED and press down to remove one." << std::endl;
std::cout << "When you are satisfied press SPACEBAR to confirm" << std::endl;
std::cout << "Press ESC to quit" << std::endl;
//onderstaande stukje code zal blijven draaien tot je op ESC drukt
static int leds[4] = { 0 }, i = 0;
int offset = 0;
leds[0]++;
while (i <4)
{
if (GetAsyncKeyState(VK_SPACE)) //Als escape is ingedrukt zet exit true
{
offset += leds[i];
i++;
Sleep(500);
}
if (GetAsyncKeyState(VK_UP))
{
leds[i]++;
ZeroMemory(Tx_buffer, 600 * 3);
for (int j = 0; j < leds[i]; j++)
{
for (int k = 0; k < 3; k++)
{
Tx_buffer[(j + offset) * 3 + k] = 0xff;
}
}
SP->WriteData((char*)Tx_buffer, 1800);
Sleep(50);
}
if (GetAsyncKeyState(VK_DOWN) && leds[i] > 1)
{
leds[i]--;
ZeroMemory(Tx_buffer, 600 * 3);
for (int j = 0; j < leds[i]; j++)
{
for (int k = 0; k < 3; k++)
{
Tx_buffer[(j + offset) * 3 + k] = 0xff;
}
}
SP->WriteData((char*)Tx_buffer, 1800);
Sleep(50);
}
}
SP->~Serial();
return leds;
}
示例9: main
//.........这里部分代码省略.........
ScreenCalc Scherm(105, //init de kleur bereken functies
pBits, //De PixelData
D3DCap.return_hres(), //De Hori Resolutie
D3DCap.return_vres(), //De Verti Resolutie
Config[1], //Hoeveel procent die moet nemen aan de bovenkant/onderkant
Config[2], //Hoeveel procent die aan de zijkant moet nemen
Config[3], //Leds Boven
Config[5], //Leds Onder
Config[4], //Leds Links
Config[6], //Leds Rechts
Config[7]);
Scherm.Bereken_Grid(); //stel de hoeveelheid leds in die worden gebruikt en bereken Grid Grootte
Scherm.set_Gamma(gamma);
//Het programma moet eerst 0xff binnen krijgen als dat het geval is dan mag die beginnen met het oversturen
//van de hoeveelheid leds
//Als die hoeveelheden overeenkomen mag die beginnen met het zenden van led data
std::string String;
String = "\\\\.\\COM";
String += std::to_string(Config[8]);
char *temp = new char[String.size() + 1];
std::copy(String.begin(), String.end(), temp);
temp[String.size()] = '\0';
Serial* SP = new Serial(temp);
delete[] temp;
temp = nullptr;
if (SP->IsConnected())
std::cout << "Connected with COM5" << std::endl;
else
{
std::cout << "Communication Error. Exiting" << std::endl;
return 0;
}
char Rx_buffer[100] = ""; //Dit is de Rx_buffer deze moet een char zijn
//je kan hier op escape drukken om het programma af ste sluiten hier
std::cout << "Waiting for Arduino. Press ESC to quit" << std::endl;
SP->ReadData(Rx_buffer, 2);
while (Rx_buffer[0] != '0') //blijf hier hangen tot de arduino klaar is
{
Sleep(100);
SP->ReadData(Rx_buffer, 2);
if (GetAsyncKeyState(VK_ESCAPE))
{
exit = true;
}
if (exit == true)
{
std::cout << "Something went wrong with communication. Check baudrate settings and COM port" << std::endl;
return 0; //beeindig de software
}
}
Rx_buffer[0] = '0';
std::cout << "Got response from arduino sending amount of leds" << std::endl;
示例10: run
void MpuReader::run()
{
//連線藍芽
#ifndef USE_WIRE_CONNECTION
blue_connector = new cwz_c_blue();
int result = blue_connector->connect(this->stopFlag);
if(result == 1)//如果成功連線
emit connectionCreated();
#endif
//********************************************************//
// 變數宣告
//********************************************************//
//Handle Serial Buffer
const int incomming_buf_len = 2048;
char incomingData[incomming_buf_len] = ""; // don't forget to pre-allocate memory
int dataLength = 256;
const int bSize = 10000;
char buffer[bSize] = "";
int bLen = 0;
//Decode information from buffer string
int count = 0;
int flag = -1; //-1等於上次是不合法結束的情況
int accl[3]; // x, y, z
int gyro[3]; // x, y, z
float gravity[3];
float quatern[4];
int buttons[2];
int period;
//中位值濾波
int MFLen = 5; //濾波器長度為5
int **Accls = allcIntDArray(MFLen, 3);
int **Gyros = allcIntDArray(MFLen, 3);
int MFCount = 0; // 只用於前五次, 確認filter的data set是不是被裝滿了, 裝滿了才開始濾波
//Symbol record
//SymbolRecorder SR = SymbolRecorder();
//fileNameSStream << racketFilePath << date_string << "_" << type_string << "_" << person_string << "_" << racket_file_count << ".txt";
//********************************************************//
// 連接Com port並確認連線
//********************************************************//
#ifdef USE_WIRE_CONNECTION
std::cout << "Arduino with GY521 board and chip MPU6050!" << std::endl;
char *COM_NUM = "COM5";
Serial* SP = new Serial(COM_NUM); // adjust as needed
if (SP->IsConnected()){
emit connectionCreated();
std::cout << "We're connected" << std::endl;
}else{
stopFlag = true;
}
//read few set of data until it's getting stable
waitUntilSerialStable(SP, incomingData, dataLength);
std::cout << "Data should be stable, start to read MPU6050" << std::endl;
#else
blue_connector->send("Start to read mpu6050 data from bluetooth.\n");
#endif
while(!stopFlag){
#ifdef USE_WIRE_CONNECTION
if(!SP->IsConnected()){
std::cout << "Failed to read " << COM_NUM << " Mpu6050 reader is off." << std::endl;
emit readingEnded();
break;
}
if( !readSerialIntoBuffer(SP, incomingData, dataLength, readResult, bLen, bSize, buffer) )
continue;//If no valid serial data are read or buffer overflow, skip this round
#else
dataLength = blue_connector->receive(incomingData, incomming_buf_len);
if(dataLength > 0){//有收到東西
incomingData[dataLength] = '\0';
strcpy_s(&buffer[bLen], bSize, incomingData);
bLen += dataLength;
}
#endif
//decode mpu6050 data from buffer str, take off processed part from buffer
strcpy_s(buffer, bSize, getAccelAndGyro(&count, &flag, &bLen, buffer, accl, gyro, quatern, buttons, &period, bSize));
// 每一組合法數值為 (acclX,acclY,acclZ,gyroX,gyroY,gyroZ,quatern1,quatern2,quatern3,quatern4,buttonRight,buttonLeft,readperiod)
if( flag != GETAANDG_NEW_VALID_DATA )
continue;//尚未讀到整組完整資料 不處理 繼續讀
SHORT downKeyState = GetAsyncKeyState( VK_DOWN );
//std::cout << "gravity: " << gravity[0] << ", " << gravity[1] << ", " << gravity[2] << std::endl;
if( writeRawToFile )
{//按ctrl鍵
std::cout << "period: " << period << std::endl;
if( ( 1 << 16 ) & downKeyState ){
//writeAcclAndGyroAndGravity(fileNameSStream.str().c_str(), accl, gyro, gravity, 1);
writeMpu6050RawToFile(fileNameSStream.str().c_str(), accl, gyro, quatern, period, 1);
//std::cout << "Down Key State: " << 1 << std::endl;
}else{
//writeAcclAndGyroAndGravity(fileNameSStream.str().c_str(), accl, gyro, gravity, 0);
writeMpu6050RawToFile(fileNameSStream.str().c_str(), accl, gyro, quatern, period, 0);
//.........这里部分代码省略.........
示例11: main
//.........这里部分代码省略.........
// Parametros do PID na seguinte ordem: PF, IF, DF, PT, IT, DT, PFR, IFR, DFR, PTR, ITR, DTR
float param0[12] = { 11.45, 1.49, 26.9, 13.59, 1.63, 25.86, 1.03, 0.14, 9.36, 1.4, 0.23, 9.44 };
float param1[12] = { 25.72, 1.01, 20.07, 22.34, 0.94, 21.1, 10, 0.64, 4.92, 10, 0.61, 6.92 };
float param2[12] = { 21.86, 1.06, 18, 22, 1.03, 25.03, 3.59, 0.32, 4.94, 2.9, 0.89, 3.79 };
CvFont fonte;
cvInitFont(&fonte, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, 8);
cvNamedWindow("Live", CV_WINDOW_AUTOSIZE);
//cvNamedWindow("Filtro Atual");
//cvNamedWindow("Estrategia");
// Inicialização da Visão
vision Camera;
Camera.createCamera(0);
Camera.getImage(ROI);
Camera.configParam(parametro, amin, amax, time, min_distance, ROI);
// Inicialização da Estratégia
estrategia Estrategia(Camera.h, Camera.w, side, canto_gol1, canto_gol2, canto_area1, canto_area2);
Estrategia.Config(Camera.h, Camera.w);
pesos = cvCreateImage(cvGetSize(Camera.frame), Camera.frame->depth, 1);
Estrategia.ConfigAreas(canto_gol1, canto_gol2, canto_area1, canto_area2);
// Inicialização do Controle
controle_bili Controle_bili;
// Inicialização do Serial
Serial* SP = new Serial("COM4");
if (SP->IsConnected())
printf("We're connected\n");
//============================== VARIÁVEIS DE TESTE ============================//
int contador = 0;
float t;
float ref = 0.0, T = 40000.0, f1 = 0.0, f2 = 0.0, torque = 0.0, fx_B = 0.0, d = 3.75, KP_w = 0.0, KI_w = 0.0, flag = 0.0, K, KP_u, R = 55.0, a, dist = 0.0;
//float x = Camera.players[0].x,e =0.0;
//float y = Camera.players[0].y;
Camera.players[0].theta_acumulated = 0;
Camera.players[0].theta_old = 0;
//float theta = Camera.players[0].theta;
//float t = visionF - start;
//float v1 = 15;
//float v2 = -15;
float c, alpha = 0.0, biel = 0.0, v1_send = 0.0, v2_send = 0.0;
float dx0, dy0, Kp, /*v1 = 0.0, v2 = 0.0,*/ theta2 = 0.0, thetad = 0.0, Kt, refaux = 0.0, i = 0.0, o = 0.0, ang_error = 0.0;
float ct, st, erro_angulo = 0.0, x_bola = 0.0, y_bola = 0.0, thetad_old = 0.0, u_i = 0.0, KI_u = 0.0;
float w = 0.0, u = 0.0, w_i = 0.0, w_p = 0.0, h = 0.0, wc = 0.0, uc = 7.0, f = 300.0, u_p = 0.0, x_0 = 155, y_0 = 116;
h = 1.0 / 12.0;
int xd = 0, yd = 0;
char temp[2];
char tempread[2];
//char msg[12];
//byte sum;
float xd_old = 0.0, yd_old = 0.0;
float n_xd = Camera.players[0].x, n_yd = Camera.players[0].y;
start = clock();
示例12: main
//.........这里部分代码省略.........
CvFont fonte;
cvInitFont(&fonte, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 1, 8);
cvNamedWindow("Live", CV_WINDOW_AUTOSIZE);
//cvNamedWindow("Filtro Atual");
//cvNamedWindow("Estrategia");
// Inicialização da Visão
vision Camera;
Camera.createCamera(1);
Camera.getImage(ROI);
Camera.configParam(parametro, amin, amax, time, min_distance, ROI);
// Inicialização da Estratégia
estrategia Estrategia(Camera.h, Camera.w, side, canto_gol1, canto_gol2, canto_area1, canto_area2);
Estrategia.Config(Camera.h, Camera.w);
pesos = cvCreateImage(cvGetSize(Camera.frame), Camera.frame->depth, 1);
Estrategia.ConfigAreas(canto_gol1, canto_gol2, canto_area1, canto_area2);
// Inicialização do Controle
//controle Controle00((float)0.2, (float)0.007, (float)6, (float)0.3, (float)0.000001, (float)4);
controle Controle00(param0);
controle Controle01(param1);
controle Controle02(param2);
Controle00.distance_lim = 50;
Controle01.distance_lim = 50;
Controle02.distance_lim = 50;
// Inicialização do Serial
Serial* SP = new Serial("COM3");
if (SP->IsConnected())
printf("We're connected\n");
start = clock();
while (1)
{
counter++;
totalI = clock();
// =========================== VISÃO =========================== //
visionI = clock();
Camera.getImage();
Camera.dataAcquire();
Camera.players[1] = robot(-1, -1);
Camera.players[2] = robot(-1, -1);
visionF = clock();
//if (Camera.players[0].x != -1)
// fprintf(xFile, "%f, %i\n", Camera.players[0].x * (184 / ROI.width), int(visionF - start));
//if (Camera.players[0].y != -1)
// fprintf(yFile, "%f, %i\n", Camera.players[0].y * (95 / ROI.height), int(visionF - start));
//if (Camera.players[0].x != -1)
// fprintf(thetaFile, "%f, %i\n", Camera.players[0].theta, int(visionF - start));
//if (Camera.players[0].x != -1)
// fprintf(gFile, "%f,%f,%f %i\n", Camera.players[0].x * (184 / ROI.width), Camera.players[0].y * (95 / ROI.height), Camera.players[0].theta, int(visionF - start));
示例13: _tmain
// application reads from the specified serial port and reports the collected data
int _tmain(int argc, _TCHAR* argv[])
{
// connect the COM
printf("Welcome to the serial test app!\n\n");
#if defined (_MSC_VER)
Serial* SP = new Serial("\\\\.\\COM6"); // adjust as needed
#elif defined (__linux__)
string PORTNAMEIN;
cout << "Input Serial Port (e.g. /dev/ttyACM0): " << endl;
cin >> PORTNAMEIN;
char *PORTNAME = new char [PORTNAMEIN.length() + 1];
std::strcpy(PORTNAME, PORTNAMEIN.c_str());
Serial* SP = new Serial(PORTNAME);
unsigned int JOYSTICKID1;
#endif
if (SP->IsConnected())
printf("We're connected!\n");
//data communication
char incomingData[256] = ""; // don't forget to pre-
int dataLengthin = 127;
int readResult = 0;
int steer=2048;
int breaking = 255;
const int encoder_resolution=4096;
char outSteer[6]="2048s";
int driveDutycycle=0;
const int fullDutycycle=255;
char outDrive[5]="001d";
char outBreak[5]="100b";
//joystick initialize***********************
joyinfoex_tag joyinfo;
#ifdef __linux__
if (SDL_Init(SDL_INIT_JOYSTICK) < 0){
cout << "Error initializing SDL!" << endl;
return 1;
}
SDL_Joystick *joy;
int CtrlNum = SDL_NumJoysticks();
if (CtrlNum == 1)
JOYSTICKID1 = 0;
else{
cout << "There are " << CtrlNum << " controllers found..." << endl;
for(int i=0;i<CtrlNum;i++)
{
joy = SDL_JoystickOpen(i);
printf("%s\n", SDL_JoystickName(joy));
}
cout << "Choose the one you wish to use: " << endl;
cin >> JOYSTICKID1;
}
joy=SDL_JoystickOpen(JOYSTICKID1);
if (joy) {
printf("Opened Joystick %d\n",JOYSTICKID1);
printf("Name: %s\n", SDL_JoystickNameForIndex(0));
printf("Number of Axes: %d\n", SDL_JoystickNumAxes(joy));
printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(joy));
printf("Number of Balls: %d\n", SDL_JoystickNumBalls(joy));
} else {
printf("Couldn't open Joystick %d\n", JOYSTICKID1);
return -1*JOYSTICKID1;
}
#endif
//button status
bool is_in_situ=false;
bool is_any_direction=false;
bool is_tradition=true;
bool now_in_situ=false;
bool now_any_direction=false;
bool now_tradition=false;
bool last_in_situ=false;
bool last_any_direction=false;
bool last_tradition=false;
//int count = 0;
//start control
bool action = 1;
#if defined(_MSC_VER)
while(SP->IsConnected()) // CYCLES HERE...
{
//acquire joystick info **********************
joyGetPosEx(JOYSTICKID1, &joyinfo);
#elif defined(__linux__)
SDL_Event SysEvent;
bool NoQuit = true;
while(SP->IsConnected() && NoQuit)
{
if (SDL_PollEvent(&SysEvent))
{
switch (SysEvent.type)
{
case SDL_JOYAXISMOTION:
{
//.........这里部分代码省略.........
示例14: main
int main( int argc, char** argv )
{
VideoCapture cap(0);
if ( !cap.isOpened() )
{
cout << "Cannot open the web cam" << endl;
return -1;
}
Serial* SP = new Serial("COM7");
if (SP->IsConnected())
printf("We're connected");
char outgoingData[1] = "";
int dataLength = 1;
int readResult = 0;
while(SP->IsConnected())
{
namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
int iLowH = 0;
int iHighH = 30;
int iLowS = 150;
int iHighS = 255;
int iLowV = 142;
int iHighV = 255;
createTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
createTrackbar("HighH", "Control", &iHighH, 179);
createTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
createTrackbar("HighS", "Control", &iHighS, 255);
createTrackbar("LowV", "Control", &iLowV, 255);//Value (0 - 255)
createTrackbar("HighV", "Control", &iHighV, 255);
int iLastX = 320;
int iLastY = 240;
Mat imgTmp;
cap.read(imgTmp);
Mat imgLines = Mat::zeros( imgTmp.size(), CV_8UC3 );;
while (true)
{
Mat imgOriginal;
bool bSuccess = cap.read(imgOriginal);
if (!bSuccess)
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
Mat imgHSV;
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
Mat imgThresholded;
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
//morphological opening (removes small objects from the foreground)
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
//morphological closing (removes small holes from the foreground)
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)) );
//Calculate the moments of the thresholded image
Moments oMoments = moments(imgThresholded);
double dM01 = oMoments.m01;
double dM10 = oMoments.m10;
double dArea = oMoments.m00;
// if the area <= 10000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
if (dArea > 10000)
{
//calculate the position of the ball
int posX = dM10 / dArea;
int posY = dM01 / dArea;
if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0)
{
//Draw a red line from the previous point to the current point
// line(imgLines, Point(posX, posY), Point(iLastX, iLastY), Scalar(0,0,255), 2);
Point pt1(posX-10, posY-10);
Point pt2(posX+10, posY+10);
//.........这里部分代码省略.........