Youtube Channel
scrivimi: fraranux@gmail.com
chiamami: 345 04.22.\pi

venerdì 17 ottobre 2014

Attiny 85 e servomotore: amore possibile!

Per muovere un servomotore ci vuole una libreria apposta per Attiny, la Softwareservo.h,
per la programmazione dell'Attiny  vi rimando qui.
Lo schema qui sotto:




qui il codice ad esempio per il Knob:


#include <SoftwareServo.h>

#define PIN_SERVO 0
#define PIN_POT 2
#define PULSE_MIN 600 // in microsecs
#define PULSE_MAX 2400 // in microsecs
#define READINGS_COUNT 10

SoftwareServo servo;
long potValue = 0;
int readings[READINGS_COUNT] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
byte readingsPos = 0;
unsigned long nextReadingDue = 0;

void setup(){
servo.attach(PIN_SERVO);
servo.setMinimumPulse(PULSE_MIN);
servo.setMaximumPulse(PULSE_MAX);
}

void loop(){
// read the analog pin once every millisec, and store the data until we have enough to filter
unsigned long currentTime = micros();
if(currentTime > nextReadingDue){
readings[readingsPos] = analogRead(PIN_POT);
readingsPos ++;

nextReadingDue = currentTime + 1000;
}

// once every READINGS_COUNT readings, clean the data and update the servo
// also filter using weighted moving average to avoid excessive jittering due to poor potentiometer
if(readingsPos > READINGS_COUNT){
potValue = (9 * potValue + getCleanReading())/ 10;

servo.write(map(potValue, 0, 1023, 0, 180));

readingsPos = 0;
}

// good to call this as often as we can, so that we don't miss the moment when the signal has to go up or down
SoftwareServo::refresh();
}

// reads several analog values and tries to do some smart filtering
int getCleanReading(){
int reading, minReading=9999, maxReading=0;
long result = 0;

for(byte i=0; i<READINGS_COUNT; i++){
readings[i] = analogRead(PIN_POT);
result += readings[i];

if(readings[i] < minReading){
minReading = readings[i];
}
if(readings[i] > maxReading){
maxReading = readings[i];
}
}

// reaturn the average after eliminating min and max readings
return (result - minReading - maxReading) / (READINGS_COUNT - 2);
}





Nessun commento:

Posta un commento