Read exampleΒΆ

The following example shows how data can be read from a CAN object. The driver should already having been opened and the CAN object should have been defined as a read-object:

unsigned long read_data(int driver_handle, int object_id, int port)
  { /* reads 4 bytes from the CAN object with the id <object_id> */
    vcan_request     vreq; /* a variable of this type is needed for
                              read- and write commands */

    vreq.tag             = VCAN_READ;/* the command is a READ */
    vreq.message.id      = object_id;/* the CAN object-id */
    vreq.message.datasize= 4;        /* an "unsigned long" has 4 bytes,
                                        "sizeof(unsigned long)" could
                                        (in this example) also be used */
    vreq.message.port    = port;     /* No. of the CAN port that is used */
    read(driver_handle, (char *)(&vreq), sizeof(vreq));
    if (vreq.message.stat != VCAN_OK)
      /* a STATUS was returned, e.g. VCAN_TM_OUT (timeout) */
      { if (vreq.message.stat==VCAN_TX_ERR)
          { printf("an error occured, error-code: %d",
                   vreq.message.errcode);
            return(-1);
          };
        /* there can be other status-values e.g.  VCAN_INCONSISTENT,
           in this example we return always when the status is not
           VCAN_OK */
        return(-1);
      };
    /* The data from the CAN bus is now in the data-array,
       vreq.message.data. This is defined as an array of 8 bytes. In this
       example, the data is returned without a second copying into a local
       variable, just by a typecast */
    return( *( (unsigned long *)(vreq.message.data) ) );
  }