Last active
November 24, 2015 00:49
-
-
Save jrleeman/e56f6e0466cfbf83efe5 to your computer and use it in GitHub Desktop.
Reads strain gauge load cell with HX711 and controls large pointer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <HX711.h> | |
#include <Servo.h> | |
#define DOUT 3 | |
#define CLK 2 | |
#define SERVOPIN 9 | |
const int nAvg=5; | |
const int nXPixels=160; | |
const int nYPixels=128; | |
#define maxservo 125 // Maximum degree setting that is safe for servo | |
#define minservo 45 // Minimum degree setting that is safe for servo | |
HX711 loadCell(DOUT, CLK); | |
Servo pointerServo; | |
float relative_position; | |
int absolute_position; | |
int initial_reading; | |
int servo_range; | |
void setup() { | |
// Setup the LCD | |
Serial.begin(115200); | |
// Initialize Servo and set to far left | |
pointerServo.attach(SERVOPIN); | |
move_servo(pointerServo, 0); | |
loadCell.set_gain(128); | |
// Set all values in history array to 100 point average | |
initial_reading = loadCell.read_average(50); | |
//initial_reading = abs(initial_reading); | |
} | |
void loop() { | |
int reading = loadCell.read_average(2); | |
reading = abs(reading - initial_reading); | |
reading = runningAverage(reading); | |
Serial.println(reading); | |
//Serial.print(","); | |
set_pointer(pointerServo, 0, 1000, reading); | |
} | |
void set_pointer(Servo &servo,float min_val, float max_val, float input_val) { | |
// Sets the pointer to point at the input value given the full scale | |
// and zero values of the scale. | |
relative_position = float(input_val - min_val)/(max_val - min_val); | |
servo_range = maxservo - minservo; | |
absolute_position = relative_position * servo_range + minservo; | |
move_servo(servo, absolute_position); | |
} | |
long runningAverage(int M) | |
{ | |
static int LM[20]; // LastMeasurements | |
static byte index = 0; | |
static long sum = 0; | |
static byte count = 0; | |
static int LMSIZE=20; | |
// keep sum updated to improve speed. | |
sum -= LM[index]; | |
LM[index] = M; | |
sum += LM[index]; | |
index = index % LMSIZE; | |
if (count < LMSIZE) count++; | |
return sum / count; | |
} | |
void move_servo(Servo &servo, int position) { | |
// Moves the servo to the desired position, only if it fits | |
// within the safety bounds defined | |
if (position > maxservo) { position = maxservo; } | |
if (position < minservo) { position = minservo; } | |
servo.write(position); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment