Skip to content

Host I/O Updates to the AVR

February 16, 2017

Over the last week or so i’ve made a bunch of changes to the AVR code to do with host I/O basically to support the xmodem bootloader but more generally to allow bidirectional serial data.

The external changes are:

  • the AVR program can be put in quiet mode by entering ‘p’ quickly after startup, entering ‘q’.  Quiet mode eliminates the run1802 message and shortens the startup delay to 1 second
  • the AVR recognizes STX in the input stream from the 1802 and enables interrupts so host serial data can be handled properly.  ETX disables interrupts so that SPI doesn’t get screwed up.
  • The AVR recognizes 0x12 in the input stream as a request to read serial.available().  The AVR puts the value into the input shift register so the 1802 can read it with an INP(6);
  • The AVR recognizes 0x00 as a request to read a character from the serial buffer
  • The AVR recognizes 0x1B as an escape so that following character is passed on without interpretation.

Additionally, there are a couple of housekeeping changes related to moving to arduino 1.6.5: char1802 is defined unsigned char and output with _BYTE; a #define of MISO was removed because it’s in the standard defines.

ALSO, I increased the size of the input serial buffer from 64 to 256 bytes.  I did that by editing
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\HardwareSerial.h and replacing the 64 with 256.

This will get lost when i upgrade the arduino but there doesn’t seem to be a better option for the moment.

//now needs to be compiled with 1.6.5 and the minicore addon.
//ISPV6 meant for use with olduino_2.0_V4E/V8 hardware AND NEW AVRDUDE
//this sketch turns the Arduino into a loader for the 1802 membership card
//adapted from the arduinoisp sketch included with arduino-022 
//with credit to David Mellis and Randall Bohen
//July 12 2012 - revamped from aduinoisp1802v8
//mostly pin changes to start
//August 1 - dinking around expanding ? code trying to debug verification failure
//aug 9 changing ! to ~ in interface() ddr settings
//aug 10/11 changed run code to make memrd output and low.
//saved back to olduinoispv2_2
//Aug 16 trying shorter timeout delay (1 sec)
//August 18 trying 57600 baud
//Jan 15, 2014 first build for Olduino V@.0 - all serial/spi
//Jan 26, fixing spi clocking logic in justclock
//Mar 10, 2014 speeding up busout/busin for program loading
//April 3, 2014 moving clock pins to PORTC SCK=PC1, /SCK=PC0, circuit olduino_2.0_v2b.sch
//May 25, 2014 pin definitions changed to match olduino_2.0_v4e schematic
//ldsw,clrsw,datapin=mosi,spiclk,/srclk,srclk,clockbvs
//June 12 speeding up clocking and tightening up timing - 1st try @20mhz
//Aug 10 - increasing presstimeu to 20 us
//aug 10 -presstimeu 
//15-01-13 avrdude is requesting version with a 5630 sequence instead of 75'
//17-01-23 experimenting with sending data from host to 1802 program
//         also had to change MISO to MISOX to avoid compile error
//??-??-?? changed char1802 in run1802 to unsigned char cout <<_BYTE(...
//17-02-06 verbose/quites runmode controls run1802 msg
//17-02-14 stx/etx trigger enable/disable interrupts
#define INsw 5 // IN bus pin 27 - normally high
#define presstimeu 20 //us to hold input switch down
#define LDsw 8 // /LOAD(/WAIT) bus pin 29 - arduino PB0 14
#define CLRsw 7 // /CLEAR bus pin 28 - ard pd7 13
#define MEMrd  0 //not connected
//all comm to 1802 is serial.  datapin is connected to the output of MOSR
//MISOX is connected to the input of the 1802's MISR
//sr_sck loads a bit into MISR 
//spi_sck tells other devices to grab top bit of MOSR
//notsr_sck advances MOSR and clocks the data in MISR To the storage register
#define datapin 9 //pin to receive shift register data
#define MISOX 12   //output pin hooked to 1802's input shift register
#define MISOPORT PORTB
#define MISODDR DDRB
#define MISOBIT 4  //miso is on port B bit 4
#define sr_sck 15 //pin to clock the data in the shift registers
#define notsr_sck 16 //inverse of sr_sck
#define spi_sck 14 //clock seen at the spi connector.
#define clockport PORTC
#define clockddr DDRC
#define clockbv 3  //both clocks high
#define notclockbv 4 //clocks low, notclock high
#define N0pin 2    //N0 is the 1802 signalling to do host output
#define OUT2pin 6  //signals the 1802 is writing to MOSR
#include <Streaming.h>
#define cout Serial
#define endl '\n'

#define HWVER 2
#define SWMAJ 5
#define SWMIN 0

// STK Definitions
#define STK_OK 0x10
#define STK_FAILED 0x11
#define STK_UNKNOWN 0x12
#define STK_INSYNC 0x14
#define STK_NOSYNC 0x15
#define CRC_EOP 0x20 //ok it is a space...

unsigned long timeoutstart, timeoutinterval=2000; //used to timeout the loader and start the olduino
byte state1802=0;
#define running 1
#define reset 2
#define loading 3
//char runmode; //setting this to 'v' means verbose
char runmode __attribute__ ((section (".noinit")));

void setup() {
  Serial.begin(57600);
  //delay(2000);
  //cout<<"OlduinoII_ISPV6.1 here with runmode="<<runmode<<'\n';
  DDRB=0; //all B pins are inputs (PB5 will have been left as an output by the bootloader)
  digitalWrite(sr_sck,LOW); digitalWrite(spi_sck,LOW);digitalWrite(notsr_sck,HIGH);
  pinMode(sr_sck,OUTPUT); pinMode(notsr_sck,OUTPUT);pinMode(spi_sck,OUTPUT);//set up to drive the shift register
 //doitall(); 
   //while(1); //loop
  timeoutstart=millis(); //if we don't get anything within timeouttime ms we start the 1802 running
  reset1802();

  //while(1){
  //  justclock();
  //}
}
int error=0;
int pmode=0;
int here; // address for reading and writing, set by 'U' command
uint8_t buff[256]; // global block storage

#define beget16(addr) (*addr * 256 + *(addr+1) )
typedef struct param {
  uint8_t devicecode;
  uint8_t revision;
  uint8_t progtype;
  uint8_t parmode;
  uint8_t polling;
  uint8_t selftimed;
  uint8_t lockbytes;
  uint8_t fusebytes;
  int flashpoll;
  int eeprompoll;
  int pagesize;
  int eepromsize;
  int flashsize;
} 
parameter;

parameter param;  

void loop(void) {
  uint8_t char1802=0x55;
  if (Serial.available()) {
    avrisp();
    timeoutstart=millis();
  }
  if(millis() - timeoutstart > timeoutinterval){
      run1802(); //run - does not return.
  }
}

uint8_t getch() {
  while(!Serial.available());
  return Serial.read();
}
void readbytes(int n) {
  for (int x = 0; x < n; x++) {
    buff[x] = getch(); //was Serial.read();
  }
}


void empty_reply() {
  char gc=getch();
  if (CRC_EOP == gc) {
    Serial.print((char)STK_INSYNC);
    Serial.print((char)STK_OK);
  } 
  else {
    Serial.print((char)STK_NOSYNC);
  }
}

void breply(uint8_t b) {
  if (CRC_EOP == getch()) {
    Serial.print((char)STK_INSYNC);
    Serial.print((char)b);
    Serial.print((char)STK_OK);
  } 
  else {
    Serial.print((char)STK_NOSYNC);
  }
}

void get_version(uint8_t c) {
  switch(c) {
  case 0x80:
    breply(HWVER);
    break;
  case 0x81:
    breply(SWMAJ);
    break;
  case 0x82:
    breply(SWMIN);
    break;
  case 0x93:
    breply('S'); // serial programmer
    break;
  default:
    breply(0);
  }
}

void set_parameters() {
  // call this after reading paramter packet into buff[]
  param.devicecode = buff[0];
  param.revision = buff[1];
  param.progtype = buff[2];
  param.parmode = buff[3];
  param.polling = buff[4];
  param.selftimed = buff[5];
  param.lockbytes = buff[6];
  param.fusebytes = buff[7];
  param.flashpoll = buff[8]; 
  // ignore buff[9] (= buff[8])
  //getch(); // discard second value
  
  // WARNING: not sure about the byte order of the following
  // following are 16 bits (big endian)
  param.eeprompoll = beget16(&buff[10]);
  param.pagesize = beget16(&buff[12]);
  param.eepromsize = beget16(&buff[14]);

  // 32 bits flashsize (big endian)
  param.flashsize = buff[16] * 0x01000000
    + buff[17] * 0x00010000
    + buff[18] * 0x00000100
    + buff[19];

}

void start_pmode() {
  start_pmode_1802();
  //cout<<"entering program mode";
  pmode = 1;
}

void end_pmode() {
  end_pmode_1802();
  //cout<<"leaving program mode";
  pmode = 0;
}


uint8_t write_flash(int length) {
  write_flash_1802(length);
  return STK_OK;
}

void program_page() {
  char result = (char) STK_FAILED;
  int length = 256 * getch() + getch(); //gets length 1-256
  if (length > 256) {
      Serial.print((char) STK_FAILED);
      return;
  }
  char memtype = getch();
  for (int x = 0; x < length; x++) {
    buff[x] = getch();
  }
  if (CRC_EOP == getch()) {
    Serial.print((char) STK_INSYNC);
    if (memtype == 'F') result = (char)write_flash(length);
    Serial.print(result);
  } 
  else {
    Serial.print((char) STK_NOSYNC);
  }
}

void read_signature() {
  if (CRC_EOP != getch()) {
    Serial.print((char) STK_NOSYNC);
    return;
  }
  Serial.print((char) STK_INSYNC);
  #define sig_high 0x1e //dummy (code for part ATMEGA644P
  #define sig_middle 0x96 //device
  #define sig_low 0x0A //signature
  Serial.print((char) sig_high);
  Serial.print((char) sig_middle);
  Serial.print((char) sig_low);
  Serial.print((char) STK_OK);
}
void universal() {//15-01-13 this is being used to retrieve the signature
  int w;
  uint8_t ch;

  for (w = 0; w < 4; w++) { //take the data
    buff[w] = getch();
  }
  if ((buff[0]==0x30)  && (buff[2]==0x00)){
    breply(sig_high);
  }
  else if ((buff[0]==0x30)  && (buff[2]==0x01)){
     breply(sig_middle);
  }
  else if ((buff[0]==0x30)  && (buff[2]==0x02)){
    breply(sig_low);
  }
  else{
    breply(STK_FAILED); //see if this gets a rise out of avrdude
  }
}
//////////////////////////////////////////
//////////////////////////////////////////



void read_page() {
  char result = (char)STK_FAILED;
  int length = 256 * getch() + getch();
  char memtype = getch();
  //cout<<"reading "<<length<<" bytes of "<<memtype<<" ";
  if (CRC_EOP != getch()) {
    Serial.print((char) STK_NOSYNC);
    return;
  }
  Serial.print((char) STK_INSYNC);
  if (memtype == 'F') result = read_page_1802(length);
  Serial.print(result);
  return;
}

////////////////////////////////////
////////////////////////////////////


I always want the last word so that wordpress doesn’t eat my code!

int avrisp() { 
  uint8_t data, low, high, gc;
  uint8_t ch =getch();    //cout<<"<"<<_HEX(ch)<<" ";
  switch (ch) {
  case '?': //debug
    doitall();
    break;
  case 'v': //verbose mode
    runmode='v';
    break;
  case 'q': //quiet mode
    runmode='q';
    cout<<"going silent\n";
    break;
  case '!': //run
    cout<<"!=runq\n";
    runmode='q';
    run1802();
    break;
  case '0': // signon
    empty_reply();
    break;
  case '1':
    gc=getch(); //cout<<":"<<_HEX(gc)<<" ";
    if (gc == CRC_EOP) {
      Serial.print((char) STK_INSYNC);
      Serial.print("AVR ISP");
      Serial.print((char) STK_OK);
    }
    break;
  case 'A':
    gc=getch(); //cout<<":"<<_HEX(gc)<<" ";
    get_version(gc);
    break;
  case 'B':
    readbytes(20);
    set_parameters();
    empty_reply();
    break;
  case 'E': // extended parameters - ignore for now
    readbytes(5);
    empty_reply();
    break;

  case 'P':
    start_pmode();
    empty_reply();
    break;
  case 'U':
    here = getch() + 256 * getch();
    sethere_1802();
    //cout<<"here="<<_HEX(here);
    empty_reply();
    break;

  case 0x60: //STK_PROG_FLASH
    low = getch();
    high = getch();
    empty_reply();
    break;
  case 0x61: //STK_PROG_DATA
    data = getch();
    empty_reply();
    break;

  case 0x64: //STK_PROG_PAGE
    program_page();
    break;
    
  case 0x74: //STK_READ_PAGE
    read_page();    
    break;

  case 'V':
    universal();
    break;
  case 'Q':
    error=0;
    end_pmode();
    empty_reply();
    //run1802();
    break;
    
  case 0x75: //STK_READ_SIGN
    read_signature();
    break;

  // expecting a command, not CRC_EOP
  // this is how we can get back in sync
  case CRC_EOP:
    Serial.print((char) STK_NOSYNC);
    break;
    
  // anything else we will return STK_UNKNOWN
  default:
    if (CRC_EOP == getch()) 
      Serial.print((char)STK_UNKNOWN);
    else
      Serial.print((char)STK_NOSYNC);
  }
}

I always want the last word so that wordpress doesn’t eat my code!
 

#define sbi(sfr,bit) (_SFR_BYTE(sfr) |= _BV(bit))
#define cbi(sfr,bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
void busout(uint8_t t){ //put a byte on the bus
  sbi(MISODDR,MISOBIT);
  for (int i=0;i<8;i++){
      if(MISOX, t&0x80){
        sbi(MISOPORT,MISOBIT);
      }else{
        cbi(MISOPORT,MISOBIT);
      }
      clockport=clockbv;//clock up, notclock down
      asm("  nop\n");
      clockport=notclockbv;//clock down, notclock up
      t<<=1;
  }
  cbi(MISODDR,MISOBIT);
}
uint8_t busin(){ //read a byte from the 1802
  uint8_t buschar;
//bit 7 of the byte is already in position to be read, the others have to be clocked in
  buschar=0; //clear the character
  for (uint8_t i = 0; i < 8; ++i) {  //get the 8 bits in sequence
	buschar = (buschar<<1)|digitalRead(datapin); //read bits 0-7 in sequence ad set them in the byte
      clockport=clockbv;//clock up, notclock down
      asm("  nop\n");
      clockport=notclockbv;//clock down, notclock up
  }
  return buschar;
}
void justclock(){ //just run the spi clock
      clockport=clockbv;//clock up, notclock down
      clockport=notclockbv;//clock down, notclock up
      asm("nop\n");
      clockport=clockbv;//clock up, notclock down
      asm("nop\n");
      clockport=notclockbv;//clock down, notclock up
      asm("nop\n");
      clockport=clockbv;//clock up, notclock down
      asm("nop\n");
      clockport=notclockbv;//clock down, notclock up
      asm("nop\n");
      clockport=clockbv;//clock up, notclock down
      asm("nop\n");
      clockport=notclockbv;//clock down, notclock up
      asm("nop\n");
      clockport=clockbv;//clock up, notclock down
      asm("nop\n");
      clockport=notclockbv;//clock down, notclock up
      asm("nop\n");
      clockport=clockbv;//clock up, notclock down
      asm("nop\n");
      clockport=notclockbv;//clock down, notclock up
      asm("nop\n");
      clockport=clockbv;//clock up, notclock down
      asm("nop\n");
      clockport=notclockbv;//clock down, notclock up
      asm("nop\n");
      clockport=clockbv;//clock up, notclock down
      asm("nop\n");
      clockport=notclockbv;//clock down, notclock up
}
void run1802(){
  unsigned char char1802=21, pindsave,escmode=false; //char from 1802, captured PIND;
  if ('v'==runmode){
    cout<<" run1802.6.1("<<timeoutinterval<<")"<<"\n";
  }
  //Serial.end(); Serial.begin(9600);
  interface(INPUT); //release the pins(really just INsw)
  digitalWrite(CLRsw,LOW);   digitalWrite(LDsw,LOW);//ensure wait state
  delay(5);
  digitalWrite(LDsw,HIGH); //reset
  delay(5);
  pinMode(MEMrd,OUTPUT); digitalWrite(MEMrd,LOW); //AUG 10 -make sure 1802 can write
  digitalWrite(CLRsw,HIGH); //run
  state1802=running;
  cbi(TIMSK0,TOIE0);
  noInterrupts(); //default is no interrupts
  while(true){ //loop for 1802 program output
    while (PIND&0x40); //wait for SPI signal to go low
    pindsave=PIND; //grab the n0 line while it's valid
    while (0==(PIND&0x40)); //wait for trailing edge - signal goes high again
    if (pindsave&0x04){ //if it's for me  ** have to test this now
      char1802=busin(); //grab the character and clock the SPI bus
      if (escmode==1){//escaping this character
        cout<<_BYTE(char1802); //send it to the host
        escmode=0;
      }else{
        switch(char1802){
          case 0x12: //querying for avail characters
            busout(Serial.available());
            break;
          case 0: //wanting host characters
            busout(getch());
            break;
          case 0x1b: //escape next character
            escmode=1;
            break;
          case 0x02: // allow interrupts
            interrupts(); break;
          case 0x03: // disallow interrupts
            noInterrupts(); break;            
          default:
            cout<<_BYTE(char1802); //send it to the host
        }
      }
   } else{ //not for me, have to do this fast
      justclock(); //just clock the SPI bus
    }
  }
}
void domeall(){
 }
  
void doitall(){
  uint8_t c18;
  cout<<"doing it all\n";
  interface(OUTPUT);
   //start the write sequence
  reset1802();
  digitalWrite(LDsw,LOW);  //then go to load mode
 // busout(0xaa);
  //while(1);
  busout(0x7b);
  pressin();
  busout(0x7a);
  pressin();
  busout(0x7a);
  pressin();
  busout(0x7a);
  pressin();
  busout(0x7a);
  pressin();
  busout(0x30);
  pressin();
  busout(0x00);
  pressin();
  reset1802();
  run1802();
while(1);
}  
void sethere_1802(){
  if (here==0){ //if it wants to read from the beginning, fine
    reset1802();
    digitalWrite(LDsw,LOW);  //then go to load mode
  } //otherwise ignore it
}
void start_pmode_1802() {
  interface(OUTPUT); //set rquired pins to OUTPUT
  reset1802();
  digitalWrite(LDsw,LOW);  //then go to load mode
  //cout<<"entering program mode";
  pmode = 1;
}

void end_pmode_1802() {
  //cout<<"leaving program mode";
  pmode = 0;
}
void pressin(){
  digitalWrite(INsw,LOW); //toggle
  delayMicroseconds(presstimeu);
  digitalWrite(INsw,HIGH);
  delayMicroseconds(presstimeu);
}  
void reset1802(){
  pinMode(CLRsw,OUTPUT); pinMode(LDsw,OUTPUT);
  digitalWrite(CLRsw,LOW);   digitalWrite(LDsw,LOW);//reset
  digitalWrite(LDsw,HIGH); //1802
  state1802=reset;
}

void interface(uint8_t io){ //setting pins to INPUT or OUTPUT
 //really need to rethink this
  digitalWrite(MISOX,LOW);
  digitalWrite(INsw,HIGH);
  digitalWrite(spi_sck,LOW);digitalWrite(sr_sck,LOW);digitalWrite(notsr_sck,HIGH);
  digitalWrite(LDsw,LOW);digitalWrite(CLRsw,LOW);
  pinMode(MISOX,INPUT);//MISO is controlled by busout
  pinMode(spi_sck,OUTPUT);pinMode(sr_sck,OUTPUT);pinMode(notsr_sck,OUTPUT); //clocks are always output
  pinMode(CLRsw,OUTPUT);pinMode(LDsw,OUTPUT);  //ld & clr are always output
  pinMode(INsw,io);  //in controlled here
}



uint8_t read_byte_1802() {//first try
  digitalWrite(INsw,LOW);//push input button
  delayMicroseconds(presstimeu);
  digitalWrite(INsw,HIGH);
  delayMicroseconds(presstimeu);
  uint8_t buschar=busin();  
  return buschar;
}
char read_page_1802(int length) {//first try
  digitalWrite(MEMrd,HIGH); //make sure we're read only
  for (int x = 0; x < length; x+=1) {
    Serial.print((char) read_byte_1802());
  }
  return STK_OK;
}

uint8_t write_flash_1802(int length) {
  int x = 0;
  digitalWrite(MEMrd,LOW); //allow memory write
  while (x < length) {
    write_byte_1802(buff[x++]); //we can only write bytes sequentially from address 0
  }
  digitalWrite(MEMrd,HIGH); //make sure we're read only
  return STK_OK;
}

void write_byte_1802(char data){ //write a byte to the 1802
  busout(data); //put it on the data bus
  digitalWrite(INsw,LOW);//push input button
  delayMicroseconds(presstimeu);
  digitalWrite(INsw,HIGH);
  delayMicroseconds(presstimeu);
}

I always want the last word so that wordpress doesn’t eat my code!

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: