arduino-libraries / Arduino_PortentaMachineControl

The official, revamped Arduino Library for the Portenta Machine Control.
Mozilla Public License 2.0
10 stars 8 forks source link

Encoder channels as interrups #19

Open wallahi06 opened 3 months ago

wallahi06 commented 3 months ago

Hey! is it possible to use the encoder channels on the portenta machine control as interrups to control a stepper motor?

manchoz commented 1 week ago

Hey @wallahi06, please see the following sketch:

/*
    This sketch shows how to use the six Encoders ports on
    the Arduino Machine Control as 24V-GPIOs for IRQ detection.

    *** NOTE ***
    Please, note that the six Encoder ports are pulled up to 24V
    by a 10k resitor, thus is possible to detect only
    HIGH-to-LOW transitions.

    Circuit:
    - Arduino Portenta Machine Control
    - External 24V power supply

    Testing:
    - For testing purposes, momentarly short-circuit the desiderd port with GND.
*/

// Call to PinNameToIndex is needed to create pins
// compatible with classic Arduino API from an MbedOS pin (Px_y)
#include <pinDefinitions.h>
const auto ENCODER_A0 { PinNameToIndex(PJ_8) };
const auto ENCODER_B0 { PinNameToIndex(PH_12) };
const auto ENCODER_Z0 { PinNameToIndex(PH_11) };
const auto ENCODER_A1 { PinNameToIndex(PC_13) };
const auto ENCODER_B1 { PinNameToIndex(PI_7) };
const auto ENCODER_Z1 { PinNameToIndex(PJ_10) };

volatile auto count { 0ul };
auto prevCount { 0ul };

void setup()
{
    pinMode(PinNameToIndex(PJ_8), INPUT);

    // Wait for Serial Monitor connection
    Serial.begin(115200);
    for (const auto timeout = millis() + 2500; !Serial && millis() < timeout; delay(250))
        ;

    Serial.println("Testing Encoder Ports as 24V IRQs");

    // Encoder ports are pulled up to 24V by a 10k resistor
    // thus we can only detect HIGH-to-LOW transitions
    attachInterrupt(PinNameToIndex(PJ_8), [] { count++; }, FALLING);
}

void loop()
{
    // Print only when new IRQs have been detected
    if (count != prevCount) {
        Serial.print("IRQ count: ");
        Serial.println(count);
        prevCount = count;
    }
}