Saturday, April 18, 2015

Make a decision and change the speed of the motor : 2 push buttons and data taken from serial port (0 or 1)

In this improvement, we take binary data 0 or 1 from serial port. We have 2 push buttons. With using these three things, we make a decision; whether the speed of the motor increases or decreases. If our first button state is low, and the second one is high and also the data taken from serial port is 1 then, we choose to increase the speed. The other case is   the data taken from serial port is 1 but the button states are inverse of the first case, meaning that first button state low and second button state is high, we decrease the speed. In this code we used analogWrite() function while changing the value of speed. The photo of this improvement is given below.

Berrak Şişman & İlker Çam


Arduino code:


const int btn1Pin = 2;
const int btn2Pin = 3;
const int motorPin = 9;

int theBitThatIReadFromSerialIfTheMotorIsRunningOrNot = 1;
int motorSpeed = 0;
void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(btn1Pin, INPUT);
  pinMode(btn2Pin, INPUT);
  Serial.begin(9600);
}


void loop()
{
     //serialSpeed();
     motor();
}

void motor(){
  int btnState, btn2State;
  btnState = digitalRead(btn1Pin);
  btn2State = digitalRead(btn2Pin);

  if(btnState == LOW && btn2State == HIGH && theBitThatIReadFromSerialIfTheMotorIsRunningOrNot == 1){
    motorSpeed = (motorSpeed+40);
    motorSpeed = constrain(motorSpeed,0,255);
    analogWrite(motorPin, motorSpeed);
  }else if(btnState == HIGH && btn2State == LOW && theBitThatIReadFromSerialIfTheMotorIsRunningOrNot == 1){
    motorSpeed = (motorSpeed-40);
    motorSpeed = constrain(motorSpeed,0,255);
    analogWrite(motorPin, motorSpeed);
  }

  if(Serial.available() > 0){
    int readed = Serial.parseInt();
    if(readed == 1){
      theBitThatIReadFromSerialIfTheMotorIsRunningOrNot = 1;
      if(motorSpeed<=0){
        motorSpeed = 200;
        analogWrite(motorPin, motorSpeed);
      }
    }else if(readed == 0){
      theBitThatIReadFromSerialIfTheMotorIsRunningOrNot = 0;
      if(motorSpeed>0){
        motorSpeed = 0;
        analogWrite(motorPin, motorSpeed);
      }
    }
  }

  delay(100);
}

No comments:

Post a Comment