Напиши функцию в языке ардуино. Она должна считывать 4 входа в цикле. На этих входах…
- User
Напиши функцию в языке ардуино. Она должна считывать 4 входа в цикле. На этих входах подключены источники прерывания от mcp23018 (экспандер портов по i2c, сконфигурированный на вход). Если на данном входном пине появляется высокий уровень, то данный порт должен быть прочитан. Полученное значение из формата 0b00100100 (где 1 - высокий уровень на порте экспандера) должно быть преобразовано в порядковые значения (начиная от 0) активных выводов порта экспандера, то есть 2 и 5 для данного примера. После чего через все активные значения должны быть упорядочены через массив подставлений. Этот упорядоченный массив является результатом работы функции. Поскольку подключено 2 экспандера, то всего возможно прочесть 32 входа. Соответственно конечный массив должен иметь длину 32
- Assistant
#include <Wire.h> // Define interrupt input pins #define INT_PIN1 2 #define INT_PIN2 3 #define INT_PIN3 4 #define INT_PIN4 5 // Define expander I2C addresses #define EXPANDER_ADDR0 0x20 #define EXPANDER_ADDR1 0x21 // Define the permutation array (mapping array) uint8_t permutationArray[32] = { /* Fill this array with your specific permutation values */ // Example values: 15, 3, 8, 2, 23, 16, 7, 1, 24, 9, 30, 12, 0, 25, 18, 20, 4, 6, 21, 11, 13, 5, 29, 10, 27, 19, 14, 31, 22, 17, 28, 26 }; void setup() { // Initialize serial communication for debugging Serial.begin(9600); // Initialize interrupt pins as inputs pinMode(INT_PIN1, INPUT); pinMode(INT_PIN2, INPUT); pinMode(INT_PIN3, INPUT); pinMode(INT_PIN4, INPUT); // Initialize I2C communication Wire.begin(); // Configure expanders // Set all GPIO pins as inputs for expander at address 0x20 Wire.beginTransmission(EXPANDER_ADDR0); Wire.write(0x00); // IODIRA register Wire.write(0xFF); // Set all GPIOA pins as inputs Wire.write(0xFF); // Set all GPIOB pins as inputs Wire.endTransmission(); // Set all GPIO pins as inputs for expander at address 0x21 Wire.beginTransmission(EXPANDER_ADDR1); Wire.write(0x00); // IODIRA register Wire.write(0xFF); // Set all GPIOA pins as inputs Wire.write(0xFF); // Set all GPIOB pins as inputs Wire.endTransmission(); // Additional configurations (enable pull-ups, etc.) can be added here } void loop() { // Create an array to store the result uint8_t resultArray[32]; // Call the function to read expanders and process inputs readExpanders(resultArray); // For demonstration, print the result array Serial.println("Result Array:"); for (int i = 0; i < 32; i++) { Serial.print(resultArray[i]); Serial.print(" "); } Serial.println(); // Delay for a while before the next reading delay(500); } // Function to read expanders and process inputs void readExpanders(uint8_t* resultArray) { uint8_t mappedValues[32]; int mappedCount = 0; // Check interrupt pins for expander at address 0x20 if (digitalRead(INT_PIN1) == HIGH || digitalRead(INT_PIN2) == HIGH) { // Read GPIO values from expander at address 0x20 uint16_t gpioVals0 = readExpanderGPIO(EXPANDER_ADDR0); // Process GPIO values and map active inputs mappedCount = processGPIOVals(gpioVals0, 0, mappedValues, mappedCount); } // Check interrupt pins for expander at address 0x21 if (digitalRead(INT_PIN3) == HIGH || digitalRead(INT_PIN4) == HIGH) { // Read GPIO values from expander at address 0x21 uint16_t gpioVals1 = readExpanderGPIO(EXPANDER_ADDR1); // Process GPIO values and map active inputs mappedCount = processGPIOVals(gpioVals1, 16, mappedValues, mappedCount); } // Sort the mapped values sortArray(mappedValues, mappedCount); // Copy the sorted mapped values to the resultArray, fill remaining positions with zeros for (int i = 0; i < mappedCount; i++) { resultArray[i] = mappedValues[i]; } for (int i = mappedCount; i < 32; i++) { resultArray[i] = 0; } } // Function to read GPIO values from an expander uint16_t readExpanderGPIO(uint8_t expanderAddress) { uint8_t gpioA, gpioB; Wire.beginTransmission(expanderAddress); Wire.write(0x12); // Address of GPIOA register Wire.endTransmission(); Wire.requestFrom(expanderAddress, (uint8_t)2); // Request GPIOA and GPIOB if (Wire.available() >= 2) { gpioA = Wire.read(); gpioB = Wire.read(); uint16_t gpioVals = ((uint16_t)gpioB << 8) | gpioA; return gpioVals; } else { // Handle error: not enough data received return 0; } } // Function to process GPIO values and map active inputs int processGPIOVals(uint16_t gpioVals, int startIndex, uint8_t* mappedValues, int mappedCount) { for (int i = 0; i < 16; i++) { if (gpioVals & (1 << i)) { int inputPosition = startIndex + i; // Compute global input position (0-31) uint8_t mappedValue = permutationArray[inputPosition]; mappedValues[mappedCount++] = mappedValue; } } return mappedCount; } // Simple bubble sort function to sort the mapped values void sortArray(uint8_t* array, int length) { for (int i = 0; i < length - 1; i++) { for (int j = 0; j < length - i - 1; j++) { if (array[j] > array[j + 1]) { // Swap elements uint8_t temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } }Explanation:
-
The function
readExpanders(uint8_t* resultArray)reads the interrupt input pins connected to the MCP23018 expanders. If a high level is detected on any of the interrupt pins, it reads the corresponding expander's GPIO registers. -
The GPIO values are read using the
readExpanderGPIO(uint8_t expanderAddress)function, which reads both GPIOA and GPIOB registers and combines them into a single 16-bit value representing all 16 inputs of the expander. -
The
processGPIOValsfunction loops through each bit of the GPIO values. For every bit that is high (indicating a high level on that input), it calculates the global position (from 0 to 31) of the input, applies the permutation mapping usingpermutationArray, and stores the mapped value in themappedValuesarray. -
After processing all expanders, the
sortArrayfunction sorts themappedValuesarray in ascending order. -
Finally, the sorted mapped values are copied into the
resultArray, and the remaining positions up to length 32 are filled with zeros.
Notes:
-
Replace the example permutation array with your actual mapping values required for your application.
-
Ensure that the I2C addresses (
EXPANDER_ADDR0andEXPANDER_ADDR1) match the addresses configured on your MCP23018 expanders. -
Additional configurations, such as enabling pull-up resistors or setting up the interrupt control registers on the expanders, may be necessary depending on your specific hardware setup.
-
For a production environment, consider using more efficient sorting algorithms and handling possible communication errors more robustly.
-