[How To] Arduino attachInterrupt

Posted on
  • I have an arduino sketch that I would like to port JavaScript and run on a pico.
    The sketch is reading input from pins 2 and 3 and then attaching two interrupts to get 0/1 bits.

    What would be the way to achieve this using a pico?

    The following is an excerpt of the sketch I'm using, I could post the whole script but I figured this encompasses the core of my question.

    void ISR_INT0()
    {
        bitCount++;
        flagDone = 0;
        pulseCounter = WAIT_TIME;
    
    }
    
    void ISR_INT1()
    {
        databits[bitCount] = 1;
        bitCount++;
        flagDone = 0;
        pulseCounter = WAIT_TIME;
    }
    
    void setup()
    {
        pinMode(13, OUTPUT);   // LED
        pinMode(2, INPUT);     // DATA0 (INT0)
        pinMode(3, INPUT);     // DATA1 (INT1)
    
        Serial.begin(115200);
        Bridge.begin();
    
        while (!Serial);
    
        attachInterrupt(1, ISR_INT0, RISING);
        attachInterrupt(0, ISR_INT1, RISING);
    
        pulseCounter = WAIT_TIME;
    }
    
    void loop()
    {
        if (!flagDone)
        {
            if (--pulseCounter == 0)
            {
                flagDone = 1;
            }
        }
    
        // if we have bits and we the pulse counter went out
        if (bitCount > 0 && flagDone)
        {
            //... logic removed
            bitCount = 0;
        }
    }
    
  • instead of attachInterrupt, use setWatch() - note that they don't actually run as ISRs - an ISR records the pin state and the timestamp, and then the callback is called when the interpreter is idle. And it can queue up... i forget if it was 64 or 128 callbacks waiting to execute before it starts missing things.

    It may make sense to use compiled functions if speed is an issue (though afaik this is still a little rough around the edges).

    Instead of setup(), your initialization goes in onInit().

    There's no concept of loop() like there is in Arduino - instead you might, say, have the watch callback check how many bits are received, and then call a function do do what you want with those bits. Take a look at the DHT modules I wrote (though those don't use compiled watch callbacks, because those didn't exist when I wrote it)

    It's interesting to port an Arduino sketch to Espruino - though the grammar of the language is so similar that sometimes you can just copy-paste functions, conceptually, the two are very different.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

[How To] Arduino attachInterrupt

Posted by Avatar for goliatone @goliatone

Actions