Thursday, November 12, 2037
About the projects // О проектах
Idea:here
Read by tag:68kavr
Z80 project (considered complete, but will be updated sometimes)
Idea here
Read about Searle Grant's SBC SD interface (and generally CP/M SD implementation) by tag sgsbcsd
Note, that the early records were imported from Livejournal and should be edited by me sometimes later (I bet that will never happen). Also, some early records may contain some weird letters - that's russian, but it is always translated, do not be afraid.
Also, sometimes I write about some unrelated (even PC!) but weird hardware, some unrelated but weird network technologies, and some weird things. May be even I'll attempt to write a big post about butterflies. If I ever got interested in butterflies.
Tuesday, December 19, 2017
RCA / CDP1802 project with the same ideas
Wednesday, November 15, 2017
Tiny AVR based project to reset Z80 (or any other CPU) by a serial line
But all that Z80 and MC68000 CPUs sometimes HANGS! (Well, do not blame them, blame yourself for a buggy code). But no matter - we have to reset them. And to do that remotely.
So this tiny tool does that: it uses 2 lines from your DIY computer - the reset line and TTL-level RX line of the console. To initiate /RESET, just send break.
You need ATTINY2313, avr-gcc compiler, mm...avrdude and (probably) to edit 2 lines of code in main.c:
#define F_CPU 12000000L
#define BAUD 57600
First is the freq of yours' quarts, the second is the baudrate of your console.
And all that work for me.
Get it all here
Tuesday, May 20, 2014
68kavr - considered competed
I consider 68kavr project competed.
That means that it loads OS from SD card
Today I've published my SD card image with the source of BIOS/LDRBIOS, as usuially, here , I'll check two last chapters and copy them there (to be able to discuss them and just they not to be lost one day) in few days.
Thursday, April 17, 2014
I've burned one more Atmega8A
I have some Atmega8L's (max 8 Mhz), and tried to make them work at least at 9600.
Ha! It works on 38400! My 68kavr flow control algorithm considered to be good.
Thursday, March 20, 2014
68k project: step 5 - SD interface
The idea of SD interface is just an adoptation of my SD interface for Searle's Grant SBC. So go there for SD card pinout,resistor values, 3.3V power, etc. The only change is 2*7474 to one 74175. Or you can use 2*7474. Or any latch of this sort.
Some notes: a rewiring /AC0000,CPURESET->SETAVRCLK, FCE,AVRCE->MIXEDCLK2 on the scheme is not significant at all and is here just to correspond my actual wiring.
As for SD interface, it consists of a 74175 trigger for data output and 7403 as data input. To write to 74175 we mix /A80000 line with /MEMWR and /DS (on an extra 7432) and latch D0-D2 to the trigger, so that are SD card's Clock (SDCLK), DataIn (SDDATAIN) and Chip Select (SCCS) [why SCCS? Rename it to SDSC later] SPI lines. They should be mixed via resistors to get 3.3V-alike signals (again, see this). Do not forget that SD card itself should be feed with +2.8 - +3.3V so you can use 7833 or just a LED to drop the voltage.
For data in, we mix /A80000 line with /MEMRD and /DS to get /80000RD and invert it to get 80000RD. Passed throw 7403 (with SDDATAOUT) we direct this open-collecor output to D0. So this output is low only when 80000RD is active (high) and SDDATAOUT is high too, so this is inverted input. So, from 68k side we can
move.b #7,$80000 ; CS - up, Dataout - up, CLK - up
move.b #2,$80000 ; CS - down, Dataout - up, CLK - down
manage that bits this way (but better keep higher bits high - we may have some extra SPI devices in future), and
to read it just read lower bit from $80000 and invert it.Just to remind:
D0 - CLK
D1 - DATAOUT
D2 - CS
D3 and D4-D7 - reserved for future SPI devices (who knows which? extra Atmega, RTC, etc)
The Code for ChV can detect (command "BOOT") the card (CMD0), can send it CMD1 for (doing smth usefull), some command to ensure the card's sector size is 512 bytes, but nothing more still. (I use this and this) as reference)
Also, scince now I use Atmega's PC5 pin for CTS. That's because I've tried to cut-and-paste CP/M-68 S-record files and was unable to do that without hardware flow. So in AVR code there is a #define WITH_CTS to use this code (enabled by default) and 256 bytes ring boofer for handling input bytes from serial.
As you could note, there is a sort-of-monitor program included in 68k asm Currently it can:
BF Blink SDCLK fast (with fullspeed clock)BS Blink SDCLK slow (with AVRCLK)BLINK Blink until key pressed (fullspeed clock)ON Set SDCLK to 0 (or 1)OFF Set SDCLK to 0 (or 1)1 Set SDCLK to 1, SDDATAIN to 0, SCCS to 0)2 Set SDCLK to 0, SDDATAIN to 1, SCCS to 0)4 Set SDCLK to 0, SDDATAIN to 0, SCCS to 1)IN Tell SDDATAOUT status (or inverted SDDATAOUT?)DUMP[optional address] Dump memory from address (or continue to dump from that address if no address given)BOOT Try to init the SD cardS[srecord] Parce S-Records. It understands S1,S2,S3 records and ignores all the othersIt's easy to extend this command set:
first, write an f_myfunc subrotine which should return to monotor with rts. Then add it's mnemonic to commands: and it's address (f_myfunc) to commands_vector When called, A1 will point to the first byte after you's command mnemonic in input buffer, so if was called as
myfuncbebebe
, A1 will point to "bebebe"
 :Also there is one more thing I want to warn you: I use ISP programming of ATmega via SCLK/MOSI/MISO/RESET pins of ATmega, AND THIS IS UNRELATED TO SPI BUS WE'VE JUST DISCUSSED!
 : Be careful: I've burned 3 Atmega's while ISP programming it until I installed a RESET switch for CPU (RESET+HALT)
So to make an ISP firmware update, hold down RESET+HALT of CPU, then do firmware update (I use avrdude and usbasp)
Wednesday, February 26, 2014
68k project: step IV - Switching to fast clock
20140129
We will add fast clock. Just will, because out current CPU clock is slow. And for future 68681 UART which I am planning.
On my opinion, our AVR clock is about 60 times slower then external clock. (I run ATmega8A from 12Mhz crystal).
So lets' add an external quarts. (around 12 in my case; it will be devided by 2, read more). We will use
the Searle Grant's scheme on 74HCT04 and get FASTCLK signal pins 3,4,5,6.
And a trigger - 7474 (should be ALS or HCT, but I've tried old 7474 and it worked too.)
The trigger (1-7 pin) will behave the following manner: on reset, it will be at 1 (CLKFROMAVR high), and
by accessing E0000 address it will go low, that will be switching to fast clock. Also, by accessing C0000
from CPU you can switch it back to AVR clock. So we will mix /C0000 and /CPURESET signals on 7400, so
it will go high when any of /CPURESET and /C0000 will be active, and invert it on 74HCT00 pins 0 and 1
Then, we'll take the trigger output (CLOCKFROMAVR and /CLOCKFROMAVR) and mix it with CPUCLK on one segment
of 7400 and with FASTCLK. We'll get AVRCE (AVR Clock Enabled) and FCE (Fast Clock Enabled) signals.
When any of them disabled, it will go high, the other should tick. And let's mix them on one extra 7400
to get MIXEDCLK2
Is MIXEDCLK2 is good for clocking CPU? Maybe, I'm not sure.
Imagine you switch from AVR clock by accessing E0000, and fast clock front comes right after that?
That may be not good (because that will lead to a very fast clock tick) (or may not, because when you
switch the trigger you are at the end of cycle)
So let's use the other side of the moon 7474 trigger it to revert on any even clock change.
(And this devides clock by two.) I do not remember why I've decided that, but I really thought we'll have
one guaranteed tick in the worst case; it looks I'm wrong.
Anyway, this works ;-) (it really was an argument of doing it, but I forgot)
And unsolder CPUCLK clock from CPU and connect it to the output of that trigger (called CPUCLK')
20140213 Well, here it the worst case this trigger prevents: imagine we switch the clock
from slow to fast, and the MIXEDCLK2 is high. And saying when switched to fast clock it's low and
just before rising edge. So, the MIXEDCLK2 will go from high (from AVR) to low and back to high
too fast.
This is the case this trigger prevents.
We've never discussed M68K assembler code; some code in examples, but now it's time to speak about it
Currently I use A68K assembler (not pila) to get binary output of program; it has $1D bytes prefix (is it
for HP calc?), so I cut it and translate the rest of binary to C code via bin2c.tcl script.
While what you see in the 68K code is very experimetal (this is my first attempt to write 68K code),
at least here you can see an example (in byteio_fast.asm) file how to read and write bytes via AVR UART emulation
uartstat equ $A0002
uartdata equ $A0000
slowclock equ $C0000
fastclock equ $E0000
;------------------ RX char
rx_char:
bsr rx_notempt ; while rx is not empty, ie, no char
beq rx_char ; loop
move.b d0,(slowclock) ; switching clock slow
move.b (uartdata),d0 ; read from uart
move.b d0,(fastclock) ; switching clock fast
cmpi.b #CTRLC,d0 ; CTRL-C?
beq warm ; warm reset
rts
;------------------ Test input for a char (NOT ZERO if IS)
rx_notempt:
move.b d0,(slowclock) ; switching clock slow
move.b (uartstat),d0
move.b d0,(fastclock) ; switching clock fast
andi.b #$02,d0 ; bit 1 is 1? (I've told you that it is my first attempt to write 68k code!)
rts
;------------------ Wait for clear to send -------
tx_rdy_w:
move.l d0,-(sp)
tx_rdy_w1:
bsr tx_rdy
bne tx_rdy_w1
move.l (sp)+,d0
rts
;------------------ TX char
tx_char:
bsr tx_rdy_w
move.b d0,(slowclock) ; switching clock slow
move.b d0,(uartdata)
move.b d0,(fastclock) ; switching clock fast
rts
;----------------- Returns TX ready (Z)
tx_rdy:
move.b d0,(slowclock) ; switching clock slow
move.b (uartstat),d0
move.b d0,(fastclock) ; switching clock fast
andi.b #$01,d0
rts
The most interesting in this code is that it is working. I do not know what to tell you about this code,
may be the only thing: do not forget to switch the clock fast in your's main program
Avr/GCC/A86k source code
Thursday, January 16, 2014
68k project: step III - execute some bytes by 68008 from RAM
Well, to run program from RAM we should solder it in.
So, the Scheme 2:
First, note the 74138. It decodes higher adress lines. It's all clear with it. Also, that it clear that RAM should start on Addr 0h, so put the /A0000 line to /CE of RAM.
Look at Atmega. The most significant of the new connections is the /BOOTMODE line. It is used to inform RAM to behave the following way: when /BOOTMODE is active, CPU should read not from RAM, but from MCU. It is AND-NOTed with R/W, so when /BOOTMODE is active (0) and READ(1) happens, the output of 7400 leg 8 is not active (high). When /BOOTMODE is not active and READ goes high, the output of 7400/8 goes low, and, ORed with /DS, this is fed (as /MEMRD) to /OE pin of RAM.
7432 also ORs /DS and R//W to get /MEMWR.
Sure, we'll use ATmega as uart, so we should connect one of the lines from 74138 ORed with DS to one of ATmega's leg (again, as interrupt, while that's not absolutely needed). And add an address line (A1) to get two registers for read and for write.
It's all clear that one pair is read byte from line and write byte to line, the other read register is status saying "we have an byte in input" and "it's clear to send the next char". The extra writing register is a HEX output.
So here will be an algorythm (bold is new code):
/* Interrupt handling - DS gone low */
void ISR0()
{
if (RWline is UP) {
/* feed a byte to CPU */
writing_on_bus = 1;
b = bytefeeder();
if (b != -1)
{
write_on_bus(b);
} else { // The boot 68k program is ended!
bootmode = 0; /* and /BOOTMODE leg*/
reset_CPU();
/*optional*/ uninstall_IRQ_0_handler();
}
} else {
/* CPU is writing byte to memory*/
}
}
void ISR2(USART_RXC_vect) // Serial event: a char came from terminal to AVR
{
byte_came = byte_from_serial();
byte_in_rx_que = 0x02; // Flag to be ORed when we'll tell CPU the status
}
void ISR1() // interrupt happened on /AVRSERAIL goes low
{
if (RWline is UP)
{
/* CPU is reading from serial */
writing_on_bus = 1;
if (A2_line_is_up) // CPU reads status
{
write_on_bus (clear_to_send | byte_in_rx_que);
} else
{
write_on_bus(byte_came); // last recieved byte from serial
byte_in_rx_que = 0;
}
} else /*CPU is writing to bus*/
{
if (A2_line_is_up)
{
serial_send_hex(byte_from_data_bus());
} else
{
serial_send(byte_from_data_bus());
}
}
}
void main()
{
bootmode = 1; /* as well as /BOOTMODE leg */
byte_in_rx_que = 0; // No pending serial bytes
reset_CPU(); reset_ticks = RESET_TICKS_VAL;
install_int0_handler(DS_line_does_down);
install_int1_handler(AVRSERIAL_goes_down); // Both can be done when leaving bootmode
install_serial_rx_handler();
while(1)
{
click_clock();
if (reset_ticks > 0)
{
if (!(reset_ticks--))
{
release_reset_CPU(); // reset - up!
}
}
if (DS_line_got_high)
{
if (writing_on_bus) {
switch_data_bus_to_read_mode();
writing_on_bus = 0;
}
}
}
}
What do we feed to cpu, you may ask?
Here it is (in file bytefeeder.c):
uint8_t PROGMEM prologue[] = {
0x00,0x00,0x10,0x00 // 0 dc.l stack pointer
,0x00,0x00,0x00,0x08 // 0 dc.l start
,0x20,0x7C ,0x00,0x00,0x00,0x00 // 8 movea.l #0,A0
};
, then, in loop,
uint8_t PROGMEM program_loop_bytes[] = {
0x30, 0xFC, 0, 0, // move.w #XX,(A0)+
0x4e, 0x71 // NOP
};
, replacing zeroes by the bytes from the actual program. The trailing NOP is needed because 68008 prefetches one command before executing the prevous (as shown in Chapter II)
And here
K1533LA3 = 74ALS00, K1533LL1 = 74ALS32, K555ID7 == 74LS138 (Soviet/russian chips)
The GCC source of AVR program for chapter III
68k project: step II - execute some bytes by 68008 taken from AVR, actually!
The scheme for Running first program
The GCC source or AVR program
The result of running program:
(* is a clock tick , is a comment)
************************************************************************************************************************************
********************************************************************************************
Calling release reset
[Released reset]
**************************** clock after reset
INT: R Int happens when /DS goes low; R means that CPU is READING
State 0000***** "State 00" is some debug message, the other byte is actual byte
Releasing bus*** 5 clock changes /DS from low to high; 'Releasing bus' - MCU put data bus to high impedance.
INT: R
State 0000*****
Releasing bus***
INT: R
State 0000*****
Releasing bus***
INT: R
State 0008***** fed with 00000008; really the address does not matter, but it must be even, as you understand ;-) -
Releasing bus*** the first thing I've got was a trap leading write 14 bytes to somewhere
INT: R
State 0000*****
Releasing bus***
INT: R
State 0000*****
Releasing bus***
INT: R
State 0000*****
Releasing bus***
INT: R
State 00C0***** fed by stack pointer
Releasing bus***
INT: R
State 0020*****
Releasing bus***
INT: R
State 007C*****
Releasing bus*******
INT: R
State 0000*****
Releasing bus***
INT: R
State 0000*****
Releasing bus***
INT: R
State 0000*****
Releasing bus***
INT: R
State 0000***** fed with movea.l #0,A0
Releasing bus***
INT: R
State 0020*****
Releasing bus***
INT: R
State 003C*****
Releasing bus***
INT: R
State 00AA*****
Releasing bus***
INT: R
State 0055*****
Releasing bus***
INT: R
State 0033*****
Releasing bus***
INT: R
State 00CC***** fed with move.l #$aa5533cc,D0
Releasing bus***
INT: R
State 0020*****
Releasing bus***
INT: R
State 0080***** move.l D0,(A0)
Releasing bus***
INT: R
State 004E*****
Releasing bus***
INT: R
State 0071***** fed with NOP - that's prefetching
Releasing bus*****
INT: WAA******** Writing data! Whuuuuaaaaaauhuhhhh!
INT: W55********
INT: W33********
INT: WCC******
INT: R
State 004E*****
Releasing bus***
INT: R
State 0071*****
Releasing bus***
INT: R
State .....
So, we see that at least one command was executed by CPU
68k project: step I - execute some bytes by 68008 taken from AVR - the theory
Getting falling font of DS the MCU's INT0 is accured; while serving INT, main program waits until INT0 finished, so clock does not click, and there is no reason to play DTACK
INT0 feeds next byte of program to the CPU data bus (if CPU reads it), and leaves it there, returning from INT0 hanlder and making the main clock clicks. When main loop detects that DS is not active, it removes data from data bus.
So here it is:
/* Interrupt handling - DS gone low */
void ISR0()
{
if (RWline is UP) {
/* feed a byte to CPU */
writing_on_bus = 1;
write_on_bus(bytefeeder());
} else {
/* CPU is writing byte */
}
}
void main()
{
bootmode = 1;
reset_CPU(); reset_ticks = RESET_TICKS_VAL;
install_int0_handler(DS_line_does_down);
while(1)
{
click_clock();
/* may be some minimal delay, but CPU should be much faster then MCU*/
if (reset_ticks > 0)
{
if (!(reset_ticks--))
{
release_reset_CPU(); // reset - up!
}
}
if (DS_line_got_high)
{
if (writing_on_bus) {
switch_data_bus_to_read_mode();
writing_on_bus = 0;
}
}
}
}
While in boot mode, CPU should transfer some initial program to to memory,
then MCU should leave boot mode and send reset. After reset, CPU should execute the
main program already in RAM. It can later switch the clock source to run from a fast quartz.
2014016
Note 1. We have serial on ATmega, and you can use MAX232 or whatever you like
to connect it to COM port or USB.
Note 2. It is mentioned that interrups are used to determine /DS signal. Generally,
you do not need that because while CPU is clocked from MCU they are fully syncronized
(and when CPU will be clocked from external source there will be no way to talk with MCU
because it is slow). AVR interrupts are used because the code is clearer.
Monday, October 21, 2013
Launching 68k project
I'm not going to stop poking the soldering iron to Z80, for sure, but now I want to implement 68k project.
The idea is mostly the same.
We'll boot it from AVR, sure ;-)
AVR will also always click the clocks (for stage 1) and serve as UART (for stage 1 and 2)
This is the start of desiging.
Stage 1: chips: AVR (Atmega8, I suppose, CPU (68008), SRAM chip), DTACK grounded
Stage 2: same with external quartz and the ability of cpu to turn on external quartz or switch back to AVR clock. This will be needed when we use AVR as UART. So before accessing AVR, we'll switch to AVR clock, write/read AVR, switch to fast clock.
No need to use DTACK.
SPI port. SD card.
Stage 3: same with external UART. DTACK will be grounded always except external UART accessing. So some BGERR logic is planned.
MMU is not planned, so the best I'll be able to run here is CP/M 68, not NetBSD.
[UPD error: R//W line should be inverted before going to OR to atmega; it should catch /Reads, not /Writes]
The first stage and booting logic follows:
Main program for avr -
- Hold down RESET & HALT lines, click the clock for some time.
- clock the clk line. If we have data on data line and /DS got high, put data in hi-impedance mode.
On RESET, Trigger should set 0 on Q line [/BOOTMODE], and in every read access to 0-1FFFF it will generate an INT0 on avr.
Getting the interrupt, AVR will put the byte data from the program to data line:
LEA $800,A0
LOOP: MOVE.B #$BYTE_FROM_A_PROGRAM_TO_BE_BOOTED,(A0+)
BRA LOOP
BRA $800 (and turn off the boot mode!)
(or like that)
and pausing for clicking clock until interrupt ends.
While beeing in BOOTMODE (and Q is not active) if we /write anything to 0-1FFFF the data will go to RAM. And when the bootmode ends, every access to the 0-1FFFF will go there.
Accessing D0000 - FFFFF from CPU will end boot mode. Really, now it's not clear to me should boot mode be terminated by CPU or AVR. [UPD 20140313 Later this idea was significantly simpified]
Sunday, November 18, 2012
Today I've made Z80 to execute the first command. And used Atmega as Z80 debug processor ;-)
install flash, feed the processor with a clock source from ATmega, and install ATmega
as data bus spy - write all the data bus to RS232.
It's easy.
Сегодня Z80 у меня выполнил первую осмысленную программу. И попользовал Atmega как Debug Processor. Надо этот термин запатентовать ;-)
Прожигаем флешку (рассказывал как), и суем туда наипростейшую программулину, суем Z80, сум флешку, кормим ее тиканьем от ATmegавой ноги, и пользуем саму AtMegу как сниффер шины данных.
First, burn flash (AT29C256) with the following :
C3 00 00 FF FF FF FF to the end of chip (JP 0 ; NOP; NOP; NOP ...)
Next, connect data bus from CPU to ROM and port B of the atmega.
Here are legs (Atmega, Z80, 29C256) in triplets:
(14,15,11)(15,15,12)(16,12,13)(17,8,15)
(18,7,16)(19,9,17)(9,10,18)(10,13,19).
Connect address bus from CPU to flash.
Flash: leg 1 - +5, 20 - gnd, 22 OE - to CPU's RD(leg 21);
Cpu: 21 - RD to flash 22 OE and to INT0 of Atmega (leg 4),
22 - WR to INT1 of Atmega (leg 5).
It means that if Z80 reads, it reads from ROM (and causes interrupt on ATmega to read
the data bus, filled by flash), and if it writes, it writes to ATmega by interrupting it on INT1
That also means that *no* address decoding is performed, and no IO/MEM decoding is
performed, too.
So if you do OUT 0x7F,A or LD (0x1488),A - no matter - you write to ATmega.
Burn atmega with the program (attached here somewhere aroud (UPD: at the end of this post!)) and lets try to read it.
It install 4 Interrupt vectors:
ISR(USART_RXC_vect) - doing nothing in this project, do not care.
ISR(TIMER1_COMPA_vect) - blinks led on PORTC 0 and provides clock to Z80
ISR (INT0_vect) - external interrupt, catches RD from Z80.
ISR (INT1_vect) - external interrupt, catches WR from Z80 (I do not care about it, BTW)
But lets start from main().
DDRC = _BV(PC0) ; // Enabling output for LED on leg 23 of atmega
TIMSK = _BV(OCIE1A); // Timer stuff
TCCR1B = _BV(CS12) // 256 prescale
| _BV(WGM12); // CTC mode, TOP = OCR1A
// OCR1A = 825; // count up to TOP 1hz with 8 meg system clock BLINK FAST
OCR1A = 25; // count up to TOP 1hz with 8 meg system clock BLINK FAST
//Install timer of atmega to blink. I do not remember where I got this code - but it works.
/* Com port settings */
USART_Init(MYUBRR);
UCSRB |= (1 << RXCIE); // enable UDRempty intr.
/* Setting IRQ0 handling - read data bus on read */
DDRD &= ~(1 << DDD2); // Declare INT0/PortD 2 as input
PORTD |= (1 << PORTD2); // turn On the Pull-up
MCUCR &= ~(1 << ISC00); // Tell the interrupts to cause on falling edge only
MCUCR |= (1 << ISC01);
GICR |= (1 << INT0); // Turns on INT0
/* Setting IRQ1 handling - read data bus on write */
DDRD &= ~(1 << DDD3); // Clear the PD3 pin
PORTD |= (1 << PORTD3); // turn On the Pull-up
MCUCR &= ~(1 << ISC10); // Oh no, falling edge only
MCUCR |= (1 << ISC11);
GICR |= (1 << INT1); // Turns on INT0
DDRB = 0b00000000; // Configure as input for data bus
static unsigned PROGMEM char b[] = "\n\r**SP: RESETTED**\n\r";
USART_PUTS_my(b);
while(1) {}
And after all we get:
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
That's means the Z80 CPU is working! (if not - short the reset pin on Z80)
And, more, that means we assembled the computer.
Note: it's a very slow computer. It runs around ~10hz, saying because ATmega has to send several bytes over a serial link (4800 baud in this example) while Z80 executes ONE command.
UPD: the code
Шьем флешку (AT29C256) следущим:
C3 00 00 FF FF FF FF to the end of chip (JP 0 ; NOP; NOP; NOP ...)
Распаиваем data bus - триплеты ног (Atmega,Z80,29C256)
(14,15,11)(15,15,12)(16,12,13)(17,8,15)
(18,7,16)(19,9,17)(9,10,18)(10,13,19).
Распаиваем адресную шину от Z80 до флешки.
Далее:
Флешка: нога 1 - +5, 20 - gnd, 22 OE - на CPU's RD(нога 21);
Cpu: 21 - RD к флешкиной 22 OE и на INT0 Atmegи (нога 4),
22 - WR на INT1 Atmegи (нога 5).
Понятно из этого что если проц что-то читает - то из флешки (и дергает ATmegу за INT0, которая радостно читает в этот момент данные которые родила фешка), а если пишет - то вообще безусловно попадает в ATMegа, дергая ее за INT1.
Заливаем а ATMegу программулину (где-то тут надо ее залить (UPD: залил, в конце!)) и давайте читать программулю.
Она устанавливает 4 вектора прерываний:
ISR(USART_RXC_vect) - это щаз нам пох
ISR(TIMER1_COMPA_vect) - моргает ledом на PORTC 0 и клочит Z80на CLK (нога 6)
ISR (INT0_vect) - внешнее перывание, ловит RD от Z80.
ISR (INT1_vect) - внешнее перывание, ловит WR от Z80
Давате почитаем от main()
DDRC = _BV(PC0) ; // Нога 23 - это LED моргалка и клоки для Z80
TIMSK = _BV(OCIE1A); // Timer stuff
TCCR1B = _BV(CS12) // 256 prescale
| _BV(WGM12); // CTC mode, TOP = OCR1A
// OCR1A = 825; // count up to TOP 1hz with 8 meg system clock BLINK FAST
OCR1A = 25; // count up to TOP 1hz with 8 meg system clock BLINK FAST
// Это инициализация таймера. Спер откуда-то, работает.
/* Это ком порт - сеттинги */
USART_Init(MYUBRR);
UCSRB |= (1 << RXCIE); // enable UDRempty intr.
/* Натравливаем INT0 на падение уровня на ноге INT0 */
DDRD &= ~(1 << DDD2); // Declare INT0/PortD 2 as input
PORTD |= (1 << PORTD2); // turn On the Pull-up
MCUCR &= ~(1 << ISC00); // Tell the interrupts to cause on falling edge only
MCUCR |= (1 << ISC01);
GICR |= (1 << INT0); // Turns on INT0
/* То же самое про INT1 */
DDRD &= ~(1 << DDD3); // Clear the PD3 pin
PORTD |= (1 << PORTD3); // turn On the Pull-up
MCUCR &= ~(1 << ISC10); // Oh no, falling edge only
MCUCR |= (1 << ISC11);
GICR |= (1 << INT1); // Turns on INT0
DDRB = 0b00000000; //Объявлем регистр B - вводом, и все его 8 бит будут тырить наш Data Bus
static unsigned PROGMEM char b[] = "\n\r**SP: RESETTED**\n\r";
USART_PUTS_my(b);
while(1) {}
Должны увидеть
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
READS: 00
READS: 00
READS: C3
Это значит что проц работает - читает комманду JP 0000. (а если нет - то коротните reset на ноге 26 у Z80)
А так же это значит что мы собрали компьютер ;-)
Кстати, заметим, что при этом достаточно тормозной (герц 10). Например потому что atmega должна перекинуть пару байт по rs232 на скорости 4800.
UPD: the code
Saturday, November 17, 2012
Running Z80 in no-nothing mode
The great news (oh, well, maybe for someone that's really news) that NOP operator in Z80 is exactly FF [UPDATE: FF IS RST38!] since at least Intel i8080 times (4040? 4004? I do not know.).
It means that if we put FF on data bus via pull-up resistors- the CPU will execute NOP, then take the following address, execute NOP, etc, blinking LED on the address bus.
[UPD: It's all wrong. It will execute RST 38, but will blink, yeah. That's because it refreshes memory]
And here is idea.
What I changed:
1) they use 8 resistors from +5 to data bus. Actually, I used one - one side to +5, the other to shorded data bus.
2) they used some weird chip as clock source (what's this? 555 clone? to lazy to find it out), but I used... You know - ATmega8!
The photos: 1, 2
Continued under cut
Ну чо, самая тема запустить Z80 который будет делать нихуя. (кстати это - мое любимое занятие).
Для некоторых может и новость - но это для кого как - что команда Нихуя - NOP - еще со времен как миниум i8080 имеет код FF, за что большое спасибо компании Intel. [UPD: А аффтор-то лошок! FF - это RST 38] То есть если повесить легкий плюс на весь data bus - CPU будет перебирать адресной шиной. Куда я повесил светодиод.
[UPD: Боже, какой я кретин. Но моргать адресными шинами все равно будет - потому что будет рефрешить память]
Основная идея - тут
Разница:
1) у них 8 резюков, я на них сэкономил - повесил один от +5 на всю шину данных, ее замкнул нахуй
2) хрен поймет что у них там за чип в качестве тактового генератора, я, естественно, взял Atmega8.
А теперь -
I assume you have Atmega8 or smth like that on your's breadboard.
On the photo that's a 28 pin chip. It has 2 leds near it, one on leg 23 (PC0 port) via 1kohm resistor to +5, the other is just gnd-to-power via resistor, too.
It has resistor on reset leg 1 to +5. 10kohm, I suppose.
The white/grey cable is (usbasp) programmer. It connect via 10 pin standard connector to MOSI/RESET/SCK/MISO and provides power.
On my board you also see MAX232 (ADM232L) actually, surrounded by capacitors, not used while blinking Z80 bus, but connected to a standard atmega's legs 2/RXD & leg 3/TXD leading to DB9 RS232 socket, and yellow led - connected to address line (leg 30) of the Z80 via transistor.
The scheme of transistor: Z80 leg30 -[resistor 1kohm] - base of pnp transisor. Transistor emitter on gnd, collector to led, the other leg of led on +5.
You can also see an empty 28 pin socket and two red resistors with smth wht looks like a transistor. 20 pin socket will be used for flash ROM later, and the transistor is not a transistor at all but ds18s20 temperature sensor. I just made an thermometer on atmega8, if you are interested - it's here, but not going ds18s20 in Z80 project in the nearest future.
Z80 is connected the following way: leg 11 power, leg 29 gnd, data bus - 7-8-9-10-12-13-14 shorted and via the resistor (10k?) to +5 - YOU *MUST* INSTALL THE RESISTOR, leg 6 to atmega8's leg 23, +5 on 24,16,17,25, leg 30 as described.
The firmware of atmega follows, but it's very simple firmware.
Ну atmega8 у вас на макетке распаяна конечно, у меня это 28 ногий чип. Там 2 светодиода рядом, один на 23 ноге (порт PC0) через килоомный резистор на +5, второй - просто земля-резюк-led-+5.
На ноге 1 (reset) на +5 висит резистор. Наверное 10k.
Серобелый кабель это программатор avrки (usbasp). Там 10 пиновый коннектор на MOSI/RESET/SCK/MISO и с него идет +5 и gnd.
Также на плате у меня видно MAX232 (на самом деле ADM232L, но не ссуть), окруженная кондерами, но в данный момент нас это не интересует. Ну там ноги 2 и 3 atmega8 идут на MAX232, к нему прихерачен ком-порт, а дальше торчит желтый светодиод, который влючен так: Z80 нога30 -[резюк 1kohm] - база 3107. Его эмиттер на земле, коллектор-LED-+5.
Ну там еще кровать на 28 пин неюзанная пока и 2 красных резюка с чем-то похожим на транзюк, хотя это нифига не транзюк, а ds18s20 температурный сенсор. Я его в обозримом будущем в Z80 сувать не собирался, я просто собирал на atmega термометр - получилось такое, кстати.
Z80 соединен так: нога 11 +5, 29 - земля, датабас вся закорочена, нахуй, как я и обещал, от нее торчит резюк (тоже наверное 10k) на +5 и ОН ПРАВДА НУЖЕН БЕЗ НЕГО НИЧЕГО РАБОТАТЬ НЕ БУДЕТ, 6 нога на atmegaвскую 23, +5 на 24,16,17,25,про 30ую я уже сказал.
Фирмваря под atmega, но как бы это совсем простенько.
/*
File: main.c
Version: 1.0.0
Date: May. 12, 2006
AVR Tutorial #1 - Toggle and LED on PC0
Schematic available at http://www.micahcarrick.com.
****************************************************************************
Copyright (C) 2006 Micah Carrick
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define F_CPU 1000000UL /* 1 MHz Internal Oscillator */
#include <avr/io.h>
#include <inttypes.h>
#include <util/delay.h>
/* function for long delay */
void delay_ms(uint16_t ms) {
while ( ms )
{
_delay_ms(1);
ms--;
}
}
int main (void)
{
/* PC0 is digital output */
DDRC = _BV (PC0);
/* loop forever */
while (1)
{
/* clear PC0 on PORTC (digital high) and delay for 1 Second */
PORTC &= ~_BV(PC0);
delay_ms(200);
PORTC |= _BV(PC0);
delay_ms(200);
}
}
Tuesday, November 13, 2012
A pair words on AVR
А сейчас - пару слов об AVRках. Я собрался их сувать куда только смогу и вообще юзать как инструмент - как пяльник или тестер. Туториалов в сети просто до японой матери, поэтому я только покажу свой сетап который дальше я буду юзать в хвост и в гриву.
Compiler: sure, avg-gcc + avr-libc.
Chip: Atmega8.
Me: a newbie in avrs.
Programmer: initially I've soldered FBPRG for use with avreal and it worked fine, but then I've ordered USBasp from here and quite happy with avrdude. I made a "standart" MAX232A RS232 interface, and it works fine on 2400 with internal 1MHz. Also I have a led on PC0. That's the basic setup.
When setting your's first avr, first solder power and a socket for programmer, and then try to program it with anything. It should work. Next, install LED via resistor (~510 ohm) and blink it. Next, attach MAX232A.
In my setup it found that only one half of MAX232A works properly, and this is very strange for me, I've tried different chips from different manufacturers (MAX232, MAX232A, Analog Devices), different capacitors (1μF for MAX232 and 0.1μF for MAX232A), so try it. And do not forget to disable hardware handshake, all the RTS/CTS/DTR/DSR and all.
Компилятор: естественно, avr-gcc + avr-libc.
Chip: Atmega8.
Я: лошок в avrах.
Изначально я спаял FBPRG и юзал его с avreal (и тащем-то это круто и все такое), а по ходу дела заказал на алиэкспрессе USBasp у этого косорылого товарища , который весьма себе товарищ и я теперь весьма рад с этого USBasp. Прицепил туда через MAX232A RS232, и на 2400 он весьма себе работает от внутреннего 1MHz тактового генератора. Ну, там, светодиод в PC0. Ну вобщем все так.
Будучи лошком в avrках я рекомендую таким же лошкам делать так: распаять питание и разьем под программатор и сразу же попытаться зашить любую ересь. Там мало где можно ошибиться, так что должно прошиться. Потом прицепить светодиод какой-нибудь простенький через резюк (ну, 510 ом) и поморгать им. Тоже вроде ничего сложного. А потом прицепить MAX232A.
А вот тут меня ждала засада. Половина MAX232A почему-то работала, а вторая - нет. Чипы менял на MAX232 и Analog Devices, кондеры с 1μF для MAX232 и 0.1μF для MAX232A, ничего не понял, но методом Перетыка все работает, да и хер.
А, и не забудьте в терминалке вырубить все RTS/CTS/DSR/DTR.