Всем доброго времени суток. Палками сильно не бить, т.к. совсем нуб в этом деле, и все же... Есть готовый скетч работы одного сервопривода с одной кнопки на заданный угол отклонения, нажал кнопку-сервак "туда", нажал еще раз, "обратно". Так же, после остановки в крайних положениях, нам сигнализируют 2 светодиода (условно красный и зеленый). Так вот, не доходит до меня: 1. При отключении питания (reset), сервопривод должен "запомнить" свою текущую позицию, до момента "сбоя", но этого не происходит. 2. Как мне добавить в готовый скетч еще один такой комплект (сервак-кнопка-2 светодиода), а если надо 3 или 4. И сколько можно максимум "повесить" на Mega2560. Заранее, спасибо. Схема подключения http://thenscaler.com/wp-content/uploads/2014/12/Servo-Control-by-Button.jpg Код: Код (C++): #include <Servo.h> // constant variables used to set servo angles, in degrees const int straight = 50; const int divergent = 150; // constant variables holding the ids of the pins we are using const int divergent_led = 6; const int straight_led = 7; const int buttonpin = 8; const int servopin = 9; // servo movement step delay, in milliseconds const int step_delay = 5; // create a servo object Servo myservo; // global variables to store servo position int pos = straight; // current int old_pos = pos; // previous void setup() { // set the mode for the digital pins in use pinMode(buttonpin, INPUT); pinMode(straight_led, OUTPUT); pinMode(divergent_led, OUTPUT); // setup the servo myservo.attach(servopin); // attach to the servo on pin 9 myservo.write(pos); // set the initial servo position // set initial led states digitalWrite(straight_led, HIGH); digitalWrite(divergent_led, 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); } } }// end of loop
И не произойдет хотя бы по двум причинам: 1. При отключении питания для сохранения данных устройство должно иметь хоть какое-то питание. Этого нет. 2. Даже при наличии дополнительного (аварийного) ИП, при пропадании основного питания (или нажатия Reset) должна быть программно выполнена обработка этих событий для сохранения данных. Этого тоже нет... Вот и не доходит...
Отследить событие "пропадание питания", лучше прерыванием, чтоб не мониторить в программе. По прерыванию - сохранить нужные данные. Как это сделать в программе - учимся программировать, а не копипастить. Пример "аварийного ИП" можно найти в "часовом" модуле.
Для сохранения данных - за глаза, а после этого можно МК загнать в сон и потребление будет мизерное. Периферия без команд та же практически ничего кушать не будет.
Как это не будет? Если не принять специальных мер по моментальному отключению питания на всех датчиках и индикаторах, то будет еще как. И потребление самого МК на этом фоне вообще незначительный мизер. Но смысла заморачиваться с этим нет никакого, потому что аккумулятор LiPo стоит копейки и тянет часами. Добавьте контроллер заряда и будет вам ИПБ. Отличить от какого источника питания в данный момент идет потребление - как два пальца. Узнать остаток заряда - тоже. И меры принимать в зависимости от этой информации легко и просто.
я на верном пути??? Код (C++): #include <Servo.h> // constant variables used to set servo angles, in degrees const int straight = 0; const int divergent = 180; // constant variables holding the ids of the pins we are using const int divergent_led = 6; const int straight_led = 7; const int buttonpin = 8; const int servopin = 9; const int divergent_led1 = 10; const int straight_led1 = 11; const int buttonpin1 = 12; const int servopin1 = 13; // servo movement step delay, in milliseconds const int step_delay = 5; // create a servo object Servo myservo; Servo myservo1; // global variables to store servo position int pos = straight; // current int old_pos = pos; // 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); // setup the servo myservo.attach(servopin); // attach to the servo on pin 9 myservo.write(pos); // set the initial servo position myservo1.attach(servopin1); // attach to the servo on pin 13 myservo1.write(pos); // set the initial servo position // set initial led states digitalWrite(straight_led, HIGH); digitalWrite(divergent_led, LOW); // set initial led states digitalWrite(straight_led1, HIGH); digitalWrite(divergent_led1, 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); } } }// end of loop
Код (C++): #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 подскажите, как можно упростить этот скетч...
Путем шевеления извилин, я пришел к желаемому результату,чему несказанно рад. Но мне кажется, выше выложенный код, можно "упростить", отсюда вопрос/совет- с помощью каких команд я могу осуществить задуманное?