/**
* @auther naru
* http://naruken.cweb.tk
*/
#include <3694.h>

struct color{
  unsigned char r;
  unsigned char g;
  unsigned char b;
};

union bf{
  unsigned char byte;
  struct {
    unsigned char b7:1;
    unsigned char b6:1;
    unsigned char b5:1;
    unsigned char b4:1;
    unsigned char b3:1;
    unsigned char b2:1;
    unsigned char b1:1;
    unsigned char b0:1;
  } bit;
};

struct rgb{
  unsigned char r:6;
  unsigned char g:6;
  unsigned char b:6;
};

#define IO_CK IO.PDR8.BIT.B6  //サンプリングクロック
#define IO_DE IO.PDR8.BIT.B7  //0で有効
#define IO_HS IO.PDR7.BIT.B4  //水平同期信号
#define IO_VS IO.PDR7.BIT.B5  //垂直同期信号
#define IO_UN6 IO.PDR7.BIT.B6   //不明

#include "data/data.c"
void out(struct rgb); //色を出力する
void init();            //初期化

int main(void){
  int x, y;
  unsigned int gx,gy;
  struct rgb red={63,0,0};
  struct rgb green={0,63,0};
  struct rgb blue={0,0,63};
  init();
  IO_DE=0;
  for(;;){
    IO_VS=1;
    for(x=0;x<153;x++){
      IO_CK=1;IO_CK=0; 
    }//for x  152クロックでは同期しませんでした。
    IO_VS=0;
    for(y=0;y<16;y++){
      for(x=0;x<323;x++){
        IO_CK=1;IO_CK=0;
      }//for x  322クロックで表示が出ませんでした。
      IO_CK=1;
      IO_HS=1;
      IO_CK=0;
      IO_HS=0;
    }
    for(y=0;y<96;y++){
      gy=y>>1;
      for(x=0;x<107;x++){
        IO_CK=1;IO_CK=0;
      }
      for(x=0;x<400;x++){
        gx=x>>1;
        IO_CK=1;
        out(vrom[gx][gy]);
        IO_CK=0;
      }//for x
      IO_CK=1;
      IO_HS=1;
      IO_CK=0;
      IO_HS=0;
    }//for y
  }//for
  return 1;
}

void out(struct rgb c){
  //逆エンディアンで結線してしまったので時間かかりそう
  union bf b;
  b.byte=c.r;
  IO.PDR5.BIT.B0=b.bit.b5;
  IO.PDR5.BIT.B1=b.bit.b4;
  IO.PDR5.BIT.B2=b.bit.b3;
  IO.PDR5.BIT.B3=b.bit.b2;
  IO.PDR5.BIT.B4=b.bit.b1;
  IO.PDR5.BIT.B5=b.bit.b0;

  b.byte=c.g;
  IO.PDR1.BIT.B0=b.bit.b5;
  IO.PDR1.BIT.B1=b.bit.b4;
  IO.PDR1.BIT.B2=b.bit.b3;
  IO.PDR1.BIT.B4=b.bit.b2;
  IO.PDR1.BIT.B5=b.bit.b1;
  IO.PDR1.BIT.B6=b.bit.b0;
  
  b.byte=c.b;
  IO.PDR8.BIT.B0=b.bit.b5;
  IO.PDR8.BIT.B1=b.bit.b4;
  IO.PDR8.BIT.B2=b.bit.b3;
  IO.PDR8.BIT.B3=b.bit.b2;
  IO.PDR8.BIT.B4=b.bit.b1;
  IO.PDR8.BIT.B5=b.bit.b0;
}

void init(){
   //▼▼▼IO設定
  IO.PCR1=0x77;	// 0111 0111
  IO.PCR2=0x04; // 0000 0100
  IO.PCR5=0x3f;	// 0011 1111
  IO.PCR7=0x70;	// 0111 0000
  IO.PCR8=0xff;	// 1111 1111
  
  IO.PDR1.BYTE=0;
  IO.PDR2.BYTE=0;
  IO.PDR5.BYTE=0;
  IO.PDR7.BYTE=0;
  IO.PDR8.BYTE=0;
}

