• Does digitalRead() do that too?

    Yes, it does - pretty much all the IO functions do it.

    Could you tell a bit more about the reasoning for this?

    Sure, it's that in Arduino, you have to know what to do with pinMode before you do anything. It's a mess, because you can write perfectly good code, and it'll fail silently because the pin mode is wrong.

    If you say digitalRead, digitalWrite, or analogRead it's pretty obvious what you want - so why force the user to use pinMode beforehand as well?

    For instance you'd write digitalWrite(LED1,1) and absolutely nothing would happen - no warning, no error. It's not exactly friendly.

    As I'm trying to be easy to use for beginners, if nobody specifies pinMode then Espruino tries to work out what you want from the function you called. If you did call pinMode it behaves like an Arduino though - what you specified with pinMode overrides everything.

    Reading pinMode documentation with its eight possible values is a bit rough

    Yes, thanks for letting me know - I've put that on my to-do list and I'll try and improve it. I'll make sure digitalRead and .read mention that they change the pin's state to input in order to read its value too.

    Do I have to know pullup, opendrain and the difference between "output" and "af_output" just to play around with LED1 like in op example?

    Yes and no. If you want to set LED1, you use digitalWrite and it will just work, but the best way to know the current state of it is just to remember it in a variable.

    The reason is that digitalRead is probably not doing what you expect. The actual GPIO is like in the circuit below. It's a bit overcomplicated, but basically the input value doesn't come from the same register as the output value - it's actually reading the voltage on the output pin.

    So if you have a capacitor (for instance) connected to the pin, and you do:

    for (var i=0;i<100;i++) console.log(digitalRead(pin));

    You'd expect that it would just print a bunch of 1s - But it almost certainly won't. It'll actually print 0 until the capacitor charges up, and then 1.

    Now maybe that's not a huge issue, but what if you were trying to pulse-width modulate the capacitor's voltage to 3.3v/2 by simply toggling the output high and low the way you'd think would work fine:

    while (true) digitalWrite(pin,!digitalRead(pin));

    and now it's going to do something really different from what you expect. Instead of a nice quick square wave it's actually going to wait until the capacitor has charged before discharging, and vice versa

    It would be totally possible to add a .readOutputValue() method to the Pins that would do what I guess you're expecting, but to be honest I think that's probably confusing matters.

    1 Attachment

    • Screenshot from 2015-08-05 16:59:40.png

Avatar for Gordon @Gordon started