Write exampleΒΆ

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

int write_data(int driver_handle, int object_id, int port,
                unsigned long data)
  { /* writes 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_WRITE;/* the command is a WRITE */
    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 */

    /* now copy the data to the data-area of the request-structure, which
       is vreq.message.data and is an array of 8 bytes. In this example,
       however, only 4 bytes are written to the object. */
    memcpy(vreq.message.data, &(data), 4);

    write(driver_handle, (char *)(&vreq), sizeof(vreq));

    if (vreq.message.stat != VCAN_OK)
      /* a STATUS was returned, e.g. VCAN_TX_ERR (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_ACCESS_ERR,
           in this example we return always -1 when the status is not
           VCAN_OK */
        return(-1);
      };
    return(0);
  }