Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <iostream>
- #include <string>
- #include <sstream>
- #include <vector>
- using namespace std;
- /* // Скетч для Arduino
- void setup()
- {
- Serial.begin(9600);
- }
- void loop()
- {
- if (Serial.available() > 0)
- {
- String input = Serial.readString();
- Serial.print("OK"); // Простой ответ
- }
- delay(100);
- } */
- ///////////////////////
- class ArduinoFinder
- {
- private:
- int baud_rate;
- bool isArduinoPort(const string& port_name)
- {
- HANDLE hSerial = CreateFile(port_name.c_str(),
- GENERIC_READ | GENERIC_WRITE,
- 0, NULL, OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL, NULL);
- if (hSerial == INVALID_HANDLE_VALUE) {
- return false;
- }
- DCB dcb = {0}; // Настройка параметров порта
- dcb.DCBlength = sizeof(dcb);
- if (!GetCommState(hSerial, &dcb))
- {
- CloseHandle(hSerial);
- return false;
- }
- dcb.BaudRate = baud_rate;
- dcb.ByteSize = 8;
- dcb.StopBits = ONESTOPBIT;
- dcb.Parity = NOPARITY;
- if (!SetCommState(hSerial, &dcb))
- {
- CloseHandle(hSerial);
- return false;
- }
- COMMTIMEOUTS timeouts = {0}; // Настройка таймаутов
- timeouts.ReadIntervalTimeout = 50 ;
- timeouts.ReadTotalTimeoutConstant = 50 ;
- timeouts.ReadTotalTimeoutMultiplier = 10 ;
- SetCommTimeouts(hSerial, &timeouts);
- const char* test_cmd = "AT\r\n"; // Тестирование порта
- char buffer[256] = {0};
- DWORD bytes_written, bytes_read;
- bool is_arduino = false;
- if (WriteFile(hSerial, test_cmd, strlen(test_cmd), &bytes_written, NULL))
- {
- Sleep(100);
- if (ReadFile(hSerial, buffer, sizeof(buffer)-1, &bytes_read, NULL))
- {
- is_arduino = (bytes_read > 0);
- }
- }
- CloseHandle(hSerial);
- return is_arduino;
- }
- public:
- ArduinoFinder(int baud = 9600) : baud_rate(baud) {}
- ////////////////////
- string findArduino()
- {
- cout << "Поиск Arduino Uno (" << baud_rate << " бод)..." << endl << endl;
- for (int i = 1; i <= 30; ++i)
- {
- ostringstream oss;
- oss << i;
- string port = "COM" + oss.str(); // + to_string(i); // 2011 STD
- cout << "Проверка " << port << "... ";
- if(isArduinoPort(port))
- {
- cout << "! НАЙДЕНО !" << endl;
- return port;
- }
- cout << "? не Arduino" << endl;
- }
- return "";
- }
- };
- /////////////////////////////////////////////////////////////
- int main() //
- {
- setlocale(LC_ALL, "rus");
- cout << "=== AUTOMATIC ARDUINO UNO FINDER ===" << endl;
- cout << " Поиск на скорости 9600 бод" << endl;
- cout << "=====================================" << endl << endl;
- ArduinoFinder finder(9600);
- string arduinoPort = finder.findArduino();
- cout << endl << "=====================================" << endl;
- if (!arduinoPort.empty()) {
- cout << "?? Arduino найдено на: " << arduinoPort << endl;
- } else {
- cout << "?? Arduino не найдено!" << endl;
- cout << "Проверьте подключение и драйверы" << endl;
- }
- cout << endl << "Нажмите Enter для выхода...";
- cin.get();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment