Skip to content

Instantly share code, notes, and snippets.

@Robotto
Last active August 29, 2015 14:26
Show Gist options
  • Save Robotto/1f1a6584c5348a6ce940 to your computer and use it in GitHub Desktop.
Save Robotto/1f1a6584c5348a6ce940 to your computer and use it in GitHub Desktop.
// Arrays to save our results in
unsigned long start_time;
unsigned long stop_time;
unsigned int dX;
unsigned int dY;
unsigned int lastX;
unsigned int lastY;
unsigned int currentX;
unsigned int currentY;
unsigned int filterAlpha=16;
unsigned int dThreshold=15; //minimum average change over filterAlpha samples (62µS per sample at PS_64 prescaler - ~35µS per sample at PS_32)
//So a consistent change of 15 over 16 samples is: TBD mV/µS
// Define various ADC prescaler
const unsigned char PS_16 = (1 << ADPS2);
const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
const unsigned char PS_64 = (1 << ADPS2) | (1 << ADPS1);
const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
static int xPin=A0;
static int yPin=A1;
static int greenLaserInput=7;
static int blueLaserInput=8;
static int redLaserInput=9;
static int redLaserOutput=10;
static int greenLaserOutput=14;
static int blueLaserOutput=16;
// Setup the serial port and pin 2
void setup() {
Serial.begin(9600);
pinMode(redLaserOutput,OUTPUT);
pinMode(greenLaserOutput,OUTPUT);
pinMode(blueLaserOutput,OUTPUT);
//remember to pull down physically
pinMode(greenLaserInput,INPUT);
pinMode(blueLaserInput,INPUT);
pinMode(redLaserInput,INPUT);
pinMode(xPin, INPUT);
pinMode(yPin, INPUT);
// set up the ADC
ADCSRA &= ~PS_128; // remove bits set by Arduino library
// you can choose a prescaler from above.
// PS_16, PS_32, PS_64 or PS_128
ADCSRA |= PS_32; // set our own prescaler to 32
//startup condition:
lastX = analogRead(xPin);
lastY = analogRead(yPin);
unsigned int i;
//populate filter with real values on startup:
for(i=0;i<filterAlpha;i++) {
currentX = analogRead(xPin);
dX = ( dX * filterAlpha + abs( lastX - currentX ) ) / (filterAlpha + 1);
lastX = currentX;
currentY = analogRead(yPin);
dY = ( dY * filterAlpha + abs( lastY - currentY ) ) / (filterAlpha + 1);
lastY = currentY;
}
}
void loop() {
//start_time = micros();
//read X
currentX = analogRead(xPin);
dX = ( dX * filterAlpha + abs( lastX - currentX ) ) / (filterAlpha + 1);
lastX = currentX;
//read y
currentY = analogRead(yPin);
dY = ( dY * filterAlpha + abs( lastY - currentY ) ) / (filterAlpha + 1);
lastY = currentY;
if(dY+dX<dThreshold) killAll();
else
{
digitalWrite(greenLaserOutput, digitalRead(greenLaserInput) );
digitalWrite(blueLaserOutput, digitalRead(blueLaserInput) );
digitalWrite(redLaserOutput, digitalRead(redLaserInput) );
}
//stop_time = micros();
//Serial.println(stop_time-start_time,DEC);
}
void killAll(void)
{
digitalWrite(greenLaserOutput,LOW);
digitalWrite(blueLaserOutput,LOW);
digitalWrite(redLaserOutput,LOW);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment