|
91
|
Programación / Programación C/C++ / Desde que pulse una tecla, que ejecuta dicha acción
|
en: 2 Febrero 2023, 20:54 pm
|
Buenas gente: Aquí tengo un programa que solo se ejecuta una orden si pulso el 1 y luego Enter. ¿Hay alguna manera que pulse la tecla 1 y me ejecute una acción sin luego pulsar Enter? El código que es este. #include <iostream> #include <fstream> #include <Windows.h> // Para mostrar texto en el título de la ventana. #include <stdio.h> // Cambio color de fondo y letras. #include "SerialClass.h" using namespace std; //using std::cout; //using std::cin; // Función posición del cursor. void gotoxy(int x, int y) { HANDLE hcon; hcon = GetStdHandle(STD_OUTPUT_HANDLE); COORD dwPos; dwPos.X = x; dwPos.Y = y; SetConsoleCursorPosition(hcon, dwPos); } int main() { #pragma region "Configuración ventana." // Mostrar caracteres correctamente en pantalla y título de la ventana. SetConsoleOutputCP(65001); wchar_t titulo[128]; MultiByteToWideChar(CP_UTF8, 0, "Led Arduino C++ nativo", -1, titulo, 128); SetConsoleTitleW(titulo); // Tamaño de la pantalla. Se cambia en los dos últimos dígitos. SMALL_RECT r = { 0, 0, 80, 20 }; // X = 49, Y = 9. SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &r); // Cambio color de 6 (naranja claro), color letras 0 (negro). system("color 60"); // Ocultar cursor. CONSOLE_CURSOR_INFO cci; GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci); cci.bVisible = 0; // 0 oculta. 1 muestra cursor. SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci); #pragma endregion // Puerto serie. Serial* Puerto = new Serial("COM4"); // Comandos para Arduino. char Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie. char Luz_OFF[] = "Luz_OFF"; char lectura[50] = "\0"; // Guardan datos de entrada del puerto. int opc; // Guarda un 1 o 2 tipo entero queintroduces desde la consola. while (Puerto->IsConnected()) { cout << endl; // Retorno. cout << "Introduzca la opcion deseada: " << endl; cout << "Pulse 1 para encender el Led, pulse 2 para apagar." << endl << endl; // Muestra texto en pantalla. cin >> opc; // Aquí introduces un número, el 1 o el 2. switch (opc) // Espera recibir un 1 o un 2. { case 1: // Encener luz. cout << "Enviando: " << Luz_ON << endl; // Muestra en pantalla textos. Puerto->WriteData(Luz_ON, sizeof(Luz_ON) - 1); // Envía al puerto el texto "Luz_ON". break; case 2: // Apagar luz. cout << "Enviando: " << Luz_OFF << endl; Puerto->WriteData(Luz_OFF, sizeof(Luz_OFF) - 1); break; default: // Si haz pulsado otro número distinto del 1 y 2, muestra cout << "Puse del 1 al 2."; // este mensaje. } Sleep(500); int n = Puerto->ReadData(lectura, 49); // Recibe datos del puerto serie. if (n > 0) { lectura[n + 1] = '\0'; // Limpia de basura la variable. cout << "Recibido: " << lectura << endl; // Muestra en pantalla dato recibido. cout << "-------------------" << endl; } cin.ignore(256, '\n'); // Limpiar buffer del teclado. } }
Saludos.
|
|
|
92
|
Programación / .NET (C#, VB.NET, ASP) / Enviar y recibir información
|
en: 26 Enero 2023, 21:18 pm
|
Hola: Con un programa envío el comando Luz_ON a este programa de abajo MAL HECHO que lo tengo de prueba en la consola de C# para que me devuelva también, pero no funciona. Código C#:using System; using System.IO.Ports; namespace Emulador_Puerto_Serie_Arduino_03 { internal class Program { static void Main(string[] args) { // alguna inicialización SerialPort sp = new SerialPort (); sp.PortName = "COM4"; sp.BaudRate = 115200; sp.Open(); // esperamos while (true) { string comando = sp.ReadLine(); if (comando == "Luz_ON") { // Enciende el Led. Console.ForegroundColor = ConsoleColor.Green; Console.SetCursorPosition(0, 0); Console.WriteLine("\u2588\u2588\u2588\u2588"); Console.WriteLine("\u2588\u2588\u2588\u2588"); Console.WriteLine("\u2588\u2588\u2588\u2588"); // devuelve el resultado sp.WriteLine("ON - Led encendido."); } // Si le llega el mensaje Luz_OFF. if (comando == "Luz_OFF") { // Apaga el Led. Console.ForegroundColor = ConsoleColor.DarkGreen; Console.SetCursorPosition(0, 0); Console.WriteLine("\u2588\u2588\u2588\u2588"); Console.WriteLine("\u2588\u2588\u2588\u2588"); Console.WriteLine("\u2588\u2588\u2588\u2588"); // devuelve el resultado sp.WriteLine("OFF - Led apagado. "); } } // cerramos sp.Close(); Console.ReadKey(true); } } }
En Arduino si funciona, que este es su código de abajo, ya que quiero convertir de ARduino a C#, que haga lo mismo. Recibir datos por el puerto serie y enviarlo automáticamente. Código Arduino:const byte Led = 13; // Declaramos la variable pin del Led. char caracter; String comando; void setup() { pinMode(Led, OUTPUT); // Inicializa el pin del LED como salida: Serial.begin(115200); // Puerto serie 115200 baudios. } void loop() { /* Voy leyendo carácter a carácter lo que se recibe por el canal serie (mientras llegue algún dato allí), y los voy concatenando uno tras otro en una cadena. En la práctica, si usamos el "Serial monitor" el bucle while acabará cuando pulsamos Enter. El delay es conveniente para no saturar el canal serie y que la concatenación se haga de forma ordenada. */ while (Serial.available() > 0) { caracter = Serial.read(); comando.concat(caracter); delay(10); } /* Una vez ya tengo la cadena "acabada", compruebo su valor y hago que la placa Arduino reacciones según sea este. Aquí podríamos hacer lo que quisiéramos: si el comando es "tal", enciende un Led, si es cual, mueve un motor... y así. */ // Si le llega el mensaje Luz_ON. if (comando.equals("Luz_ON") == true) { digitalWrite(Led, HIGH); // Enciende el Led 13. Serial.write("ON - Led encendido."); // Envía este mensaje a C++. } // Si le llega el mensaje Luz_ON. if (comando.equals("Luz_OFF") == true) { digitalWrite(Led, LOW); // Apaga el Led 13. Serial.write("OFF - Led apagado. "); // Envía este mensaje a C++. } // Limpiamos la cadena para volver a recibir el siguiente comando. comando = ""; }
Saludos.
|
|
|
94
|
Programación / Programación C/C++ / Re: No funciona con la versión VS 202
|
en: 25 Enero 2023, 00:07 am
|
Quiero añadir este código. #pragma region "Configuración ventana." // Mostrar caracteres correctamente en pantalla y título de la ventana. SetConsoleOutputCP(65001); wchar_t titulo[128]; MultiByteToWideChar(CP_UTF8, 0, "Led Arduino C++ nativo", -1, titulo, 128); SetConsoleTitle(titulo); // Tamaño de la pantalla. Se cambia en los dos últimos dígitos. SMALL_RECT r = { 0, 0, 80, 20 }; // X = 49, Y = 9. SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &r); // Cambio color de A (verde claro), color letras 0 (negro). system("color A0"); // Ocultar cursor. CONSOLE_CURSOR_INFO cci; GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci); cci.bVisible = 0; // 0 oculta. 1 muestra cursor. SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci); #pragma endregion
Y me falla con este error. Gravedad Código Descripción Proyecto Archivo Línea Estado suprimido Error C2664 'BOOL SetConsoleTitleA(LPCSTR)': el argumento 1 no puede convertirse de 'wchar_t [128]' a 'LPCSTR' Led Arduino CPP nativo 02 D:\Visual Studio 2022\Led Arduino CPP nativo 02\Led Arduino CPP nativo 02\Led Arduino CPP nativo 02.cpp 30
|
|
|
96
|
Programación / Programación C/C++ / Re: No funciona con la versión VS 202
|
en: 22 Enero 2023, 22:46 pm
|
Uso el que me viene predeterminado. Puedes seleccionar el 14, 17 y 20. Hasta ahí llegaron. No he tocado nada, me imagino que toco el que viene por defecto. En cuanto al const. Me imagino que será en la .h public: //Initialize Serial communication with the given COM port Serial(const char *portName);
Edito: Ya compila, por fin. Todo por no incluir el const en cpp y h. Muchísimas gracias a todos.
|
|
|
97
|
Programación / Programación C/C++ / Re: No funciona con la versión VS 202
|
en: 22 Enero 2023, 22:15 pm
|
No me puedo creer que te funcione. Si te refieres a esto, da más errores aún. Serial::Serial(const char *portName)
Ya que hablas del proyecto... El .h es este. #ifndef SERIALCLASS_H_INCLUDED #define SERIALCLASS_H_INCLUDED #define ARDUINO_WAIT_TIME 2000 #include <windows.h> #include <stdio.h> #include <stdlib.h> 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(char *portName); //Close the connection //NOTA: for some reason you can't connect again before exiting //the program and running it again ~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
|
|
|
99
|
Programación / Programación C/C++ / Re: No funciona con la versión VS 202
|
en: 22 Enero 2023, 15:55 pm
|
No deja compilar, muestra estos errores. Viene de la librería esta. SerialClass.cpp:#include "SerialClass.h" Serial::Serial(char *portName) { //We're not yet connected this->connected = false; //Try to connect to the given port throuh CreateFile this->hSerial = CreateFile(portName, 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_115200; dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; //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; //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) && bytesRead != 0) { return bytesRead; } } //If nothing has been read, or that an error was detected return -1 return -1; } 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; }
Antes funcionaba todo. Ya no funciona ni modo 32 bits, ni 64 bits. Saludos.
|
|
|
100
|
Programación / Programación C/C++ / No funciona con la versión VS 202
|
en: 22 Enero 2023, 14:41 pm
|
Buenas gente: Usando C++ nativo de la época del Visual Studio 2017 el programa funciona de maravilla. Probando ahora la versión del Visual Studio 2022, a pesar que es el mismo código, me da error por todas partes. El código es C++ nativo, nada de C++ del .net. Código C++:#include <iostream> #include <fstream> #include <Windows.h> #include "SerialClass.h" using namespace std; int main() { // Título de la ventana SetConsoleTitle("Control Led Arduino - Visual Studio C++ 2022"); // Puerto serie. Serial* Puerto = new Serial("COM4"); // Comandos para Arduino. char Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie. char Luz_OFF[] = "Luz_OFF"; char lectura[50] = "\0"; // Guardan datos de entrada del puerto. int opc; // Guarda un 1 o 2 tipo entero queintroduces desde la consola. while (Puerto->IsConnected()) { cout << endl; // Retorno. cout << "Introduzca la opcion deseada: " << endl; cout << "Pulse 1 para encender el Led, pulse 2 para apagar." << endl << endl; // Muestra texto en pantalla. cin >> opc; // Aquí introduces un número, el 1 o el 2. switch (opc) // Espera recibir un 1 o un 2. { case 1: // Encener luz. cout << "Enviando: " << Luz_ON << endl; // Muestra en pantalla textos. Puerto->WriteData(Luz_ON, sizeof(Luz_ON) - 1); // Envía al puerto el texto "Luz_ON". break; case 2: // Apagar luz. cout << "Enviando: " << Luz_OFF << endl; Puerto->WriteData(Luz_OFF, sizeof(Luz_OFF) - 1); break; default: // Si haz pulsado otro número distinto del 1 y 2, muestra cout << "Puse del 1 al 2."; // este mensaje. } Sleep(500); int n = Puerto->ReadData(lectura, 49); // Recibe datos del puerto serie. if (n > 0) { lectura[n + 1] = '\0'; // Limpia de basura la variable. cout << "Recibido: " << lectura << endl; // Muestra en pantalla dato recibido. cout << "-------------------" << endl; } cin.ignore(256, '\n'); // Limpiar buffer del teclado. } }
Estoy siguiendo la guía del enlace de abajo a partir de la página 54. Ver tutorial. Saludos.
|
|
|
|
|
|
|