Сделал простую программу Arduino, хочу узнать, как сделать ее чище / меньше

Вот мой код Он компилируется и работает на моем Arduino MEGA 2560.

#include "Arduino.h"//Standard Arduino Library
#include "Print.h" //Print to serial library, Serial.Println would not work by default for some reason.
#define led_pin 13 //Set var led_pin to equal 13, meaning pin 13
#define pinstate digitalRead(read_pin)
#define read_pin 50 // " 50, "50
int loopstore; //Def as global var so it won't be reset on next loop iteration

void setup() //Setup function, used to set pins and vars before running main Arduino Program
{Serial.begin(9600); //Start serial comms, set baud rate

Serial.println("\nHello User.\n\nArduio has set baud rate and started serial communication.\n\nThank You, Sketch will run momentarily.\n\n");

pinMode(led_pin,OUTPUT); //Set led_pin to digital output mode;

pinMode(read_pin,INPUT); //", " read mode
}void loop() //Actual program

{
loopstart = 1;
do
{
++loopstore;
} while (loopstart == 0);

Serial.println("This program has ran this many times:\n");

Serial.println(loopstore);

digitalWrite(led_pin,HIGH); //Set pin high
delay(1000); //Wait

if (pinstate == 1) //If else statement for outputting pin state to console
{
Serial.println("\nPin is in a HIGH state\n\n"); // Output to console
}
else
{
Serial.println("Pin is in a LOW state\n\n"); // Output to console
}

delay(1500); //Wait

digitalWrite(led_pin,LOW); //Set pin to Low State
delay(1000); //Wait

if (pinstate == 1) //If else funct for outputting pin state to console
{
Serial.println("Pin is in a HIGH state\n\n"); // Output to console
}
else
{
Serial.println("Pin is in a LOW state\n\n"); // Output to console
}

delay(1000); //Wait

digitalWrite(led_pin,HIGH); //Set pin high
delay(1500); //Wait

if (pinstate == 1) //If else funct for outputting pin state to console
{
Serial.println("Pin is in a HIGH state\n\n"); // Output to console
}
else
{
Serial.println("Pin is in a LOW state\n\n"); // Output to console
}

delay(1000); //Wait

digitalWrite(led_pin,LOW); //Set pin to Low State
delay(1500); //Wait

if (pinstate == 1) //If else funct for outputting pin state to console
{
Serial.println("Pin is in a HIGH state\n\n"); // Output to console
}
else
{
Serial.println("Pin is in a LOW state\n\n"); // Output to console
}

delay(1000); //Wait

digitalWrite(led_pin,HIGH); //Set pin high
delay(500); //Wait

if (pinstate == 1) //If else funct for outputting pin state to console
{
Serial.println("Pin is in a HIGH state\n\n"); // Output to console
}
else
{
Serial.println("Pin is in a LOW state\n\n"); // Output to console
}

delay(1000); //Wait

digitalWrite(led_pin,LOW); //Set pin to Low State
delay(500); //Wait

if (pinstate == 1) //If else funct for outputting pin state to console
{
Serial.println("Pin is in a HIGH state\n\n"); // Output to console
}
else
{
Serial.println("Pin is in a LOW state\n\n"); // Output to console
}
}

Я только учусь работать с Arduino, и я сделал быструю и грязную программу, которая просто устанавливает состояние вывода светодиодного контакта на Arduino (13), а затем читает его с помощью контакта 50. Это бессмысленная программа, но я пытаюсь учиться / практиковаться.

Для дополнительной практики я также сделал счетчик количества выполнений функции loop ().

Сделанное мною «Делай пока» увеличивает счетчик. Затем я печатаю результат в серийный. Обратите внимание, что если loopstart == 0, оператор «Do While» запускается снова. Это невозможно, потому что он никогда не устанавливается на 0. Я хотел своего рода счетчик «passthrough», но это лучший способ?

Я почти уверен, что должен быть способ сделать то, что я делал выше, более эффективно, но, будучи новичком в Arduino (и программировании в целом), я понятия не имею, как я смогу упростить это.

У кого-нибудь есть какие-либо предложения или, возможно, место, где они могли бы указать мне?

Я пытался найти в Интернете примеры счетчиков в C ++, но я не смог найти ничего, что находилось бы вне цикла «For».

Спасибо за ваше время и помощь ребенку учиться!

Изменить: не знал о CodeReview. Спасибо!

0

Решение

Может быть, что-то подобное лучше всего подойдет вам.
Если я правильно понимаю, ваша программа в основном переключает светодиод в 3 раза, а затем проверяет состояние выводов с задержкой до и после (которая является переменной).

Если вы хотите, чтобы я подробно описал некоторые части, попросите меня отредактировать свой пост;)

#include "Arduino.h"//Standard Arduino Library
#include "Print.h" //Print to serial library, Serial.Println would not work by default for some reason.

// Some debugging macros
#define DEBUG 1
#define slog(a) { if (DEBUG) Serial.println(a); }; // No debug directive will be in compiled file if DEBUG is set to 0

// Let's define our port mapping
#define LED_PIN _BV(7) //bit 7 on PORTB on 2560 correspond to digital pin 13 (check http://arduino.cc/en/Hacking/PinMapping2560)
#define READ_PIN _BV(3)

// Some quick access for led pin / read pin manipulation
// Let's use bitwise operation on PORTB, digitalRead => 28 cycle, direct read with PORTB => 1 cycle (28x faster!)
// I prefer defining setters as functions, easier to read, but you are not force to (it is exactly the same once compiled)
//#define LED_ON() { PORTB |= LED_PIN; } // Put LED_PIN bit to 1 on PORTB
//#define LED_OFF() { PORTB &= ~LED_PIN; } // Put LED_PIN bit to 0 on PORTB
#define LED_TOGGLE() { PORTB ^= LED_PIN; } // Put LED_PIN bit to 0 if it was 1 or to 1 if it was 0

#define READ_STATE PORTB & READ_PIN // Read LED_PIN bit on PORTBint loopcount = 0; //Def as global var so it won't be reset on next loop iteration

// Let's create an array which will define all the delays before and after serial calls
// ex: {1000, 1500} => 1000ms before serial output, 1500ms after serial output
int wrapDelays[][2] = { {1000, 1500}, {1000, 1000}, {1500, 1000}, {1500, 1000}, {500, 1000}, {500, 0} };

void setup() //Setup function, used to set pins and vars before running main Arduino Program
{
if (DEBUG) Serial.begin(9600); //Start serial comms, set baud rate
slog("\nHello User.\n\nArduio has set baud rate and started serial communication.\n\nThank You, Sketch will run momentarily.\n\n");

// Output/Input for PORTB (in DDRB register)
DDRB |= LED_PIN; // Set LED_PIN to digital output mode (put LED_PIN bit to 1)
DDRB &= ~READ_PIN; // Ensure READ_PIN is in input mode (put READ_PIN bit to 0)
}

// ToggleLed, write read pin state on serial, and wait `delayBefore`ms before and `delayAfter`ms after
void toggleLedBetweenDelays(int delayBefore, int delayAfter){
LED_TOGGLE();

if (delayBefore > 0) delay(delayBefore);

if (READ_STATE) {//If else funct for outputting pin state to console
slog("Pin is in a HIGH state\n\n"); // Output to console
}
else
slog("Pin is in a LOW state\n\n"); // Output to console

if (delayAfter > 0) delay(delayAfter);
}

void loopCounter(){
loopcount++; // increase count of loops
slog("This program has ran this many times:\n");
slog(loopcount);
}

void loop() //Actual program
{
for (int i = 0, l = sizeof(wrapDelays) / sizeof(wrapDelays[0]); i < l; ++i)
{
toggleLedBetweenDelays(wrapDelays[i][0], wrapDelays[i][1]);
}

loopCounter();
}

Замечания: Не забывайте, что не потому, что код, который вы пишете, меньше, чем конечный скомпилированный бинарный файл также будет меньше / оптимизирован.

0

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector