Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    [C - C++] Creare un log

    Salve ragazzi, il seguente programma mi serve per un progetto a cui sto lavorando nell'ambito della mia tesi:

    codice:
    #include <condefs.h>   // Main pgm is a console application
    #include <time.h>      // Used when detecting timeouts
    #include <windows.h>   // We use some Windows system calls
    #include <iostream.h>  // We use cout, etc.
    #include <stdio.h>
    #include <conio.h>
    
    #define F1  59
    #define F2  60
    
    //---------------------------------------------------------------------------
    
    HANDLE   hSerPort;     // Global variables
    int      iSerOK;
    
    //---------------------------------------------------------------------------
    
    void SerMessage(char* msg1, char* msg2)
    // Displays a message to the user.
    // msg1 = main message
    // msg2 = message caption
    // Change this to your preferred way of displaying msgs.
    {
      MessageBox(NULL,msg1,msg2,MB_OK);
    }
    
    //---------------------------------------------------------------------------
    
    void SerCrash(char* msg1, char* msg2)
    // Like SerMessage, but ends the program.
    {
      SerMessage(msg1,msg2);
      iSerOK = 0;
    }
    
    //---------------------------------------------------------------------------
    
    int SerOK()
    // Returns nonzero if most recent operation succeeded,
    // or 0 if there was an error
    {
      return iSerOK;
    }
    
    //---------------------------------------------------------------------------
    
    void SerOpen(char* portname, char* handshake)
    // Opens the serial port.
    // portname = "COM1", "COM2", etc.
    // handshake = "RTS" or "DTR"
    {
      //
      // Open the port using a handle
      //
      hSerPort = CreateFile(
        portname,GENERIC_READ|GENERIC_WRITE,
        0,                           // must be opened with exclusive-access
        NULL,                        // no security attributes
        OPEN_EXISTING,               // must use OPEN_EXISTING
        FILE_ATTRIBUTE_NORMAL,       // normal file
        NULL                         // hTemplate must be NULL for comm devices
        );
    
      if (hSerPort == INVALID_HANDLE_VALUE)
        SerCrash("Can't open comm port",portname);
      //
      // Fill in DCB. Set baud rate and other attributes
      //
      DCB dcbSerPort;
      // The GetCommState function retrieves the current control settings
      // for a specified communications device.
      GetCommState(hSerPort,&dcbSerPort);
      // set the baud rate
      dcbSerPort.BaudRate = CBR_9600;
      // binary mode is enabled
      dcbSerPort.fBinary = TRUE;
      // parity checking is performed and errors are reported
      dcbSerPort.fParity = FALSE;
      // both handshaking modes are sensitive to DSR and DTR... (originally TRUE)
      dcbSerPort.fDsrSensitivity = FALSE;
      // DTR (data-terminal-ready) flow control, handshaking is enabled
      dcbSerPort.fDtrControl = DTR_CONTROL_HANDSHAKE;
      // the DSR (data-set-ready) signal is monitored for output flow control
      dcbSerPort.fOutxDsrFlow = TRUE;
      // .. but not XON/XOFF.
      // if this member is TRUE, transmission stops when the XoffChar character
      // is received and starts again when the XonChar character is received.
      dcbSerPort.fOutX = FALSE;
      // if this member is TRUE, the XoffChar character is sent when the input
      // buffer comes within XoffLim bytes of being full, and the XonChar character
      // is sent when the input buffer comes within XonLim bytes of being empty.
      dcbSerPort.fInX = FALSE;
      // Now choose the handshaking mode...
      if ((handshake[0] == 'r') || (handshake[0] == 'R'))
      {
        // the CTS (clear-to-send) signal is monitored for output flow control.
        // if this member is TRUE and CTS is turned off,
        // output is suspended until CTS is sent again
        dcbSerPort.fOutxCtsFlow = TRUE;
        // RTS (request-to-send) flow control. Enables RTS handshaking.
        dcbSerPort.fRtsControl = RTS_CONTROL_HANDSHAKE;
      }
      else
      {
        dcbSerPort.fOutxCtsFlow = FALSE;
        // enables the RTS line when the device is opened and leaves it on.
        dcbSerPort.fRtsControl = RTS_CONTROL_ENABLE;
      }
      // if this member is TRUE, null bytes are discarded when received.
      dcbSerPort.fNull = FALSE;
      // if this member is TRUE, the driver terminates
      // all read and write operations with an error status if an error occurs.
      dcbSerPort.fAbortOnError = FALSE;
      dcbSerPort.ByteSize = 8;                          // data size, xmit, and rcv
      dcbSerPort.Parity = NOPARITY;                     // no parity bit
      dcbSerPort.StopBits = ONESTOPBIT;                 // one stop bit
      // The SetCommState function configures a communications device according
      // to the specifications in a device-control block (DCB)
      iSerOK = SetCommState(hSerPort,&dcbSerPort);
      if (!iSerOK) SerCrash("Bad parameters for port",portname);
      //
      // Disable Windows' timeouts; we keep track of our own
      //
      
      COMMTIMEOUTS t = {MAXDWORD,0,0,0,0};
      SetCommTimeouts(hSerPort,&t);
    }
    
    //---------------------------------------------------------------------------
    
    void SerClose()
    // Closes the serial port.
    {
      iSerOK = CloseHandle(hSerPort);
      if (!iSerOK) SerCrash("Problem closing serial port","");
    }
    
    //---------------------------------------------------------------------------
    
    void SerPut(char* data)
    // Transmits a line followed by CR and LF.
    // Caution!  Will wait forever, without registering an error,
    // if handshaking signals tell it not to transmit.
    {
      DWORD nBytes;
      iSerOK  = WriteFile(hSerPort,data,strlen(data),&nBytes,NULL);
      iSerOK &= WriteFile(hSerPort,"\r\n",2,&nBytes,NULL);
      if (!iSerOK) SerCrash("Problem writing to serial port","");
    }
    
    //---------------------------------------------------------------------------
    
    void SerGetChar(char* c, int* success)
    // Receives a character from the serial port,
    // or times out after 10 seconds.
    // success = 0 if timeout, 1 if successful
    {
      time_t finish;
      finish = time(NULL) + 10;
      *success = 0;
      DWORD nBytes = 0;
      while ((*success == 0) && (time(NULL) < finish)) {
        ReadFile(hSerPort,c,1,&nBytes,NULL);
        *success = nBytes;
      }
      if (*success == 0)
        SerCrash("Timed out waiting for serial input","");
    }
    
    //---------------------------------------------------------------------------
    
    void SerGet(char* buf, int bufsize)
    // Inputs a line from the serial port, stopping at
    // end of line, carriage return, timeout, or buffer full.
    {
      int bufpos = 0;
      buf[bufpos] = 0;    // initialize empty string
      int bufposmax = bufsize-1;  // maximum subscript
      char c = 0;
      int success = 0;
      //
      // Eat any Return or Line Feed characters
      // left over from end of previous line
      //
      do { SerGetChar(&c,&success); }
      while ((success == 1) && (c <= 31));
      //
      // We have now read the first character or timed out.
      // Read characters until any termination condition is met.
      //
      
    while (1) {
        if (success == 0) return;         // timeout
        if (c == 13) return;              // carriage return
        if (c == 10) return;              // line feed
        if (bufpos >= bufposmax) return;  // buffer full
        buf[bufpos] = c;
        bufpos++;
        buf[bufpos] = 0;           // guarantee validly terminated string
        SerGetChar(&c,&success);
      }
    }
    
    //---------------------------------------------------------------------------
    
    void SerGetNum(double* x)
    // Reads a floating-point number from the serial port.
    {
       char buf[20];
       SerGet(buf,sizeof(buf));
       iSerOK = sscanf(buf,"%lf",x);   // "%lf" = "long float" = double
       if (iSerOK < 1) {
         SerCrash("Problem converting string to number",buf);
         *x = 0.0;
       }
    }
    
    //---------------------------------------------------------------------------
    
    int main(int argc, char *argv[])
    {
     char b[20];
     double x;
     double y;
     double d;
     double k;
     int c = 0;
    
     SerOpen("COM4","DTR");        // note DTR handshaking
     cout << "#### AGILENT 34401A MULTIMETER ####\n";
     if (iSerOK){
         cout << "\nStatus = Connected on COM4 \n";
         cout << "\nEnter difference value d(Volt): ";
         cin >> d;
             if (d == -0.135)
                 cout << "\nWe are using plate... \n";
             else
                 cout << "\nWe are using platform... \n";}
     else {
             cout << "\nDisconnected, the application will be closed! \n";
             SerClose();
             return 0;
          }
     for( ; ; ){
       SerPut("SYST:REM");
       SerPut("*RST");
       SerPut("*CLS");
       SerPut("DISP:TEXT 'OK'");
       SerPut("*RST");
       SerPut("MEAS:VOLT:DC?");
       SerGetNum(&x);
       k = (x-d);
       y = (k * 10.193679918);
       if (y < 0)
           y = (y*(-1));
       else
           y = y;
       cout << "\n - Voltage (as number) = " << x << " Volt\n";
       SerPut("MEAS:VOLT:DC?");
       SerGet(b,sizeof(b));
       cout << "\n - Voltage (as string) = " << b << "\n";
       cout << "\n - Weight (Kg) = " << y << "\n";
       cout << "Press Enter to read or F1 to exit the program \n";
       c = getch();
       if(c == F1){
          cout << "Stop reading...\n";
          break; }
               }
     return 0;
    }
    Avrei la necessità di introdurre una funzione che mi crei un file di testo nel quale ci sia il log delle misurazioni fatte. In pratica un file nel quale vi siano i valori di x, b, y magari con la rispettiva data ed il rispettivo orario. Non essendo un abile programmatore mi chiedevo se qualcuno potesse darmi una mano, mi aiutereste non poco.


    Vi ringrazio per la disponibilità!!!

  2. #2
    Ciao,

    di seguito puoi trovare una funzione di spunto....

    codice:
    #include <iostream>
    #include <cstdlib>
    #include <fstream>
    
    using namespace std;
    
    int Log_Function(double* a, double* b, double* c)
    {
       //Creazione file
       ofstream outFile("Dati.log", ios::out);
    
       //Controllo sfruttando l'overloading dell'operatore
       if(!outFile)
       {
          cerr << "File could not be opened" << endl;
          exit(1);
       }
    
       //Scrive nel file
       outFile << *a << ' ' << *b << ' ' << *c << '\n';
    
       return 0;
    }
    
    int main(int argc, char *argv[])
    {
       //Dichiarazioni
       int Val_Ctrl;
       double x=1.23, y=3.67, z=9.54;
       
       //Richiama funzione
       Val_Ctrl = Log_Function(&x,&y,&z);
       
       //Controlla esito della funzione
       Val_Ctrl != 0 ? cout << "Error at Log_Function()\n" : cout << "All it's OK!\n";
    
       return 0;
    }
    Sorry, se non ho fatto di più! Ma capirai, sono le 2.16 del mattino e sono un pò stanco.

    Tauu
    Gnix
    http://www.ptrace.net

  3. #3
    Ti ringrazio moltissimo per la tua disponibilità il codice funziona

    Una sola curiosità (al momento non sono in facoltà per verificarlo), i miei x, y, z cambiano ad ogni pressione del tasto Enter. Con questo codice riesco ad avere il log completo o solo l'ultima lettura?


    Grazie ancora moltissimo per l'aiuto

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.