elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Los 10 CVE más críticos (peligrosos) de 2020


  Mostrar Mensajes
Páginas: 1 2 3 4 5 6 7 8 9 [10] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ... 255
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.
Código
  1. #include <iostream>
  2. #include <fstream>
  3. #include <Windows.h>    // Para mostrar texto en el título de la ventana.
  4. #include <stdio.h>      // Cambio color de fondo y letras.
  5. #include "SerialClass.h"
  6.  
  7. using namespace std;
  8. //using std::cout;
  9. //using std::cin;
  10.  
  11. // Función posición del cursor.
  12. void gotoxy(int x, int y)
  13. {
  14.    HANDLE hcon;
  15.    hcon = GetStdHandle(STD_OUTPUT_HANDLE);
  16.    COORD dwPos;
  17.    dwPos.X = x;
  18.    dwPos.Y = y;
  19.    SetConsoleCursorPosition(hcon, dwPos);
  20. }
  21.  
  22. int main()
  23. {
  24.  
  25. #pragma region "Configuración ventana."
  26.    // Mostrar caracteres correctamente en pantalla y título de la ventana.
  27.    SetConsoleOutputCP(65001);
  28.    wchar_t titulo[128];
  29.    MultiByteToWideChar(CP_UTF8, 0, "Led Arduino C++ nativo", -1, titulo, 128);
  30.    SetConsoleTitleW(titulo);
  31.  
  32.    // Tamaño de la pantalla. Se cambia en los dos últimos dígitos.
  33.    SMALL_RECT r = { 0, 0, 80, 20 }; // X = 49, Y = 9.
  34.    SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &r);
  35.  
  36.    // Cambio color de 6 (naranja claro), color letras 0 (negro).
  37.    system("color 60");
  38.  
  39.    // Ocultar cursor.
  40.    CONSOLE_CURSOR_INFO cci;
  41.    GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
  42.    cci.bVisible = 0; // 0 oculta. 1 muestra cursor.
  43.    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
  44. #pragma endregion
  45.  
  46.    // Puerto serie.
  47.    Serial* Puerto = new Serial("COM4");
  48.  
  49.    // Comandos para Arduino.
  50.    char Luz_ON[] = "Luz_ON";       // Envía "Luz_ON" al puerto serie.
  51.    char Luz_OFF[] = "Luz_OFF";
  52.    char lectura[50] = "\0";        // Guardan datos de entrada del puerto.
  53.  
  54.    int opc; // Guarda un 1 o 2 tipo entero queintroduces desde la consola.
  55.  
  56.    while (Puerto->IsConnected())
  57.    {
  58.        cout << endl;       // Retorno.
  59.        cout << "Introduzca la opcion deseada: " << endl;
  60.        cout << "Pulse 1 para encender el Led, pulse 2 para apagar." << endl << endl; // Muestra texto en pantalla.
  61.  
  62.        cin >> opc;         // Aquí introduces un número, el 1 o el 2.
  63.  
  64.        switch (opc)        // Espera recibir un 1 o un 2.
  65.        {
  66.        case 1:
  67.            // Encener luz.
  68.            cout << "Enviando: " << Luz_ON << endl;         // Muestra en pantalla textos.
  69.            Puerto->WriteData(Luz_ON, sizeof(Luz_ON) - 1);  // Envía al puerto el texto "Luz_ON".
  70.            break;
  71.  
  72.        case 2:
  73.            // Apagar luz.
  74.            cout << "Enviando: " << Luz_OFF << endl;
  75.            Puerto->WriteData(Luz_OFF, sizeof(Luz_OFF) - 1);
  76.            break;
  77.  
  78.        default: // Si haz pulsado otro número distinto del 1 y 2, muestra
  79.            cout << "Puse del 1 al 2.";                     // este mensaje.
  80.        }
  81.  
  82.  
  83.        Sleep(500);
  84.        int n = Puerto->ReadData(lectura, 49);          // Recibe datos del puerto serie.
  85.        if (n > 0)
  86.        {
  87.            lectura[n + 1] = '\0';                      // Limpia de basura la variable.
  88.            cout << "Recibido: " << lectura << endl;    // Muestra en pantalla dato recibido.
  89.            cout << "-------------------" << endl;
  90.        }
  91.  
  92.        cin.ignore(256, '\n');                          // Limpiar buffer del teclado.
  93.    }
  94. }

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#:
Código
  1. using System;
  2. using System.IO.Ports;
  3.  
  4. namespace Emulador_Puerto_Serie_Arduino_03
  5. {
  6.    internal class Program
  7.    {
  8.        static void Main(string[] args)
  9.        {
  10.  
  11.            // alguna inicialización
  12.            SerialPort sp = new SerialPort();
  13.            sp.PortName = "COM4";
  14.            sp.BaudRate = 115200;
  15.            sp.Open();
  16.  
  17.            // esperamos
  18.            while (true)
  19.            {
  20.                string comando = sp.ReadLine();
  21.  
  22.                if (comando == "Luz_ON")
  23.                {
  24.                    // Enciende el Led.
  25.                    Console.ForegroundColor = ConsoleColor.Green;
  26.  
  27.                    Console.SetCursorPosition(0, 0);
  28.                    Console.WriteLine("\u2588\u2588\u2588\u2588");
  29.                    Console.WriteLine("\u2588\u2588\u2588\u2588");
  30.                    Console.WriteLine("\u2588\u2588\u2588\u2588");
  31.  
  32.                    // devuelve el resultado
  33.                    sp.WriteLine("ON - Led encendido.");
  34.                }
  35.  
  36.                // Si le llega el mensaje Luz_OFF.
  37.                if (comando == "Luz_OFF")
  38.                {
  39.                    // Apaga el Led.
  40.                    Console.ForegroundColor = ConsoleColor.DarkGreen;
  41.  
  42.                    Console.SetCursorPosition(0, 0);
  43.                    Console.WriteLine("\u2588\u2588\u2588\u2588");
  44.                    Console.WriteLine("\u2588\u2588\u2588\u2588");
  45.                    Console.WriteLine("\u2588\u2588\u2588\u2588");
  46.  
  47.                    // devuelve el resultado
  48.                    sp.WriteLine("OFF - Led apagado. ");
  49.                }
  50.            }
  51.  
  52.            // cerramos
  53.            sp.Close();
  54.            Console.ReadKey(true);
  55.        }
  56.    }
  57. }

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:
Código
  1. const byte Led = 13;   // Declaramos la variable pin del Led.
  2. char caracter;
  3. String comando;
  4.  
  5. void setup()
  6. {
  7.  pinMode(Led, OUTPUT);  // Inicializa el pin del LED como salida:
  8.  Serial.begin(115200);     // Puerto serie 115200 baudios.
  9. }
  10.  
  11. void loop()
  12. {
  13.  /*
  14.     Voy leyendo carácter a carácter lo que se recibe por el canal serie
  15.     (mientras llegue algún dato allí), y los voy concatenando uno tras otro
  16.     en una cadena. En la práctica, si usamos el "Serial monitor" el bucle while
  17.     acabará cuando pulsamos Enter. El delay es conveniente para no saturar el
  18.     canal serie y que la concatenación se haga de forma ordenada.
  19.   */
  20.  while (Serial.available() > 0)
  21.  {
  22.    caracter = Serial.read();
  23.    comando.concat(caracter);
  24.    delay(10);
  25.  }
  26.  
  27.  /*
  28.     Una vez ya tengo la cadena "acabada", compruebo su valor y hago que
  29.     la placa Arduino reacciones según sea este. Aquí podríamos hacer lo
  30.     que quisiéramos: si el comando es "tal", enciende un Led, si es cual,
  31.     mueve un motor... y así.
  32.   */
  33.  
  34.  // Si le llega el mensaje Luz_ON.
  35.  if (comando.equals("Luz_ON") == true)
  36.  {
  37.    digitalWrite(Led, HIGH); // Enciende el Led 13.
  38.    Serial.write("ON - Led encendido.");    // Envía este mensaje a C++.
  39.  }
  40.  
  41.  // Si le llega el mensaje Luz_ON.
  42.  if (comando.equals("Luz_OFF") == true)
  43.  {
  44.    digitalWrite(Led, LOW); // Apaga el Led 13.
  45.    Serial.write("OFF - Led apagado. ");  // Envía este mensaje a C++.
  46.  }
  47.  
  48.  // Limpiamos la cadena para volver a recibir el siguiente comando.
  49.  comando = "";
  50. }

Saludos.
93  Programación / Programación C/C++ / Re: No funciona con la versión VS 202 en: 25 Enero 2023, 07:09 am
Ya funciona, te la saber toda. Muchas gracias horonable Eternal Idol.  ;-)
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.
Código
  1. #pragma region "Configuración ventana."
  2.    // Mostrar caracteres correctamente en pantalla y título de la ventana.
  3.    SetConsoleOutputCP(65001);
  4.    wchar_t titulo[128];
  5.    MultiByteToWideChar(CP_UTF8, 0, "Led Arduino C++ nativo", -1, titulo, 128);
  6.    SetConsoleTitle(titulo);
  7.  
  8.    // Tamaño de la pantalla. Se cambia en los dos últimos dígitos.
  9.    SMALL_RECT r = { 0, 0, 80, 20 }; // X = 49, Y = 9.
  10.    SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &r);
  11.  
  12.    // Cambio color de A (verde claro), color letras 0 (negro).
  13.    system("color A0");
  14.  
  15.    // Ocultar cursor.
  16.    CONSOLE_CURSOR_INFO cci;
  17.    GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
  18.    cci.bVisible = 0; // 0 oculta. 1 muestra cursor.
  19.    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
  20. #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   
95  Programación / Programación C/C++ / Re: No funciona con la versión VS 202 en: 22 Enero 2023, 23:19 pm
No te había leído. Reedité el post de la página anterior, ya funciona.
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
Código
  1.    public:
  2.        //Initialize Serial communication with the given COM port
  3.        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.
Código
  1. Serial::Serial(const char *portName)

Ya que hablas del proyecto...


El .h es este.

Código
  1. #ifndef SERIALCLASS_H_INCLUDED
  2. #define SERIALCLASS_H_INCLUDED
  3.  
  4. #define ARDUINO_WAIT_TIME 2000
  5.  
  6. #include <windows.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9.  
  10. class Serial
  11. {
  12.    private:
  13.        //Serial comm handler
  14.        HANDLE hSerial;
  15.        //Connection status
  16.        bool connected;
  17.        //Get various information about the connection
  18.        COMSTAT status;
  19.        //Keep track of last error
  20.        DWORD errors;
  21.  
  22.    public:
  23.        //Initialize Serial communication with the given COM port
  24.        Serial(char *portName);
  25.        //Close the connection
  26.        //NOTA: for some reason you can't connect again before exiting
  27.        //the program and running it again
  28.        ~Serial();
  29.        //Read data in a buffer, if nbChar is greater than the
  30.        //maximum number of bytes available, it will return only the
  31.        //bytes available. The function return -1 when nothing could
  32.        //be read, the number of bytes actually read.
  33.        int ReadData(char *buffer, unsigned int nbChar);
  34.        //Writes data from a buffer through the Serial connection
  35.        //return true on success.
  36.        bool WriteData(char *buffer, unsigned int nbChar);
  37.        //Check if we are actually connected
  38.        bool IsConnected();
  39.  
  40.  
  41. };
  42.  
  43. #endif // SERIALCLASS_H_INCLUDED
98  Programación / Programación C/C++ / Re: No funciona con la versión VS 202 en: 22 Enero 2023, 19:46 pm
Holaaaaaaa:



Y la clase.


Que deje de funcionar los programas que hacer en C++ nativo es lo que me pone de mala leche. En los .net estas cosas ocurren cuando pasan unos 10 años o más.
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:
Código
  1. #include "SerialClass.h"
  2.  
  3. Serial::Serial(char *portName)
  4. {
  5.    //We're not yet connected
  6.    this->connected = false;
  7.  
  8.    //Try to connect to the given port throuh CreateFile
  9.    this->hSerial = CreateFile(portName,
  10.            GENERIC_READ | GENERIC_WRITE,
  11.            0,
  12.            NULL,
  13.            OPEN_EXISTING,
  14.            FILE_ATTRIBUTE_NORMAL,
  15.            NULL);
  16.  
  17.    //Check if the connection was successfull
  18.    if(this->hSerial==INVALID_HANDLE_VALUE)
  19.    {
  20.        //If not success full display an Error
  21.        if(GetLastError()==ERROR_FILE_NOT_FOUND){
  22.  
  23.            //Print Error if neccessary
  24.            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);
  25.  
  26.        }
  27.        else
  28.        {
  29.            printf("ERROR!!!");
  30.        }
  31.    }
  32.    else
  33.    {
  34.        //If connected we try to set the comm parameters
  35.        DCB dcbSerialParams = {0};
  36.  
  37.        //Try to get the current
  38.        if (!GetCommState(this->hSerial, &dcbSerialParams))
  39.        {
  40.            //If impossible, show an error
  41.            printf("failed to get current serial parameters!");
  42.        }
  43.        else
  44.        {
  45.            //Define serial connection parameters for the arduino board
  46.            dcbSerialParams.BaudRate=CBR_115200;
  47.            dcbSerialParams.ByteSize=8;
  48.            dcbSerialParams.StopBits=ONESTOPBIT;
  49.            dcbSerialParams.Parity=NOPARITY;
  50.  
  51.             //Set the parameters and check for their proper application
  52.             if(!SetCommState(hSerial, &dcbSerialParams))
  53.             {
  54.                printf("ALERT: Could not set Serial Port parameters");
  55.             }
  56.             else
  57.             {
  58.                 //If everything went fine we're connected
  59.                 this->connected = true;
  60.                 //We wait 2s as the arduino board will be reseting
  61.                 Sleep(ARDUINO_WAIT_TIME);
  62.             }
  63.        }
  64.    }
  65.  
  66. }
  67.  
  68. Serial::~Serial()
  69. {
  70.    //Check if we are connected before trying to disconnect
  71.    if(this->connected)
  72.    {
  73.        //We're no longer connected
  74.        this->connected = false;
  75.        //Close the serial handler
  76.        CloseHandle(this->hSerial);
  77.    }
  78. }
  79.  
  80. int Serial::ReadData(char *buffer, unsigned int nbChar)
  81. {
  82.    //Number of bytes we'll have read
  83.    DWORD bytesRead;
  84.    //Number of bytes we'll really ask to read
  85.    unsigned int toRead;
  86.  
  87.    //Use the ClearCommError function to get status info on the Serial port
  88.    ClearCommError(this->hSerial, &this->errors, &this->status);
  89.  
  90.    //Check if there is something to read
  91.    if(this->status.cbInQue>0)
  92.    {
  93.        //If there is we check if there is enough data to read the required number
  94.        //of characters, if not we'll read only the available characters to prevent
  95.        //locking of the application.
  96.        if(this->status.cbInQue>nbChar)
  97.        {
  98.            toRead = nbChar;
  99.        }
  100.        else
  101.        {
  102.            toRead = this->status.cbInQue;
  103.        }
  104.  
  105.        //Try to read the require number of chars, and return the number of read bytes on success
  106.        if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
  107.        {
  108.            return bytesRead;
  109.        }
  110.  
  111.    }
  112.  
  113.    //If nothing has been read, or that an error was detected return -1
  114.    return -1;
  115.  
  116. }
  117.  
  118.  
  119. bool Serial::WriteData(char *buffer, unsigned int nbChar)
  120. {
  121.    DWORD bytesSend;
  122.  
  123.    //Try to write the buffer on the Serial port
  124.    if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
  125.    {
  126.        //In case it don't work get comm error and return false
  127.        ClearCommError(this->hSerial, &this->errors, &this->status);
  128.  
  129.        return false;
  130.    }
  131.    else
  132.        return true;
  133. }
  134.  
  135. bool Serial::IsConnected()
  136. {
  137.    //Simply return the connection status
  138.    return this->connected;
  139. }

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++:
Código
  1. #include <iostream>
  2. #include <fstream>
  3. #include <Windows.h>
  4. #include "SerialClass.h"
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.    // Título de la ventana
  10.    SetConsoleTitle("Control Led Arduino - Visual Studio C++ 2022");
  11.  
  12.    // Puerto serie.
  13.    Serial* Puerto = new Serial("COM4");
  14.  
  15.    // Comandos para Arduino.
  16.    char Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie.
  17.    char Luz_OFF[] = "Luz_OFF";
  18.    char lectura[50] = "\0"; // Guardan datos de entrada del puerto.
  19.  
  20.    int opc; // Guarda un 1 o 2 tipo entero queintroduces desde la consola.
  21.  
  22.    while (Puerto->IsConnected())
  23.    {
  24.        cout << endl; // Retorno.
  25.        cout << "Introduzca la opcion deseada: " << endl;
  26.        cout << "Pulse 1 para encender el Led, pulse 2 para apagar." << endl << endl; // Muestra texto en pantalla.
  27.  
  28.        cin >> opc; // Aquí introduces un número, el 1 o el 2.
  29.  
  30.        switch (opc) // Espera recibir un 1 o un 2.
  31.        {
  32.        case 1:
  33.            // Encener luz.
  34.            cout << "Enviando: " << Luz_ON << endl; // Muestra en pantalla textos.
  35.            Puerto->WriteData(Luz_ON, sizeof(Luz_ON) - 1); // Envía al puerto el texto "Luz_ON".
  36.            break;
  37.  
  38.        case 2:
  39.            // Apagar luz.
  40.            cout << "Enviando: " << Luz_OFF << endl;
  41.            Puerto->WriteData(Luz_OFF, sizeof(Luz_OFF) - 1);
  42.            break;
  43.  
  44.        default: // Si haz pulsado otro número distinto del 1 y 2, muestra
  45.            cout << "Puse del 1 al 2."; // este mensaje.
  46.        }
  47.  
  48.  
  49.        Sleep(500);
  50.        int n = Puerto->ReadData(lectura, 49); // Recibe datos del puerto serie.
  51.        if (n > 0)
  52.        {
  53.            lectura[n + 1] = '\0'; // Limpia de basura la variable.
  54.            cout << "Recibido: " << lectura << endl; // Muestra en pantalla dato recibido.
  55.            cout << "-------------------" << endl;
  56.        }
  57.  
  58.        cin.ignore(256, '\n'); // Limpiar buffer del teclado.
  59.    }
  60. }

Estoy siguiendo la guía del enlace de abajo a partir de la página 54.

Ver tutorial.

Saludos.
Páginas: 1 2 3 4 5 6 7 8 9 [10] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ... 255
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines