Using a pro micro.
The separate sketches work fine. When I combine them into one, every readout of the MLX (i2c) interrupts the PMW sensor.
So when I set the update interval of the MLX to 1000ms, I get:
- smooth mouse movement for 1s,
- it stops for a fraction of a second, when I get a new readout from the MLX
- jumps to another position
- goto 1
So I'm wondering if this is an issue with the pro micro that can't handle both i2c and spi interfaces simultaneously and continuously?
Or should I put both on the SPI bus?
Here is the code, which is basically a mashup from the Adafruit MLX90393 and a PMW3389 sketch from github.
#include <Keyboard.h>
#include <Wire.h>
#include <SPI.h>
#include <avr/pgmspace.h>
#include "Adafruit_MLX90393.h"
#include <AdvMouse.h>
#define MOUSE_BEGIN AdvMouse.begin()
#define MOUSE_PRESS(x) AdvMouse.press_(x)
#define MOUSE_RELEASE(x) AdvMouse.release_(x)
unsigned long lastUpdatePMW = 0;
unsigned long lastUpdateMLX = 0;
const long PMWUpdateInterval = 1; //ms for PMW sensor
const long MLXUpdateInterval = 1000; //ms for MLX sensor
Adafruit_MLX90393 sensor = Adafruit_MLX90393();
//#define MLX90393_CS 10
// Configurations
// Variables to track angular change
float lastAngle = 0;
float cumulativeAngle = 0; // Tracks total rotation
// Define thresholds for scrolling
float scrollThreshold = 20; // Angular difference threshold to trigger scroll
int scrollStep = 3; // Amount to scroll per threshold exceeded
// The default CPI value should be in between 100 -- 12000
#define CPI 8000
#define DEBOUNCE 10 //unit = ms.
//Set this to a pin your buttons are attached
#define NUMBTN 4
#define Btn1_Pin 4 // left button
#define Btn2_Pin 5 // right button
#define Btn4_Pin 6 // middle button
#define Btn8_Pin 7 // Mission control F3
// Registers
#define Product_ID 0x00
#define Revision_ID 0x01
#define Motion 0x02
#define Delta_X_L 0x03
#define Delta_X_H 0x04
#define Delta_Y_L 0x05
#define Delta_Y_H 0x06
#define SQUAL 0x07
#define Raw_Data_Sum 0x08
#define Maximum_Raw_data 0x09
#define Minimum_Raw_data 0x0A
#define Shutter_Lower 0x0B
#define Shutter_Upper 0x0C
#define Ripple_Control 0x0D
#define Resolution_L 0x0E
#define Resolution_H 0x0F
#define Config2 0x10
#define Angle_Tune 0x11
#define Frame_Capture 0x12
#define SROM_Enable 0x13
#define Run_Downshift 0x14
#define Rest1_Rate_Lower 0x15
#define Rest1_Rate_Upper 0x16
#define Rest1_Downshift 0x17
#define Rest2_Rate_Lower 0x18
#define Rest2_Rate_Upper 0x19
#define Rest2_Downshift 0x1A
#define Rest3_Rate_Lower 0x1B
#define Rest3_Rate_Upper 0x1C
#define Observation 0x24
#define Data_Out_Lower 0x25
#define Data_Out_Upper 0x26
#define SROM_ID 0x2A
#define Min_SQ_Run 0x2B
#define Raw_Data_Threshold 0x2C
#define Control2 0x2D
#define Config5_L 0x2E
#define Config5_H 0x2F
#define Power_Up_Reset 0x3A
#define Shutdown 0x3B
#define Inverse_Product_ID 0x3F
#define LiftCutoff_Cal3 0x41
#define Angle_Snap 0x42
#define LiftCutoff_Cal1 0x4A
#define Motion_Burst 0x50
#define SROM_Load_Burst 0x62
#define Lift_Config 0x63
#define Raw_Data_Burst 0x64
#define LiftCutoff_Cal2 0x65
#define LiftCutoff_Cal_Timeout 0x71
#define LiftCutoff_Cal_Min_Length 0x72
#define PWM_Period_Cnt 0x73
#define PWM_Width_Cnt 0x74
const int ncs = 10; // This is the SPI "slave select" pin that the sensor is hooked up to
const int reset = 8; // Optional
int Btn_pins[NUMBTN] = { Btn1_Pin, Btn2_Pin, Btn4_Pin, Btn8_Pin };
bool Btns[NUMBTN] = { false, false, false, false }; // button state indicator
uint8_t Btn_buffers[NUMBTN] = { 0xFF, 0xFF, 0xFF, 0xFF }; // button debounce buffer
char Btn_keys[NUMBTN] = { MOUSE_LEFT, MOUSE_RIGHT, MOUSE_MIDDLE, KEY_F3 };
byte initComplete = 0;
bool inBurst = false; // in busrt mode
bool reportSQ = false; // report surface quality
int16_t dx, dy;
unsigned long lastTS;
unsigned long lastButtonCheck = 0;
unsigned long curTime;
//Be sure to add the SROM file into this sketch via "Sketch->Add File"
extern const unsigned short firmware_length;
extern const unsigned char firmware_data[];
void setup() {
Serial.begin(115200);
MLXsetup();
pinMode(ncs, OUTPUT);
pinMode(reset, INPUT_PULLUP);
pinMode(Btn1_Pin, INPUT_PULLUP);
pinMode(Btn2_Pin, INPUT_PULLUP);
pinMode(Btn4_Pin, INPUT_PULLUP);
pinMode(Btn8_Pin, INPUT_PULLUP);
SPI.begin();
SPI.setDataMode(SPI_MODE3);
SPI.setBitOrder(MSBFIRST);
//SPI.setClockDivider(4);
Serial.println("ON");
performStartup();
dx = dy = 0;
delay(1000);
initComplete = 9;
lastTS = micros();
MOUSE_BEGIN;
}
void MLXsetup() {
Wire.begin(); // Initialize I2C communication
AdvMouse.begin(); // Initialize AdvMouse for scroll emulation
while (!Serial) {
delay(10); // Wait for serial port to open
}
Serial.println("Starting Adafruit MLX90393 Demo");
// Initialize MLX90393 sensor using I2C
if (!sensor.begin_I2C()) {
Serial.println("No sensor found ... check your wiring?");
while (1) {
delay(10); // If sensor is not found, keep waiting
}
}
Serial.println("Found a MLX90393 sensor");
// Configure the sensor settings
sensor.setGain(MLX90393_GAIN_1X); // Set gain to 1x
sensor.setResolution(MLX90393_X, MLX90393_RES_17); // Set resolution for X axis
sensor.setResolution(MLX90393_Y, MLX90393_RES_17); // Set resolution for Y axis
sensor.setResolution(MLX90393_Z, MLX90393_RES_16); // Set resolution for Z axis
sensor.setOversampling(MLX90393_OSR_1); // Set oversampling rate
sensor.setFilter(MLX90393_FILTER_1); // Set filter to level 5
}
void MLXLoep() {
float x, y, z;
// Read data from MLX90393 sensor
if (sensor.readData(&x, &y, &z)) {
Serial.print("X: ");
Serial.print(x, 4);
Serial.print(" uT\t");
Serial.print("Y: ");
Serial.print(y, 4);
Serial.print(" uT\t");
Serial.print("Z: ");
Serial.print(z, 4);
Serial.println(" uT");
// Calculate angle in the XY plane
float angle = atan2(y, x) * 180.0 / PI; // Convert radians to degrees
// Calculate change in angle
float deltaAngle = angle - lastAngle;
lastAngle = angle;
// Adjust for angular wrap-around
if (deltaAngle > 180) deltaAngle -= 360;
if (deltaAngle < -180) deltaAngle += 360;
cumulativeAngle += deltaAngle;
Serial.print("Cumulative Angle: ");
Serial.println(cumulativeAngle);
// Trigger scroll when cumulative angle change exceeds threshold
if (cumulativeAngle > scrollThreshold) {
AdvMouse.move(0, 0, scrollStep); // Scroll up by scrollStep units using AdvMouse
cumulativeAngle = 0; // Reset cumulative angle after scrolling
} else if (cumulativeAngle < -scrollThreshold) {
AdvMouse.move(0, 0, -scrollStep); // Scroll down by scrollStep units using AdvMouse
cumulativeAngle = 0; // Reset cumulative angle after scrolling
}
} else {
Serial.println("Unable to read XYZ data from the sensor.");
}
delay(20); // Adjust delay for scroll speed responsiveness
}
void setCPI(int cpi) {
unsigned cpival = cpi / 50;
adns_com_begin();
adns_write_reg(Resolution_L, (cpival & 0xFF));
adns_write_reg(Resolution_H, ((cpival >> 8) & 0xFF));
adns_com_end();
Serial.print("Got ");
Serial.println(cpi);
Serial.print("Set cpi to ");
Serial.println(cpival * 50);
}
void PMWLoep() {
byte burstBuffer[12];
unsigned long curTime = micros();
unsigned long elapsed = curTime - lastTS;
// Process button state (no delays, just checks)
check_button_state();
// Start burst mode only if it's not already started
if (!inBurst) {
adns_write_reg(Motion_Burst, 0x00); // Start burst mode
lastTS = curTime;
inBurst = true;
}
// Ensure this logic runs at the desired polling interval (e.g., 1ms)
if (elapsed >= 1) { // Polling interval > 0.5 ms
adns_com_begin();
SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE3));
SPI.transfer(Motion_Burst);
delayMicroseconds(35); // Waits for tSRAD
SPI.transfer(burstBuffer, 12); // Read burst buffer
delayMicroseconds(1); // tSCLK-NCS for read operation is 120ns
SPI.endTransaction();
// Extract data from burstBuffer
int motion = (burstBuffer[0] & 0x80) > 0;
int surface = (burstBuffer[0] & 0x08) > 0; // 0 if on surface, 1 if off surface
int xl = burstBuffer[2];
int xh = burstBuffer[3];
int yl = burstBuffer[4];
int yh = burstBuffer[5];
int squal = burstBuffer[6];
// Calculate X and Y motion
int x = xh << 8 | xl;
int y = yh << 8 | yl;
// Invert axes if needed (adjust as necessary for your setup)
dx -= y;
dy -= x;
adns_com_end();
// Update mouse only if motion is detected
if (AdvMouse.needSendReport() || motion) {
AdvMouse.move(dx, dy, 0);
dx = 0;
dy = 0;
}
// Update last timestamp for PMW sensor
lastTS = curTime;
// Command process routine
if (Serial.available() > 0) {
char c = Serial.read();
switch (c) {
case 'C': // Set CPI
int newCPI = readNumber();
setCPI(newCPI);
break;
}
}
}
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - lastUpdatePMW >= PMWUpdateInterval) {
lastUpdatePMW = currentMillis;
// Read and process PMW sensor data
PMWLoep();
}
if (currentMillis - lastUpdateMLX >= MLXUpdateInterval) {
lastUpdateMLX = currentMillis;
// Read and process MLX sensor data
MLXLoep();
}
}
// Button state checkup routine
void check_button_state() {
// runs only after initialization
if (initComplete != 9)
return;
unsigned long elapsed = curTime - lastButtonCheck;
// Update at a period of 1/8 of the DEBOUNCE time
if (elapsed < (DEBOUNCE * 1000UL / 8))
return;
lastButtonCheck = curTime;
// Debounce
for (int i = 0; i < NUMBTN; i++) {
int btn_state = digitalRead(Btn_pins[i]);
Btn_buffers[i] = Btn_buffers[i] << 1 | btn_state;
if (!Btns[i] && Btn_buffers[i] == 0x00) // button press stabilized
{
MOUSE_PRESS(Btn_keys[i]);
Btns[i] = true;
} else if (Btns[i] && Btn_buffers[i] == 0xFF) // button release stabilized
{
MOUSE_RELEASE(Btn_keys[i]);
Btns[i] = false;
}
}
}
unsigned long readNumber() {
String inString = "";
for (int i = 0; i < 10; i++) {
while (Serial.available() == 0)
;
int inChar = Serial.read();
if (isDigit(inChar)) {
inString += (char)inChar;
}
if (inChar == '\n') {
int val = inString.toInt();
return (unsigned long)val;
}
}
// flush remain strings in serial buffer
while (Serial.available() > 0) {
Serial.read();
}
return 0UL;
}
//Firmware things//
void performStartup(void) {
// hard reset
adns_com_end(); // ensure that the serial port is reset
adns_com_begin(); // ensure that the serial port is reset
adns_com_end(); // ensure that the serial port is reset
adns_write_reg(Shutdown, 0xb6); // Shutdown first
delay(300);
adns_com_begin(); // drop and raise ncs to reset spi port
delayMicroseconds(40);
adns_com_end();
delayMicroseconds(40);
adns_write_reg(Power_Up_Reset, 0x5a); // force reset
delay(50); // wait for it to reboot
// read registers 0x02 to 0x06 (and discard the data)
adns_read_reg(Motion);
adns_read_reg(Delta_X_L);
adns_read_reg(Delta_X_H);
adns_read_reg(Delta_Y_L);
adns_read_reg(Delta_Y_H);
// upload the firmware
adns_upload_firmware();
delay(10);
Serial.println("Optical Chip Initialized");
}
void adns_com_begin() {
digitalWrite(ncs, LOW);
}
void adns_com_end() {
digitalWrite(ncs, HIGH);
}
byte adns_read_reg(byte reg_addr) {
adns_com_begin();
// send adress of the register, with MSBit = 0 to indicate it's a read
SPI.transfer(reg_addr & 0x7f);
delayMicroseconds(35); // tSRAD
// read data
byte data = SPI.transfer(0);
delayMicroseconds(1); // tSCLK-NCS for read operation is 120ns
adns_com_end();
delayMicroseconds(19); // tSRW/tSRR (=20us) minus tSCLK-NCS
return data;
}
void adns_write_reg(byte reg_addr, byte data) {
adns_com_begin();
//send adress of the register, with MSBit = 1 to indicate it's a write
SPI.transfer(reg_addr | 0x80);
//sent data
SPI.transfer(data);
delayMicroseconds(20); // tSCLK-NCS for write operation
adns_com_end();
delayMicroseconds(100); // tSWW/tSWR (=120us) minus tSCLK-NCS. Could be shortened, but is looks like a safe lower bound
}
void adns_upload_firmware() {
// send the firmware to the chip, cf p.18 of the datasheet
Serial.println("Uploading firmware...");
//Write 0 to Rest_En bit of Config2 register to disable Rest mode.
adns_write_reg(Config2, 0x00);
// write 0x1d in SROM_enable reg for initializing
adns_write_reg(SROM_Enable, 0x1d);
// wait for more than one frame period
delay(10); // assume that the frame rate is as low as 100fps... even if it should never be that low
// write 0x18 to SROM_enable to start SROM download
adns_write_reg(SROM_Enable, 0x18);
// write the SROM file (=firmware data)
adns_com_begin();
SPI.transfer(SROM_Load_Burst | 0x80); // write burst destination adress
delayMicroseconds(15);
// send all bytes of the firmware
unsigned char c;
for (int i = 0; i < firmware_length; i++) {
c = (unsigned char)pgm_read_byte(firmware_data + i);
SPI.transfer(c);
delayMicroseconds(15);
}
//Read the SROM_ID register to verify the ID before any other register reads or writes.
adns_read_reg(SROM_ID);
//Write 0x00 (rest disable) to Config2 register for wired mouse or 0x20 for wireless mouse design.
adns_write_reg(Config2, 0x00);
adns_com_end();
}