Hi! I'm trying to program an Arduino to replace a fried Intel microcontroller on a very old Apple keyboard. I'm using an ATMega644A.
When researching "bit-banging" to emulate the old protocol, I read that the digitalWrite() function used to toggle the pin HIGH/LOW takes anywhere from 0-6us to execute, which I assume would have a negative (and random) effect on the timings.
The protocol calls for a 160us high and a 180us low state per bit sent; how big an impact will the ~5us delay from the digitalWrite() command have?
I could obviously just subtract, say, 3-5us from the HIGH/LOW delays as I'm sending the data, but that feels wrong somehow, and ideally I'd know how long the command actually took and adjust on the fly. Is that possible?
You should not subtract the 5 us.
Assume the line is low and at at some moment t0 you want to set it HIGH, it actually is set HIGH at t0 + 5. If you set it LOW at t0 + 160 it actually sets LOW at t0 +160 + 5.
The length of the pulse is still 160 us, there is only a “phase shift” of 5 us.
Because between the hardware and using the Arduino-safetied digitalWrite() it –Can– take that long but be sure that it will be very close to the same interval every time. The variance is mostly in the particular ways it could be done.
Fact is that when you bit-bang the IO port registers, the pin state can be changed in very few cycles and still need some time to change the circuit it is attached to. Arduino digitalWrite() takes about 5x as long as direct port manipulation which done incorrectly may damage pins/chip so ya haveta know what you’re doing to do it right.
As Rob notes above, coding for triggers that pull the same means that the effects happen on time one to the next the same.
One thing I add, that if your code uses delay() or much of any internal loop, it will NOT get the triggers right to any 5 micros, or usually to any 100 millis to 1 second. A really tight void loop can take 12 to 20 micros (192 to 320 16MHz cycles) on average can do a few things over and over reliably.. but printing during that time may fatten a loop-cycle just as often.
I’m not sure, maybe you only need <10 micros all the time or just for short bursts cause if it’s all the time you may need a chip that runs at a higher clock speed, many times 16MHz and not just 48MHz.