message:
Arduino transmitter and receiver

hi I am using Arduino transmitter and receiver it works properly with sending and receiving username and password but I would include to check the username if its true open the led , I added this in the code but it seems that the code ignoring it ( the last part) as well as I want it to take the password and username at the same time

this is the recover code

    #include <RH_ASK.h>//include radioHead ASK library
    #include <SPI.h> // include dependant SPI libray

     RH_ASK rf_driver; // create ASK object
    int ledon = 13;
    String userid;
    String password;
     //RH_ASK ID1; // create ASK object
    //RH_ASK pass1; // create ASK object

    void setup() {

      rf_driver.init(); //initialize ASK object

      Serial.begin(9600); //setup serial monitor to 9600

      //if(!rf_driver.init())
           //Serial.print("init failed");
    }

    void loop() {

      // set buffer to size of expected message
      uint8_t buf[9];
      uint8_t buflen =sizeof(buf);

      //check if recevied packet is correct size
      if (rf_driver.recv(buf,&buflen))
      {
        int i;
        // message received with valid checksum
        Serial.print("id: ");
        Serial.println((char*)buf);
          userid =(char*)buf;
            Serial.println(userid);

      }

    delay(5000);

       uint8_t buf2[8];
      uint8_t buflen2 = sizeof(buf2);

       if (rf_driver.recv(buf,&buflen))

      {

        int i;
        // message received with valid checksum
        Serial.print("password: ");
        Serial.println((char*)buf);
          password = (char*)buf;
          Serial.println(password);

      }
      delay(5000);

    while ( userid =="A00034732" && password == "123456789"){
    digitalWrite(ledon, HIGH);
    delay(2000);
    digitalWrite(ledon, LOW);

    }
    }

transmitter code ----

    //Include RadioHead Amplitidue shift keying library
    #include <RH_ASK.h>
    // Include dependatnt ISP library
    #include <SPI.h>

    //create Ampitude shift keying object
    RH_ASK rf_driver;

    void setup() {
     // intialize ASK objct
    rf_driver.init();

    Serial.begin(9600);

      //if(!rf_driver.init())
          //Serial.print("init failed");

    }

    void loop()
    {

      const char *pass= "123456789";
    rf_driver.send((uint8_t *)pass, strlen(pass));
    rf_driver.waitPacketSent();
    delay(5000);

    const char *ID= "A00034732";

    rf_driver.send((uint8_t *)ID, strlen(ID));
    rf_driver.waitPacketSent();
    delay(5000);

    //const char *pass= "12345678";
    //rf_driver.send((uint8_t *)pass, strlen(pass));
    //rf_driver.waitPacketSent();
    //delay(5000);

    }

body:
You're not comparing strings - you're comparing addresses of strings.  Use [`strcmp()`](https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm).

    while (
        (strcmp(userid, "A00034732") == 0) &&
        (strcmp(password, "123456789") == 0)
    ) {


sender: user

message:
TimerOne Hanging

For the following program. Compiles and runs. I start the Serial Monitor (shown following code) and it asks me to input the Blink Rate. This runs in setup. Then it enters the loop and prints to the serial monitor the rate and starts the >Serial.println("the bl    And it hangs! I can exit the serial monitor and restart it and it does the same thing. So the program/sketch seems to be running fine but somehow the serial communication hangs?  Others have tried it and it works for them?  Using an Alien Aurora R5 running Win10 64bit Home.  Added some delays after another person tried it and it hung on them before adding delay and then ran for them.  They are using Win10 32bit and when tried on their 64bit laptop it hangs.

    //Testing the Serial Port

    #include <TimerOne.h>

    int state = 0;
    int value;
    long int newtime;

    void setup() {
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      digitalWrite(13, state);
      Serial.println("Enter the Blink Rate: ");
    }

    void loop() {
      if (Serial.available()) {
        value = Serial.parseInt();
        delay(100);
        Serial.print("the blink rate is: ");
        Serial.println(value);
        Serial.println("Enter a new blink rate: ");
        newtime = value * 1000000;
        Timer1.initialize(newtime);
        Timer1.attachInterrupt(blinkme);
        delay(500);
      }
    }

    void blinkme() {
      state = !state;
      digitalWrite(13, state);
      delay(100);
    }

[![Serial Monitor][1]][1]

  [1]: https://i.stack.imgur.com/8ge1i.jpg

sender: assistant

body: If you enter 1 in Serial Monitor and you have line ends selected, the Serial Monitor sends "1\r\n". parseInt() reads 1 and in next loop \r or \n is available and parses as 0. You then set the Timer to 0. The Serial can't finish printing because the Timer fires without a pause.


body:
Change io 13 to (suggestion) 10 and attach led + 1k resister to io 10.
13 seems to be in use. Also No line end in Serial.


message:
Protecting variables and functions within a library that has no class

If you want to have functions within a library that only the library itself should be able to use or variables that shouldn't be accessed from outside, you usually make them private by writing this in the header file:

```c++
class Lib{
  public:
    // All these can be accessed from outside
    void function1();
    void function2();
    int someNumber;
  private:
    // These two can't be accessed from outside
    void secretFunction();
    int secretNumber;
};
```
My question is this:

I want to write this library without using classes. How do I protect things from being accessed from anywhere in this case?

body:
If your library is implemented in a single .cpp file, you can define these
variables and functions within that file, and give them the `static`
qualifier:

```c++
static int my_private_variable = 42;

static void my_private_function()
{
    ...
}
```

Obviously, there should be no mention of them in the .h file.

Note also that we are talking about global variables. Local variables
are already hidden within the defining function.


message:
Arduino uno toggle switch help

I am building a box that will start a genset. It has two buttons, run and stop.
I would like button run to be able to start (and remain constant) until pressed a second time, I have sussed this bit so far, but this is where I get stuck.
I would like the stop button to only stop the the engine (as a single function)
So my question is how do I integrate the second button (stop) to carry out this one task?

    int LEDYelState=0;
    int LEDRedState=0;
    int LEDGrnState=0;
    int RELAYRedState=0;
    int RELAYYelState=0;
    int RELAYGrnState=0;
    int LEDRedPin=10;
    int LEDYelPin=9;
    int LEDGrnPin=8;
    int RELAYRedPin=7;
    int RELAYYelPin=6;
    int RELAYGrnPin=5;
    int buttonPin=13;
    int buttonNew;
    int buttonOld=1;
    int dt=100;
    int buttonOff;
    int buttonPinOff=12;
    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(LEDRedPin, OUTPUT);
    pinMode(buttonPin, INPUT);
    pinMode (LEDYelPin,OUTPUT);
    pinMode (LEDGrnPin, OUTPUT);
    pinMode (RELAYRedPin, OUTPUT);
    pinMode (RELAYYelPin, OUTPUT);
    pinMode (RELAYGrnPin, OUTPUT);
    pinMode (buttonPinOff, INPUT);
    }
    void loop() {
    buttonNew=digitalRead(buttonPin);
    buttonOff=digitalRead(buttonPin);
    if(buttonOld==0 && buttonNew==1){
      if (LEDRedState==0){
        digitalWrite(LEDRedPin,HIGH);
        LEDRedState=1;
        digitalWrite(RELAYRedPin,LOW);
        RELAYRedState=1;

        digitalWrite(LEDYelPin, HIGH);
        LEDYelState=1;
        digitalWrite(RELAYYelPin, LOW);
        RELAYYelState=1;
        delay (8000);
        digitalWrite(LEDYelPin,LOW);
        digitalWrite(RELAYYelPin,HIGH);

        digitalWrite (LEDGrnPin,HIGH);
        LEDGrnState=1;
        digitalWrite (RELAYGrnPin, LOW);
        RELAYGrnState=1;
        delay(2000);
        digitalWrite  (LEDGrnPin,LOW);
        digitalWrite (RELAYGrnPin,HIGH);
        RELAYGrnState=1;
      }
      else{
        digitalWrite(LEDRedPin, LOW);
        LEDRedState=0;
        digitalWrite(RELAYRedPin, HIGH);
        RELAYRedState=0;
        digitalWrite(LEDYelPin,LOW);
        LEDYelState=0;

      }
    }
    buttonOld=buttonNew;
    delay(dt);

    }

body:
A general hint first: indent your code correctly. It makes it much easier to read and easier to spot logical errors.

Another improvement would be to name the pins with the same names as you name them when explaining the problem to us. I expected to find a `int buttonRunPin` and `int buttonStopPin`.

The first issue I see is:

    buttonNew=digitalRead(buttonPin);
    buttonOff=digitalRead(buttonPin);

This reads the same button twice. You probably wanted to read two different buttons: the "run" button and the "stop" button.

The next issue I see is:

    delay(8000);
    delay(2000);

During these 10 seconds, you can press and let go the button many times. But since there is no `digitalRead()` during that time, the button press will not be recognized.

The same applies to

    int dt=100;
    delay(dt);

If you press the button within these 100 ms, it will not be noticed.

Unfortunately, to fix that, you need to learn a completely new concept: [interrupts](https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/). And even worse, not all pins support interrupts. On the Arduino Uno, it's only pin 2 and pin 3, which means you would need to change your hardware setup (because you use pin 12 and 13). Put both buttons from the pin to ground, so that it closes when pushed.

You would then prepare the interrupt in the `setup()` routine:

    pinMode(buttonPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
    pinMode(buttonPinOff, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);

You also define global variables for the state of the buttons:

    volatile bool running = false;
    volatile bool stopped = false;

`volatile` is needed here to prevent the compiler from optimizing too much. The compiler does not know about the interrupts and thus can't know when the variable changes.

Next, you need two methods that are being executed whenever an interrupt occurs, i.e. you press a button:

    void toggleRun() {
        running = !running;
    }
    void toggleStopped() {
        stopped = !stopped;
    }

Note: the above `x = !x;` pattern is a short and efficient form of

    if (x == false) {
        x = true;
    }
    else if (x == true) {
       x = false;
    }

Once you have all that, you don't need the two `digitalRead()`s any more.

I'm afraid I haven't understood what your code's supposed to do. You have a lot of state variables that seem to have no use and especially they don't correspond to the motors. E.g. once `RELAYGrnState` is set to 1, it never changes back to 0.

This is what I have in the end:

    int LEDYelState=0;
    int LEDRedState=0;
    int LEDGrnState=0;
    int RELAYRedState=0;
    int RELAYYelState=0;
    int RELAYGrnState=0;
    int LEDRedPin=10;
    int LEDYelPin=9;
    int LEDGrnPin=8;
    int RELAYRedPin=7;
    int RELAYYelPin=6;
    int RELAYGrnPin=5;
    int buttonPin=13;
    int buttonNew;
    int buttonOld=1;
    int dt=100;
    int buttonOff;
    int buttonPinOff=12;

    volatile bool running = false;
    void toggleRun() {
        running = !running;
    }

    volatile bool stopped = false;
    void toggleStopped() {
        stopped = !stopped;
    }

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(LEDRedPin, OUTPUT);
      pinMode (LEDYelPin,OUTPUT);
      pinMode (LEDGrnPin, OUTPUT);
      pinMode (RELAYRedPin, OUTPUT);
      pinMode (RELAYYelPin, OUTPUT);
      pinMode (RELAYGrnPin, OUTPUT);

      pinMode(buttonPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
      pinMode(buttonPinOff, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);
    }

    void doSomething() {
      digitalWrite(LEDRedPin,HIGH);   // red LED is on
      LEDRedState=1;
      digitalWrite(RELAYRedPin,LOW);  // red motor off? others unclear
      RELAYRedState=1;

      digitalWrite(LEDYelPin, HIGH);  // yellow LED and red LED are on
      LEDYelState=1;
      digitalWrite(RELAYYelPin, LOW);  // yellow motor off?
      RELAYYelState=1;
      delay (8000);
      digitalWrite(LEDYelPin,LOW);     // red LED on
      digitalWrite(RELAYYelPin,HIGH);  // yellow motor on

      digitalWrite (LEDGrnPin,HIGH);  // red and green LED are on
      LEDGrnState=1;
      digitalWrite (RELAYGrnPin, LOW);  // green motor off
      RELAYGrnState=1;
      delay(2000);
      digitalWrite  (LEDGrnPin,LOW);    // red LED on
      digitalWrite (RELAYGrnPin,HIGH);  // green motor on
      RELAYGrnState=1;
    }

    void doLess() {
      digitalWrite(LEDRedPin, LOW);     // red LED off
      LEDRedState=0;
      digitalWrite(RELAYRedPin, HIGH);  // red motor on
      RELAYRedState=0;
      digitalWrite(LEDYelPin,LOW);      // yellow LED off
      LEDYelState=0;
    }

    void loop() {
      if(running){
        if (!stopped){
          doSomething();
        }
        else{
          doLess();
        }
      }
      delay(dt);
    }


message:
Determine what size power supply I need to run stepper motors

I have recently purchased two 7.4V, 1A, Planetary Gear Unipolar Stepper Motors as well as two Cytron 3A 4-16V Dual Channel DC Motor Drivers. I was told that I would need these to run the motors off an Arduino board. The question I forgot to ask was: what size power supply I would need for something like this?

I am just looking to learn how to code these arduino boards. I was hoping to get something that I could plug into a wall to save me from buying multiple batteries.

body:
You can't run these off the Arduino board for several reasons:

0. the Arduino board does not provide 7.4V on any pin, only 5V (model dependent, but never 7.4 V)
0. the Arduino board can provide about 20mA per pin, never 1A or higher
0. even if the board would only need to pass the voltage on, the total current were >2A. This would possibly fry the board.

So, what you need is: a power supply with constant 7.4V or a regulated one where 7.4V is within the range. From this power supply you will power 3 devices only:

0. one arduino board via the Vin pin (accepts 7 to 12 V, so 7.4V is ok)
0. two Dual Channel DC Motor Drivers (accepts 4 to 16V, so 7.4V is ok)

From each motor driver, you will power

0. one Planetary Gear Unipolar Stepper Motors (designed for 7.4V)

Now, let's sum of the currents:

0. Arduino Uno board without any peripherals: ~45 mA
0. two Stepper motors: 1000 mA each
0. two motor drivers: hard to say. In theory, the motor driver would not consume power by itself, just forward it to the motors. In practice, it cannot forward everything. The driver will get hot and thus consume some power itself. The [datasheet](https://www.robotshop.com/media/files/content/c/cyt/pdf/cytron-3a-4-16v-dual-channel-dc-motor-driver-datasheet.pdf) is not specific about the power consumption. Let's assume a 70% efficiency = 30% loss. 30% of 1000mA is 300mA each.

The total current needed for this setup is 2645mA. Depending on your budget you could buy a 3A or 5A power supply. At constant 7.4V, that's 23W or 37W. For a regulated 0V to 20V power supply, go for 60W or 100W.

A cheap regulated one should be at ~50 USD. Expect those to be loud because of bad cooling / fan noise.


message:
7 segment display with common anode

I am brand new to electronics. I am trying to use a seven segment display breakout module with my arduino uno. My problem is that the display has a common positive instead of negative common. How do I make this work? As far as I am aware, all the arduino pins output positive with the exception of the ground, which is the negative common.

body:
This answer assumes Arduino Uno. For other types, refer to the documentation.

Ardino pins are not positive per se: you can change the voltage with `digitalWrite()` to either 0V (`LOW`, equal to the GND pin) or 5V (`HIGH`, equal to VCC).

The difference between a common cathode or common anode will be the flow of the current. With a common cathode (negative), the pins will need to provide current ("source" current), with a common anode, the pins will need to receive current ("sink" current).

There is a [description](https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations/) for the limits of sourcing and sinking:

> Pin SOURCE Current Limitations:
>
> 20 mA at VCC = 5 V
>
> Pin SINK Current Limitations:
>
> 20 mA at VCC = 5 V

Please also read about the maximum total of 150 mA sourcing and 100 mA sinking.

You'll need to compare those current limits with the current requirements of your 7 segment display. My guess is that your a 7 segment display has 1 VCC pin and 7 output pins that you connect to the Arduino. The limiting factor is the total maximum here. The Arduino can handle 100 mA/7 = 14mA in the worst case. If that's enough for your 7 segment, it should work.

For example, [this one](https://cdn-reichelt.de/documents/datenblatt/A500/SA39-11#KIN.pdf) works with 10 mA, so it would be compatible with Arduino. Make sure you have resistors in place.


message:
New OLED seems dead, how can I be sure?

I bought this 2.8" OLED from Aliexpress a few weeks ago: https://www.aliexpress.com/item/32988174566.html?spm=a2g0s.9042311.0.0.72304c4dAWcHG8

And after a ridiculous amount of searching for a datasheet, I came across this one that seems to match the board I bought: https://www.buydisplay.com/download/manual/ER-OLEDM028-1_Series_Datasheet.pdf

Wiring up pins 1 and 2 to ground and 3.3V on a breadboard, I'd expect something to happen with the display, but I get nothing. The display is in 8080 mode, so I wire everything up to a standard UNO board and power everything on. Still nothing. Try changing the power to 5V, no joy.

During my testing, I noticed the back of the display is getting hot. Not sure if that's a good thing or not yet.

So what's the best way to 1) determine if the datasheet I found is correct? 2) check if the OLED is just broken? I don't have a ton of experience with these displays yet, so I'm not sure if just powering the thing on should net some visual response.

body:
The datasheet you have found is not for the same display. Yes, it's similar, and yes, it has the same actual OLED display unit on the board, but the PCB is different. So you cannot assume that the pinout is the same.

The fact that it's getting hot tells me that you have probably wired something wrong and you are injecting voltage into it somewhere where voltage doesn't want to be injected.

To find if an OLED is working you have to actively wire it up.  With an LCD you can just give it power and you should be able to see some visual indication that it's working (back light, some shadowing of the display matrix, etc). But with an OLED you can't do that.  An OLED is made up of a matrix of LEDs which are either on or off. By default they are off, and when they are off it's no different to there being no power. That's the big benefits of OLED displays - low power consumption and true black.

To get any kind of indication that the display works you both need to wire it 100% correctly and program the Arduino in the right way to actively drive it by displaying something on the screen.  My usual test program when working with a new screen is to simply print `millis()` in the top left corner.


message:
My code seems to be a train wreck

I am new to programming and I thought a simple project to do would be to create an ammo counter.
I have been troubleshooting this code for several hours now, and can not figure out why my code is riddled with errors. Below is my program. Please give it a glance and let me know what mistake I have made. I will post the error report beneath my program. I apologize for my bad programming in advance and hope that there is still hope for me with the proper tutelage.
The program worked just fine when I ran a test using only one saved function, "twentyBullets()". After I added a 30 additional functions and created a chain of if-else-if conditions, the program began to report all sorts of errors.

     /*
        7-SEGMENT DISPLAY HANDLING CODE!
        The below code handles the 7-segment display for the digital ammo counter.

         A
        ___
      F|   |B
       G---G
      E|___|C
         D

     Above is the alphabet letter assignment for the different segments of
     the B07BMPPNQY display. Digital ammo counter project will use common pins, L3 and L4.
     */
      // Display pin declaration.
      // P_: Where P indicates the pin output for the segment of the display to be illuminated followed by a lower case letter
      // which indicates which specific led in the segment to illuminate.
      // ten: Where ten indicates the ten's place on the 7 segment display.
      // one: Where one indicates the one's place on the 7 segement display.

    int Pa = 0;
    int Pb = 1;
    int Pc = 2;
    int Pd = 3;
    int Pe = 4;
    int Pf = 5;
    int Pg = 6;
    int ten = 7;
    int one = 8;
    int ammo = 10;

    void setup() {
      // put your setup code here, to run once:

    pinMode(Pa, OUTPUT);
    pinMode(Pb, OUTPUT);
    pinMode(Pc, OUTPUT);
    pinMode(Pd, OUTPUT);
    pinMode(Pe, OUTPUT);
    pinMode(Pf, OUTPUT);
    pinMode(Pg, OUTPUT);
    pinMode(ten, OUTPUT);
    pinMode(one, OUTPUT);

    }

    void loop(){
      // put your main code here, to run repeatedly:
      if (ammo == 1) {
      oneBullet();
      }
      else if (ammo == 2) {
      twoBullets();
      }
      else if (ammo == 3) {
       threeBullets();
      }
      else if (ammo == 4) {
        fourBullets();
      }
      else if (ammo == 5) {
        fiveBullets();
      }
      else if (ammo == 6) {
        sixBullets();
      }
      else if (ammo == 7) {
        sevenBullets();
      }
      else if (ammo == 8) {
        eightBullets();
      }
      else if (ammo == 9) {
        nineBullets();
      }
      else if (ammo == 10) {
        tenBullets();
      }
      else if (ammo == 11) {
        elevenBullets();
      }
      else if (ammo == 12) {
        twelveBullets();
      }
      else if (ammo == 13) {
        thirteenBullets();
      }
      else if (ammo == 14) {
        fourteenBullets();
      }
      else if (ammo == 15) {
        fifteenBullets();
      }
      else if (ammo == 16) {
        sixteenBullets();
      }
      else if (ammo == 17) {
        seventeenBullets();
      }
      else if (ammo == 18) {
        eighteenBullets();
      }
      else if (ammo == 19) {
        nineteenBullets();
      }
      else if (ammo == 20) {
       twentyBullets();
      }
      else if (ammo == 21) {
       twentyoneBullets();
      }
      else if (ammo == 22) {
        twentytwoBullets();
      }
      else if (ammo == 23) {
        twentythreeBullets();
      }
      else if (ammo == 24) {
        twentyfourBullets();
      }
      else if (ammo == 25) {
        twentyfiveBullets();
      }
      else if (ammo == 26) {
        twentysixBullets();
      }
      else if (ammo == 27) {
       twentysevenBullets();
      }
      else if (ammo == 28) {
       twentyeightBullets();
      }
      else if (ammo == 29) {
       twentynineBullets();
      }
      else if (ammo == 30){
       thirtyBullets();
      }
      else {
        zeroBullets();
      }
    }
    void zeroBullets()
               //0
    { digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);

            //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void oneBullet()
              //1
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }

    void twoBullets()
              //2
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void threeBullets()
              //6
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void fourBullets()
              //4
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void fiveBullets()
              //5
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, HIGH);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void sixBullets()
              //6
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, HIGH);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void sevenBullets()
              //7
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void eightBullets()
              //8
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void nineBullets()
                  //9
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);

              //0
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void tenBullets()
                  //0
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void elevenBullets()
                  //1
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void twelveBullets()
                 //2
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void thirteenBullets()
              //3
    {  digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void fourteenBullets()
              //4
    {  digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void fifteenBullets()
              //5
    {  digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, HIGH);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void sixteenBullets()
              //6
    {  digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, HIGH);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void seventeenBullets()
              //7
    {  digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void eighteenBullets()
              //8
    {  digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void nineteenBullets()
              //9
    {  digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //1
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);
    }
    void twentyBullets()
            //0
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentyoneBullets()
            //1
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentytwoBullets()
            //2
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentythreeBullets()
            //3
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentyfourBullets()
            //4
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, HIGH);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentyfiveBullets()
            //5
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, HIGH);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentysixBullets()
            //6
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, HIGH);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentysevenBullets()
            //7
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, HIGH);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentyeightBullets()
            //8
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }
    void twentynineBullets()
          //9
    {  digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, HIGH);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, LOW);
      delay(10);

              //2
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, HIGH);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }

    void thirtyBullets()
            //0
      digitalWrite(one, LOW);
      digitalWrite(ten, HIGH);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, LOW);
      digitalWrite(Pf, LOW);
      digitalWrite(Pg, HIGH);
      delay(10);

              //3
      digitalWrite(one, HIGH);
      digitalWrite(ten, LOW);
      digitalWrite(Pa, LOW);
      digitalWrite(Pb, LOW);
      digitalWrite(Pc, LOW);
      digitalWrite(Pd, LOW);
      digitalWrite(Pe, HIGH);
      digitalWrite(Pf, HIGH);
      digitalWrite(Pg, LOW);
      delay(10);
    }

THE ERROR REPORT:

    Arduino: 1.8.10 (Windows 10), Board: "Arduino/Genuino Uno"

    Digital_Ammo_Counter.ino: In function 'void loop()':

    sketch_Digital_Ammo_Counter:138:4: error: 'thirtyBullets' was not declared in this scope

        thirtyBullets();

        ^~~~~~~~~~~~~

    sketch_Digital_Ammo_Counter.ino:138:4: note: suggested alternative: 'twentyBullets'

        thirtyBullets();

        ^~~~~~~~~~~~~

        twentyBullets

    sketch_Digital_Ammo_Counter.ino: At global scope:

    sketch_Digital_Ammo_Counter:898:3: error: expected initializer before 'digitalWrite'

       digitalWrite(one, LOW);

       ^~~~~~~~~~~~

    sketch_Digital_Ammo_Counter:899:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(ten, HIGH);

                   ^

    sketch_Digital_Ammo_Counter:900:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pa, LOW);

                   ^

    sketch_Digital_Ammo_Counter:901:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pb, LOW);

                   ^

    sketch_Digital_Ammo_Counter:902:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pc, LOW);

                   ^

    sketch_Digital_Ammo_Counter:903:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pd, LOW);

                   ^

    sketch_Digital_Ammo_Counter:904:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pe, LOW);

                   ^

    sketch_Digital_Ammo_Counter:905:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pf, LOW);

                   ^

    sketch_Digital_Ammo_Counter:906:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pg, HIGH);

                   ^

    sketch_Digital_Ammo_Counter:907:8: error: expected constructor, destructor, or type conversion before '(' token

       delay(10);

            ^

    sketch_Digital_Ammo_Counter:910:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(one, HIGH);

                   ^

    sketch_Digital_Ammo_Counter:911:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(ten, LOW);

                   ^

    sketch_Digital_Ammo_Counter:912:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pa, LOW);

                   ^

    sketch_Digital_Ammo_Counter:913:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pb, LOW);

                   ^

    sketch_Digital_Ammo_Counter:914:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pc, LOW);

                   ^

    sketch_Digital_Ammo_Counter:915:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pd, LOW);

                   ^

    sketch_Digital_Ammo_Counter:916:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pe, HIGH);

                   ^

    sketch_Digital_Ammo_Counter:917:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pf, HIGH);

                   ^

    sketch_Digital_Ammo_Counter:918:15: error: expected constructor, destructor, or type conversion before '(' token

       digitalWrite(Pg, LOW);

                   ^

    sketch_Digital_Ammo_Counter:919:8: error: expected constructor, destructor, or type conversion before '(' token

       delay(10);

            ^

    sketch_Digital_Ammo_Counter:920:1: error: expected declaration before '}' token

     }

     ^

    exit status 1
    'thirtyBullets' was not declared in this scope

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

body:
The error cascade is caused by the missing opening curly bracket `{` at the start of the `thirtyBullets()` function. This causes the function name to be not declared and also the following function calls to `digitalWrite()` to fail. Putting in this missing opening curly bracket should fix all the errors (though I cannot test it since I don't have a compiler at hand currently).

Besides that, your code can be made way shorter with a trick. Currently you use one function for every number, where you write the corresponding digital pins. So the situation is, that you always need to write to the same pins, just different values depending on a simple unsigned integer number. So I suggest, that you define the pin patterns for the digits in a 2 dimensional array. Then you can use only 1 function to output any of them. I will give you an example:

    uint8_t led_pattern[10][7]= {
        {0, 0, 0, 0, 0, 0, 1}, // pattern for the digit 0
        {1, 0, 0, 1, 1, 1, 1}, // pattern for the digit 1
        {0, 0, 1, 0, 0, 1, 0}, // pattern for the digit 2
        ...
        {0, 0, 0, 0, 1, 0, 0}}; // pattern for the digit 9

    void display_digit(uint8_t position, uint8_t digit){
        digitalWrite(one, position); // Writes low (aka zero) to pin one, when position is zero, else high
        digitalWrite(ten, !position); // Writes low to pin ten, when position is greater than zero, else high

        for(uint8_t i=0; i<7; i++){
            digitalWrite(i, led_pattern[digit][i]);
        }
        delay(10);
    }

    void display_number(uint8_t number){
        display_digit(0, number % 10);
        display_digit(1, number / 10);
    }

    void loop(){
        display_number(ammo);
    }

**So, what is happening here?**

First we define the LED patterns in a 2 dimensional array. It's first index is the digit, that we want to display; it's second index is the number of the LED to light. The value then is the state of the corresponding LED. I wrote `1` and `0`, because it is short. You could also write `HIGH` and `LOW` (since these are also only defines for `1` and `0`). So the pattern `{1, 0, 0, 1, 1, 1, 1}` means, that only the segments b and c output low, thus are turned on.

Then we define a function to display one digit. It takes the position of the digit and the actual digit (0 to 9) as parameters. We write the two outputs for our position directly with the variable. This is a very short way to do it and it doesn't work, when you have more than 2 digits. If you want to extend your counter one day, you can replace these 2 lines by a different construct (for example a switch case statement). Then we do a for loop from 0 to 6, so that we go through all the digits. In your case you use the pin numbers 0 to 6, so we can directly use `i` as pin number. (If you want to use other pins, you could save those pins in an array and reference the values in the array with `i`). In every iteration of the for loop, we write the value for the corresponding digit and LED to the corresponding output pin. After that, we only delay a short time and leave the function.

To make it easier, I also defined the function `display_number()`, which will display the complete number, by displaying the it's digits successively on the corresponding positions. If you are a beginnner, you might not recognize, what calculations I made there. The modulo operator `%` returns the rest of an integer division. So if I take `23 % 10` this would return `3` (integer division `23 / 10` is 2 and the rest is 3). This gives us the first (least significant) digit. We can then get the second digit by simply doing an integer division with 10, as it will cut the part after the decimal point. If you want to display numbers greater than 99 one day, you have to change both functions to accomodate for that.

Note, that I used `uint8_t` as type everywhere. This is just the smallest unsigned number type (8 bit wide). I used the smallest, since you don't need greater numbers here and it saves a bit of memory. When you want to extend your display to show values greater than 255, you need to change the type of the `number` parameter in the `display_number()` function to a greater type, for example `unsigned int` (which is 16 bits wide).

Also note, that I have not tested this code, since I don't have a compiler or Arduino at hand currently.

---

So now, you can display a number on your digit with just one function call and you don't need nearly 1000 lines of code for it.

When extending your code to do more things, than displaying numbers, you can easily get to the point, where using `delay()` is a bad thing, since the Arduino cannot do anything else during that time. Then you need to rewrite your code to avoid `delay()` and use the `millis()` function instead to make it unblocking. There are tons of tutorials out there for this and I just wanted to mention it.


body:
You've found the bug, but how could you have found it easier?

The most important step mentally is to accept that _you_ did something wrong. We don't know yet what, but it is exceedingly unlikely that the compiler complains about correct code. So the question is: What did you do wrong?

The compiler complained about a function "thirtyBullets". It didn't complain about "twentynineBullets". It doesn't realise that there is a function "thirtyBullets". The first thing is to check the spelling. If you named the function "thirrtyBullets" by mistake, that would explain things. But the name is right.

Then you see that the compiler complains about the line immediately after the start of the function. Hard to figure out what the compiler is complaining about, so something you did just before confused it. So now you check the line "void thirtyBullets()", that's Ok, the next line "digitalWrite(one, LOW);" looks Ok but something MUST be wrong here, and that's where you hopefully figure out the missing "{".


body:
Just to add to the idea of using an array—since C does not care about whitespace you can quite easily format your data like this:

    uint8_t led_pattern[10][7]= {
          {0,  // pattern for the digit 0
         0,  0,
           0,
         0,  0,
           0},

          {0, // pattern for the digit 1
         0,  1,
           0,
         0,  1,
           0},

          {1, // pattern for the digit 2
         0,  1,
           1,
         1,  0,
           1},
          ...
    };

This is an example of the "good habit" of making your code about your _intent_ rather than about _instructing_ the machine. You can spend 50% more time making your code clear, or spend 500% more time debugging it. As the saying goes,

> There are two ways to develop software: Make it so simple that there are obviously no bugs, or so complex that there are no obvious bugs.

**Note:** The above code will give you your digitalOut values in a different order to your pins (so chrisl's `for` loop won't work.) You can just manually do 7 digitalWrites to the correct pins when displaying the `digit`.

    digitalWrite( <pin number> , led_pattern[digit][ <led position> ]);


body:
Your code actually isn't bad. There aren't very many good ways of doing this sort of pin mapping, and the few that are have their own downsides as well. The main issue was the missing bracket, which I found by checking the drawThirty function since it was mentioned specifically and had cascading errors implying a missed semicolon or bracket.

One further tweak is that your code will only work on Arduino (so you're fine, but a different IDE may get mad at you). C does not search the whole file for function names, so if you declare/define the function after you use it, it will error out. Arduino uses a special pre-parser to fix this for you.

The proper way is to forward-declare the function as follows:
```
int returnAPieceOfData(byte x, char c, int i);//Now C knows it exists somewhere and won't error.

void foo(){

//somewhere in here you need returnAPieceOfData
}

int returnAPieceOfData(byte x, char c, int i){
//You now define the function after it's used, but have no errors!

}
```
This usually results in a C file where all the functions are declared at the top, and then the function definitions below can use them in any order without problems. It also makes it easier to tell if the file has a function, and if you add them in the same order, where it is.

---------

I will mention a potentially-useful method of alternately implementing the array lookup table for writing the pins. The above are very good suggestions, especially the shaped whitespace, but that approach will use a lot of extra memory because it uses full bytes per pixel.

If you are willing to accept a format that is somewhat harder to visualize, you could encode the entire space into a single byte, which I'll show below. You can also put the **pin numbers** into an array so that you *can* use a FOR loop.

Essentially, you have two options when writing this sort of system. You can go for code complexity, which is what your example did, or you can go for memory/data complexity, which I'm showing here. The downsides to THIS technique are that the data is somewhat arcane and hard to modify (since it's encoded and there's kinda a lot of it), and that it uses extra memory to hold that data.

```
void drawAllSegments(byte ammo_ct){
  byte hi=ammo_ct/10;
  byte lo=ammo_ct;
  drawLowSegments(lo);
  drawHighSegments(hi);
}

byte lpinNums[]={apin,bpin,cpin,dpin,epin,fpin,gpin};//pins for 0s display
byte hpinNums[]={apin,bpin,cpin,dpin,epin,fpin,gpin};//pins for 10s display
byte numbers[]={0b00111111,0b01111001,...};
//Format the "numbers" as 0bXGFEDCBA, where X is a don't-care
//(its value is never used and can be either 0 or 1)
//My example may be wrong. I think it's negative logic, but could also have made an error on top of that.

void drawLowSegments(byte ammo_ct){
  digitalWrite(one, HIGH);//set up the display select
  digitalWrite(ten, LOW);
  for (byte i=0;i<7;i++){//then draw!
    byte state=(numbers[ammo_ct]>>i)&0x01;//decompress the state of that segment
    digitalWrite(lpinNums[i],state);
  }
}

void drawHighSegments(byte ammo_ct){
  digitalWrite(one, HIGH);//set up the display select
  digitalWrite(ten, LOW);
  for (byte i=0;i<7;i++){//then draw!
    byte state=(numbers[ammo_ct]>>i)&0x01;//decompress the state of that segment
    digitalWrite(hpinNums[i],state);
  }
}
```
The advantages of this approach is that the code is just as compact as the array system, but that it uses 1/8 the RAM for that array. I don't imagine you are doing something that uses a whole lot of RAM, but it's still a good idea to minimize it where possible. In this case it also is much further expandable, since you can fit more numbers in before you run out of RAM.

You can also switch to PROGMEM, but reading that is a bit weird in some ways and it's easy to forget to read it in the first place (which results in reads of random RAM). In this case it should be small enough that further such optimization isn't required.

One last note is that, if you ever do something for which a byte is too small, you can use larger numbers up to the uint32_t, which is 32 bits of useful pixels, or potentially the uint64_t, which is 64 bits but may not be supported on the Arduino (I've never tried the latter).


message:
automated parking system (sir sensor+ stepper motor)

my project about automated system I am using stepper motor to open and close the gate

I want my code be like when the gate opened it stays 5 seconds

then check the sensor, if there is a motion the gate should not close and stay open, when there is no motion the gate should close

if the gate is closing and there is a motion, motion should interrupt closing the gate and reopening the gate

I am using Arduino uno

the code is :

    #include <RH_ASK.h>//include radioHead ASK library
    #include <SPI.h> // include dependant SPI libray
    #include <Stepper.h> // Include the Arduino Stepper.h library:
    // Define number of steps per rotation:

    RH_ASK rf_driver; // create ASK object
    int ledon = 13;
    int ledoff = 5;
    int sensor = 3;

    const int stepsPerRevolution = 2048;// Define number of steps per rotation:

    // Wiring:
    // Pin 8 to IN1 on the ULN2003 driver
    // Pin 9 to IN2 on the ULN2003 driver
    // Pin 10 to IN3 on the ULN2003 driver
    // Pin 11 to IN4 on the ULN2003 driver
    // Create stepper object called 'myStepper', note the pin order:
    Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

    void setup() {

      rf_driver.init(); //initialize ASK object

      // Begin Serial communication at a baud rate of 9600:
      Serial.begin(9600);

      // Set the speed to 5 rpm:
      myStepper.setSpeed(5);
      pinMode(ledon, OUTPUT);
      pinMode(ledoff, OUTPUT);

    }

    void loop() {

      //set buffer to size of expected message
      //uint8_t buf[8];
      // uint8_t buflen =sizeof(buf);

      //check if recevied packet is correct size
      //  if (rf_driver.recv(buf,&buflen))
      //{
      // int i;
      // message received with valid checksum
      // Serial.print("id: ");
      // Serial.println((char*)buf);
      // String userid =(char*)buf;
      // Serial.println(userid);

      // }

      //delay(5000);

      // uint8_t buf2[8];
      // uint8_t buflen2 = sizeof(buf2);

      // if (rf_driver.recv(buf,&buflen))

      // {

      //  int i;
      // message received with valid checksum
      // Serial.print("password: ");
      // Serial.println((char*)buf);
      // String password = (char*)buf;
      //  Serial.println(password);

      // }
      // delay(5000);

      String pass = "1234";
      String id = "A00036757";

      if (pass == "1234" ) {
        Serial.print("car exists");
        digitalWrite(ledon, HIGH);
        delay(300);
        myStepper.step(stepsPerRevolution / 3); //clockwise -OPEN GATE
        delay(10000);

        //if(digitalRead(sensor) == HIGH){
        delay(500);
      }

      if (digitalRead(sensor) == LOW) {

        digitalWrite(ledon, LOW);
        delay(300);

        digitalWrite(ledoff, HIGH);
        delay(300);
        myStepper.step(-stepsPerRevolution / 3); // CLOSE AFTER 5s COUNTERCLOCKWISE -  close gate
        digitalWrite(ledoff, LOW);
      }
      else {
        Serial.print("NO CAR");
      }

body:
When you use `delay()`, your code stops and dont check anything at all until the delay is over, if you want to check for sensors during a timer, you have to use `millis()`

There is a lot of documentation and tutorials you can find to replace delay with millis when you know what you are searching for


message:
Arduino ds3231to TM1638 problems,alarm clock project

Good morning,
I am coding an alarm clock on arduino by using a DS3231 and a TM1638.
The code works and the time updates in the serial monitor,although the time doesn't update on the tm1638.
I'll attach the code here:

    #include <DS3231.h>
    #include <TM1638.h>
    #include <Streaming.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <InvertedTM1638.h>
    #include <TM1638.h>
    #include <TM1638QYF.h>
    #include <TM1640.h>
    #include <TM16XX.h>
    #include <TM16XXFonts.h>
    byte buttons;
    #define TM1638_STB D5
    #define TM1638_CLK D6
    #define TM1638_DIO D7

    TM1638 module(TM1638_DIO, TM1638_CLK, TM1638_STB);
    // DS3231 uses I2C - device ID 0x68
    // on Wemos mini pins SDA -> D1 and SCL -> D2
    DS3231 rtc;
    int hours;
    int minutes;
    int seconds;
    bool h12;
    bool PM;
    int data;
    RifTime t;
    char buffer[24];

    void setup()
    {
      // set up the 7-segment display
      module.clearDisplay();
      module.setupDisplay(true, 2);
      Wire.begin();
      Serial.begin(115200);

      Serial.println(F("\nDS3231 Hi Precision Real Time Clock"));

      // Fill these variables with the date and time.
      int seconds, minutes, hours, dayofweek, dayofmonth, month, year;

      // Example for april 15, 2013, 10:08, monday is 2nd day of Week.
      // Set your own time and date in these variables.
      // dayofweek = 4; // Day of week, any day can be first, counts 1...7
      hours = 14;
      minutes = 30;
      seconds = 0;
      year = 2019;
      month = 8; // month 1...12
      dayofmonth = 28; // Day of month, 1...31

      data=( hours * 10000 + minutes * 100 + seconds * 1 );

      rtc.setClock(year,month,dayofmonth,hours,minutes,seconds);
    }

    void loop()
    {
      rtc.getTime(t);
      Serial << rtc.toString(buffer) << endl;

      delay(1000); // do nothing

      module.setDisplayToDecNumber(data,4,false);

      if(seconds==60)
      {
        seconds=00;
        minutes++;
      }
      if(minutes==60)
      {
        minutes=0;
        hours++;
      }

      if(hours==24)
      {
        data=00000000;
      }

      if((data)==143000)
      {
        module.setLEDs(0x0001);
      }
      else
      {
        module.setLEDs(0x0000);
      }

    }

body:
You set the variable `data` only in the setup function.

You also do not print out `data` to `Serial` but the output of `rtc.toString(buffer)`.

If data is not updated in the `loop` method, the display constantly shows the time you initially set in the setup method.


message:
How to toggle LED and motor on button press?

we want to have a LED turn on with the press of a button, and become brigther and brighter as times go by (whithin  a defined time frame), and when it reaches maximum brightness to turn off for a couple of seconds and then start again. in addition to that, we are trying to add a motor that will start spinning 720 degrees when the button has been pressed.
Our main problem is the fact that when we let go of the button the led turns off. How do we set the button so that when it is pressed once it turns everything on, and the led runs in a loop, but the motor doesn't; and when we press it again the whole led turns off completely and the motor runs 720 degrees in the opposite spinning direction than the previous.

Here is what we have managed so far (we didn't get to introduce the motor yet as we got stuck along the way):

    const int switchPin = 11;
    const int motorPin = 6;
    int led = 9;
    int switchState = LOW;
    int previous = LOW;
    int i = 0;
    int fadeAmount = 5;

    void setup()
    {
      pinMode(led, OUTPUT);
      pinMode(motorPin, OUTPUT);
      pinMode(switchPin, INPUT);
    }

    void loop()
    {
      int switchState = digitalRead(switchPin);

      for (int i = 0; i <= 255; i++)
      {
        analogWrite(led, i);
      }

      if (switchState == HIGH && previous == LOW)
      {
        if (i == 0)
        {
          digitalWrite (led, HIGH);
          i = i + fadeAmount;
          delay(1000);
        }

        analogWrite(led, i);

        for (int i = 255; i <= 255; i--)
        {
          digitalWrite (led, LOW);
          i = 0;
        }
      }
      else
      {
        //toggle off
        digitalWrite(led, LOW);
        i = 0;
      }
    }

PS. WE are beginers. Thanks for the help and understanding!

body:
Here is a program that should fade the LED as you specified. Initially the LED is off. If you press the button the LED starts fading within the time frame to its maximum. Then it switches to zero waits a couple of seconds and starts fading from new. If you press the button a second time the LED stops fading and is set to darkness. ;-) This happens emediately, but of cause, you can only see it if the LED is in the fading phase.

I used interrupts in order to have a well defined state transition I can work with.

Aquiring the button pin in the loop, would be more complex to handle. That would require a state variable and some state transition rules. And I was too lazy to work that out. If interupts can't be used for any reason, I would change the answer. (No Mum I don't want to ...)

I removed the motor pin as it makes no sense for the answer. I also think that one pin would not be enough if your motor (stepper, dc with feedback or a servo) should spin a certain amount of degrees.

I tested the program on a Arduino UNO. The button I used is of low quality so I had to debounce it.

If there is something not clear to you, please ask within a comment.

    // Attache the LED to a PWM pin UNO -> 3,5,6,9,10,11
    const byte ledPin       = 9;

    // UNO -> only pin 2 or pin 3 are interrupt pins
    // as we use pullups the button should be connected to GND
    const byte interruptPin = 2;

    // in milli seconds - The time the LED needs to fully light up
    const int timeFrame  = 5000;

    // in milli seconds
    const int aCoupleOfSeconds = 2000;

    const int fadeAmount =    5;

    volatile boolean fadeOn = false;
    volatile long debounceTime = 800;
    volatile long actTime = 0;

    int brightness =   0;

    int stepCount = 256       / fadeAmount;
    int stepDelay = timeFrame /  stepCount;

    void setup()
    {
      pinMode( ledPin,       OUTPUT       );
      pinMode( interruptPin, INPUT_PULLUP );

      attachInterrupt( digitalPinToInterrupt( interruptPin ), pressed, CHANGE );
    }

    void loop()
    {
      if ( fadeOn )
      {
        delay( stepDelay );
        brightness += fadeAmount;
        if ( brightness >= 255 )
        {
           brightness = 0;
           analogWrite( ledPin, brightness );
           delay( aCoupleOfSeconds );
        }
        analogWrite( ledPin, brightness );
      }
      else
      {
        brightness = 0;
        analogWrite( ledPin, brightness );
      }
    }

    void pressed()
    {
      // the debouncing does not work perfectly

      if ( digitalRead( interruptPin ) == LOW )
      {
        if ( millis() - actTime > debounceTime )
        {
          fadeOn = !fadeOn;
        }
      }
      else
      {
        actTime = millis();
      }
    }


body:
Have a look at some code inside the forum from marcello.romani. He posted it on jan 1st, 2013.
  The topic on subject is called : "button pressed more than 2 seconds do somethingelse"
  Marcello's code is so KISS (Keep It Simple Stupid) and efficient that it deserves a Nobel prize.
  The goals is to handle the different signals that come from a button or switch action :
  keyPress, keyRelease, longKeyPress etc.. as you can find in the original sketch.


message:
Can I read from a memory card with three pins?

I have a project where I have three pins to use and I just realized it would be better to use a memory card than replacing the code each time.

I'm building a Arduino with a push button. Press the button and it sends keystrokes to the connected computer with login details.
The login details need to change every three months so having that on a memory card will be easier.

So since I use a digispark Attiny 85 with a total of 6 pins (where two is used to send the keystrokes).
I have one to the push button, and three pins left.

Is there any card reader that can work with three pins? I only need to read if that makes a difference.
The ones I find use four pins (+ vcc and gnd).

Pretty much any memory card type is ok.

body:
SD cards work with SPI. This needs only one pin per device (SlaveSelect) but 3 pins for the other common signals ( MISO / MOSI / SCK )

Card reader modules simply do some voltage level shifting (if at all).

But, you need a lot of RAM to work with SD cards, as data transfer always happens in 512 byte "sectors". With a file system, you need at least two such blocks in parallel. An attiny85 is simply too small.


body:
Not with an ATTiny85, and not with so few pins, no.

However, all is not lost.

The ATTint85 has 512 bytes of EEPROM inside it where you can store your login details. All you need is some way of telling setting that data in your sketch from the PC - and the simplest way is probably through a USB serial connection.

If you don't have a serial connection available (I think Digispark has a custom interface they use) then you can use whatever interface you have available to do the job.


message:
Using Arduino Wifi Shield to Receive Signal

I am trying to use an Arduino Uno with Arduino Wifi Shield 101 to receive a signal from phone or webpage over wifi so it will "initiate" my circuit. I was able to connect the board to wifi but am unsure on how I should continue. My main goal is to be able to send it two different commands that would run different parts of code in my arduino script. I am very new to this stuff! Thanks :)

body: Look for the Web Server example in the arduino IDE.  That will give you a starting point to allow you to control the arduino via a web page.  This tutorial is also very in depth : https://startingelectronics.org/articles/arduino/switch-and-web-page-button-LED-control/


message:
Will an Arduino Uno be able to read 3x incremental encoders?

Encoders are quadrature 600ppr encoders with X2 counting. Therefore 1200 counts per revolution for each encoder. Is there an edge rate limit? I currently have one encoder hooked up using code with interrupts.

body:
The answer to the title's question is likely yes. But it would appear the real question is how fast can a given Arduino read a GPIO pin.

Consider there are multiple Arduino platforms.  Each possibly using a different type of processors.  Likely those processors are running at different speeds.  To give a specific answer we need to assume a specific platform, processor and speed.  The [current (3rd generation) Arduino Uno runs at 16MHz][1].  And the [Arduino Due runs at 84Mhz][2].  Since most people use an Arduino Uno let us use it for an example.

In [this arduino.cc forum thread][3] it is commented that an Arduino Uno running at 16MHz can execute the "Digital Pin Read" function call in about 4.78us.  Rounding that up to 5us that would be 1/5E-6 or 200000 samples per second.  Likely this can be improved upon if code were written to directly control the processors register for the desired outcome.  This is usually considered a moderately difficult embedded programming task.  And well outside normal Arduino knowledge.  In addition, such code would likely no longer be portable between different Arduino platforms.

  [1]: https://store.arduino.cc/usa/arduino-uno-rev3
  [2]: https://store.arduino.cc/usa/due
  [3]: https://forum.arduino.cc/index.php?topic=337578.0
  [4]: https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/


body:
Here is an example of some code I used to read two encoders using pin change interrupts.  This is possible to do with one ISR since they all share a common port.  The key is it has to be short.  As long as you can keep all 6 pins from your encoder on the same port, this should be easy to extend to 3 encoders.  It might even work for four on one port.  Or you can make a use a second port and get 3 or 4 more depending on which chip you have.

    volatile uint8_t lastPortRead = 0;

    volatile int32_t leftCounter = 0;
    volatile int32_t rightCounter = 0;

    ISR(PCINT2_vect){

     uint8_t portRead = PINC;

     uint8_t whoFired = portRead ^ lastPortRead;
     uint8_t pinsDiff = portRead ^ (portRead << 1); // Will have bits 5 or 7 set if pins on right motor or left motor are diff.  Cleared if same.

     if (whoFired & LEFT_INT_MASK) {
      if (pinsDiff & LEFT_INT_MASK) {
       leftCounter++;
      } else {
       leftCounter--;
      }
     }
     if (whoFired & RIGHT_INT_MASK) {
      if (pinsDiff & RIGHT_INT_MASK) {
       rightCounter++;
      } else {
       rightCounter--;
      }
     }

     lastPortRead = portRead;
    }


message:
How to connect MPU6050 to arduino using only digital pins

I am relatively new to Arduino and microchips, but I am good at electronics. I want to connect MPU6050 accelerometer+gyroscope module to Arduino. I searched on the internet and everywhere it is said to connect the SCL and SDA pins to two analog pins of the Arduino. As far as I know, the MPU6050 is a digital sensor, so why 2 analog pins are required for the sensor?

Also, is there any way to connect the sensor with only digital pins? because I need the analog pins for some other purpose.

body:
The MPU6050 communicates over I2C. I2C uses clock line SCL and data line SDA. I2C pins on Uno are pins A4 and A5.
This is because the ATmega328p MCU used on Uno has the I2C peripheral on the same pins. It has nothing to do with the DAC function of the pins.

<s>Alternatively MPU6050 can communicate over SPI. This are pins 11, 12, 13 on Uno and one more pin for CS. Pin 10 must be output while ATmega328p is SPI master so it is recommended to use it as CS for the SPI slave device. </s>  EDIT Sorry, only MPU6000 has SPI.


message:
Compass heading not varying linearly

I am using an HMC-5983 magnetometer compass on my arduino uno to find the heading of a car I'm building.But my compass readings aren't varying linearly.For example when I physically turn my compass by 90 degrees the change in the reading doesn't correspond to 90 degrees.I tried mapping the raw output of the compass to the actual heading but when I do this , the headings in between the points I mapped aren't accurate enough thereby causing my car to behave abnormally.I also looked up on google but couldn't find anything helpful though there was some mention about using an algorithm to sort this issue.Please help me fix this problem.

        #include <Wire.h> //I2C Arduino Library
    #define Magnetometer_mX0 0x03
    #define Magnetometer_mX1 0x04
    #define Magnetometer_mZ0 0x05
    #define Magnetometer_mZ1 0x06
    #define Magnetometer_mY0 0x07
    #define Magnetometer_mY1 0x08
    int mX0, mX1, mX_out;
    int mY0, mY1, mY_out;
    int mZ0, mZ1, mZ_out;
    float heading, headingDegrees, headingFiltered, declination;
    float Xm,Ym,Zm;
    #define Magnetometer 0x1E //I2C 7bit address of HMC5883
    void setup(){
      //Initialize Serial and I2C communications
      Serial.begin(9600);
      Wire.begin();
      delay(100);

      Wire.beginTransmission(Magnetometer);
      Wire.write(0x02); // Select mode register
      Wire.write(0x00); // Continuous measurement mode
      Wire.endTransmission();
    }
    void loop(){

    //---- X-Axis
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mX1);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
        if(Wire.available()<=1)
      {
        mX0 = Wire.read();
      }
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mX0);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mX1 = Wire.read();
      }
      //---- Y-Axis
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mY1);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mY0 = Wire.read();
      }
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mY0);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mY1 = Wire.read();
      }

      //---- Z-Axis
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mZ1);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mZ0 = Wire.read();
      }
      Wire.beginTransmission(Magnetometer); // transmit to device
      Wire.write(Magnetometer_mZ0);
      Wire.endTransmission();
      Wire.requestFrom(Magnetometer,1);
      if(Wire.available()<=1)
      {
        mZ1 = Wire.read();
      }

      //---- X-Axis
      mX1=mX1<<8;
      mX_out =mX0+mX1; // Raw data
      // From the datasheet: 0.92 mG/digit
      Xm = mX_out*0.00092; // Gauss unit
      //* Earth magnetic field ranges from 0.25 to 0.65 Gauss, so these are the values that we need to get approximately.
      //---- Y-Axis
      mY1=mY1<<8;
      mY_out =mY0+mY1;
      Ym = mY_out*0.00092;
      //---- Z-Axis
      mZ1=mZ1<<8;
      mZ_out =mZ0+mZ1;
      Zm = mZ_out*0.00092;
      // ==============================
      //Calculating Heading
      heading = filtered_angle(Zm, Xm);// arc tangent of z/x

      // Correcting the heading with the declination angle depending on your location
      // You can find your declination angle at: http://www.ngdc.noaa.gov/geomag-web/
      // At my location it's 4.2 degrees => 0.073 rad
      declination = 0.03717551307 ;
      heading += declination;

      // Correcting when signs are reveresed
      if(heading <0) heading += 2*PI;
      // Correcting due to the addition of the declination angle
      if(heading > 2*PI)heading -= 2*PI;
      headingDegrees = heading * 180/PI; // The heading in Degrees unit
      // Smoothing the output angle / Low pass filter
      headingFiltered = headingDegrees;
      //Sending the heading value through the Serial Port to Processing IDE

      if(headingFiltered >= 0 && headingFiltered <= 89){
                    c_head=map(headingFiltered,0,90,270,359);
            }
        if(headingFiltered > 89 && headingFiltered <= 204){
                    c_head=map(headingFiltered,90,204,0,90);
            }
        if(headingFiltered > 204 && headingFiltered <= 290){
                    c_head=map(headingFiltered,205,290,91,180);
            }
          if(headingFiltered > 290){
                   c_head=map(headingFiltered,291,359,181,269);
            }

    // Serial.print("Degrees - ");
     Serial.println(headingDegrees);
    delay(500);
    }

    float filtered_angle(float p, float q) {
             const float filter_constant = 0.15;
             static float q_f, p_f; // filtered components
             q_f += filter_constant * (q - q_f);
             p_f += filter_constant * (p - p_f);
             return atan2(p, q);
            }

body:
If you can't find and eliminate a systemic error, such as nearby ferrous, magnetic, or electromagnetic sources, causing the errors you see, you'll need to do what navigators have done for ages: swing the compass.

Swinging a compass involves taking the vehicle - your robo-car - somewhere away from external error sources (building wiring, iron/steel masses, f/ex) and taking a set of measurements by heading the vehicle in a number of directions known by a means independent of its own compass. Eg., with a boat, you'd choose a known place in the middle of a harbor and plot a line from that known position to each landmark (for a car, you could use a large playing field). That gives you the True bearing (bearing relative to the north pole) from the chosen position to the landmark. Make a list of those landmarks and their true bearings in columns 1 & 2 of sheet of paper, in clockwise order starting a true north.

Convert the True bearings to Magnetic bearings (relative to the direction from where you are now to the earth's magnetic north pole): Navigation charts will show the difference (in degrees) between True bearings and magnetic bearings for the location(s) covered by that chart; the difference is called "variation" (sometimes called declination). If the magnetic variation at your location is westerly (compasses point 15 degrees W of True North, f/ex), add that value to those bearings you just listed. This third column of numbers is the magnetic bearing to each of those landmarks, and the value an error-free compass should read.

Now take your vehicle to that known point (playing field, middle of the harbor, etc.) and point its center line at each of those landmarks and read its compass for each one. Write these numbers in the fourth column - the compass headings to the landmarks, for *this compass* in *this vehicle*.

Columns 3 & 4 are now a compass correction table. When the compass reads a number that is in column 4 (compass bearing), the actual (corrected) magnetic heading is the corresponding number in column 3 (the magnetic headings).

But of course you don't have every possible heading in your compass correction table. So when you need to know your car's direction, you have to interpolate between a pair of bearings you do have:

 1. Find a pair of bearings in column 4, the compass headings, that bracket the reading you just took.
 2. Find the percentage that reading is of the difference between the bracketing compass bearings.
 3. Apply that same percentage to the difference between the adjacent magnetic bearings in column 3 to find the actual magnetic bearing.

I glossed over the process of interpolation pretty quickly as the question was about correcting the compass. Interpolation, or other ways of applying a correction, is a whole 'nuther topic but the Arduino `map()` function will be great help here. Also, the more correction values (landmarks) you use to make your table, and the more evenly they are spread around the compass, the more accurate your corrections will be.


message:
Reset Arduino by connecting vcc and gnd?

A follow up question on my previous question, if a memory card reader can be used with three pins (digispark Attiny 85):

https://arduino.stackexchange.com/questions/70590/can-i-read-from-a-memory-card-with-three-pins

Now I came up with another idea.
Since the USB connector or the VCC pin can power an Arduino my guess is that they are in parallel and the actual Arduino is connected to both.
Kind of like this very bad schematic made on my phone: (sorry for that)
[![enter image description here][1]][1]
Where the blue stuff is the Arduino chip.

If that is true then adding the push button between VCC and GND with a resistor between should remove the power of the Arduino?
In that case I can have my code in setup() and use the pus button to reset the Arduino, and still have four pins to the memory card reader.

Or is this wrong? What kind of resistor value do I need to make sure I don't short the USB connector but still have less resistance than the Arduino chip?

  [1]: https://i.stack.imgur.com/j7yUJ.png

body:
That is wrong. That is very, very wrong. That is one of the worst things you can do to a USB connection short of plugging it into the mains.

Do not even consider doing this.  Short circuits are never a good idea.


message:
Uno to NodeMCU Serial Connection Problem

This is my first project with any sort of development board and it has been a blast so far.

I am running into some issues, however, while trying to send serial data from my Uno to a NodeMCU board.

I have the following connections:

Uno Rx to NMcu Tx

Uno Tx to NMcu Rx

Uno GND to NMcu GND

microUSB from computer to power NMcu

usb from computer to power Uno

**EDIT:** after some suggestions, I have also tried the following.

Uno DigitalPin 5 to NMcu D6

Uno DigitalPin 6 to NMcu D5

Uno GND to NMcu GND

microUSB from computer to power NMcu

usb from computer to power Uno

With the following code:

    // UNO sender Code
    #include <SoftwareSerial.h>
    SoftwareSerial toESP(0, 1); //Rx, Tx (also tried 5,6)

    void setup()
    {
      Serial.begin(115200);
      toESP.begin(9600);
    }

    void loop()
    {
      Serial.println("sending");
      toESP.println("message from Nano");
      delay(1000);
    }

--------------------------------------

    // NodeMCU receiver code
    #include <SoftwareSerial.h>
    SoftwareSerial fromNano(3, 2); //Rx, Tx (also tried D5, D6)

    void setup()
    {
      Serial.begin(115200);
      fromNano.begin(9600);
    }

    void loop()
    {
      if (fromNano.available())
      {
        char inChar = fromNano.read();
        Serial.print(inChar);
      }
      else {
        Serial.println("not available");
      }
      delay(2000);
    }

I can pull up a serial monitor from both and see the UNO sending data (the TX led also blinks on the uno).

The NodeMCU code never satisfies the `fromNano.available` condition.

Is there anything I am overlooking that is causing this not to work? I've attached a picture of my connections as well.

[![enter image description here][1]][1]

Any help is much appreciated.

  [1]: https://i.stack.imgur.com/ChFWa.jpg

body: Arduino UNO is using pin 0 and pin 1 to have serial with USB serial Communication. You can not use them to softserial. Change softserial to other pins.  /Mikael


body:
@Carlmikael is definitely correct in his answer, I should not have been using hardware pins with softwareserial.

Besides that problem, my issue was resolved ultimately when I noticed that if I powered up the NodeMCU before powering up the Arduino, everything worked as expected.

Maybe someone can elaborate as to why this caused an issue?


message:
Some Blocks of Code gets stuck in a loop, I do not know why

[![enter image description here][1]][1]

The code below Gets stuck at function "Led Off?" & "Check button".
I'm using Blockyduino editor.
The check button code was intended as a toggle switch for the lights. When I deleted "Led Off?" and "Turn off All LED", the code did not get stuck.

    int Button_Status;

    // Toggle Code for the button.
    void Check_Button() {
      Serial.println("Check button Activated");
      if (Button_Status == 1) {
        if (digitalRead(13)) {
          Button_Status = 0;
        }
      }
      if (Button_Status == 0) {
        if (digitalRead(13)) {
          Button_Status = 1;
        }
      }
      LED_OFF_();
    }

    void Left_Animation() {
      Check_Button();
      digitalWrite(2, HIGH);
      digitalWrite(3, HIGH);
      Check_Button();
      delay(1000);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      Check_Button();
      delay(500);
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      Check_Button();
      delay(300);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      Serial.println("Finshed Left cycle");
    }

    void Right_Animation() {
      Check_Button();
      digitalWrite(8, HIGH);
      digitalWrite(9, HIGH);
      Check_Button();
      delay(1000);
      digitalWrite(10, HIGH);
      digitalWrite(11, HIGH);
      Check_Button();
      delay(500);
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
      Check_Button();
      delay(300);
      digitalWrite(10, LOW);
      digitalWrite(11, LOW);
      Serial.println("Finished Right cycle");
    }

    // Main Loop Core
    void Main_Loop() {
      while (Button_Status == 1) {
        Left_Animation();
        Right_Animation();
        Serial.println("Finshed Main Loop 1111");
      }
      while (Button_Status == 0) {
        Check_Button();
        Serial.println("Finished Main Loop 2222");
      }
    }

    // Checks if button toggle variable is off.
    void LED_OFF_() {
      Serial.println("LED off? Activated");
      if (Button_Status == 0) {
        Turn_Off_All_LED();
      }
      Main_Loop();
    }

    // Turns off all LED
    void Turn_Off_All_LED() {
      Serial.println("LED Turn off Activated");
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
      digitalWrite(10, LOW);
      digitalWrite(11, LOW);
      Main_Loop();
    }

    void setup()
    {
      Serial.begin(9600);
      pinMode(13, INPUT);
      pinMode(2, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);
    }

    void loop()
    {
      // Start
      Button_Status = 1;
      Main_Loop();
    }

  [1]: https://i.stack.imgur.com/2rsRi.png

body:
You have a problem with infinite recursion in this program: `loop()`
calls `Main_Loop()`, which calls `Left_Animation()`, which calls
`Check_Button()`, which calls `LED_OFF_()`, which calls `Main_Loop()`,
which calls `Left_Animation()`, which calls `Check_Button()`, which
calls `LED_OFF_()`, which calls `Main_Loop()`, which calls... This will
pretty quickly exhaust the memory of your Arduino.

If you only know about graphical programming, this may not make too much
sense to you. So I ask you to imagine that, in your definition of
`Main_Loop()` (the big structure titled “to Main Loop”) you replace the
smallish box labeled “Left Animation” by its own definition (the big
structure labeled “to Left Animation”). Within this definition, you
replace “Check Button” by its own definition and so on. You will soon
reach a point where you need to embed the definition of `Main_Loop()`
within itself. It should then look more or less like this:

```text
Main Loop
│ repeat while Button Status = 1
│ do Left animation
│ │  │ Check Button
│ │  │ │ Serial Print “Check button Activated”
│ │  │ │ ...
│ │  │ │ LED OFF?
│ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ if Button Status = 0
│ │  │ │ │ do Turn Off All LED
│ │  │ │ │ Main Loop
│ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ Main Loop
│ │  │ │ │ │ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Main Loop
...etc ad infinitum...
```

Note that it is possible to write programs using [recursion][], but:

1. This is kind of an “advanced topic”, not suitable for someone still
   programming at a graphic level.
2. You have to take precautions in order to avoid the program to
   infinitely recurse.
3. On a microcontroller with little memory, you have to make sure the
   recursion is always very shallow. Which is hard, so people writing
   embedded code tend to avoid recursion altogether.

[recursion]: https://en.wikipedia.org/wiki/Recursion_(computer_science)


message:
I want to send the last 10 minute data via bluetooth

This was for photocell data logging for 30 sec intervals, now I want to write a code which commands from the cellphone and sends back the last 10 minute data.

At first I thought if I make an array of 20 buckets and put it in a loop, then send the loop function to android would make it right. But it just sends me continues data. I only want the last 10 minute data of the program.

    float sensorvalue[20];

    void setup()
    {
     // put your setup code here, to run once:
     Serial.begin(9600);

     for (int i = 0; i < 20; i++) {
      pinMode(sensorvalue, OUTPUT);
     }
    }

    void loop()
    {
     // put your main code here, to run repeatedly:
     sendvalues();
     char c;

     if(Serial.available()) {
      c=Serial.read();
      if (c=='t')
       sendvalues();
     }
    }

    void sendvalues()
    {
     for (int i=0 ; i<20 ; i++) {

      Serial.println(sensorvalue);
      sensorvalue   = analogRead(A0);
      delay(30000); //every 30 seconds read data

      if (i>=20) {
       i=0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
      }
     }
     Serial.println("***********************************");
    }

body:
Your code doesn't make much sense as written.

You need to:

Collect a new value every 30 seconds and save it into an array of values, incrementing a "current value index" variable with each read.

Do you want to trigger the sending of a buffer-full of data when the array is full, or using a command from the remote phone? If you want to trigger the sending from a phone, what would you do if there wasn't a full buffer of data? What would you do if the buffer gets full and there's no command sent from the phone?

Assuming you send a buffer-full of data every time it's available, just wait until the array index reaches the end. When that happens, transmit the entire buffer of data to your phone and reset the array index to start collecting new data.

If you want to trigger sending from your phone you have to handle edge cases like buffer overflow, or trying to send before you have a full buffer of data. I would suggest creating an array larger than you need (say 100 values), making it a ring buffer (google it) and saving new values continuously until the ring buffer is full. If the sketch receives a send command, it could check to see if it has at least 20 values in the buffer, and send those/remove them from the buffer if it does, or send back a "not enough data collected" message if not.