Oh, I'm a noob, can someone move this to Software >> Developement -- Sorry!
And here is my go at a Potentiometer class
There might be some errors, but I know the example works.
-updates might come.
I'd be glad if people who use this code and modifies it, posts it back up here for others to see.
One can initiate a pot on analog pin 2 as simple as this:
Potentiometer pot(2);
Now call
pot.calibrate(num_of_sectors_minus_one);
And the:
pot.readSector() //this returns values from 1 --> num_of_sectors
Example:
#include <Potentiometer.h>
Potentiometer pot(2);
void setup()
{
Serial.begin(9600);
Serial.println("Calibrate:");
pot.calibrate(10); // now pot.readSector() returns 1 - 11 || it counts 0, possible improvement
}
void loop()
{
Serial.print("Sector: ");
Serial.print(pot.readSector()); //the sector returned can be used turn on/off leds, or.. whatever.
Serial.print(" Value: ");
Serial.println(pot.readVal());
delay(1000);
}
Potentiometer.cpp
#include "WProgram.h"
#include "Potentiometer.h"
//Constructor
Potentiometer::Potentiometer(int potPin)
{
_potPin = potPin;
//deafults:
_sectors = 4;
_range = 1;
_step = _range / _sectors;
}
void Potentiometer::calibrate(int sectors){
//finds max and min values from the pot
for(int i=0; i<100;i++){
_val = analogRead(_potPin);
if(_val<_minVal) { _minVal=_val; }
if(_val>_maxVal) { _maxVal=_val; }
delay(100);
}
_sectors = sectors-1;
_range = _maxVal - _minVal;
_step = _range / _sectors;
}
int Potentiometer::getMin(){
return _minVal;
}
int Potentiometer::getMax(){
return _maxVal;
}
int Potentiometer::readVal(){
return analogRead(_potPin);
}
int Potentiometer::readSector(){
_val = analogRead(_potPin);
_sector=0; //sectors start at 1, 0 indicates an error
_currentUpperVal=_minVal+_step; //refered to as cUV
//finds the current sector
while(_val > _currentUpperVal){
_sector++;
_currentUpperVal=_sector*_step+_minVal;
if(_val > _currentUpperVal){
break;
}
}
if(_val<_minVal || _val>_maxVal){
return 0; //errorhandeling
}
return _sector;
}
Potentiometer.h
/*
*/
#ifndef Potentiometer_h
#define Potentiometer_h
#include "WConstants.h"
class Potentiometer
{
public:
Potentiometer(int potpin);
void calibrate(int sectors);
int readVal();
int readSector();
int getMin();
int getMax();
private:
int _potPin;
int _range;
int _step;
int _val;
int _minVal;
int _maxVal;
int _sectors;
int _sector;
int _currentUpperVal;
};
#endif
keywords.txt
Potentiometer KEYWORD1
calibrate KEYWORD2
readVal KEYWORD2
readSector KEYWORD2
getMin KEYWORD2
getMax KEYWORD2