#include #include #include #include #include #include #include //シリアルデバイス #define DEVICE "/dev/ttyACM0" //#define DEVICE "/dev/ttyACM1" #define BAUDRATE B38400 //MemCARDuinoコマンド #define GETID 0xA0 //MemCARDuinのID取得 #define GETVER 0xA1 //MemCARDuinのバージョン取得 #define MCREAD 0xA2 //メモリカード読み出し #define MCWRITE 0xA3 //メモリカード書き込み #define BUFFERSIZE 131072 unsigned char buff[BUFFERSIZE]; unsigned char msb, lsb; char *mcfile = NULL; struct termios oldtio, newtio; int fd; FILE *file; unsigned char sum, dat, chk; int err = 0; //メモリカード読み出し void ReadMemorycard() { file = fopen(mcfile, "wb"); if(file == NULL) { printf("%s open error.\n", mcfile); return; } fd = open(DEVICE, O_RDWR|O_NONBLOCK); if(fd < 0) { printf("Serial device open error.\n"); fclose(file); return; } ioctl(fd, TCGETS, &oldtio); newtio = oldtio; newtio.c_cflag = BAUDRATE | CS8; ioctl(fd, TCSETS, &newtio); //アドレス0〜3ff読み出し for(int f=0; f<0x400; f++) { msb = (f & 0xff00) >> 8; lsb = (f & 0x00ff); buff[0] = MCREAD; buff[1] = msb; buff[2] = lsb; write(fd, buff, 3); usleep(100000); read(fd, buff, 130); sum = 0; printf("Address %02X\n", f); for(int j=0; j<8; j++) { for(int i=0; i<16; i++) { dat = buff[j*16 + i]; printf("%02X ", dat); sum ^= dat; } printf("\n"); } fwrite(buff, sizeof(unsigned char), 128, file); //ステータス0x47"G"...Good 0x4E"N"...NG 0xFF...BadSector printf("\nCheck sum:%02X Status:%c\n",buff[128], buff[129]); //チェックサム確認 chk = msb ^ lsb ^ sum; if(buff[128] != chk) { ++err; printf("Checksum error !!\n"); } printf("\n"); } ioctl(fd, TCSETS, &oldtio); close(fd); fclose(file); printf("Total error= %d\n", err); } //メモリカード書き込み void WriteMemorycard() { unsigned char *p; file = fopen(mcfile, "rb"); if(file == NULL) { printf("%s open error.\n", mcfile); return; } //書き込みデータを一括読み込み fread(buff, sizeof(unsigned char), BUFFERSIZE, file); fclose(file); fd = open(DEVICE, O_RDWR|O_NONBLOCK); if(fd < 0) { printf("Serial device open error.\n"); return; } ioctl(fd, TCGETS, &oldtio); newtio = oldtio; newtio.c_cflag = BAUDRATE | CS8; ioctl(fd, TCSETS, &newtio); //アドレス0〜3ff書き込み for(int f=0; f<0x400; f++) { printf("Address %02X ", f); msb = (f & 0xff00) >> 8; lsb = (f & 0x00ff); dat = MCWRITE; write(fd, &dat, 1); dat = msb; write(fd, &dat, 1); dat = lsb; write(fd, &dat, 1); p = &buff[f * 128]; write(fd, p, 128); //チェックサム確認 sum = 0; for(int i=0; i<128; i++) { sum ^= *(p++); } chk = msb ^ lsb ^ sum; write(fd, &chk, 1); printf("Check sum:%02X ", chk); usleep(50000); if(read(fd, &dat, 1) == -1) printf("Serial read error!\n"); else //ステータス0x47"G"...Good 0x4E"N"...NG 0xFF...BadSector printf("Status:%c\n", dat); if(dat != 0x47) { ++err; printf("Checksum error !!\n"); } } ioctl(fd, TCSETS, &oldtio); close(fd); printf("Total error = %d\n", err); } void message() { printf("\nUsage:\n\n"); printf(" memcard -i \n"); printf(" or\n"); printf(" memcard -o \n\n"); } void main(int argc, char *argv[]) { char *p; int isRead = -1; if(argc != 3) { message(); return; } for(int i=0; i