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 " Usage: mcu_dload [OPTIONS] *.bin " 10 " -a Specify device I2C slave address(7Bit), eg: -a 5E, default is 0x58 " 11 " -d Download binary code for MCU only " 12 " -h This Page. " 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. ", 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! "); 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! "); 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. ", 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 ... "); 80 printf("Dowloading bin ... "); 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(" File download succeed, %d Bytes transfered! ", binsize); 90 91 free(bincode); 92 return 0; 93 }