I think we would all LOVE for you to interview Steve Wozniak, from a technical standpoint. All the interviews ive seen with him are just people asking him about Steve Jobs but I think hearing you ask technical questions to him would be so fascinating. Especially someone like you who clearly appreciates the things he made.
@@axelBr1that’s not what Ben meant. He meant that at the transmission rate of the serial connection, it can process the character in 10% of the time it takes to transmit a single character. i.e. it takes 500us to transmit a character over serial, the computer can read and store that character in 50us. The total “CPU time” (i.e. what the % utilization is) is much lower, as that is the proportion of microseconds used / second reported as a percentage. It’s much closer to 0.005% CPU utilization to read a character! (Assuming it takes 50us to read and store a char)
@@Comeyd I want back and checked what Ben said, and he did say that the processor will spend about 10% of its time in the interrupt handler. Great catch that what Ben calculated was that only 10% of the time to send the character was spent in the interrupt handler and only 0.005% of the actual CPU time was spent in the interrupt handler.
It was a stroke of genius when he observed that the circular buffer's write pointer's value didn't matter as long as it was set the same as the read pointer's value, and therefore didn't require initialization.
In the early 80s I programmed an RCA 1802 in assembly language with 20k of CMOS RAM to buffer incoming data at 19.2k and stream it through a 300 baud modem to a remote printer. The circular buffer in this case was a 16k memory board, which cost $1,100 and drew 5 mA at 5 volts. The data was coming in slowly enough that a simple software poll was adequate, no interrupts were needed. That was a fun project! Thanks for your videos Ben!
Ben Eater is one of the best sources for learning about all sorts of low level stuff, I mean I can barely find anyone else coding firmware for its educational value, and i've been looking, i love this stuff.
Vim is awesome! Learning at least vim motions inside your editor of choice is super useful. It took me about 6-12 months to get really comfortable with nvim but it’s totally worth it. Editing is way quicker.
Crazy timing! I just got my version of 6502 up and running just about 10 minutes before this video came out. 55 year old nerd giggling like a school girl after seeing that first "\" pop up in my terminal!! Just a CPU, RAM, EEPROM and 6551. I wrote a relocated wozmon code so I can copy it from ROM to RAM and run the wozmon out of RAM so I can edit the EEPROM in circuit. No more wrestling with arduino programmers. Thanks for the very clear explanations in all your videos.
At 7:53 you could have saved a register modification by storing whatever was already in the A register into READ_PTR. It would also make the program a little more deterministic, and allow the caller to specify a value for A, if it wanted.
Yup, and his interrupt routine isn't quite correct. Namely, the P register needs to be saved and restored. As things stand, he has a rather nasty unpredictable intermittent bug there. For instance, if the interrupt occurs immediately after a compare, but before a conditional branch that depends upon the result of that compare.
I’m pretty sure that the CPU’s control logic pushes the status register to the stack before jumping to the interrupt vector. Then RTI will pop it from the stack. That’s the difference between RTS and RTI.
@@bradywb98 Yep. I forgot about that little detail and was just about to check the instruction set when I noticed your response. A little niggling memory was bothering me about the BRK instruction. Was thinking it used the hardware interrupt vector, yet the interrupt handler could distinguish BRK from an actual hardware interrupt by some means. Turns out to be bit 4 of the saved status register. And my quick check revealed another trap averted by the 65C02, it clears the decimal flag during interrupts unlike the 6502 which leaves it intact.
(13:33) If I did my cycle counting correctly, the interrupt handler takes 53 cycles to execute, but if you include the "context switch" to get from program code to the interrupt handler, it ends up working out to _exactly_ 60 cycles (assuming the interrupt happens between instructions). (15:36) The BUFFER_SIZE routine doesn't modify X, so you can move the PHX instruction down to right before calling READ_BUFFER and get rid of the PLX insruction on the no_keypressed path.
In CHRIN you could only push x once you know you have to read a character from the buffer. This will save 1 byte again. Since you are already optimizing for size (7:53).
You are right. BUFFER_SIZE does not modify X, so pushing is only required before READ_BUFFER. Therefore no pulling from the stack is necessary in @no_keypressed (15:32)
Thank you Mr. Eater, for gracing us with another flawless performance. You have such a thorough grasp of the subject matter that you're effectively leading us on a choreographed dance from problem through to solution.
For those who know, when Ben pushes the registers to the stack before jumping into a subroutine, why do that outside of the subroutine? Why not push at the start of the subroutine and pop at the end? Else, should you want to call that subroutine elsewhere, you have to remember to push and pop there also.
It's the calling convention. If you want a faster calling convention, then use registers, but most software isn't setup for that on 6502's, so only use it in your own code. However, the reason that you can't push inside the function is because the arguments could be stored anywhere by the user and the function doesn't know where to push them from, but more importantly, if they're already in registers then it makes more sense to just use them as registers.
It's a choice. Saving outside means you can choose to only save once while calling several routines that clobber the same registers, or choose not to save at all since you're in a region the value is not needed.
What 0LoneTech said, if you push and pull from within the subroutine you end up doing it more often than necessary, say e.g. you call the same subroutine 50 times in a loop you end up pushing and pulling 50 times as well, while pushing and pulling once would have been enough.
Just prior to 7:50, I was thinking "Why are you setting A to zero? You don't need to do that." And he immediately got rid of that statement. Then he did the rather foolish thing of loading A with whatever random value was in the read pointer. He didn't need to do that. Just store whatever random value is in A into both the read and write pointers. Has the nice side effect of not altering A either. 14:00 LDA changes the status register as well, so you need PHP PLP to save that as well.
I love your stuff. I write bare metal C on various 8-bit AVR processors and seeing everything at such a low level really helps me with not just optimization but also understanding the how and why. I feel that's the more important part, and I thank you for it.
Oh, I can only imagine being back in university and having someone like you as a professor in engineering classes. Given how few people understand the concepts you touch upon, you have certainly made quite a name for yourself. I speak not only of this video, but everything you have produced. People like you ( the hardcore engineers), define our world...with or without the people in suits watching over your shoulder...
It's always insane how you make it seem like you do these without planning in the first take, especially if you seemingly run into typical errors anyone following could run into instead of just doing it perfectly the first time.
That's the most impressive part to me. I get confused as hell if I have more than one buffer open. I only just figured out how to change my indent tab/space settings for e.g. Makefiles and I felt so accomplished.
That's what years of experience brings! And he seemed to understand and fix problems quickly too, like that spurious interrupts from floating input pins. A newbie would have taken a long time to figure that thing out.
Frankly, the ability to pull out an exact-length, carefully and perfectly bent breadboard wire from the drawer instantly is more shocking to me. The permutations and combinations of lengths, bends, and colours is mind boggling.
DId a fair amount of 'slow' serial communication and data transfers. Looking forward to watching you get the 'flow control' aspect working (pause incoming data when your input-buffer is full). Then we can talk about putting in pauses to resync the serial clocking between your transmitting program and the 6502 (i.e. ala Kermit or other data transfer protocol). :) Love your videos, great discussions.
Replace "full" with "nearly full". Assuming that something like XON/XOFF is used for handshaking, you need to allow for any data already in transit to arrive before the sender can stop transmitting.
Started watching you back in high school when you built your own gpu. Kept on watchin even though I didn't understand much. Feels so good to come back and rewatch some of the stuff after getting my EE bachelor and getting a job in embedded engineering. Great review of core concepts used in microprocessors. Thanks for reigniting my love for programming/engineering and keeping me interested through the years ❤❤
Am I right in assuming since the read and write pointers must only be identical, leaving the code as it was at 7:55 would also work, (STA READ_PTR / STA WRITE_PTR) , because the same value is still written to both pointers. The values of both pointers would inherit A's previous value rather than that at READ_PTR. There's no performance difference because LDA and STA for zero page addressing mode are both 3 clocks. There is a higher abstraction reason to prefer one over the other: using A in a subroutine implies to readers of the code, and some static analysis tools, that the subroutine depends meaningfully on the value of A which imposes some theoretical obligation at the call sites. It's arguable that reading A has a lower impact than clobbering it. In Ben's version, both A and the status register are modified by LDA. STA does not modify any registers. If performance was critical, it seems preferable to make the INIT_BUFFER routine into a macro to avoid the cycle overhead of JSR/RTS . Not clobbering A would also make such a macro more usable. I'm guessing it would also use less memory in practice although I haven't done the calculation.
I love your content, and have been watching since forever ago. But truly, I cannot stress this enough, I got it all, it all clicked, the moment I started toying around with a commodore 64(Emulator or similarly structured system I recommend too). It's old and slow, yes, even frustrating to use at some points, but I KNOW my keyboard buffer, understand it and take it into account after some extensive use of such a barebones sistem. This goes for the general memory map, significant bits in memory and what to flip them to, as well as charsets pointers, etc. I really recommend the experience for other people interested in this field, it make each and everyone of your videos that much more informative and entertaining. (ALSO, as a bonus for the logic aspect of computing, I recommend reasing about multiplexors and demultiplexors, I mean, the theory behind logical sistems, I've truly come to love computing a lot more through a more educated lense, even from an amateurish understanding atm) Lot's of love from Spain! :3
I work developing electronic products. We still to this day program MCUs in Assembly, as this allows to save huge in MCU pricing, because we can squeeze the maximum from the speed, the memory and processor capacity from a cheaper controller. The fun part is that some of my codes do implement circular buffer, but without any separated memory or processor managing it. I simply do it internally, so I can simply stack up the received data in the time of interrupt, and the rest of the process will get back to roll as fast as a single clock pulse. And so, when the time to process arrive, the program will roll the buffer and do whatever it gotta do, without spending a bit to additional interrupt coding. Seems like too much work, but my client managed to save millions of dollars last year, just because of this very optimized way of development.
Well I'll be damned! I got it working. Took me a while to figure out how to run the .sh file in Windows. Also had to learn a lot about paths. Backspace doesn't work like it does in other programs. I get syntax errors if I use it. Don't really know how to use basic, but it does work finally.
Great video.... just a small point. You said it yourself in the commentary, read_ptr and write_ptr are offsets, so maybe read_ofs, write_ofs. The base address of the buffer would be a pointer, base+offset is also a pointer, but personally I would not call an offset a pointer as it confuses. Nice work though, I did appreciate it.
@@0LoneTech A stack pointer would be base+offset as I described. But an array index is not itself a pointer as it needs the offset (base) added to it before it becomes an address. We could argue forever over this one, but the modern accepted use of pointer is that it is something containing an address in the machines native word format rather than any kind of offset. If you include indexes and offsets then almost everything would qualify as a pointer, hence my comment "as it confuses". This is why programming books use "index" for offsets and pointer to describe memory references to clarify the distinction. On modern CPU even address gets vague though, hence being a topic that could argued forever!
@@0LoneTech I did not say "word size", but "native word format" - if you want to be pedant I guess "native address format", but as I said even "address" gets fuzzy on newer architectures, hence a "topic that could be argued forever", as you so kindly seem keen to demonstrate.
I knew immediately that you should have sent a command to the UART to disable all interrupt requests apart from RBF (Receive Buffer Full) so that nothing else would trigger an interrupt. (So far as I remember, you can do that with the UART so that you don't have to bother figuring out what part of the UART caused the interrupt). I like how you leave your errors in since it helps us to learn "what to watch out for" if we want to do something similar. In this case, I knew what needed to be done, but I've found a lot of your videos informative and learned several things from them.
I've hit those problems when interfacing to other people's embedded systems. My Atmel AVR could easily handle 115200 in both directions, but the other system needed a full mS inbetween chars at 9600, and I've always done my serial exactly as you describe. The key to interrupts is to do absolutely as little as possible in the ISR and get out! I've seen people write an ISR with pages and pages of code, interpreting the string IN THE ISR!! (head.. desk..) I also reserve a byte for counting the chars in the buffer, but I just inc it in the rx char ISR, and dec it when I take a char from the buffer. +1 on using a buffer size which is a binary multiple as well. Then overflow is handled by masking rather than calculation. I wouldn't call any routines from the ISR though, the call and return wastes time. When I init the buffers, I take the time to fill the buffer with something like 'A' or whatever so I can easily see where it is when debugging with an ICE. Very well done!
Fabulous stuff. One thought - it's been a loooong while since I've done any assembly programming. My habit at the time was for subroutines that modified registers to save those registers for me. Move the push/pops to the beginning/end of the routines themselves as opposed to having the caller have to accommodate. I noticed a couple of places where you used your new buffer routines that you said "have to remember to save X." What do you think?
This comes down to a balance between style and efficiency. Most ABIs include registers that must be saved and those that will be modified. Since a 6502 has so few registers and performance is more critical, I think that uniform register spill and load requirements would be too costly, both in terms of CPU overhead and in terms of ROM space. A comment is probably more instructive, and it may save a push or pop, since the caller is free to manipulate spills or loads to avoid them.
@@maxaafbackname5562Yes, I'm aware of that. But if you try to send several hundred bytes of data all in one lump, the xmit clock and the rcv clock often 'drift' apart a bit over such a long transmission. This means the rcv starts to 'sample' each bit at the wrong time and you get garbage. How much data you can successfully xmit depends on the accuracy of the two clocks and how long they can free-run without losing sync. Async communication has to periodically have a pause, so the rcv can reset itself and start it's clock/ sampling on the 'start bit'. With a continuous stream of bits, it can't do that. Hence the old protocols of xmitting data like Kermit that broke up the data into 'blocks' with a short (about 10 bit times) of no data. Sometimes referred to sending a 'transmit break'. Been there, done that. ;)
@@maxaafbackname5562 Indeed, synchronized by the start bit. Any character length gap will do to resynchronize if the receiver somehow started out of phase with a continuous input stream, but break is meant for lost connections.
Ben! Where are you! Missing your new premium deluxe brain-fuxx videos! IT-basics, cpu, bus, no caching, no pipeline, all that, thanks to you I got an idea what the basics are. Thanks a LOT from Austria!
I think the WRITE_BUFFER subroutine needs to be something like this pseudo-code: if (WRITE_PTR == 0xFF) && (READ_PTR == 0) { // fail } else if (WRITE_PTR == READ_PTR-1) { // fail } else { *(WRITE_PTR)++ = Acc // the 6502 Accumulator } This way, the write pointer doesn’t overrun the read pointer. Here, “fail” could simply be an RTS, or maybe a JMP to some routine in the kernel ROM to “dump core”. Maybe it could even send the character (0x07) to beep the speaker locally, or at the terminal. This way, if a running program isn’t expecting input, but the user falls asleep on their keyboard (ouch), it’ll beep at them until they wake up. 😀 Heck, it could just clear the buffer and drop back into Wozmon.
Here is a suggestion for you: The computer runs on programs uploaded directly to the EEPROM. So, if you give the computer video capability, then add a couple buttons as inputs, you can use the computer as a video game console if you upload the correct program to the EEPROM. Electronics are fun!
I mean surely we can't be too far away from the day when he starts a video with: "so I've hacked into the pentagon from my homemade breadboard computer"
I tried to make an input buffer for midi on a cyclone4 board not using altera(at the time) specific code but eventually did that anyway because it kind of just worked perfectly..
300 baud? Such a speed demon. The ASR 33 ran at 110 baud and we liked it. And even then, if it was being used as a printer as well as a keyboard, NULS needed to be sent as padding after lengthy operations such as carriage return and line feed.
I keep wondering if this is going to lead to you converting the bread board to a circuit board. For that matter, will you test keyboard input with a bread board keyboard?
I'm really enjoying this series; it's reminding me a lot of my HW & SW hacking days in the 80s! I'm curious to see how you react when you discover that CTRL+C no longer works while a Basic program is running. ;) Also, you need to implement CTS/RTS handshaking, which would've eliminated the (original) need for the input buffer. You also need to implement error handling for when the buffer overflows.
I got confused for a moment a couple times with WRITE_PTR and READ_PTR because despite being called pointers, they are actually just offsets. Otherwise, great edutainment.
Ben's videos on logic circuits certainly helped me study for some of my classes! Though I will say that I've learned more from watching his videos about how computers work than I have from classes. Your mileage may vary but my classes were mostly separate EE and CS classes, with only 1 or 2 having combined the two fields.
Ben you lovely person. It might be useful to take a moment and side track to running these same programs on a qemu, that might enable the studious to follow along with the assembly dev even if they don't have a hand crafted computer in front of them
12:13 phx phy? Are they legal 6502 opcodes or compiler marcos? Because i was raised in PHA; TXA; PHA; (interrupt service routine); PLA;TAX;PLA;RTI fashion.
@@fatemonkeysigh, me being old fart be like ;P thanks! actually WDC gave handful of new toys to programmers without extra cost if not cheaper (phx takes same 3 cycles as pha and one doesn't have to bother transferring X->A), neat.
There is an error in the buffer_size routine. If you initialize the two pointers to 0 the routine should return 0. The routine is subtracting two pointers plus the carry. It will return 255 instead of 0. The routine should clear the carry before the subtraction.
From 6502 instruction set documentation: "for subtractions, which are just an addition using the inverse of the operand (complement value of the operand), the role of the carry is inverted, as well." ;SBC: A = A - M - C̅ ("C̅": "not carry") Subtraction is done via two's complement which is inverting the operand and adding 1. That's why carry bit needs to be set in subtraction. What 6502 is doing is just adding the A register to the two's complement (the inverted operand plus the carry bit).
I wonder if Mr. Eater would be more efficient without the code completion running. He never seems to use it (except at 11:34), but it must be distracting to have the choices pop up.
I thought that, too, but the handler is so much faster than what the UART is doing that there's no chance of another character arriving before the interrupt completes. Ben doesn't state it outright, but he alludes to it when he talks about how many cycles the interrupt handler takes.
I like the way u just start the video without intro.
I wish all creators had no intro ... I habitually skip the intro so it might as well not be there.
Me too❤
I believe if you watch one of his playlist it's literally like one just giant video. Proof that Les is more.
@@johngrider737 sponsorblock has a very specific category for that. I can't live without sponsorblock browser extension now
Something something no foreplay
I think we would all LOVE for you to interview Steve Wozniak, from a technical standpoint. All the interviews ive seen with him are just people asking him about Steve Jobs but I think hearing you ask technical questions to him would be so fascinating. Especially someone like you who clearly appreciates the things he made.
Im am sure Steve Wozniak would do this. Someone just show Ben's work to him and let that happen !!
I would love to see this happen
It has all been covered... in nauseating detail.
Whenever Woz is on camera the audience is forced to stare into his gaping, upturned nostrils.
@@user-ym4xy6us5e Keep your fetishes to yourself, please.
7:53 i love this 80s programmer mindset "we could save a byte".
Next up: we could save a nibble by reusing least significant bits there ^^
Also have to save every clock cycle, 10% of the CPU's performance is spent reading a character from the buffer!
@@axelBr1that’s not what Ben meant.
He meant that at the transmission rate of the serial connection, it can process the character in 10% of the time it takes to transmit a single character.
i.e. it takes 500us to transmit a character over serial, the computer can read and store that character in 50us.
The total “CPU time” (i.e. what the % utilization is) is much lower, as that is the proportion of microseconds used / second reported as a percentage.
It’s much closer to 0.005% CPU utilization to read a character! (Assuming it takes 50us to read and store a char)
@@Comeyd I want back and checked what Ben said, and he did say that the processor will spend about 10% of its time in the interrupt handler. Great catch that what Ben calculated was that only 10% of the time to send the character was spent in the interrupt handler and only 0.005% of the actual CPU time was spent in the interrupt handler.
Well, it’s kind of funny considering that he doesn’t inline INIT_BUFFER or WRITE_BUFFER which would save two instruction each.
It was a stroke of genius when he observed that the circular buffer's write pointer's value didn't matter as long as it was set the same as the read pointer's value, and therefore didn't require initialization.
In the early 80s I programmed an RCA 1802 in assembly language with 20k of CMOS RAM to buffer incoming data at 19.2k and stream it through a 300 baud modem to a remote printer. The circular buffer in this case was a 16k memory board, which cost $1,100 and drew 5 mA at 5 volts. The data was coming in slowly enough that a simple software poll was adequate, no interrupts were needed. That was a fun project! Thanks for your videos Ben!
Cathode Ray Dude will be so happy that the Eater homebrew computer can keep up with his machine-gun typing now
Ben Eater is one of the best sources for learning about all sorts of low level stuff, I mean I can barely find anyone else coding firmware for its educational value, and i've been looking, i love this stuff.
I’ve learned more from Ben’s videos than I did from my CS major.
Thanks Ben!
Ben is a great teacher.
He's great but that can't possibly be true lol
@@uwirl4338Oh, I think it can be.
Maybe they were busy partying or slacking off@@uwirl4338
I never before realized what a vim god you were as i did not know much of vim, but now i see how efficiently you are moving and deleting stuff
You should watch theprimeagen. He does everything in vim
he’s actually intentionally slowing himself down and using very few Vim features, because it would be too disorienting for anyone to watch otherwise!
Yeah, you don't wanna watch William Lin @@krallja
Vim is awesome! Learning at least vim motions inside your editor of choice is super useful. It took me about 6-12 months to get really comfortable with nvim but it’s totally worth it. Editing is way quicker.
Crazy timing! I just got my version of 6502 up and running just about 10 minutes before this video came out. 55 year old nerd giggling like a school girl after seeing that first "\" pop up in my terminal!! Just a CPU, RAM, EEPROM and 6551. I wrote a relocated wozmon code so I can copy it from ROM to RAM and run the wozmon out of RAM so I can edit the EEPROM in circuit. No more wrestling with arduino programmers. Thanks for the very clear explanations in all your videos.
At 7:53 you could have saved a register modification by storing whatever was already in the A register into READ_PTR. It would also make the program a little more deterministic, and allow the caller to specify a value for A, if it wanted.
But, he did?
@@der.SchtefanHe did `lda READ_PTR, sta WRITE_PTR, rts`.
I mean `sta READ_PTR, sta WRITE_PTR, rts `.
Yup, and his interrupt routine isn't quite correct. Namely, the P register needs to be saved and restored. As things stand, he has a rather nasty unpredictable intermittent bug there. For instance, if the interrupt occurs immediately after a compare, but before a conditional branch that depends upon the result of that compare.
I’m pretty sure that the CPU’s control logic pushes the status register to the stack before jumping to the interrupt vector. Then RTI will pop it from the stack. That’s the difference between RTS and RTI.
@@bradywb98 Yep. I forgot about that little detail and was just about to check the instruction set when I noticed your response. A little niggling memory was bothering me about the BRK instruction. Was thinking it used the hardware interrupt vector, yet the interrupt handler could distinguish BRK from an actual hardware interrupt by some means. Turns out to be bit 4 of the saved status register. And my quick check revealed another trap averted by the 65C02, it clears the decimal flag during interrupts unlike the 6502 which leaves it intact.
You are bringing me back some odd 25 years in the past, when I was learning assembly and interrupt handling with a 6809 platform!
Thank you for this!
(13:33) If I did my cycle counting correctly, the interrupt handler takes 53 cycles to execute, but if you include the "context switch" to get from program code to the interrupt handler, it ends up working out to _exactly_ 60 cycles (assuming the interrupt happens between instructions).
(15:36) The BUFFER_SIZE routine doesn't modify X, so you can move the PHX instruction down to right before calling READ_BUFFER and get rid of the PLX insruction on the no_keypressed path.
you don't knonw how much we appreciate your content!
Circular buffer implementation in assembly! Feeling so nostalgic. Thanks for the video Ben. Please keep it going.
In CHRIN you could only push x once you know you have to read a character from the buffer. This will save 1 byte again. Since you are already optimizing for size (7:53).
You are right. BUFFER_SIZE does not modify X, so pushing is only required before READ_BUFFER. Therefore no pulling from the stack is necessary in @no_keypressed (15:32)
Thank you Mr. Eater, for gracing us with another flawless performance. You have such a thorough grasp of the subject matter that you're effectively leading us on a choreographed dance from problem through to solution.
For those who know, when Ben pushes the registers to the stack before jumping into a subroutine, why do that outside of the subroutine? Why not push at the start of the subroutine and pop at the end?
Else, should you want to call that subroutine elsewhere, you have to remember to push and pop there also.
It's the calling convention. If you want a faster calling convention, then use registers, but most software isn't setup for that on 6502's, so only use it in your own code. However, the reason that you can't push inside the function is because the arguments could be stored anywhere by the user and the function doesn't know where to push them from, but more importantly, if they're already in registers then it makes more sense to just use them as registers.
It's a choice. Saving outside means you can choose to only save once while calling several routines that clobber the same registers, or choose not to save at all since you're in a region the value is not needed.
What 0LoneTech said, if you push and pull from within the subroutine you end up doing it more often than necessary, say e.g. you call the same subroutine 50 times in a loop you end up pushing and pulling 50 times as well, while pushing and pulling once would have been enough.
@@anon_y_moussethat wasn’t the question
@@wich1 Since you're clearly not a programmer, go ahead and ask what you need clarified.
Thank you Ben. Your videos are invaluable to anyone trying to develop at the circuit level.
Just prior to 7:50, I was thinking "Why are you setting A to zero? You don't need to do that."
And he immediately got rid of that statement. Then he did the rather foolish thing of loading A with whatever random value was in the read pointer. He didn't need to do that. Just store whatever random value is in A into both the read and write pointers. Has the nice side effect of not altering A either.
14:00 LDA changes the status register as well, so you need PHP PLP to save that as well.
No need for pushing status register on the stack during irq. The CPU does that by itself.
@@Farull I realized that about an hour after commenting. Perhaps I was thinking about a Z80.
I love your stuff. I write bare metal C on various 8-bit AVR processors and seeing everything at such a low level really helps me with not just optimization but also understanding the how and why. I feel that's the more important part, and I thank you for it.
Oh, I can only imagine being back in university and having someone like you as a professor in engineering classes. Given how few people understand the concepts you touch upon, you have certainly made quite a name for yourself.
I speak not only of this video, but everything you have produced. People like you ( the hardcore engineers), define our world...with or without the people in suits watching over your shoulder...
It's always insane how you make it seem like you do these without planning in the first take, especially if you seemingly run into typical errors anyone following could run into instead of just doing it perfectly the first time.
That's the most impressive part to me. I get confused as hell if I have more than one buffer open. I only just figured out how to change my indent tab/space settings for e.g. Makefiles and I felt so accomplished.
That's what years of experience brings!
And he seemed to understand and fix problems quickly too, like that spurious interrupts from floating input pins. A newbie would have taken a long time to figure that thing out.
Frankly, the ability to pull out an exact-length, carefully and perfectly bent breadboard wire from the drawer instantly is more shocking to me. The permutations and combinations of lengths, bends, and colours is mind boggling.
😅
Nothing like a Saturday morning with Ben!
DId a fair amount of 'slow' serial communication and data transfers. Looking forward to watching you get the 'flow control' aspect working (pause incoming data when your input-buffer is full).
Then we can talk about putting in pauses to resync the serial clocking between your transmitting program and the 6502 (i.e. ala Kermit or other data transfer protocol). :)
Love your videos, great discussions.
Replace "full" with "nearly full". Assuming that something like XON/XOFF is used for handshaking, you need to allow for any data already in transit to arrive before the sender can stop transmitting.
Started watching you back in high school when you built your own gpu. Kept on watchin even though I didn't understand much. Feels so good to come back and rewatch some of the stuff after getting my EE bachelor and getting a job in embedded engineering. Great review of core concepts used in microprocessors. Thanks for reigniting my love for programming/engineering and keeping me interested through the years ❤❤
Always a good day when there's a Ben Eater video!
I literally just finished watching the Wozmon videos when this dropped. Perfect timing.
Am I right in assuming since the read and write pointers must only be identical, leaving the code as it was at 7:55 would also work, (STA READ_PTR / STA WRITE_PTR) , because the same value is still written to both pointers. The values of both pointers would inherit A's previous value rather than that at READ_PTR. There's no performance difference because LDA and STA for zero page addressing mode are both 3 clocks.
There is a higher abstraction reason to prefer one over the other: using A in a subroutine implies to readers of the code, and some static analysis tools, that the subroutine depends meaningfully on the value of A which imposes some theoretical obligation at the call sites. It's arguable that reading A has a lower impact than clobbering it. In Ben's version, both A and the status register are modified by LDA. STA does not modify any registers.
If performance was critical, it seems preferable to make the INIT_BUFFER routine into a macro to avoid the cycle overhead of JSR/RTS . Not clobbering A would also make such a macro more usable. I'm guessing it would also use less memory in practice although I haven't done the calculation.
I love your content, and have been watching since forever ago. But truly, I cannot stress this enough, I got it all, it all clicked, the moment I started toying around with a commodore 64(Emulator or similarly structured system I recommend too). It's old and slow, yes, even frustrating to use at some points, but I KNOW my keyboard buffer, understand it and take it into account after some extensive use of such a barebones sistem. This goes for the general memory map, significant bits in memory and what to flip them to, as well as charsets pointers, etc. I really recommend the experience for other people interested in this field, it make each and everyone of your videos that much more informative and entertaining.
(ALSO, as a bonus for the logic aspect of computing, I recommend reasing about multiplexors and demultiplexors, I mean, the theory behind logical sistems, I've truly come to love computing a lot more through a more educated lense, even from an amateurish understanding atm)
Lot's of love from Spain! :3
Incredible clarity
NEW VID UPLOADED. THE TIME HAS COME !!
My life only exists in the few minutes before, during, and right after I watch a new video upload. Everything else is irrelevant.
I chuckle every time I see your Dynex RS232 dongle. Can't be many of us rocking those.
I work developing electronic products.
We still to this day program MCUs in Assembly, as this allows to save huge in MCU pricing, because we can squeeze the maximum from the speed, the memory and processor capacity from a cheaper controller.
The fun part is that some of my codes do implement circular buffer, but without any separated memory or processor managing it.
I simply do it internally, so I can simply stack up the received data in the time of interrupt, and the rest of the process will get back to roll as fast as a single clock pulse.
And so, when the time to process arrive, the program will roll the buffer and do whatever it gotta do, without spending a bit to additional interrupt coding.
Seems like too much work, but my client managed to save millions of dollars last year, just because of this very optimized way of development.
Time to drop everything
Well I'll be damned! I got it working. Took me a while to figure out how to run the .sh file in Windows. Also had to learn a lot about paths. Backspace doesn't work like it does in other programs. I get syntax errors if I use it. Don't really know how to use basic, but it does work finally.
Great video.... just a small point. You said it yourself in the commentary, read_ptr and write_ptr are offsets, so maybe read_ofs, write_ofs. The base address of the buffer would be a pointer, base+offset is also a pointer, but personally I would not call an offset a pointer as it confuses. Nice work though, I did appreciate it.
They're also array indices. The choice of words is pretty free here; they are indeed pointers within a page, just like the stack pointer.
@@0LoneTech A stack pointer would be base+offset as I described. But an array index is not itself a pointer as it needs the offset (base) added to it before it becomes an address. We could argue forever over this one, but the modern accepted use of pointer is that it is something containing an address in the machines native word format rather than any kind of offset. If you include indexes and offsets then almost everything would qualify as a pointer, hence my comment "as it confuses". This is why programming books use "index" for offsets and pointer to describe memory references to clarify the distinction. On modern CPU even address gets vague though, hence being a topic that could argued forever!
@@jonshouse1 Go argue with the datasheet. This is on the world's most famous 8 bit CPU; its native word size is 8 bits.
@@0LoneTech I did not say "word size", but "native word format" - if you want to be pedant I guess "native address format", but as I said even "address" gets fuzzy on newer architectures, hence a "topic that could be argued forever", as you so kindly seem keen to demonstrate.
I knew immediately that you should have sent a command to the UART to disable all interrupt requests apart from RBF (Receive Buffer Full) so that nothing else would trigger an interrupt. (So far as I remember, you can do that with the UART so that you don't have to bother figuring out what part of the UART caused the interrupt).
I like how you leave your errors in since it helps us to learn "what to watch out for" if we want to do something similar. In this case, I knew what needed to be done, but I've found a lot of your videos informative and learned several things from them.
You have awakened in me something that has been dormant for 30 years. TY
If university was a man he would be called BEN EATER❤.
THANKS FOR
THE EFFORT YOU PUT IN TO TEACH US
When watching one of Ben's videos, I feel like he is speaking a completely different language that I somehow understand, but don't remember learning.
A new video already
March is already a great month
Now to spend 3 days trying and failing to understand this
Me: sad
Ben: posts a video
Me:happy
I've hit those problems when interfacing to other people's embedded systems. My Atmel AVR could easily handle 115200 in both directions, but the other system needed a full mS inbetween chars at 9600, and I've always done my serial exactly as you describe. The key to interrupts is to do absolutely as little as possible in the ISR and get out! I've seen people write an ISR with pages and pages of code, interpreting the string IN THE ISR!! (head.. desk..) I also reserve a byte for counting the chars in the buffer, but I just inc it in the rx char ISR, and dec it when I take a char from the buffer.
+1 on using a buffer size which is a binary multiple as well. Then overflow is handled by masking rather than calculation.
I wouldn't call any routines from the ISR though, the call and return wastes time.
When I init the buffers, I take the time to fill the buffer with something like 'A' or whatever so I can easily see where it is when debugging with an ICE.
Very well done!
Thank you Mr. Eater. Seriously.
You're one of the best teachers i have ever know in my life
Thank you Ben for another awesome video ❤
Your vidoes are very inspiring! I built my own 8-bit computer back then and I now extended it with a serial module and got Wozmon running on it 😁
Which MacOS serial terminal program is that? I like the "Pacing" option. (Thanks Ben for this series, it's fun!)
+1
I think it's "Serial"
Fabulous stuff.
One thought - it's been a loooong while since I've done any assembly programming. My habit at the time was for subroutines that modified registers to save those registers for me. Move the push/pops to the beginning/end of the routines themselves as opposed to having the caller have to accommodate. I noticed a couple of places where you used your new buffer routines that you said "have to remember to save X." What do you think?
This comes down to a balance between style and efficiency. Most ABIs include registers that must be saved and those that will be modified. Since a 6502 has so few registers and performance is more critical, I think that uniform register spill and load requirements would be too costly, both in terms of CPU overhead and in terms of ROM space.
A comment is probably more instructive, and it may save a push or pop, since the caller is free to manipulate spills or loads to avoid them.
It's either software flow control or hardware flow control up in the next video ;-)
Yup, looking forward to that! ;) Then some discussion about async clocks getting out of phase and resyncing periodically with tx breaks.
@@mikefochtman7164eh, I it is already async communication...?
@@maxaafbackname5562Yes, I'm aware of that. But if you try to send several hundred bytes of data all in one lump, the xmit clock and the rcv clock often 'drift' apart a bit over such a long transmission. This means the rcv starts to 'sample' each bit at the wrong time and you get garbage. How much data you can successfully xmit depends on the accuracy of the two clocks and how long they can free-run without losing sync.
Async communication has to periodically have a pause, so the rcv can reset itself and start it's clock/ sampling on the 'start bit'. With a continuous stream of bits, it can't do that.
Hence the old protocols of xmitting data like Kermit that broke up the data into 'blocks' with a short (about 10 bit times) of no data. Sometimes referred to sending a 'transmit break'.
Been there, done that. ;)
@@maxaafbackname5562 Indeed, synchronized by the start bit. Any character length gap will do to resynchronize if the receiver somehow started out of phase with a continuous input stream, but break is meant for lost connections.
Love your videos
Every day there's a new ben eater video, it's a good day.
This is so interesting! I did this just a couple of days ago for a class!
Basic did not have to have line numbers. Microsoft "GW-BASIC" required line numbers. Other versions of Basic did not require line numbers.
I would love to see a video on the 6532 RIOT next!!
After this video all my inputs will be buff AF.
Kiitos!
I've learn a lot from you. Thanks for sharing all you do
We missed you Ben eater😢
Thank you, for your accuracy and brief communication.
Ben! Where are you!
Missing your new premium deluxe brain-fuxx videos!
IT-basics, cpu, bus, no caching, no pipeline, all that, thanks to you I got an idea what the basics are.
Thanks a LOT from Austria!
I think the WRITE_BUFFER subroutine needs to be something like this pseudo-code:
if (WRITE_PTR == 0xFF) && (READ_PTR == 0) {
// fail
}
else if (WRITE_PTR == READ_PTR-1) {
// fail
}
else {
*(WRITE_PTR)++ = Acc // the 6502 Accumulator
}
This way, the write pointer doesn’t overrun the read pointer. Here, “fail” could simply be an RTS, or maybe a JMP to some routine in the kernel ROM to “dump core”. Maybe it could even send the character (0x07) to beep the speaker locally, or at the terminal. This way, if a running program isn’t expecting input, but the user falls asleep on their keyboard (ouch), it’ll beep at them until they wake up. 😀 Heck, it could just clear the buffer and drop back into Wozmon.
Nice video, as usual.
Just a little reminder: The interrupt handler should also deal with the BRK instruction...
He's back! It's a great day when he uploads a new video!
Here is a suggestion for you:
The computer runs on programs uploaded directly to the EEPROM. So, if you give the computer video capability, then add a couple buttons as inputs, you can use the computer as a video game console if you upload the correct program to the EEPROM. Electronics are fun!
Hello new addiction
I mean surely we can't be too far away from the day when he starts a video with:
"so I've hacked into the pentagon from my homemade breadboard computer"
Artificially slowing output... perhaps microsoft BASIC is too powerful.
😂😂😂
I tried to make an input buffer for midi on a cyclone4 board not using altera(at the time) specific code but eventually did that anyway because it kind of just worked perfectly..
Motion to award Ben an Honoris Causa PhD in Computer Science
great video as always!
Ben you’re incredible. Thanks!!!!
It’s a good day when ben uploads
*notification that Ben Eater posted a new video, immediately clicks* We love your videos Ben, keep them coming.
Nice! I hope the next video will be about race conditions :D
In the old days, 300baud hid all these problems. Still works today.
300 baud? Such a speed demon. The ASR 33 ran at 110 baud and we liked it. And even then, if it was being used as a printer as well as a keyboard, NULS needed to be sent as padding after lengthy operations such as carriage return and line feed.
17:43 after realising spurious interrupts were being generated: NNNNNNNNNNNNNOOOOOOOOOOOOOOOO!!!!!!!!!!!!!!
I keep wondering if this is going to lead to you converting the bread board to a circuit board. For that matter, will you test keyboard input with a bread board keyboard?
i did that. i could never get breadboards to work. one loose connection and it doesn't work. maddening!
I'm really enjoying this series; it's reminding me a lot of my HW & SW hacking days in the 80s!
I'm curious to see how you react when you discover that CTRL+C no longer works while a Basic program is running. ;)
Also, you need to implement CTS/RTS handshaking, which would've eliminated the (original) need for the input buffer.
You also need to implement error handling for when the buffer overflows.
Love these videos
I got confused for a moment a couple times with WRITE_PTR and READ_PTR because despite being called pointers, they are actually just offsets. Otherwise, great edutainment.
I might just go back to college and get a computer engineering degree. I enjoy this channel too much.
Ben's videos on logic circuits certainly helped me study for some of my classes! Though I will say that I've learned more from watching his videos about how computers work than I have from classes. Your mileage may vary but my classes were mostly separate EE and CS classes, with only 1 or 2 having combined the two fields.
Thanks for sharing!
Absolutely neat.
Mesmerizing
That's really cool, You code in Assembly flawlessly which is not the case for me.
I thought you stopped to make videos about computers... you are cool dude😊
Thanks for the interesting content!
Ben you lovely person. It might be useful to take a moment and side track to running these same programs on a qemu, that might enable the studious to follow along with the assembly dev even if they don't have a hand crafted computer in front of them
12:13 phx phy? Are they legal 6502 opcodes or compiler marcos? Because i was raised in PHA; TXA; PHA; (interrupt service routine); PLA;TAX;PLA;RTI fashion.
This is a Western Design Center 65c02, which has those instructions natively.
@@fatemonkeysigh, me being old fart be like ;P thanks! actually WDC gave handful of new toys to programmers without extra cost if not cheaper (phx takes same 3 cycles as pha and one doesn't have to bother transferring X->A), neat.
Sounds good!
Omg my day just got better 🙏🙏🙏🙏🙏🙏🙏
There is an error in the buffer_size routine. If you initialize the two pointers to 0 the routine should return 0. The routine is subtracting two pointers plus the carry. It will return 255 instead of 0. The routine should clear the carry before the subtraction.
From 6502 instruction set documentation: "for subtractions, which are
just an addition using the inverse of the operand (complement value of the operand),
the role of the carry is inverted, as well." ;SBC: A = A - M - C̅ ("C̅": "not carry")
Subtraction is done via two's complement which is inverting the operand and adding 1. That's why carry bit needs to be set in subtraction. What 6502 is doing is just adding the A register to the two's complement (the inverted operand plus the carry bit).
I wonder if Mr. Eater would be more efficient without the code completion running. He never seems to use it (except at 11:34), but it must be distracting to have the choices pop up.
As usual very good video
nothing is better than after a hard day seeing ben eater upload a new video.
❤Love that typeface
Just a dumb quick thought, but could you theoretically write a simple HTTP server running on that breadboard computer?
Shouldn't you use a SEI at the start of your interrupt handler and a CLI before leaving the handler?
I thought that, too, but the handler is so much faster than what the UART is doing that there's no chance of another character arriving before the interrupt completes. Ben doesn't state it outright, but he alludes to it when he talks about how many cycles the interrupt handler takes.
This is handled automatically, by the interrupt mechanism itself and the RTI instruction. Interrupt handler routines by default cannot nest.
nice job