How do hardware timers work?

  Переглядів 958,276

Ben Eater

Ben Eater

2 роки тому

In this video, learn how a CPU uses hardware timers to control execution timing.
More 6502 stuff: eater.net/6502
Support these videos on Patreon: / beneater or eater.net/support for other ways to support.
------------------
Social media:
Website: www.eater.net
Twitter: / ben_eater
Patreon: / beneater
Reddit: / beneater
Special thanks to these supporters for making this video possible:
Aleksey Smolenchuk, Anders Carlsson, Andrew C. Young, Anson VanDoren, Anthanasius, anula, Armin Brauns, Ben, Ben Cochran, Ben Kamens, Ben Williams, Benny Olsson, Bill Cooksey, Binh Tran, Bouke Groenescheij, Bradley Pirtle, Bradley Stach, Bryan Brickman, Burt Humburg, Carlos Ambrozak, Chris, Christian Carter, Christopher Blackmon, Dale Andrew Darling, Daniel Jeppsson, Daniel Tang, Dave Burley, Dave Walter, David Clark, David Cox, David Dawkins, David House, David Sastre Medina, David Turner, David Worsham, Dean Bevan, Dean Winger, Dilip Gowda, Dissy, dko, Dmitry Guyvoronsky, Dušan Dželebdžić, Dzevad Trumic, Emilio Mendoza, Eric Dynowski, Erik Broeders, Eugene Bulkin, Evan Thayer, Eveli László, fisksvett, fxshlein, George Miroshnykov, Harry McDow, hotwire33, Ingo Eble, Ivan Sorokin, James Capuder, james schaefer, Jared Dziedzic, Jason DeStefano, JavaXP, Jaxon Ketterman, Jay Binks, Jayne Gabriele, Jeremy, Jeremy Cole, Jesse Miller, Jim Kelly, Jim Knowler, Jim Van Meggelen, Joe Beda, Joe OConnor, Joe Pregracke, Joel Miller, John Fenwick, John Hamberger jn., John Meade, Jon Dugan, Jonn Miller, Joseph Portaro, Joshua King, Jurģis Brigmanis, Kai Wells, Kefen, Kenneth Christensen, Kitick, Koreo, Lambda GPU Workstations, Larry, László Bácsi, Lucky Resistor, Lukasz Pacholik, Marcos Fujisawa, Marcus Classon, Mark Day, Marko Clemente, Martin Noble, Martin Roth, Mats Fredriksson, Matt Krueger, Matthäus Pawelczyk, Matthew Duphily, Max Gawletta, Maxim Hansen, melvin2001, Michael Tedder, Michael Timbrook, Michael Weitman, Miguel Ríos, mikebad, Mikel Lindsaar, Miles Macchiaroli, Muqeet Mujahid, My Yiddishe Mama, Nicholas Counts, Nicholas Moresco, Nick Chapman, Not Yet Wise, Örn Arnarson, Paul Pluzhnikov, Paul Randal, Pete Dietl, Phil Dennis, Philip Hofstetter, Phillip Glau, PixelSergey, Porus, ProgrammerDor, Randal Masutani, Randy True, raoulvp, Renaldas Zioma, Ric King, Richard Butler-Malone, Richard Ertel, Rick Hennigan, Robert Comyn, Robert Diaz, Robey Pointer, §çīŤøşHï ŇåĶąýŐbŕÔ, Scott Holmes, Sean Patrick O’Brien, Sergey Kruk, SonOfSofaman, Stefan Nesinger, Stefanus Du Toit, Stephen, Stephen Kovalcik, Stephen Riley, Stephen Smithstone, Steve Jones, Tayler Porter, TheWebMachine, Thomas Bruggink, Thomas Eriksen, Thomas Rolfs, Tim Walkowski, Tom, Tom Yedwab, Tommaso Palmieri, Tyler Latham, Vincent Bernat, Walter Montalvo, Warren Miller, William, Wim Coekaerts, Wraithan McCarroll, xisente, Yee Lam Wan

КОМЕНТАРІ: 1 000
@hashtagPoundsign
@hashtagPoundsign 2 роки тому
Given the lack of activity from Ben there are two explanations: 1. Off camera events have taken priority. 2. Ben set a sleep timer on himself and misplaced the decimal. Either way it may be a while before an update.
@BjornHarrier
@BjornHarrier Рік тому
My hope is that he's planning another series and product suite, perhaps on another architecture or something and is busy doing research for that project. When he's done, he will shower us with videos and have another project ready for us to buy from his site.
@danman32
@danman32 Рік тому
Yep, like a series on 8088. Another UKposts channel started one, but he stalled too. I've still been messing with the 8 bit CPU on BB, expanded it to 256 bytes as many have, and some other enhancements.
@mashrien
@mashrien Рік тому
I'm terrified he caught the 'rona and didn't survive it :(
@ShawnC22002
@ShawnC22002 Рік тому
@@mashrien I hope that is not the case but I was wondering the same.
@Learning_Daily
@Learning_Daily Рік тому
@@ShawnC22002 ben's github did show activity in July, so that might be a sign of life.
@XenoTravis
@XenoTravis 2 роки тому
This is why breadboard computers should be more common in colleges. The simple questions are overlooked with the abstraction we have added.
@kilrahvp
@kilrahvp 2 роки тому
When I was taught that stuff in school in the early 2000s we were using 8051 microcontollers, so everything in one chip... worked, but obviously you don't get to see and poke the internals. Then at the end of the year we had to inventory the lab and I came across the tool from the 80s they were using before they moved to that, and it was a delightful single board computer running around a 6809, a monitor ROM, some battery-backed RAM, both a 6321 and 6522 and a keypad and LCD, and it was so much more fun having access to the chips and being able to enter your code directly on the machine and run it that I borrowed it for the summer holidays and played a ton with it. Ended up being able to keep one when leaving that school, still have it of course, and the 34 year old battery is still faithfully keeping those RAM contents.
@ShALLaX
@ShALLaX 2 роки тому
This is absolutely right. I don’t think any software developers with whom I work these days grasps the technology at this low level. It explains a lot about the performance of modern systems.
@dubbynelson
@dubbynelson 2 роки тому
I wanna know where the hell I could go to study this kind of low-level computing stuff. I'm so sick of all of this needless abstraction.
@delphicdescant
@delphicdescant 2 роки тому
​@@dubbynelson Electrical engineering is a little too low level, and computer science is a little too high level, but there is sometimes a major offered in universities called "computer engineering" that is halfway in-between. That seems like the most likely field to touch on this in my experience. Although I think that in both EE and CS departments, there are often elective 400 or 500-level classes offered that will go in this direction, so it's probably not necessary to center an entire major degree around it.
@nickwilson3499
@nickwilson3499 2 роки тому
@@delphicdescant to be fair, today it’s not really that useful to know this stuff these days. For the average software related job today you’ll never use any of this information
@RandallStephens397
@RandallStephens397 2 роки тому
I love everything about this series. I'm eagerly awaiting the point where Ben eventually builds a C compiler for the breadboard 6502.
@sadhlife
@sadhlife 2 роки тому
You'd love the book "Assembly language step-by-step" by Jeff D. It does exactly this
@ElSenorEls
@ElSenorEls 2 роки тому
@@sadhlife it is not the same thing. It has to be done by Ben.
@fathomisticfantasy2681
@fathomisticfantasy2681 2 роки тому
@@sadhlife if not then thanks for the link. I will be looking into it. Thanks for adding to the YT conversation.
@seekingthelovethatgodmeans7648
@seekingthelovethatgodmeans7648 2 роки тому
@@ElSenorEls Well, not everything has to be from scratch. Ben might be able to demonstrate an integration of existing freeware into his machine in such a way that one can readily duplicate it.
@chiblast100x
@chiblast100x 2 роки тому
Do you mean a C compiler that runs on the breadboard 6502 or a C compiler that merely targets the breadboard 6502? While I get that compiling C on the machine that targets itself would be a really solid learning experience in many ways, especially if it's capable of self compiling, there are a lot of reasons most consumer level computers using 8-bit processors defaulted to an off the shelf Basic interpreter within such constraints and many of those would equally apply to a project like this.
@GuildOfCalamity
@GuildOfCalamity 2 роки тому
If Armageddon happens, we will only need Ben to bring us back to the future.
@jeremiahbroccante
@jeremiahbroccante 2 роки тому
Ben is the Foundation!
@Scrogan
@Scrogan 2 роки тому
Hope you stockpiled on milspec radiation hardened 6502s!
@khatharrmalkavian3306
@khatharrmalkavian3306 2 роки тому
Primitive Technology can make the transistors from mud and pineapples.
@Aragubas
@Aragubas 2 роки тому
yes
@CMDRunematti
@CMDRunematti 2 роки тому
@@khatharrmalkavian3306 i mean sure we can joke about it, but let's take it seriously... Mud and pineapples, if they work as transistors, they would use a lot of power. We would need chipmakers along with Ben to get back to speed. And some electrical engineers to feed it power... Otherwise, i already learned so much from these videos I'm bloody stunned, how simple and yet how complicated a computer is
@invent0r137
@invent0r137 2 роки тому
I was literally just learning about AVR Timers. This video is perfect timing.
@dramforever
@dramforever 2 роки тому
"This video is perfect timing." I see what you did there
@rpeetz
@rpeetz 2 роки тому
time spent learning is time well spent am i right?
@el-hech2889
@el-hech2889 2 роки тому
God s plan
@maxlee3838
@maxlee3838 2 роки тому
Lots of overlap in concepts in how to configure the bits and check status bits between 6502 (a grandfather in many ways to modern microcontrollers) and AVR chips.
@alexanderiakimov482
@alexanderiakimov482 2 роки тому
What a time to be alive
@JiffyJames85
@JiffyJames85 2 роки тому
Sometimes, when I don't have an o-scope at hand, and I'm testing stuff like this, I like to use a speaker (with a resistor in line). After a while you can make pretty good guesses on order of magnitude of frequencies. In this case, it would sound a B on the far right end of a piano.
@SamVidovich
@SamVidovich 2 роки тому
Wicked cool
@myleslos9658
@myleslos9658 2 роки тому
You are one mad lad 💀💀😂😂
@420oppa69
@420oppa69 2 роки тому
i think you can build some synth modules like that
@heisenbug3542
@heisenbug3542 2 роки тому
You debug using hearing, instead of reading, or in case of diode, seeing. That's cool!
@JiffyJames85
@JiffyJames85 2 роки тому
@@heisenbug3542 it's not so much a choice as, "you use the tools you have"
@d1ngd0
@d1ngd0 2 роки тому
As a software engineer I really appreciate these videos. It makes things make so much more sense.
@infinitesimotel
@infinitesimotel Рік тому
The abstraction people get lost in things that are too removed from the reality of the cold dead machine.
@IRedBerryI
@IRedBerryI Рік тому
​@@infinitesimotel but arguably, each layer of abstraction you remove is a new layer of programming you can progress. If an AI engineer first had to learn basic breadboards, then machine code, then assembly, and so on further and further up the chain, it would take exponentially more time for each new progression.
@Jarikraider
@Jarikraider 4 місяці тому
When he said you can write a 'delay' subroutine with a bunch of nop's in it, I was like, "Please tell me that isn't how hardware timers work."
@deltakid0
@deltakid0 2 роки тому
Busy-Loop Delay 0:41 One-Shot Timer Mode 7:31 Free-Run Timer Mode 14:57
@TheKhalamar
@TheKhalamar 2 роки тому
The first method, depending on the processor speed, reminds me a lot of those games in the 80s that became impossible to play when you upgraded your computer to the latest 386 dx-33.
@JonJaques0
@JonJaques0 2 роки тому
This was one part I didn’t understand, isn’t the 2nd method still clock speed based? From previous context I know it’s running on 1mhz oscillator, so isn’t it technically a coincidence that 10k phi2 pulses = 10ms?
@willb.2800
@willb.2800 2 роки тому
@@JonJaques0 It is clock-dependent, but I'm pretty sure he intends to keep it at 1MHz (and anyway, there's no RTC so the clock is literally the only thing it can use to time).
@shaikhahmed7929
@shaikhahmed7929 2 роки тому
@@JonJaques0 Basically if your unit of time measurement is cpu cycles, it becomes clock speed dependent. The idea is to measure the time independently of cpu cycles. The Timer timeout implementation does exactly that.
@harrytsang1501
@harrytsang1501 2 роки тому
Same issue in video games. In-game physics sometimes use frames as the unit of time. Anything from Mario 64 to Mario Kart 8 only works right in 60fps.
@doctorbobstone
@doctorbobstone 2 роки тому
@@JonJaques0 Many systems specify the tick timer in real time (so here that might be a constant indicating 10 ms or, equivalently, 10,000 us, for example) or they give you constants for how many ticks their tick timer makes per second (so, 100 ticks per second here). There are other variations, but that's the idea. Given those tools, you can write your code to be portable because someone else did some or all of the work needed to figure out how to measure time portably. In situations where people are ignoring portability ("Everyone's got the same computer I do, right?") or at some points in the past when this type of thing may have been less common, people would often write things to only work on their hardware, causing the issues when you switch to new computers. Another issue might be in small systems where memory was tight and CPU time limited, it might be too hard (or at least perceived to be too hard) to make the code flexible and portable. So, basically, it *is* clock dependent, but with the right tools you can easily compensate.
@joiscode3832
@joiscode3832 2 роки тому
These vids are just amazing. UKposts doesnt have enough high quality highly technical videos that are relatively easy to understand for the average joe
@fghsgh
@fghsgh 2 роки тому
Note: in both the software timer at the beginning and the hardware timer (probably, depending on the datasheet, but most hardware timers are like this), you can set the counter value to 0 to loop 256 (software) or 65536 (hardware) times. This means you get one more counting value to use! This works because the loop checks for 0 _after_ decrementing, at which point it will already have overflowed.
@TheChrisey
@TheChrisey 2 роки тому
Almost every timer starts counting from 0. 1 extra count doesn't give much at all tho. The most practical function of modern timer peripherals are the prescalers that lets you divide the actual clock frequency, so the timer could go an X number of magnitudes slower than the CPU clock. I wish you could see the blueprints of the entire clock schematic for the current processor I'm working with. It's massive, and quite amazing tbh.
@fghsgh
@fghsgh 2 роки тому
@@TheChrisey Timers usually count _down_ just like assembly loops usually do. What I'm talking about here is just the technical inaccuracy that 255 isn't the highest value, 0 is, because it acts like 256. And don't worry. I am working on some comparatively massive and amazing stuff.
@TheChrisey
@TheChrisey 2 роки тому
@@fghsgh Timers can either count up or down, there is no standard. I always have mine count up for convenience. Obviously if you were to count down you would start at a larger value and auto reload at a lower one. Everyone knows that. I didn't see anywhere that the timer he used were by default counting down.
@fghsgh
@fghsgh 2 роки тому
@@TheChrisey 1. Counters are definitely easier to implement in hardware if you just have to check for zero than if you have to match against a specific value. 2. The assembly loop definitely works like this. It's obvious from the instructions he uses. 3. Given other details about the hardware timer he used, I suspect that one also counts down. And even if it were counting up, setting it to 0 would still count all the way to 65536, because there is just no reason to overcomplicate silicon logic, especially not in the 70s, when this chip was designed.
@allanrichardson3135
@allanrichardson3135 Рік тому
The instruction BCT/BCTR IN THE IBM mainframe similarly decrements a 32-bit register containing a 31-bit signed number in 2-s complement notation and tests for zero AFTER decrementing, branching if not yet zero. So if you put that into a loop, you can execute that loop the number of times you set in the register to before you start. But if you START at zero, you go through the loop 2^32 times, or about 4 billion (0 becomes -1, then -2, down through -2^31, then +2^32-1, 2^32-2, then down to 3, 2, 1, and 0 fails to branch and stops the loop). Even on a moderately fast mainframe this could take hours, even with the branch being back to itself in a one-instruction loop.
@MatkatMusic
@MatkatMusic 2 роки тому
everyone who writes any type of code really owes Dennis Ritchie a lot of gratitude. This syntax and how loops are written with it really makes one appreciate the for() and while() loops that came with the C language.
@SimonBuchanNz
@SimonBuchanNz 2 роки тому
Actually structured programming was well in vogue by the time C was developed. It wasn't the first, but ALGOL 58 probably was the most influence on control flow in languages, for example it had the rather gross syntax but very familiar logic of: for i := base(increment)limit begin ... end So you should probably direct your language design praise towards John Backus and Peter Naur, though Ritchie's work on C deserves a lot of praise for actually replacing the use of assembly due to C's efficiency.
@jaredteaches894
@jaredteaches894 2 роки тому
C was actually a continuation of the programming language, B.
@TheChrisey
@TheChrisey 2 роки тому
Wherever it came from.. Let's all just appreciate the existens of C overall. Without it, we would be sitting with ridiculous overly abstract syntax and begin...end...begin..end..begin..end that would make melting clocks look like a walk in the park.
@jaredteaches894
@jaredteaches894 2 роки тому
@@TheChrisey Well, to be pedantic, B did not follow that syntax. In fact, C was very similar to B and I'd probably confuse it with C at first glance. But yes, your sentiment is correct. C is a beautiful and simple language! Dennis Ritchie was a king!
@ddognine
@ddognine Рік тому
@@TheChrisey Let's not get carried away. It was well known by the early 60s that assembly was not the ideal solution for every situation. Something better was needed. That was 60 years ago! To say that we would be stuck with an overly abstract syntax were it not for C, is like saying humans are incapable of innovating. However, assembly still plays an important role in modern programming; not everything is written in C.
@x87alpha1
@x87alpha1 2 роки тому
Man if only every teacher in the world had this amazing ability to teach and keep you interested.
@markbenedict1295
@markbenedict1295 2 роки тому
Brought back some great memories. When I was going to Data Systems Technician school in the Navy in 1974, one of our machine language programming assignments was to turn the front panel registers on a Univac 1218 (clock speed 667Khz and no you did not read that wrong) into a digital clock. We had to do a lot of calculations on the time each op took to make the clock accurate.
@priyapepsi
@priyapepsi 2 роки тому
It must be so cool to know how to work with assembly and bare metal. I really want to learn assembly and c for the fun of it, but all I know is python and java
@godfreypoon5148
@godfreypoon5148 2 роки тому
@@priyapepsi Start with assembly on the simplest microcontroller you can find, and work your way up to C. That will give you a really sound base of understanding.
@TheChrisey
@TheChrisey 2 роки тому
@@priyapepsi No, you start with C, which is one single syntax regardless of platform. Once you've learned it, you move onto basic assembly on either an x86 or some ARM/AVR/Whatever MCU and work your way from there. You need to know that while C has its specific syntax. "Assembly" is not a syntax, but a way to turn actual numbers (opcodes) into readable commands, and every CPU architecture has its own set of commands. Hence why every architecture needs a specific compiler.
@garydunken7934
@garydunken7934 2 роки тому
Just woke up on a Sunday morning, made a coffee, turned on my computer and I saw a new video from Ben... awesome!
@TomOConnor-BlobOpera
@TomOConnor-BlobOpera 2 роки тому
Ahh! That HP calculator is beautiful. I rescued a similar, but financial one from the trash recently.
@SteeleDynamics
@SteeleDynamics 2 роки тому
I have a HP-15C from '84, but not a HP-16C. They're harder to find. I have a Swiss Micros 16C. Still really nice.
@OGBhyve
@OGBhyve 2 роки тому
You do such an incredible job explaining the assembly instructions as well as your reasoning!
@6wadekey372
@6wadekey372 2 роки тому
I'm so glad you gave the shot of the timer overflowing at the end
@ast_rsk
@ast_rsk Рік тому
This was infinitely more clear how to use the 65C22 timers and interrupts to utilize the cpu's total processing time than any other video I've watched. I feel like I'm 90% of the way there on being able to write a whole (simple) game or general application for this computer (my end goal after following along with this project).
@pattersonzak
@pattersonzak 2 роки тому
Always excited to see another video!
@emacmulle
@emacmulle 2 роки тому
Thanks for posting. Brought back memories of PDP and later 6502 assembly programming. I liked the way your video progressed in complexity, including the inevitable debugging.
@ShawnC22002
@ShawnC22002 Рік тому
I found this very interesting! I work in industrial automation, with PLCs and what not, and I’ve gotta say - These videos have increased my understanding of this hardware so much! Thank you for all of this!
@tobygrover1163
@tobygrover1163 2 роки тому
After watching a trillion youtube videos on various subjects, I believe this is my first post. I felt it necessary to let you know that you inspire me. Thank you for the information you give, and the way that you present it. I find it very easy to digest and grow my confidence and intuition, and let me know that things I once thought too hard or impossible, are actually quite achievable!!
@danny_racho
@danny_racho 2 роки тому
How does this guy know all these stuff? I mean, I studied electrical engineering and this is beyond what they teach you in just few years. He's software- as well as hardware-competent. My biggest idol, wish I can be this good one day in this field as you are
@pushing2throttles
@pushing2throttles 2 роки тому
Such a cool channel. Love how you correlate hardware with software and you really teach how one is married to the other.
@alexandermaasland3494
@alexandermaasland3494 2 роки тому
You have such an elegant way of making people understand what you are doing, my compliments! Looking forward to your next video(s) Ben!
@bobweiram6321
@bobweiram6321 2 роки тому
I would literally kill to have had this Ben as a professor! It's a crying shame academia is full of people who can't teach worth a damn.
@CraftMine1000
@CraftMine1000 2 роки тому
This, 100% this
@ldskjfhslkjdhflkjdhf
@ldskjfhslkjdhflkjdhf 2 роки тому
Literally?
@bobthecomputerguy
@bobthecomputerguy 2 роки тому
@@ldskjfhslkjdhflkjdhf If they allow you to watch youtube in prison, I don't see a problem.
@seekingthelovethatgodmeans7648
@seekingthelovethatgodmeans7648 2 роки тому
@@bobthecomputerguy grooooooooooooooooan
@Elite7555
@Elite7555 2 роки тому
Because for most professors, teaching stuff is more of a inconvenience; a distraction from their research.
@argoneum
@argoneum 2 роки тому
WDC W65C02S also has a WAI (wait for interrupt) instruction, so adding it in a loop decreases the power consumption. The tick values change after an interrupt was processed anyways. The beauty of it is that in other manufacturers 65C02 it is an "undocumented NOP", and on 65C816 it also is a WAI ☺
@vdubjunkie
@vdubjunkie 2 роки тому
I’ve taken the sleep routine for granted hundreds of times. Leave it to Ben to explain it in detail, and make it so interesting! Thanks, as always, for providing these videos to us!
@ilyadaemon
@ilyadaemon 2 роки тому
Hurray! Continue videos about 6502! Thank you!
@averyjohnson138
@averyjohnson138 Рік тому
I had to take a machine programming class twice particularly because I didn't understand how timers worked. If I knew about this channel when taking the class it would've been a huge help. I love your videos
@8bits59
@8bits59 3 місяці тому
I was SCREAMING at my screen to use the ADC instruction! You can simply chain ADC #0 to automatically carry addition across bytes in fewer bytes and cycles than that INC conditional chain. You set it up exactly (but opposite) like that sbb instruction: CLC to clear any existing carry, LDA the LSB, ADC #1, STA, LDA, ADC #0, STA, and so on until all bytes are accounted for. The carry flag gets set by the ADC instructions, and only when overflow occurs. The net effect is that the ADC #0 becomes an effective ADD #1 if and only if the previous add instruction overflowed. Great work as usual ;D I hope to expand my own kit with some goodies here soon, been thinking of porting FLEX (the 6800 DOS) to it for some time.
@DelphineDofain
@DelphineDofain 2 роки тому
I always look forward to your video, I love learning with them!
@kodirovsshik
@kodirovsshik 2 роки тому
Man a new video let's gooo Seeing your new video is like one of the most happy-making me things, the topics you cover and the way you do it are super cool
@KillaKevBrah
@KillaKevBrah 2 роки тому
Love that you jumped to the display roll over at the very end. 31:09
@bobthecomputerguy
@bobthecomputerguy 2 роки тому
As a computer engineer, I love your videos. You've managed to condense a couple semesters into something I can watch in a day or two.
@hupa1a
@hupa1a 2 роки тому
Great one! Your explanations are so clear and complete, you couldn't do it better!
@danieltakacs8222
@danieltakacs8222 2 роки тому
Thanks for making these. I'm learning assembly for my emulator project, and this helps a lot and also keeps it very interesting.
@TvistoProPro
@TvistoProPro 2 роки тому
Ben, I was waiting for the next logical step on this, and then you didn't! Investigating, I realized with some shock that the 6502 doesn't have an instruction I expected. I cut my teeth not on the 6502, but the 6809, which had the SYNC instruction. SYNC on the 6809 would put the CPU into a low power sleep state to synchronize with an external interrupt. It first pushes a limited state to stack (as if an interrupt was happening), then waits for an interrupt to come in. Once the interrupt came in, it would service that interrupt, then resume (via RTI) at the instruction after the SYNC. Such and instruction would be ideal to put in the head of the loop here. It would mean you're only running the subroutines once per 10ms, and are doing so just as the interrupt returns, limiting collision. That would also mean the CPU is using less power (and making less heat) while running this task. The 6809 system I used often (the TRS80-CoCo) would use this trick to presync with hardware for everything from loading data from tape, to doing frame rendering for video output. Lots of neat tricks one can do when one can synchronize with a hardware event.
@PhilDennis
@PhilDennis 2 роки тому
The 65C02 from WDC which Ben uses in the breadboard computer does have a "WAI" instruction which pauses until an interrupt occurs and also minimizes interrupt latency. For those using vasm, the wcd extensions must be enabled with the -wdc02 option in order to use this.
@wolfboyft
@wolfboyft 2 роки тому
At the beginning when you were telling us it's a 6502 the video froze and my brain suggested that you were about to say "64 bit processor". _Wow, nice work Ben!_
@youneschroqi649
@youneschroqi649 2 роки тому
Sooo informative, well explained, extremely addictive.... Can't wait for your next upload, thank you from the bottom of my heart
@Gastell0
@Gastell0 4 місяці тому
This is incredibly informative, as someone who have accumulated lots of bits and pieces over my career as IT person (mix of admin, scripting, poor coding and poking at hardware), this allowed me to connect a lot of these bits and pieces together!
@Roxor128
@Roxor128 2 роки тому
Ah, the ticks variable. I remember hearing about something similar in Windows. The resolution is high enough that it hits the 32-bit wraparound after about 29 days of uptime, which can cause bugs if a programmer makes use of it and forgets to take it into account. Debug versions of Windows start with an uptime close to the wraparound point to try and catch such bugs before it ships. If you have a Windows machine that reliably blue-screens every 29 days, blame the hardware manufacturers, because someone forgot to include the appropriate check in one of the drivers.
@joshuah345
@joshuah345 2 роки тому
@@Duu2 yeah, because they support 64-bit
@eumim8020
@eumim8020 2 роки тому
@@joshuah345 Lol thats so true, tfw you throw money at your problems by buying better hardware and suddenly every optimization task you've done in the last months becomes nearly useless work.💸
@isse6790
@isse6790 2 роки тому
@@joshuah345 isn't all of the underlying code and api's 32-bit?
@mariocamspam72
@mariocamspam72 2 роки тому
@@isse6790 yes, but not all.
@Paulo27
@Paulo27 Рік тому
Yep, some games had issues if your PC was up for that long.
@Ryuzenski
@Ryuzenski 2 роки тому
Ben is an absolute treasure. I swear in a week we're gonna see : "How did I achieve immortality with a 6502?" With a 2 hour video on a breadboard project he made to make himself immune to dying
@endermannull4420
@endermannull4420 Рік тому
We hope.
@herethere5637
@herethere5637 3 місяці тому
This comment aged like fine wine
@faramarzfalsafinejad4511
@faramarzfalsafinejad4511 2 роки тому
Mr. Eater i have watched almost all of your playlists and i admit that I'm envious of your knowledge and (practical) skills and experience. I'm sure that others feel somewhat the same too. please share with us how you gained your knowledge and experience; like what books you read? what courses you took? etc.
@lofigirl5835
@lofigirl5835 2 роки тому
I swear you read my mind. I was JUST wondering about this yesterday. so of course you upload a vidoe about it that day and it shows up in my recommended the next. thank you!!
@tehlaser
@tehlaser 2 роки тому
I swear datasheet writers compete to see who can be the most opaque on timers. Maybe the chips just cram so much functionality into timers that it’s impossible to be clear, but something about timers specifically seems impossible to document well.
@douglashill2469
@douglashill2469 2 роки тому
Better than USARTs, generally. Those have to handle SPI, I2C, and serial (at the least). I've legitimately seen a datasheet say "don't use this feature", more or less. It was actually for talking SPI to devices which have input and output happen on different clock phases. Which is something I saw on a frequency synthesis chip, once.
@noalear
@noalear 2 роки тому
@@douglashill2469 Just came across something similar in some documentation for SPI myself. A younger me would see a challenge where current me sees compassion.
@jonmayer
@jonmayer Рік тому
I hope all is well Ben. I can't believe it's been 7 months since the last video. Please don't say this series is done.
@austinwhiteted8231
@austinwhiteted8231 Рік тому
I hope he is okay
@raphaelfranzen9623
@raphaelfranzen9623 Рік тому
@Rafael flash 8 months without any sign of live. I hope he is doing well.
@danman32
@danman32 Рік тому
I've been wondering what the use was for the 4 buttons shown in the photo on the box for the kit. But yeah, where have you been? Hope you're ok. Love to see more uses for this 6502 on BB.
@marcel151
@marcel151 Рік тому
I think there will be a new video at the 1M milestone. ;-)
@musturdx
@musturdx Рік тому
@@raphaelfranzen9623 Not to be an asshole but i think u mean life
@coyote4440
@coyote4440 2 роки тому
Hello Ben, I really love your videos and hope you are fine in such difficult time, Thank you for giving me better understanding of computer science in really low level! Waiting for new videos patiently.
@saeedradmehr1976
@saeedradmehr1976 2 місяці тому
Your stuff really delightful. I relax with it before sleep.
@linuxrf1
@linuxrf1 2 роки тому
Great video as always, Ben! Thank you! One thing I think I should point here is that this implementation is prone to a "time drift" effect. The problem here is that we check the "current time", and if the required amount had passed we "do stuff" and then we record "time of last update". But what will happen if between the check and recording a timer tick occurs (and it will sometimes)? We then will wait one tick more than necessary till the next update. Over time, those "extra ticks" will accumulate and cause our program to go "out of sync" with the real world. For small LED-blinking demo that won't hurt much, but if we used this code to drive step-motor clock, e.g., we'd notice that our clock goes further and further away over time. Still, IDK if this is a topic for a beginners' tutorial =)
@joshseide7109
@joshseide7109 2 роки тому
Would love to hear if Ben has offered a suggested reading list or favorite textbooks he’s learned from over the years.
@anindyamitra5091
@anindyamitra5091 2 роки тому
Outstanding demonstration, thank you!
@thisisnonpractice
@thisisnonpractice 2 роки тому
Thanks Ben, you are making Firmware wonderful!
@cangorkemgunes
@cangorkemgunes 2 роки тому
We need new videos sir! You are awesome!
@newoldbrain
@newoldbrain 2 роки тому
While he was writing the asm code I was mentally translating the opcodes in hex. LDA #0 -> A9 00 < edited, A5 is page 0 LDA! STA PORTA -> 8D 01 60 Last time I needed this was more than 40 years ago. Damn, I'm old!
@SimonBuchanNz
@SimonBuchanNz 2 роки тому
Fortunately I haven't quite yet done enough JIT code to do that for x86!
@gayusschwulius8490
@gayusschwulius8490 2 роки тому
Under what circumstances did you need to translate between ASM and opcodes in the early 80s? I thought that assemblers were pretty much ubiquitous at that point?
@newoldbrain
@newoldbrain 2 роки тому
@@gayusschwulius8490 Let's make it the late 70s. As a teenager I had designed and built a small 6502 based computer (hex keypad and 7 segment LEDs, a PIA, 2114 RAMs and 2708 EPROM). No cassette interface (in the beginning) and no other computer in sight. So my options to get and run an assembler were quite scarce. Internet was really slow in that age, we called it a photocopier.
@gayusschwulius8490
@gayusschwulius8490 2 роки тому
@@newoldbrain Oh wow, very cool. I'm currently trying to do a similar thing with a 65C02. Hearing that story I'm glad I live in the age of the internet where all knowledge is at my fingertips, haha. It's quite an impressive feat to do this with just book knowledge and no way to google things. Especially as a teenager!
@TheChrisey
@TheChrisey 2 роки тому
@@gayusschwulius8490 If you were to create an emulator (which I did for x86) you'll need to implement the actual opcode decoder. x86 is a mess
@your_utube
@your_utube 2 роки тому
I am using timers in Javascript and this coding is so much like what even the OS is doing at a grand scale for all sub-systems. The code is so flexible and the examples clear. Real Eater quality. I literally left looking at other videos when the YT notification showed an update from you. Thanks Ben, you are a star!
@danieltravinsky3649
@danieltravinsky3649 2 роки тому
i know nothing about these kinds of computers and code but your video explains everything really well. great video!
@Dorff_Meister
@Dorff_Meister Рік тому
Thanks. Really enjoyed this. Easy to follow, logical progression.
@JanBruunAndersen
@JanBruunAndersen 2 роки тому
A more advanced program would set up a vector (e.g. to a subroutine that controls when to toggle the LED) for the interrupt routine to call at the end. The control routine would then be called during each interrupt and can decide if something needs to be done. The main program could then be reduced to a dummy loop.
@TheChrisey
@TheChrisey 2 роки тому
A program with modern hardware would simply setup a timer with a proper prescaler that would trigger an interrupt only when you want the LED to toggle. Ofc no one in their right mind would actually create a randomly switching LED for anything other than learning
@stevedonkers9087
@stevedonkers9087 2 роки тому
I experimented with the timers a few months ago. They're pretty nifty. I worked out a timer interrupt with some counts to blink at 1 second intervals, and printed out the value to the LCD, and after around 6 hours it was still second accurate. I also used it to create a text scrolling effect on the LCD that you could speed up and slow down with some buttons, and printed the speed value on the screen as well. The datasheet is quite helpful with the 6522.
@TheChrisey
@TheChrisey 2 роки тому
Timer accuracy has nothing to do with the code tho. Everything comes down to the oscillator precision. 1 second accuracy... Try 1usec. Where heat, PCB impedance and voltage fluctuation all causes the crystal to drift.. Or even the number of times you had to resolder the crystal.
@stevedonkers9087
@stevedonkers9087 2 роки тому
@@TheChrisey Timer accuracy depends on the crystal and related components yes (although I used an oscillator can), but as far as software is concerned accuracy can definitely be hampered by code. If you spend too much time in your ISR you'll miss the next interrupt (if I remember correctly the 6502 sets the interrupt disable flag on entry to the ISR). I forget the exact numbers I used, but if you set the timer to 49998 (+2) and have the ISR count 20 times you'll get a fairly accurate 1 second event (depending on the clock accuracy of course.)
@TheChrisey
@TheChrisey 2 роки тому
@@stevedonkers9087 Well of course, you can end up writing buggy code that doesn't use the timer properly causing it to skew. But that's more of a suftware bug rather than timer accuracy. Just mere semantics :)
@doug7180
@doug7180 Рік тому
Thank you Ben best electronics teacher I have seen my 40 years
@david02251
@david02251 2 роки тому
I love everything about this series
@SvenDawitz
@SvenDawitz 2 роки тому
Can I wish for a modern version of those "ancient" videos about how transistors work down to the atoms that were never included in the "let's build 8bit CPU"-playlist and probably "nobody" of todays viewer ever saw?
@slabo8171
@slabo8171 2 роки тому
Those who didn't are the ones to be blamed :P. It's not one of those over-bloated (even if with good content) channels impossible to watch after joining the party late. I was able to browse the video list a while ago and watch them.
@Geosquare8128
@Geosquare8128 2 роки тому
great video!
@hey7328
@hey7328 2 роки тому
remove sleep calls to increase cactus finding performance by 4000%
@mthf5839
@mthf5839 2 роки тому
oh, really cool seeing you here!
@woosix7735
@woosix7735 2 роки тому
of courese it is
@atpray
@atpray 2 роки тому
Hello mod
@zLcss
@zLcss 2 роки тому
I'm following Ben for a few months now and there is no doubt for me that he has the coolest channel/ content on UKposts 😬
@tiger12506
@tiger12506 2 роки тому
In the past, I wrote a chromatic tuner, and used hardware timers for measuring the time between sound oscillations. This brings me back. :) Would be interesting to here you discuss balancing different paths. i.e. you know that when it doesn't branch here, it takes longer, so the shorter branch needs some nop to balance it out, and then you subtract the whole from the original period. Of course, you didn't really need that here because the hardware timer runs completely independently, and as long as your ISR isn't long enough to interfere with the timing period, you're good. Cheers.
@Ryuujin1024
@Ryuujin1024 2 роки тому
9:25 Notice the deliberately swapping coloured pens for the next part to be written down. Just a little indication of the preplanning effort that goes into these.
@erictwilegar
@erictwilegar Рік тому
Did Ben accidentally call sleep with an extra digit. Miss you.
@AndersJackson
@AndersJackson 2 роки тому
Great video that demonstrate how timer and interrupts works. Thanks!
@lukewebb604
@lukewebb604 2 роки тому
This came up in my recommended feed. I'm not familiar with breadboards at all, especially not programming for them, but this was really easy to understand with just the right amount of explanation but not repetition
@Aaaaaaahron
@Aaaaaaahron 2 роки тому
Great content! How many Bens have you eaten?
@Mr_ToR
@Mr_ToR Рік тому
I hope you're ok. please more content.
@white.rabbit
@white.rabbit 3 місяці тому
This video should be shown to all computer science/engineering students in the world. Thanks for the clear explanation with a working demo!
@Honeybearsphone
@Honeybearsphone 2 роки тому
Interesting does not strongly enough describe how I found this video, I love all your videos and find them incredibly informative and interesting
@TheMechatronicEngineer
@TheMechatronicEngineer 2 роки тому
Where are you gone Ben? We need you here!
@harrytsang1501
@harrytsang1501 2 роки тому
Now that you have an irq, the system requirement of an OS has been fulfilled. Just need a scheduler and a way to context switch
@mfaizsyahmi
@mfaizsyahmi 2 роки тому
thus BreadboardOS is born!
@TheChrisey
@TheChrisey 2 роки тому
Don't need a scheduler nor a context switch on a micro.
@jaredteaches894
@jaredteaches894 2 роки тому
@@TheChrisey I'm unsure if you're being facetious, but yes, you do see those in microcomputing. Mainly RTOS when it comes to microcomputing. There have been 6502 operating systems built for microcomputers as well!
@TheChrisey
@TheChrisey 2 роки тому
@@jaredteaches894 Not for anything serious. Obviously I know about RTOS, and I also know how useless, slow and bulky they are compared to a minimal HAL library.
@anotherriddle
@anotherriddle 2 роки тому
That's all really clever. Thanks a lot for the explanation!
@diogocruzdiniz3186
@diogocruzdiniz3186 2 роки тому
Haven't even finished watching, but man this is one I was really looking forwards for
@bar10dr
@bar10dr Рік тому
I miss your awesome videos Ben, hope everything is okay
@matthias916
@matthias916 Рік тому
Msi realized how much of a threat Ben is to them and took him out, R.I.P. Ben 😔
@dpatulea
@dpatulea 2 роки тому
Love the explanation! Wonderful video! I'm always watching your videos first.
@WistrelChianti
@WistrelChianti 2 роки тому
this video is so chill for a Sunday : )
@olaff667
@olaff667 2 роки тому
when you increase multi-byte 'ticks' variable, you can you adc (add with carry) instruction without jumps.
@beyondcatastrophe_
@beyondcatastrophe_ 2 роки тому
How exactly are you thinking? ADC just sets the carry flag, you still need to jump based on that Also ADC does not work directly on memory, only with the Accumulator, so you need to store it back at some point Like all instructions ADC only works with 1 byte, so you still need to stop at some point as well I think ADC only makes the operation more complex
@IanSlothieRolfe
@IanSlothieRolfe 2 роки тому
@@beyondcatastrophe_ No, ADC adds the carry in with the argument like A=A+arg+C, so to add a multibyte number you just need to do CLC/LDA num1/ADC num2/STA num1/LDA num1+1/ADC num2+1/STA num1+1 etc so no jumps would be required. ADC both adds in and creates a new carry. But you are right, if incrementing a single multi-byte variable then doing it the way Ben has is quicker and avoids having to save/restore the A register.
@beyondcatastrophe_
@beyondcatastrophe_ 2 роки тому
@@IanSlothieRolfe Ah, thank you, I just looked it up on the next-best page, they left that out
@zerobyte802
@zerobyte802 2 роки тому
Low power mode: add a WAI instruction to the main loop. This pauses the CPU in low power mode until the next interrupt occurs.
@ebenolivier2762
@ebenolivier2762 2 роки тому
Interesting that the newer 6502s have this instruction, older ones definitely did not.
@IanSlothieRolfe
@IanSlothieRolfe 2 роки тому
@@ebenolivier2762 yes, WAI was introduced with the Western Digital CMOS 65C02 which came out in 1983. 6502 based machines like the PET, VIC20, Apple 2 etc used earlier Mostek and Rockwell designs which had significant differences. I don't think the 6510 used in the C64 had a WAI instruction but I may be wrong, it had a number of variants of the chip.
@ebenolivier2762
@ebenolivier2762 2 роки тому
@@IanSlothieRolfe Interesting! And what is more interesting is how long ago this instruction was added, way before saving battery power was a "thing".
@PhilDennis
@PhilDennis 2 роки тому
@@ebenolivier2762 I think the main motivation for introducing WAI, was to improve interrupt latency, since when waiting, the processor will immediately jump to the interrupt service routing instead of having to finish the current instruction first. Indeed if interrupts are DISABLED when executing WAI, the interrupt service routing is bypassed and execution continues immediately following the WAI instruction, for the fastest possible response.
@KevanV2
@KevanV2 2 роки тому
So glad he showed the roll over... Never assume that it will always end with 00... Same with times and dates over midnight / year end / end of epoc... these will catch you and I test for them!
@ChrisAthanas
@ChrisAthanas 2 роки тому
Such an excellent explanation of a usually confusing and esoteric subject
@mfaizsyahmi
@mfaizsyahmi Рік тому
Ben suddenly ceasing any and all forms of communication is very uncharacteristic of this channel and had me fearing for the worst. Maybe he's taken a permanent break from doing breadboards and has since moved on to breaking bread with higher beings. May the metal clips on the eternal breadboards never wear out. And the wire stock never run out. And the caps, LCDs, and other components forever as pristine as the day you bought them.
@jumeme378
@jumeme378 Рік тому
he good
@great.Indian.culture
@great.Indian.culture Рік тому
Sir hope you are absolutely fine
@eigenfeynman9890
@eigenfeynman9890 Рік тому
You post the things that people actually want, thanks for pinning down more curiosity
@capcrow420
@capcrow420 2 роки тому
Thanks for these videos!
@TREmreprogaming
@TREmreprogaming Рік тому
But when the world needed him most, he vanished.
@Tresla
@Tresla 2 роки тому
We miss you Ben. Hope you're doing OK
@kmpnelson
@kmpnelson 2 роки тому
Always enjoy your videos Ben, and I'm super happy to see that there (as of writing this) are zero, yes zero, dislikes.
@hadireg
@hadireg 2 роки тому
can't wait my kit is arriving soon... yay!! 😊
@electra_
@electra_ 2 роки тому
In a more sophisticated system, I might expect the timers to be triggered a little differently. In order to not require a "main loop" like you have... perhaps you would instead set up a time to wait and then mark the "return address" of your wait somewhere, and then when an interrupt occurred it would check if it's waited long enough, and if so, jump back to your code?
@ELYESSS
@ELYESSS 2 роки тому
That's what schedulers are for.
@someguy4915
@someguy4915 2 роки тому
Or just have the timer trigger an interupt, have your interupt routine check which timer triggered it and execute the address you defined for that timer if you want that functionality with this hardware.
@tonysofla
@tonysofla 2 роки тому
@@ELYESSS I wrote my own for arm cortex using the 24bit low-power rtc timer: for (int i = 0; i < TaskListEnd; i++) { // look at all tasks interval register temp = task[i].sleepto; // get a temp copy if (temp != (uint32_t)-1 && temp > rtcmatch) { // a set value and not already past due if (temp < lowest) { // is it a new lowest eventrtc = (1
@luisjalabert8366
@luisjalabert8366 2 роки тому
@@someguy4915 This is how it should have been done. It's not "correct" to handle the LED switching in the main loop like he did, instead, what needs to be done, is to have an interrupt signal coming from the timer to make the CPU execute an interrupt subroutine (ISR). This subroutine should PUSH (and POP at the end) the status of the registers that it uses, and read some variable in memory (or directly from the output port if the CPU allows) to XOR the status of the LED, and output to the LED port. In this way he could have had a dummy while(1) loop doing nothing, and let the interrupts control the whole thing. EDIT: the 6502 has at least 3 interrupt input pins, so he could have wired the interrupt signal from the timer to the CPU, and setup the ISR accordingly. In the end I think he got confused and ended up doing the same thing as before (constantly polling a flag in a loop), but with extra steps (setting up the flag through interrupts).
@ratchet1freak
@ratchet1freak 2 роки тому
@@luisjalabert8366 the 6502 doesn't have a low-power mode though so there is no real point in "sleeping" it. You will be busy looping anyway so might as well keep it simple and check the ticks every time. And remember that this is a tutorial series, this kind of multitasking is perfectly valid and a lot simpler than a proper scheduler.
@UndiagnosedGenXer
@UndiagnosedGenXer 2 роки тому
Hope you're ok, Ben.
@Hidyman
@Hidyman 2 роки тому
Thanks for showing the roll over on the LCD at the very end.
@nicholasorro1105
@nicholasorro1105 Рік тому
Mr Ben ur one of my best youtuber i. I always enjoy your lessons and always eager to see your uploads. Receive lots of love from Kenya
The RS-232 protocol
26:10
Ben Eater
Переглядів 812 тис.
A simple BIOS for my breadboard computer
21:53
Ben Eater
Переглядів 318 тис.
Surprise Gifts #couplegoals
00:21
Jay & Sharon
Переглядів 27 млн
🔥 Україна виходить у ФІНАЛ ЄВРОБАЧЕННЯ-2024! Реакція alyona alyona та Jerry Heil #eurovision2024
00:10
Євробачення Україна | Eurovision Ukraine official
Переглядів 137 тис.
How does a USB keyboard work?
34:15
Ben Eater
Переглядів 3,1 млн
How are Images Compressed?  [46MB ↘↘ 4.07MB] JPEG In Depth
18:47
Branch Education
Переглядів 3,4 млн
Playing a Game on a MC14500 1-bit Single Board Computer!
24:55
Usagi Electric
Переглядів 195 тис.
Hacking a weird TV censoring device
20:59
Ben Eater
Переглядів 2,9 млн
World's worst video card? The exciting conclusion
24:23
Ben Eater
Переглядів 2,9 млн
Let's build a voltage multiplier!
16:32
Ben Eater
Переглядів 1,8 млн
Hardware interrupts
27:36
Ben Eater
Переглядів 585 тис.
The ARM chip race is getting wild… Apple M4 unveiled
4:07
Fireship
Переглядів 265 тис.