View Single Post
  #5   Spotlight this post!  
Unread 04-25-2012, 06:46 PM
Michael Hill's Avatar
Michael Hill Michael Hill is offline
Registered User
FRC #3138 (Innovators Robotics)
Team Role: Mentor
 
Join Date: Jul 2004
Rookie Year: 2003
Location: Dayton, OH
Posts: 1,566
Michael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond reputeMichael Hill has a reputation beyond repute
Re: Arduino and kop encoder

Too funny. I'm literally doing this as I speak. Here's my code.

Code:
// Controlling a servo position using a potentiometer (variable resistor) 
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott> 

#include <Servo.h> 
 
Servo motor1;  // create servo object to control a motor 
Servo motor2;  // ditto
 
int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin 
volatile byte rpmcount;
unsigned int rpm;
unsigned long timeold;

 
void setup() 
{ 
  motor1.attach(9);  // attaches the motor 1 on pin 9 to the servo object 
  motor2.attach(10); // attaches the motor 2 on pin 10 to the servo object
  attachInterrupt(0, rpm_fun, RISING); // attaches the encoder on (digital pin 2)
  rpmcount = 0;
  rpm = 0;
  timeold = 0;
  digitalWrite(2, HIGH);
  Serial.begin(9600);
} 
 
void loop() 
{ 
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023) 
  val = map(val, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180) 
  
  if (rpmcount >= 0) {
    rpm = 30*1000/(millis() - timeold)*rpmcount;
    timeold = millis();
    rpmcount = 0;
    Serial.print("RPM: ");
    Serial.print(rpm);
    Serial.print(" Pot: ");
    Serial.print(val);
    Serial.print("\n");
  }  
  
  motor1.write(val);                  // sets the motor speed according to the scaled value 
  motor2.write(val);
}

void rpm_fun()
{
  rpmcount++;
}
Note that you either have to use a pullup resistor or use the digitalWrite(2, HIGH) command in the setup section (as I did). This uses the internal pull-up resistor on that pin. Also, note that I'm controlling 2 motors with a potentiometer. That's what's basically happening here.

Last edited by Michael Hill : 04-25-2012 at 06:51 PM.