#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_ADS1X15.h>
char buffer [320];
// Pin definitions for the switch matrix
const int ROW_PINS[8] = {2, 3, 4, 5, 6, 7, 8, 9};
const int COL_PINS[8] = {10, 11, 12, 13, 14, 15, 16, 17};
// Variable to store the 16 bit integer ADC values
static int16_t analogValues[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
// Pin definitions for the channel multiplexer
const int MUX_S0 = 18;
const int MUX_S1 = 19;
const int MUX_S2 = 20;
const int MUX_S3 = 21;
const int MUX_SIG = 22;
// Object for the ADS1115 ADC
Adafruit_ADS1015 adc;
byte matrixValues[8] = {0,0,0,0,0,0,0,0};
// Interrupt service routine for scanning the switch matrix
void matrixScan() {
// Loop through each row
for (int row = 0; row < 8; row++) {
Serial1.print("row: ");
Serial1.println(row);
// Set the current row low
digitalWrite(ROW_PINS[row], LOW);
// Read the column values
for (int col = 0; col < 8; col++) {
// Setting the nth bit to either 1 or 0 can be achieved with the following:
// number ^= (-x ^ number) & (1 << n);
// Bit n will be set if x is 1, and cleared if x is 0.
matrixValues[row] ^= (-digitalRead(COL_PINS[col])^matrixValues[row]) & (1 << col);
}
// Set the current row high
digitalWrite(ROW_PINS[row], HIGH);
}
}
void scanAnalogs() {
for (int i = 0; i < 16; i++) {
digitalWrite(MUX_S0, (i & 0x1) > 0);
digitalWrite(MUX_S1, (i & 0x2) > 0);
digitalWrite(MUX_S2, (i & 0x4) > 0);
digitalWrite(MUX_S3, (i & 0x8) > 0);
// Read the analog value using the ADC and store it
analogValues[i] = adc.readADC_SingleEnded(MUX_SIG);
}
}
void setup() {
Serial1.begin(115200);
// Set the row pins as outputs
for (int i = 0; i < 8; i++) {
pinMode(ROW_PINS[i], OUTPUT);
}
// Set the column pins as inputs with pull-up resistors
for (int i = 0; i < 8; i++) {
pinMode(COL_PINS[i], INPUT_PULLUP);
}
// Set the pins for the channel multiplexer as outputs
pinMode(MUX_S0, OUTPUT);
pinMode(MUX_S1, OUTPUT);
pinMode(MUX_S2, OUTPUT);
pinMode(MUX_S3, OUTPUT);
// Initialize the ADC
adc.begin();
// Attach the interrupt service routine for scanning the switch matrix
//attachInterrupt(0, matrixScan, CHANGE);
}
void loop() {
// Select one of the sixteen analog signals using the channel multiplexer
matrixScan();
scanAnalogs();
// Print the values of the switches and analog inputs
for (int i = 0; i < 8; i++) {
sprintf(buffer, "(%d, %d) ", i, matrixValues[i]);
Serial1.print(buffer);
}
Serial1.println();
for (int i = 0; i < 16; i++) {
sprintf(buffer, "(%d, %d) ", i, analogValues[i]);
Serial1.print(buffer);
}
Serial1.println();
Serial1.println();
// Wait to sample again
delay(1000);
}