-1

I have a task where I need to control the airplanes thrust and altitude direction(Up-Down). For the thrust I thought of using a DC Motor and a Servo for the other. Control of servo will be from the buttons and the thrust value will be given from the serial port. (This is not a project of a real vehicle, only thing I need to do is the code, rest is imaginary.) enter image description here

I have wrote the following code. I would like to ask is there any flaws and how can I further improve it? Thanks in advance. With my regards...

#include <Servo.h>
  Servo servo1;
  int pos = 0;
  const int buttonSUP = 2;
  const int buttonSDOWN = 3;

  int buttonStateUP = 0;
  int buttonStateDOWN = 0;


  int motorPin = 4;

  void setup() {

  servo1.attach(9);
  pinMode( buttonSUP, INPUT); 
  pinMode( buttonSDOWN, INPUT); 

  pinMode(motorPin, OUTPUT);
    Serial.begin(9600);
    while (! Serial);
    Serial.println("Speed 0 to 255");

  }

  void loop() {
   buttonStateUP =digitalRead(buttonSUP);
   if(buttonStateUP=HIGH){
      servo1.write(90);    
      Serial.println("UP");                            
    } 
    if(buttonStateDOWN=HIGH){
      servo1.write(0); 
     Serial.println("DOWN");  
      }
    else{
        servo1.write(45);
        Serial.println("STABLE");  
        }    

    if (Serial.available())
    {
      int speed = Serial.parseInt();
      if (speed >= 0 && speed <= 255)
      {
        analogWrite(motorPin, speed);
        Serial.println(speed);  
      }
    }

    }
  • Your formatting is off, but also, it's always either DOWN or STABLE? – Paul Apr 1 at 5:39
  • I thought as the servo being 45 degrees shifted just as this "<". There fore with a 90 degree move, I can shift from up to down or vice versa . – E.Canberk Apr 1 at 8:15
0

while (! Serial); Is not needed if you have a board with USB-> Serial bridge Chip (arduino uno for example)

if(buttonStateDOWN=HIGH){
}

In every condition you used = instead of ==. Your "condition" actually assigns HIGH to buttonStateDOWN. If you want to compare integers, use ==.

And according to the question, I think you have misunderstood the speed buttons (or maybe I have). I think, they want you to code it so while the button is pressed or every time the button is pressed, the speed changes by +1 or -1.

Assuming the rest works fine, there could be a problem with your serial output, since you just spam messages.

Read about the millis();, it can help you so you only send something every x amount of seconds, without using delay(); Here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.