Как упростить код
- Войдите на сайт для отправки комментариев
Сб, 17/03/2018 - 22:39
Доброго времени суток.
Я совсем новичок в этом деле (программирование), но и все же, смог переписать готовый код под свои колличества и свои нужды. Теперь у меня вопрос, наверно можно "упростить" столь громоздкий код? какими командами мне необходимо это осуществить? Что надо дописать (какие команды), чтобы после перезагрузки, сбой в питании, сервомотры запоминали свою текущую позицию? Спасибо
#include <Servo.h> // constant variables used to set servo angles, in degrees const int straight = 20; const int divergent = 150; const int straight1 = 20; const int divergent1 = 150; const int straight2 = 20; const int divergent2 = 150; const int straight3 = 20; const int divergent3 = 150; const int straight4 = 20; const int divergent4 = 150; // constant variables holding the ids of the pins we are using const int buttonpin = 53; const int servopin = 2; const int buttonpin1 = 52; const int servopin1 = 3; const int buttonpin2 = 51; const int servopin2 = 4; const int buttonpin3 = 50; const int servopin3 = 5; const int buttonpin4 = 48; const int servopin4 = 6; const int divergent_led = 22; const int straight_led = 23; const int divergent_led1 = 24; const int straight_led1 = 25; const int divergent_led2 = 26; const int straight_led2 = 27; const int divergent_led3 = 28; const int straight_led3 = 29; const int divergent_led4 = 30; const int straight_led4 = 31; // servo movement step delay, in milliseconds const int step_delay = 10; // create a servo object Servo myservo; Servo myservo1; Servo myservo2; Servo myservo3; Servo myservo4; // global variables to store servo position int pos = straight; // current int old_pos = pos; // previous int pos1 = straight1; // current int old_pos1 = pos1; // previous int pos2 = straight2; // current int old_pos2 = pos2; // previous int pos3 = straight3; // current int old_pos3 = pos3; // previous int pos4 = straight4; // current int old_pos4 = pos4; // previous void setup() { // set the mode for the digital pins in use pinMode(buttonpin, INPUT); pinMode(straight_led, OUTPUT); pinMode(divergent_led, OUTPUT); pinMode(buttonpin1, INPUT); pinMode(straight_led1, OUTPUT); pinMode(divergent_led1, OUTPUT); pinMode(buttonpin2, INPUT); pinMode(straight_led2, OUTPUT); pinMode(divergent_led2, OUTPUT); pinMode(buttonpin3, INPUT); pinMode(straight_led3, OUTPUT); pinMode(divergent_led3, OUTPUT); pinMode(buttonpin4, INPUT); pinMode(straight_led4, OUTPUT); pinMode(divergent_led4, OUTPUT); // setup the servo myservo.attach(servopin); // attach to the servo on pin 2 myservo.write(pos); // set the initial servo position myservo1.attach(servopin1); // attach to the servo on pin 3 myservo1.write(pos1); // set the initial servo position myservo2.attach(servopin2); // attach to the servo on pin 4 myservo2.write(pos2); // set the initial servo position myservo3.attach(servopin3); // attach to the servo on pin 5 myservo3.write(pos3); // set the initial servo position myservo4.attach(servopin4); // attach to the servo on pin 6 myservo4.write(pos4); // set the initial servo position // set initial led states digitalWrite(straight_led, HIGH); digitalWrite(divergent_led, LOW); digitalWrite(straight_led1, HIGH); digitalWrite(divergent_led1, LOW); digitalWrite(straight_led2, HIGH); digitalWrite(divergent_led2, LOW); digitalWrite(straight_led3, HIGH); digitalWrite(divergent_led3, LOW); digitalWrite(straight_led4, HIGH); digitalWrite(divergent_led4, LOW); } void loop() { // start each iteration of the loop by reading the button // if the button is pressed (reads HIGH), move the servo int button_state = digitalRead(buttonpin); if (button_state == HIGH) { // turn off the lit led if(pos == straight){ digitalWrite(straight_led, LOW); } else { digitalWrite(divergent_led, LOW); } old_pos = pos; // save the current position // Toggle the position to the opposite value pos = pos == straight ? divergent : straight; // Move the servo to its new position if (old_pos < pos) { // if the new angle is higher // increment the servo position from oldpos to pos for (int i = old_pos + 1; i <= pos; i++) { myservo.write(i); // write the next position to the servo delay(step_delay); // wait } } else { // otherwise the new angle is equal or lower // decrement the servo position from oldpos to pos for (int i = old_pos - 1; i >= pos; i--) { myservo.write(i); // write the next position to the servo delay(step_delay); // wait } } // turn on the appropriate LED. if(pos == straight){ digitalWrite(straight_led, HIGH); } else { digitalWrite(divergent_led, HIGH); } } { // start each iteration of the loop by reading the button // if the button is pressed (reads HIGH), move the servo int button_state = digitalRead(buttonpin1); if (button_state == HIGH) { // turn off the lit led if(pos1 == straight1){ digitalWrite(straight_led1, LOW); } else { digitalWrite(divergent_led1, LOW); } old_pos1 = pos1; // save the current position // Toggle the position to the opposite value pos1 = pos1 == straight1 ? divergent1 : straight1; // Move the servo to its new position if (old_pos1 < pos1) { // if the new angle is higher // increment the servo position from oldpos to pos for (int i = old_pos1 + 1; i <= pos1; i++) { myservo1.write(i); // write the next position to the servo delay(step_delay); // wait } } else { // otherwise the new angle is equal or lower // decrement the servo position from oldpos to pos for (int i = old_pos1 - 1; i >= pos1; i--) { myservo1.write(i); // write the next position to the servo delay(step_delay); // wait } } // turn on the appropriate LED. if(pos1 == straight1){ digitalWrite(straight_led1, HIGH); } else { digitalWrite(divergent_led1, HIGH); } } } // start each iteration of the loop by reading the button // if the button is pressed (reads HIGH), move the servo { int button_state = digitalRead(buttonpin2); if (button_state == HIGH) { // turn off the lit led if(pos2 == straight2){ digitalWrite(straight_led2, LOW); } else { digitalWrite(divergent_led2, LOW); } old_pos2 = pos2; // save the current position // Toggle the position to the opposite value pos2 = pos2 == straight2 ? divergent2 : straight2; // Move the servo to its new position if (old_pos2 < pos2) { // if the new angle is higher // increment the servo position from oldpos to pos for (int i = old_pos2 + 1; i <= pos2; i++) { myservo2.write(i); // write the next position to the servo delay(step_delay); // wait } } else { // otherwise the new angle is equal or lower // decrement the servo position from oldpos to pos for (int i = old_pos2 - 1; i >= pos2; i--) { myservo2.write(i); // write the next position to the servo delay(step_delay); // wait } } // turn on the appropriate LED. if(pos2 == straight2){ digitalWrite(straight_led2, HIGH); } else { digitalWrite(divergent_led2, HIGH); } } } { // start each iteration of the loop by reading the button // if the button is pressed (reads HIGH), move the servo int button_state = digitalRead(buttonpin3); if (button_state == HIGH) { // turn off the lit led if(pos3 == straight3){ digitalWrite(straight_led3, LOW); } else { digitalWrite(divergent_led3, LOW); } old_pos3 = pos3; // save the current position // Toggle the position to the opposite value pos3 = pos3 == straight3 ? divergent3 : straight3; // Move the servo to its new position if (old_pos3 < pos3) { // if the new angle is higher // increment the servo position from oldpos to pos for (int i = old_pos3 + 1; i <= pos3; i++) { myservo3.write(i); // write the next position to the servo delay(step_delay); // wait } } else { // otherwise the new angle is equal or lower // decrement the servo position from oldpos to pos for (int i = old_pos3 - 1; i >= pos3; i--) { myservo3.write(i); // write the next position to the servo delay(step_delay); // wait } } // turn on the appropriate LED. if(pos3 == straight3){ digitalWrite(straight_led3, HIGH); } else { digitalWrite(divergent_led3, HIGH); } } } { // start each iteration of the loop by reading the button // if the button is pressed (reads HIGH), move the servo int button_state = digitalRead(buttonpin4); if (button_state == HIGH) { // turn off the lit led if(pos4 == straight4){ digitalWrite(straight_led4, LOW); } else { digitalWrite(divergent_led4, LOW); } old_pos4 = pos4; // save the current position // Toggle the position to the opposite value pos4 = pos4 == straight4 ? divergent4 : straight4 ; // Move the servo to its new position if (old_pos4 < pos4) { // if the new angle is higher // increment the servo position from oldpos to pos for (int i = old_pos4 + 1; i <= pos4; i++) { myservo4.write(i); // write the next position to the servo delay(step_delay); // wait } } else { // otherwise the new angle is equal or lower // decrement the servo position from oldpos to pos for (int i = old_pos4 - 1; i >= pos4; i--) { myservo4.write(i); // write the next position to the servo delay(step_delay); // wait } } // turn on the appropriate LED. if(pos4 == straight4){ digitalWrite(straight_led4, HIGH); } else { digitalWrite(divergent_led4, HIGH); } } } }// end of loop
Массивы, цикл от 0 до 4, eeprom.
.
а можно поподробнее, я совсем 0 в этом. Хотя бы направить, где копать
Массивы, циклы, eeprom.
Проще говоря, находимся в ветке MAIN_MENU нажали кнопку раз инкремент а a++, в MENU_MANUAL нажатие кнопки уже инкремент b,c
Возможно следует искать решение через указатели?
BuonanotteMash, вопрос то о чем?
ПС #250 и #251
Видимо проще и не получится
BuonanotteMash,проще в каком смысле. Если у вас есть уже готовая рабочая схема, то можно адаптировать под нужное устройство. Так важнее не код который проще написать с нуля, а код который легче адаптировать под нужные реалии. PROGMEM и EEPROM уже набьют вам размер. А маленький размер ОЗУ не позволит сильно разгулятся в творчестве. Вывод написание меню это попытка усидется одной жопой на 12 стульях. Урежте стулья и проще код станет. Но тогда программа станет примитив.
qwone, управляющее меню делаю для практически готовой паяльной станции, меню простое на 4 пункта, усложнять не требуется. С классом кнопки вы мне тогда помогли, благодарен. Но хотелось бы сделать обработчики класса как бы универсальными. К примеру кнопкой ">" можно было бы увеличивать значение в любом пункте меню не дублируя код, изменяя только требуемые переменные
А зачем в
MENU_MANUAL
инкремент двух переменных?Просто для примера. Смысл показать что происходит какое то действие. Считайте что там просто инкремнт b++
ну тогда int incremet_data[4];
incremet_data[current_menu_index]++;
Тут вы объявили массив типа int incremet_data[4] видимо 4 равносильно количество пунктов меню. Но когда я сказал для примера я не имел ввиду что действия будут над одной переменной, тут скорее действия будут происходить над целым фрагментом кода. Массив я считаю тут не подойдет
BuonanotteMash, я бы предлжил бы создать класс дисплей с кучей viev обработчиков и банально переключаться. Но расписывать эту идею , не сильно хочу . ,будет треп на 10 постов.
я разобрался с вопросом , вот ссылка может кому пригодится http://www.c-cpp.ru/books/ukazateli-na-funkcii-0