Linux系统getopt使用示例

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <stdint.h>
 5 
 6 void usage()
 7 {
 8     fprintf(stderr,
 9             "\nUsage:  mcu_dload [OPTIONS] *.bin\n"
10             "  -a  Specify device I2C slave address(7Bit), eg: -a 5E, default is 0x58\n"
11             "  -d  Download binary code for MCU only\n"
12             "  -h  This Page.\n\n"
13     );
14     exit(0);
15 }
16 
17 uint8_t asc2hex(char asccode)
18 {
19     uint8_t ret;
20     if('0' <= asccode && asccode <= '9')
21         ret = asccode - '0';
22     else if('a' <= asccode && asccode <= 'f')
23         ret = asccode -'a' + 10;
24     else if('A' <= asccode && asccode <= 'F')
25         ret = asccode - 'A' + 10;
26     else ret = 0;
27     return ret;
28 }
29 
30 int main(int argc, char **argv)
31 {
32     int opt;
33     uint32_t i = 0;
34     uint8_t i2c_adr = 0x58, i2c_reg;
35     FILE *fp;
36     
37     // Parse Command Line Options
38     while((opt = getopt(argc, argv, "a:h?")) != EOF) {
39         switch(opt) {
40             case 'a':
41                 i2c_adr = (asc2hex(optarg[0]) << 4) | asc2hex(optarg[1]);
42                 printf("I2C Device Address(7Bit) is 0x%2X.\n", i2c_adr);
43                 break;
44             case 'h':
45             case '?':
46             default:
47                 usage();
48                 break;
49         }
50     }
51 
52     // Last One is the input file
53     if(optind + 1 != argc) {
54         printf("Input file not found!\n");
55         usage();
56         exit(0);
57     }
58 
59     // Open *.bin file and download it to MCU
60     fp = fopen(argv[optind], "r");
61     if(fp == NULL) {
62         printf("Input file can not open!\n");
63         usage();
64         exit(0);
65     }
66     
67     // Get file size
68     fseek(fp, 0L, SEEK_SET);
69     fseek(fp, 0L, SEEK_END);
70     uint32_t binsize = ftell(fp);
71     printf("Inpuf file size is %d Bytes.\n", binsize);
72 
73     uint8_t *bincode = (uint8_t *)malloc(binsize);
74     fseek(fp, 0L, SEEK_SET);
75     fread(bincode, 1L, binsize, fp);
76     fclose(fp);
77     
78     // Download
79     printf("Reset MCU ...\n");
80     printf("Dowloading bin ...\n");
81 
82     uint32_t dpos = binsize >> 6;
83     for(i = 0; i < binsize; ++i) {
84         if(i % dpos == 0) printf("#");
85         usleep(5000);
86         //CH341WriteI2C(0, i2c_adr, i2c_reg, bincode[i]);
87         fflush(stdout);
88     }
89     printf("\nFile download succeed, %d Bytes transfered!\n", binsize);
90 
91     free(bincode);
92     return 0;
93 }

 

转载于:https://www.cnblogs.com/lyuyangly/p/8146453.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值