Write and read back from RAM AS6C62256 for Arduino Mega


/*
* PORTL - 8 data  start PL0-7 (49-42)
* PORTA PA0-7 (22-29)  + PORTC PC0-7 (37-30) - 16 address lines  
* port 29 and 30 broken 
*/

#define WE 7
#define OE 6

void setup() {
  byte data[16];
  int k=-1;
  int base;

  DDRD = 0xFF;  
  DDRA = B1111111; // all outputs
  DDRC = B1111111; // 0Xff
  PORTD = 0x00;
  PORTA = 0x00; // all low
  PORTC = 0x00; // all low
  //data line output for writing
  DDRL = 0xFF; // all output
  PORTL = 0x00;
  
  Serial.begin(57600);
  Serial.println("Start");

  pinMode(WE,OUTPUT);  //WE
  pinMode(OE,OUTPUT); // OE
  digitalWrite(WE, HIGH);  // WE=disabled
  digitalWrite(OE, HIGH);  // OE=disabled

  
  // write
  for (int i=0; i < 128; i++) {
    PORTA =i;
  for (int j=0; j< 256; j++) {
    PORTC = j;
    PORTD = PORTC & 0x80;
    PORTL = 0xAE;  
      digitalWrite(WE, LOW);
      delayMicroseconds(2);
      digitalWrite(WE, HIGH);
      delay(2);
    }
    Serial.print(".");
  }
  Serial.println();
 // read
  
  digitalWrite(WE, HIGH);  // WE= disabled
  digitalWrite(OE, LOW);  // OE=active low
  DDRL = 0x00; // all data inputs
 
  for (int i=0; i< 128; i++) {
    PORTA = i;      
  for (int j=0; j <256; j++) {
        PORTC = j;
        PORTD = PORTC & 0x80;
        k++;  // becomes 0
        data[k] = PINL;
        if (k==15) {
           base = i << 8;
           base += (j-15);
           
           char buf[80];
           
           sprintf(buf, "%04x:  %02x %02x %02x %02x %02x %02x %02x %02x   %02x %02x %02x %02x %02x %02x %02x %02x",
            base, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
            data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]);
          Serial.println(buf);
          k=-1;
          delay(10);
        }
      }
    }
}

void loop() {
}