I have a teensy project to read a joystick.
Teensy3.2 or 4.0, M1 macos 14.4, vscode 18.1, platformio
I want to calibrate it on demand from the Interface app from my mac.
That works well for the max value with the code blelow. adcindex is incremented in the loop, ringbufferindexMax is uint8_t, all other variables are uint16_t. potmaxA is set to 0 in setup.
potwertA = readJoystick(POTA_PIN); // read joystick, global var
// MAXIMUM
if(maxminstatus & (1<<MAX_A)) // statusbit for calibration maximum ON
{
if(potwertA >= joystickmaxA) // insert in Ringbuffer
{
ringbufferarraymaxA[ringbufferindexMax%4] = potwertA;
ringbufferindexMax++;
}
if(adcindex%16 == 0) // 4 runs
{
uint16_t maxsum = 0;
for (int i=0;i<4;i++)
{
maxsum += ringbufferarraymaxA[i];
}
maxsum /= 4;
if(maxsum > potmaxA) // check for update Maximum
{
potmaxA = maxsum;
}
} // %16
} // if(maxminstatus & (1<<MAX_A))
adcindex++;
For avaraging – bad potentiometers – I read the values into a ring buffer and check if the avarage is higher than before.
The same code for the minimum with potminA does not work correctly.
potminA is set to potmitteA (middle Value of joystick) in setup. The check is for
minsum <= potminA
minsum is calculated correctly.
Code:
// MINIMUM
if((maxminstatus & (1<<MIN_A))) // calibration minimum ON
{
if(potwertA <= joystickminA) // insert in Ringbuffer
{
ringbufferarrayminA[ringbufferindexMin%4] = potwertA;
ringbufferindexMin++;
}
if(adcindex%16 == 0) // 4 loops
{
// Minimum
volatile uint16_t minsum = 0;
for (int i=0;i<4;i++)
{
joystickbuffer[30+i] = (ringbufferarrayminA[i]>>2);
minsum += ringbufferarrayminA[i];
}
minsum = minsum / 4; // average
joystickbuffer[26] = (minsum & 0xFF00)>>8;
joystickbuffer[27] = minsum & 0x00FF;
if (minsum <= potminA) // check for update Minimum
{
potminA = minsum;
joystickbuffer[18] = (potminA & 0xFF00)>>8;
joystickbuffer[19] = potminA & 0x00FF;
joystickbuffer[44] = (minsum & 0xFF00)>>8;
joystickbuffer[45] = minsum & 0x00FF;
}
}// adcindex%16
}// if((maxminstatus & (1<<MIN_A)))
The var joystickbuffer is sent for reading the var’s to the mac via USB every seccond because Terminal is not working with rawHID.
Problem:
Setting potminA to a potmitteA (medium value of the joysick) in setup to start the check is useless. In the loop, the value is always 0.
nullcount is uint16_t, set global.
If I check for 0 at the beginning of the MINIMUM code with
if (potminA == 0)
{
potminA = potmitteA;
joystickbuffer[10] = (nullcount & 0xFF00)>>8; // send via USB
joystickbuffer[11] = nullcount & 0x00FF;
nullcount++;
}
counting the occurences, the code works fine. nullcount counts up rather fast, but after the first mesurement of the joystick the counting stops.