⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 special.c

📁 在linux操作系统下CAN收发程序的示例源代码。
💻 C
字号:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <asm/errno.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "can.h"

extern int errno;

int main(void)
{
  struct canmsg_t sendmsg={0,0,5,0,8,{1,2,3,4,5,6,7,8}};
  struct canmsg_t readmsg = { 0,0,5,0,0,{0,} };
  int fd, n, rv, i;
  
  if ( ( fd = open("/dev/can0", O_RDWR | O_NONBLOCK ) ) < 0 )  {
    perror("open");
    printf("Error opening /dev/can0\n");
    exit(1);
  }

  while (1) {

    // * * * W R I T E * * *
    readmsg.flags=0;
    readmsg.cob=0;
    readmsg.timestamp=0;
    
    if ( 0 > ( rv = read( fd, &readmsg, sizeof( struct canmsg_t ) ) ) )  {
      if ( EAGAIN != errno ) {
	perror("read");
      }
    }
    else {
      fprintf( stdout, "Received message: id=%lX dlc=%u", readmsg.id, readmsg.length );
      for( n=0; n < readmsg.length ; n++ )
	fprintf( stdout, " %.2X", ( unsigned char ) readmsg.data[ n ] );
      fprintf( stdout, "\n");
    }

    sleep( 1 );

    // * * * R E A D * * *
    sendmsg.data[0] = i;
    sendmsg.data[1] = ( ( 22 + i ) & 0xff );
    sendmsg.length = 8;
    if ( ( rv = write( fd, &sendmsg, sizeof(struct canmsg_t ) ) ) < 0) {
      perror("write");
      printf("Error sending message rv = %d\n", rv );
    }
    else {
      printf("Sent message %d\n", i++); 
    }
  }
  close( fd );
  return 0;
}

	






⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -