|
| 1 | +package sd |
| 2 | + |
| 3 | +import ( |
| 4 | + "io/ioutil" |
| 5 | + |
| 6 | + "github.com/pda/go6502/spi" |
| 7 | +) |
| 8 | + |
| 9 | +type SdCardPeripheral struct { |
| 10 | + state *sdState |
| 11 | + spi *spi.Slave |
| 12 | +} |
| 13 | + |
| 14 | +// SdFromFile creates a new SdCardPeripheral based on the contents of a file. |
| 15 | +func NewSdCardPeripheral(pm spi.PinMap) (sd *SdCardPeripheral, err error) { |
| 16 | + sd = &SdCardPeripheral{ |
| 17 | + state: newSdState(), |
| 18 | + spi: spi.NewSlave(pm), |
| 19 | + } |
| 20 | + |
| 21 | + // two busy bytes, then ready. |
| 22 | + sd.state.queueMisoBytes(0x00, 0x00, 0xFF) |
| 23 | + |
| 24 | + return |
| 25 | +} |
| 26 | + |
| 27 | +// LoadFile is equivalent to inserting an SD card. |
| 28 | +func (sd *SdCardPeripheral) LoadFile(path string) (err error) { |
| 29 | + data, err := ioutil.ReadFile(path) |
| 30 | + if err != nil { |
| 31 | + return |
| 32 | + } |
| 33 | + sd.state.data = data |
| 34 | + return |
| 35 | +} |
| 36 | + |
| 37 | +// via6522.ParallelPeripheral interface |
| 38 | + |
| 39 | +func (sd *SdCardPeripheral) PinMask() byte { |
| 40 | + return sd.spi.PinMask() |
| 41 | +} |
| 42 | + |
| 43 | +func (sd *SdCardPeripheral) Read() byte { |
| 44 | + return sd.spi.Read() |
| 45 | +} |
| 46 | + |
| 47 | +func (sd *SdCardPeripheral) Shutdown() { |
| 48 | +} |
| 49 | + |
| 50 | +// Write takes an updated parallel port state. |
| 51 | +func (sd *SdCardPeripheral) Write(data byte) { |
| 52 | + if sd.spi.Write(data) { |
| 53 | + if sd.spi.Done { |
| 54 | + mosi := sd.spi.Mosi |
| 55 | + //fmt.Printf("SD MOSI $%02X %08b <-> $%02X %08b MISO\n", |
| 56 | + // mosi, mosi, sd.spi.Miso, sd.spi.Miso) |
| 57 | + |
| 58 | + // consume the byte read, queue miso bytes internally |
| 59 | + sd.state.consumeByte(mosi) |
| 60 | + // dequeues one miso byte, or a default byte if queue empty. |
| 61 | + sd.spi.QueueMisoBits(sd.state.shiftMiso()) |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func (sd *SdCardPeripheral) String() string { |
| 67 | + return "SD card" |
| 68 | +} |
0 commit comments