PICWrite

//PICWrite PIC18F2550へのファーム書き込みツール
// CODEとCONFIGのみ対応。アドレスが0x300000以上ならCONFIGと判断。
// 書込み時はwコマンドの後、IntelHEXを送る。

// 端子設定
#define PGC 8
#define PGD 9

// wait time talbe ( 1uS以下は1uSに揃える)*/
#define P1 1
#define P2 1
#define P3 1
#define P4 1
#define P5 1
#define P6 1
#define P7 1
#define P8 1
#define P9 1000
#define P10 100
#define P11 5000
#define P12 2
#define P13 1
#define P14 1
#define P15 2
#define P16 1
#define P17 1
#define P18 1

// Memory block code
#define CODETYPE 0
#define EEPROMTYPE 1
#define IDTYPE 2
#define CONFIGTYPE 3

// String sを数値(long)に変換する。
// 先頭が0xで始まるならHEX.数字で始まるならDEC
long s2l(String s) {
  int i;
  String h="0x";
  int hexf=0;
  long val=0;
  byte buf[16];
  
  // 先頭が0xで始まるならhexfを1にセットする。
  if ( 0 == h.compareTo(s.substring(0,2)) ) { hexf=1; }

  s.toLowerCase(); // 小文字に統一
  s.getBytes(buf,15); // ここからは文字列配列で処理
  
  for (i=hexf? 2:0; i> 1;
    digitalWrite( PGC , HIGH );
    delayMicroseconds(P2);
    digitalWrite( PGC , LOW );
    delayMicroseconds(P2);
  }
}

// sendexec
void sendexec() {
  int i;
  digitalWrite( PGD , LOW);
  for ( i=0; i<3; i++ ) {
    digitalWrite( PGC , HIGH );
    delayMicroseconds(P2);
    digitalWrite( PGC , LOW );
    delayMicroseconds(P2);
  }
  digitalWrite( PGC , HIGH );
  delayMicroseconds(P9);
  digitalWrite( PGC , LOW );
  delayMicroseconds(P16);
  
  for ( i=0; i<16; i++ ) {
    digitalWrite( PGC , HIGH );
    delayMicroseconds(P2);
    digitalWrite( PGC , LOW );
    delayMicroseconds(P2);
  }
}

// countで指定したビット数のデータをPICから読み出す。
int getbit(int count) {
  int val=0;
  int i;
  for ( i = 0; i < count; i++ ) {
    //val=val<<1;
    digitalWrite( PGC , HIGH );
    delayMicroseconds(P2);
    digitalWrite( PGC , LOW );
    //val+= (HIGH==(digitalRead(PGD)?1:0 << (count-1-i)) );
    if (digitalRead(PGD)==HIGH) {
      val+= 1< : read from PIC ");
  Serial.println(" e : all erase  ");
  Serial.println(" w : write to PIC ");
  Serial.println(" v : verify");

  //コマンド読み込み
  command="";
  while(1){
    while( Serial.available() == 0 ) {}
    c = Serial.read();
    tmps[0]=c;
    Serial.print(tmps);//SENDBACK
    if(c==0x0d || c==0x0a) {
      break;
    } else {
      command.concat(tmps);
    }
  }
  Serial.println();
  // コマンドラインをフィールドに分ける。ccはフィールド数。
  cc=commandLine(command,commandArray);

  // コマンド毎の処理
  switch (commandArray[0][0] ) {
    
  case 'r':
    if(cc!=3) break;
    val1=s2l(commandArray[1]);
    val2=s2l(commandArray[2]);
    read(val1, val2);
    break;

  case 'e':
    Serial.println();
    Serial.println("ALL Erase ?");
    while( Serial.available() == 0 ) {}
    c=Serial.read();
    if('y' != c) {break;}
    Serial.println();
    Serial.println("ALL Erase START!!"); 
    bulkerase();
    break;
    
  case 'w':
    write();
    break;

  case 'v':
    verify();
    break;
    
  default:
    break;
  }


}