Optimizing and condensing some code

Hi guys im trying to do a little project and i can't work out the best way to condense the following code down using functions. I just need to make it more streamlined.
T.I.A

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
#include <Servo.h>
Servo inservo;
Servo outservo;
int inpir;
int outpir;
int c = 0;
void setup()

{
lcd.begin(16, 2);
Serial.begin(9600);
inservo.attach(8);
outservo.attach(10);
pinMode(A0, INPUT);
pinMode(A1, INPUT);
}
void loop()
{
inpir=digitalRead(A0);
outpir=digitalRead(A1);
Serial.println(inpir);
Serial.print("\t");
Serial.println(outpir);
Serial.println();
if (inpir == 0)
if ((c==1)or(c<5))
{
c = c+1;
Serial.println (c);
inservo.write(90);
outservo.write(90);
delay(1000);
outservo.write(0);
inservo.write(0);
delay(1000);
inservo.write(90);
outservo.write(90);
lcd.setCursor(12,0);
lcd.print(c);
}
if (outpir == 0)
if ((c==5)or(c>0))
{
c = c-1;
Serial.println (c);
inservo.write(90);
outservo.write(90);
delay(1000);
outservo.write(0);
inservo.write(0);
delay(1000);
inservo.write(90);
outservo.write(90);
lcd.setCursor(12,0);
lcd.print(c);
}
lcd.setCursor(0,0);
lcd.print("People in - ");
lcd.setCursor(0,1);
lcd.print("Stay home ");
delay(2000);
lcd.setCursor(0,1);
lcd.print("Limit 5 people");
delay(2000);
lcd.setCursor(0,1);
lcd.print("Stay safe ");
delay(2000);
}

Why, if it works for you then it works ?

What you need to do is add comments :slight_smile: .

First off, you are expected to:

In the Arduino IDE, use Ctrl T or CMD T to format your code then copy the complete sketch.

Use the </> icon from the ‘reply menu’ to attach the copied sketch.

What functions do you need ?

Show us your attempts at writing functions ?

Hello
Yes you can.
Build some objects and methods to streamline the code.
Drop all information for the servos and LCD in datablocks using the struct instruction. A method for the servos and one method for the LCD will operate the information out of the a.m. datablocks. Maybe a timer handler is needed too.
Have a nice day and enjoy coding in C++.

seems this part is repeated twice:

    Serial.println (numberOfCustomers);
    inservo.write(90);
    outservo.write(90);
    delay(1000);
    outservo.write(0);
    inservo.write(0);
    delay(1000);
    inservo.write(90);
    outservo.write(90);
    lcd.setCursor(12, 0);
    lcd.print(numberOfCustomers);

See reply #7

Hello siu3
It is recommented to take a view into some powerful C++ instructions like STRUCT, ENUM, ARRAY, CASE/SWITCH,UDT, RANGE-BASED-FOR-LOOP, etc.
Have a nice day and enjoy coding in C++.

Show us your attempts that makes you say this.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.