text:
Mildly accurate oscilloscope using Arduino Uno R3
I'm trying to make a mildly accurate oscilloscope using Arduino Uno R3 and I've done some research on the best method to do so. First of all I need to measure the voltage with a rather high sampling rate and then I'm going to transfer my data through the serial port and plot the data using Python or Matlab.
According to what I have read the analogread() function will cause some delay and therefore some inaccuracies and thus it is not suitable for my purpose.
I found on this website some good info about how I should write my code, but I have some questions:

I want my reference voltage to be 1.1 V so that by dividing it to 1023 parts I will have an accuracy of about 1 mV. How should I edit the mentioned code in order to do so?

The code in the void loop() setup is of no use to me (I prefer not to save the measured data on the Arduino and then send to my PC because of memory limitations). After deleting it will the data still be sent to the serial port?

Will sending the data through the serial port affect my sample rate/accuracy? I mean how does it effect my accuracy?

P.S: by mildly accurate this is what I mean: I want to measure voltage accurately with 1 mV precision for frequencies of max. 500 kHz (a bit less or more won't hurt).

That’s an interesting question, even if only to define the limits of “mildly accurate” imposed by the Uno platform. You may need to break your coding down a piece at a time, asking all three questions at once may constrain the answers you receive. I think the analogReference() function may assist with the first question. https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

@rowanp thanks for the help with analogreference. I will edit the question for better defining mildly accurate.

When ever hardware is pushed to its limits I find one needs to be very familiar with both the hardware and software.  Just for starters, consider Python is 100s if not over 1000 times slower then, say, compiled C.  I say this even though it sounds like you are running Python on other than an Arduino.  At the other end of the spectrum, even though the ADC has 10 bits this does not necessarily mean you can get 1024 steps of resolution for any single sample.  Noise will likely reduce this considerably.

@st2000 I understand that Python is much slower than C. So will using Matlab as the data analyzer on the other end give better results? since it is C-based or should I just test that?

You won't get anywhere near 500 kS/s (kilosamples per second) with an Uno. The ADC accuracy degrades as you speed up its clock, and it becomes essentially garbage past 1 MHz (which gives 76.9 kS/s). See ADC conversion on the Arduino, by Nick Gammon.

@EdgarBonet after what you said I did some searching about the Nyquist criterium and found out that if we dont want to use sample rates higher than 76.9kS/s the highest frequency we can measure is about 38 khz. am I right?

I don't think any of us want to discourage you @infinite.  It might be better to go into this thinking you might not make it to your target goals.  And if you have fun doing it, all the better.  Also, once you get some experience with your Uno R3, consider stepping up your game with a more advanced / faster processor. The Arudino development IDE has been ported to many many different processors / boards.

@st2000 guess you are right! but so far I've learned a lot about signals and how ADC works and all that stuff so for better learning I'm trying to do this project the best way I can.

I want my reference voltatge to be 1.1v so that by dividing it to
1023 parts I will have the accuracy of about 1mv.

You will have a resolution of about 1 mV. The accuracy will be
significantly worse than that due to the imperfections of the ADC
(offset error, gain error, non-linearity) and noise.

how should I edit the mentioned code in order to do so?

The reference is configured by the bits REFS0 and REFS1 of the
ADMUX register. The internal 1.1 V reference is selected by
setting both bits, as shown in table 24-3 of the
datasheet. You can then patch the original code like this:
@@ -8,7 +8,7 @@
   ADCSRA = 0;             // clear ADCSRA register
   ADCSRB = 0;             // clear ADCSRB register
   ADMUX |= (0 & 0x07);    // set A0 analog input pin
-  ADMUX |= (1 << REFS0);  // set reference voltage
+  ADMUX |= (1 << REFS0) | (1 << REFS1);  // set reference voltage
   ADMUX |= (1 << ADLAR);  // left align ADC value to 8 bits from ADCH register

   // sampling rate is [ADC clock] / [prescaler] / [conversion clock cycles]

the code in the void loop() setup is of no use for me (I prefer not
to save the measured data on the arduino and then send to my pc
because of memory limitations). after deleting it will the data still
be sent to the serial port?

In the linked code, loop() is the only function sending anything to
the serial port. If you remove it, nothing will be sent. You could
Serial.write() in the ISR though, in which case an empty loop()
would be fine.
Note that writing to Serial from within an ISR is generally
discouraged. Your situation though (an oscilloscope code) is one of the
very few cases where it does make sense to do so.

will sending the data through the serial port affect my sample
rate/accuracy?

It can certainly affect your sampling rate. Serial.write() is usually
non-blocking, as all it does is write the data to the RAM-based transmit
buffer. If the buffer fills up, however, Serial.write() will block
waiting for the serial port to actually send the data, and make enough
room in the buffer.
This means that, in order for the oscilloscope to not miss samples, you
have to make sure that the serial port can send the data at least as
fast as the ADC is acquiring it.
Example calculation: If you clock the ADC at 1 MHz, you get one
sample every 13 µs. You can follow the example given in the code
you linked to, and discard the last two bits in order to transmit only
8 bits of the sample. Transmitting those in plain binary will take
10 “bits” worth of the serial port bandwidth (one start bit,
8 data bits and one stop bit). Each bit should then take less than
1.3 µs, which translates to a baud rate of 769,231 bits per
second. You will probably have no other choice than configuring the
serial port for 1 Mb/s.
If you want to transmit the whole 10 bits of the ADC readings, you
will have to lower the sampling rate by a factor two.
At this point you may notice that the serial port, rather than the ADC,
is the bottleneck for the performance of your oscilloscope. If this is
too limiting, you may consider building a scope that works by bursts: it
stores a burst of samples in memory, then sends it at a leisurely rate
through the serial port.

You might want to consider using a Teensy 3.x or Teensy 4.x instead of an Arduino R3.  Teensy 4.1 has a CPU speed of 600MHz vs R3 of 16MHz.  Both use Arduino, and both are in the same price range


text:
Why is my SD shield making my Arduino not power on?
I wanted to use an SD shield on an Arduino Elegoo to make a typewriter (for saving files).
I put the shield on the Arduino Elegoo, then connected an LCD screen, then tried to power on using USB to computer, but my Arduino Elegoo wouldn't power on.
I tried to power it on with the external power supply, but it still wouldn't power on.
If I power it on without the shield it works perfectly fine, so why is my Arduino Elegoo not powering on?

When you say you "remove the shield" I assume that also implies removing that tangle of wires too? What about leaving the shield on but disconnecting the wires? I'll bet it works then. The problem won't be with the shield, it'll be a mistake in your own wiring.

Majenko  Yes you are correct it powers on without the wires but the lcd screen powers on without the sheild plus the elegoo powers on too whereas if i have the sheild and elegoo connected to the lcd screen then it does not work so how do i fix this since the lcd screen is important in the project

pins 10 to 13 are SPI pins used by the SD shield. it looks like you use the same pins for the LCD and I doubt the LCD works on SPI bus.

If you want to make your question answerable to the point of receiving specific instructions you'd need to include images of the sort of quality that would allow readers to trace each connection unambiguously. There are common SD card shield designs, but someone answering this would likely want to know exactly which design your shield follows. To get the sort of answer that would lead you to a successful outcome as a whole project you'd also want to include your code as well.

juraj yep you're right it worked

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Keypad Type 11 numbers only?
Can someone give me any idea what condition should i use in input 11 numbers only in the switch case? I only want to type and input 11 numbers only but The problem is it can type more than 11 numbers.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "Keypad.h"

LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

const byte Rows= 4; //number of rows on the keypad i.e. 4
const byte Cols= 3; //number of columns on the keypad i,e, 3

//we will definne the key map as on the key pad:

char keymap[Rows][Cols]=
{
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'*', '0', '#'}
};

//  a char array is defined as it can be seen on the above

//keypad connections to the arduino terminals is given as:

byte rPins[Rows]= {1,2,3,4}; //Rows 0 to 3
byte cPins[Cols]= {5,6,7}; //Columns 0 to 2

// command for library forkeypad
//initializes an instance of the Keypad class
Keypad kpd= Keypad(makeKeymap(keymap), rPins, cPins, Rows, Cols);

char entryStr[8];
int i=0;
long number1=0;
long number2=0;

void setup()
{
   Wire.begin();
   lcd.init();
   lcd.backlight();
   Serial.begin(9600);
   delay(100);

}

I tried that code but the problem is. Its still input more than 11 numbers

I did upload a photo in Displaying LCD it can input almost 15 numbers. I want only to input 11 numbers

Am I missing something? You count the number of digits entered, and stop when you have 11 of them. I suggest doing some C tutorials.

did you ask this same question on March 27th? .... are you Shin Doe? ... if you are, why are you asking again?

Please don't post the same question twice.

Three simple approaches.

You could get a string, and limit it to 11 characters in length. You then convert the string to num
You could check that 9999999999<num<=99999999999
You could count the number of valid 'kpd.getKey()' and when it gets to 11 exit the function (returning num as it stands)

The OP suggests only 11 digits. Of course, if less that 11 digits are acceptable, the returning value could be padded with 0.
lcd.print1 can natively takes a string, and the best approach is to treatnum` as a string instead of as a number. A number (in itself) is only useful if you want to do arithmetic. A lot of times a series of digits are used as an identifier - these are not really numbers but strings with a limited character set.
Some examples (not tested):
Example 1: counting the digits entered. Simply added a counter numcount - you can see where I use it in the conditional loop, where I increment it, and where I clear it.
long GetNumber()
{

  long num = 0;
  long numcount = 0;
  char key = kpd.getKey();
  while(key != '#' && numcount <= 11)
  {
    switch (key)
    {
    case NO_KEY:
      break;
    case '0':
[... skipped for brevity ...]
    case '9':
      lcd.print(key);
      num = num * 10 ;
      num= num+ (key-'0');
      numcount += 1;
      break;
  case '*':
    num = 0;
    numcount = 0;
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Re-type number:");
    lcd.setCursor(0,1);
    break;
  }
  key = kpd.getKey();
}
return num;
}

Example 2: Simple check on the value of num. In this case both the "#" and num reaching a certain value will exit the function in a controlled way. A better loop method would be to loop ... until - checking the condition at the end of the loop rather than at the beginning.
long GetNumber()
{
  long num = 0;
  char key = kpd.getKey();
  while(key != '#' && num <= 99999999999)
  {
    switch (key)
    {
    case NO_KEY:
      break;
    case '0':
    [... skipped for brevity ...]
    case '9':
      lcd.print(key);
      num = num * 10 ;
      num= num+ (key-'0');
      break;
    case '*':
      num = 0;
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Re-type number:");
      lcd.setCursor(0,1);
      break;
    }
    key = kpd.getKey();
      }
  return num;
}

Example 3: using a string. Same comment about checking conditions at the end of the loop instead of the beginning apply. I haven't worked with strings in C for a few decades, so the routines I used (strlen, strcat) may need some work or tweaking.
string GetNumber()
{
  string num = "";
  char key = kpd.getKey();
  while(key != '#' && strlen(num) <= 11)
  {
    switch (key)
    {
    case NO_KEY:
      break;
    case '0':
    [... skipped for brevity ...]
    case '9':
      lcd.print(key);
      num = strcat(num,key)num * 10 ;
      break;
    case '*':
      num = "";
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Re-type number:");
      lcd.setCursor(0,1);
      break;
    }
    key = kpd.getKey();
    }
  return num;
}

Thank you . Can you give me idea how to do it in my code?Im really a newbie. thanks a lot.

Thank you so much! I already tried your code and its working now. Thank you very much! :) :D

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Avrdude can't connect to butterfly programmer
I'm trying to upload my exported HEX file by avrdude using this command

/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem1421 -b57600 -D -Uflash:w:/Users/user_acc/Documents/Arduino/at_command_A6/at_command_A6.ino.with_bootloader.leonardo.hex:i

But instead of loading the file it's stuck on connecting to programmer.
Output: https://scr.hu/rYNzzm
https://paste.ubuntu.com/p/74p37fGYPN/
The output from ArduinoIDE is exactly the same and it finds the programmer without the problem and loads the file.

/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem124 -b57600 -D -Uflash:w:/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/arduino_build_78519/at_command_A6.ino.hex:i

Output: https://scr.hu/M72NaV
Can somebody help me? :)

please update the second picture  so that it shows the command line (roll the screen down a bit)

@jsotola I added the whole output from Arduino in the paste.ubuntu.com link

@jsotola Thats the output from Arduino. What command line do you want to see?

go to "preferences" in the Arduino IDE .... check "show verbose output during" upload .... do an upload ..... the actual avrdude command line gets diplayed .... post that command line

@jsotola it was all the time in the output that I provided. Its in the question now as well. Dont mind the cu.usbmodem124. I changed the port during my attempts.

I found a post of somebody with a similar issue. His solution fixed my issue!
https://stackoverflow.com/questions/46813157/avrdude-command-line-cant-connect-to-programmer-for-leonardo

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
output of yun is not 3.3
After execute the program of below, the 13 pin output is 4.8v. Why it's not 3.3v?
void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(13, HIGH);
}

The Atheros chip on the Yún is run off 3.3V, but the AVR chip, which is what is connected to the external pins, runs off 5V. What you are seeing is normal (a bit low though, but within spec).

Nothing connected to pins... I just test it. Is it should be 5v? Is it normal that I get 4.8v when nothing connected?

It should be very close to the voltage of the 5V source, whether a regulator or the USB connection.

Thanks. I mean I don't think so 4.8v is very close to 5v. Hope it's fine when I play with it, hope components will work with it.

5% is a reasonable margin for digital supply voltages.

The Yun has no voltage regulator, so the 4.8V instead of 5V is due to the PC or USB plugpack used for power.

That's what I figured, but I should have checked the schematic to be certain.


text:
Arduino does not work on battery
The day before I got my used full package arduino uno. I tested it on USB plug. Everything worked fine. I wrote a piece of testing code and uploaded. After I have accomplished with the test I have unpluged arduino from PC and connected to battery and I see that it does not work. I have used a multi-tester to find out the voltage. It showed 4.7V. Now I wonder should I buy a new battery or there is another reason for this. Anybody, please suggest me what to do.
Update
The battery came with arduino set. It is written that it is a 9V battery. I am plugging it to the battery input in my arduino uno. Polarity is ok. The same program working on connection via usb, does not when connected to battery.

What kind of battery? How did you connect the battery to the Arduino? Did you check the polarity?

@EdgarBonet updated by question.

Do you read 4.7 V between "Vin" and "GND" or between "5V" and "GND"? Does the "ON" LED light up?

@EdgarBonet I think I got the point, the "ON" ligth has not turned on. So it means that the power supplied by battery is not enough to run the arduino?

What does your DMM say?

Do you have any other components plugged in anywhere, motors, leds etc?

Did you make sure the battery is charged? Does it have enough voltage to power the board? Remember that Arduino has internal voltage regulator, so you need something little more than 5V in order to get it working okay.

@bpinhosilva you are right, the battery was not supplying enough power to make arduino work.

@zazu I'm glad that it worked okay!

@bpinhosilva - If you made your comment an answer and expanded upon it a little, then the question could be marked as accepting an answer...

Did you make sure the battery is charged? Does it have enough voltage to power the board? Remember that Arduino has internal voltage regulator, so you need something little more than 5V in order to get it working okay.
(Comment by bpinhosilva re-purposed as an answer so this will stop showing up as unanswered).

@bpinhosilva you are right, the battery was not supplying enough power to make arduino work.

Please accept this so that the number of unanswered questions goes down. :)

Check the serial number of your board. Some boards were shipped with a defective boot loader, which has the loader stuck in an infinite loop when powered off and on again. Just Google the serial range of possible defective boards, and check if your board is in that range.

Try to use a battery that provides at least 7-12 volts. The voltage regulator will regulate the needed 5 volts for the arduino.

simply you can weld a little electrolytic capacitor eg. 4 or 6 microfarads, 12 or more Volts, with the positive wire on the reset pin and the negative on the GND pin. in this way you can solve the restart without the USB connection.
This is what I did
Enjoy with Arduino.
By Daniele

This seems to address a different issue :)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
how to send input values from host computer to arduino
how to send input values from host computer to arduino,such that speficing the number of rotations for a stepper motor etc

Via serial. Most CNCs and 3D printers send GCode over serial.

The easiest method is to use the serial communication. Use the sample code at http://arduino.cc/en/Tutorial/SwitchCase2, upload that to an Arduino, start the serial monitor (Ctrl+Shift+M), make sure the baud rate is the same as set in the code (9600 in this case), then write the commands and send them to the Arduino.
Edit
Since the serial characters are usually read one by one you need a character that will signal the end of the string. This is usually a newline \n, but can be any character you choose (and can be sent to Arduino).
Sample code (processString would be your function to do something with the string):
char buf[64];
byte cnt = 0;
void loop()
{
    while (Serial.available()>0) {
        byte c = Serial.read();
        // Check for terminator character or the size of buffer
        if (c == '\n' || cnt >= 63) {
            // Add the terminating 0
            buf[cnt] = 0;
            // Process the full string
            processString(buf);
            // Prepare to read the next string
            cnt = 0;
        } else {
            // Not terminator - add to string
            buf[cnt++] = c;
        }
    }
}

okay.If i want to sent a string the same read() is used? Is there any modifications needed for sending strings?

check my updated answer above


text:
Inaccurate PWM Signal Frequency and Timing
I have a Teensy 3.2 and I am using the Arduino IDE to program it. I am trying to generate 8 pulses with the frequency of 40 kHz and this needs to be repeated every second. I have written 3 different codes and none of them is working quite the way I wanted. The duty cycle of the pulses are not always constant (i.e. the falling edge often shifts in the time axis), indicating an inaccuracy with the delay between the analogWrite commands. There seems to be an issue with delays not being consistent and changing within the 8 pulses and between the 8 pulses. This inaccuracy is different between the 3 different codes, but exists in all of them. Changing the processor speed between 16 MHz and 120 MHz does not appear to change the problem (except in code 3 where NOP is dependent on it). Is there a way to make the cycles more consistent at 40 kHz? Do I need to use an external timer or oscillator? The two images below display the two problems. The first image shows the differences in time delays and output frequency. The red dashed lines are provided to show the discrepancy in the same pulse at successive iterations of the code. The second image shows a recurring issue where the square wave is not in fact a square, and doesn't seem to be caused by software problems.
Image 1:

Image 2:

The codes I have written can be found below:
Code 1:
const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

void setup() {
  analogWriteFrequency(pin1, 40000);
  analogWriteFrequency(pin2, 40000);
}

void loop() {
  analogWrite(pin1,128);   //for 50% duty cycle
  delayMicroseconds(188);  //It takes 187.5us to generate 8 pulses at the given frequency
  analogWrite(pin1,0);
  delay(1000);
}

Code 2:
const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

void setup() {
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  PWMSignal();
  delay(1000);
}

void PWMSignal(){
  for(int i =0; i<=8; i++){
      analogWrite(pin1, 255);
      analogWrite(pin2, 0);
      delayMicroseconds(10);
      analogWrite(pin1, 0);
      analogWrite(pin2, 255);
      delayMicroseconds(10);
      analogWrite(pin2, 0);
  }
}

Code 3:
const uint8_t pin1 = 5;
const uint8_t pin2 = 6;

// Variable N determines the length of the delay.
// Execution of NOP corresponds to 62.5ns delay
// when the processor speed is 16 MHz.
const int N = 50;
#define NOP __asm__ __volatile__ ("nop\n\t")

void setup() {
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  PWMSignal();
  delay(1000);
}

void PWMSignal(){
  for(int i =0; i<=8; i++){
      analogWrite(pin1, 255);
      analogWrite(pin2, 0);
      delayNOP();
      analogWrite(pin1, 0);
      analogWrite(pin2, 255);
      delayNOP();
      analogWrite(pin2, 0);
  }
}

void delayNOP(){
  for(int j =0; j<=N; j++){
    NOP;
  }
}

Try disabling interrupts around your bursts of pulses.

Maybe using the IntervalTimer of the Teensy 3.x to manually toggle a pin (with direct port writing, not digitalWrite()) would give more reliable results.  Hint: GPIOx_PTOR will toggle a pin in one single operation.  "x" is the port number, and write (1<<p) to it where p is the pin number.

it seems in the first picture that the two pulses have different duty cycles which is why it appears shifted. It looks like the 'on' part stays on for less time than the 'off' so your duty cycle is probably <50 but your frequency might still be 40kHz.
I think the most accurate way of getting 40kHz just with a teensy is to use timer interrupts as Majenko suggested. Check out the documentation for it here, its pretty straight forward,you set the timer to go off every 12.5us and in the ISR simply toggle a digital pin and keep count of how many times you've toggled it. If your teensy needs to run other interrupts you should change the priority using myTimer.priority(number); to possibly give the 40kHz interrupt a higher priority. One thing, don't use digitalWrite in the ISR as its slow af, either try digitalWriteFast or use assembly language to toggle it as pointed by Majenko.
Alternatively you could use a 555 timer which is easy to setup and I'm pretty sure it's been used to gerate 40kHz at 50% duty cycle, although it might be a bit tricky finding the correct capacitor/resistor values if they're too small/non-standard. Then you would hook up the output of the 555 timer to whatever you're hooking it up to and also to a digital input pin on the micro. Then you would have to set an external interrupt on that pin so whenever the 555 goes high the interrupt on the pin would fire and you would keep track of how many pulses have been generated.
Alternatively, you could use a digital signal synthesizer. I used the ad9837 for one of my projects. It can generate something like 0-3Mhz with a 5Mhz external clock at a resolution of 0.02 which is pretty good. I've got an altium design for it if you don't want to buy the module and an adapted version of the adafruit miniGen library which works with teensy3.5 link. Then you'd need to do the same feedback loop as the 555 to keep track of how many pulses have been produced (or your way of waiting X microseconds). The module is actually pretty low power so you could power it from a digital pin and turn that pin on/off every second.
I think you should try the interrupt method first, as it's the easiest. Also, I get that you want 8 pulses evey one second but maybe for debugging purposes have the 40kHz pulse go constantly and change your scope to measure frequency so you can see how far off you are from 40khz.Then once you know you're actually getting 40khz have it run every 1second.

One option is to use the IntervalTimer of the Teensy:
// Set up the variables and objects:
IntervalTimer myTimer;
volatile int count = 0;

// ... later, start it:
count = 0;
myTimer.begin(togglePin, 12);

// ... and:
void togglePin() {
    GPIOB_PTOR = 1<<8; // Note: find the right register and bit for your chosen pin.
    count++;
    // 16  toggles is 8 pulses.
    if (count == 16) {
        myTimer.end();
    }
}

Note: this hasn't been tested, and you will need to do some research to get the right register and bit number, and also configure the pin for output and to your default level.


text:
How to only detect the opening and closing of door sensor once
im quite new to Arduino coding. Currently im trying to create an alarm and when the alarm ring, the user will just need to remove the door sensor once to stop the alarm and listen for the next alarm. What i have is Real Time clock module to keep track of the time.
So i have tried to code on my own but failed and here's the outcome:
After the alarm ring, and i remove the door sensor from each other, it stopped buzzing (Which is correct partly) but once i put it back together, it continued to ring for the alarm duration (Which was set as 1 min)
Here's the code i had:
#include <DS3231.h>
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
DS3231  rtc(SDA, SCL);
Time  t;
#define buz 11      //This is Buzzer that is plug into pin 11 (Change it accordingly to what you will be putting it in the arduino)
int Hor;            // This is declaring the alarm in Hours
int Min;            // This is declaring the alarm in Minutes
int Sec;            // This is declaring the alarm in Seconds
const int sensor = 10;    // Door sensor connected to Pin 10
int state; // 0 close - 1 open switch

void setup()
{
  Wire.begin();
  rtc.begin();
  Serial.begin(9600);
  pinMode(buz, OUTPUT);
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Alarm");
  lcd.setCursor(0,1);
  lcd.print("Test");
  // The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
  delay(2000);
  pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
  t = rtc.getTime();
  Hor = t.hour;
  Min = t.min;
  Sec = t.sec;
  lcd.setCursor(0,0);
  lcd.print("Time: ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());

  alarm1();
  alarm2();
  delay(1000);
}

void Buzzer()
{
  digitalWrite(buz,HIGH);
  delay(500);
  digitalWrite(buz, LOW);
  delay(500);
}

void alarm1() //E.g. This is the first alarm for the medicine
{
  state = digitalRead(sensor);
  if( Hor == 20 && (Min == 11 || Min == 12) && state == 0) //Comparing the current time with the Alarm time
  {
      Buzzer();
      lcd.clear();
      lcd.print("1st Alarm ON");
      lcd.setCursor(0,1);
      lcd.print("Morning Medicine");
     }
  else if ( Hor == 20 && (Min == 11 || Min == 12) && state == 1)
  {
    noTone(buz);
  }
  delay(200);
}

void alarm2()
{
  if( Hor == 19 && (Min == 48 || Min == 49) && state == 0) //Comparing the current time with the Alarm time
  {
      Buzzer();
      lcd.clear();
      lcd.print("1st Alarm ON");
      lcd.setCursor(0,1);
      lcd.print("Morning Medicine");
     }
  else
  {         //Once user open the door sensor, the alarm will stop buzzing
    noTone(buz);
    alarm1();
  }
  delay(200);
}

Just to clarify that the variable state i took from
http://www.instructables.com/id/How-to-Use-a-Magnetic-Door-Switch-Sensor-With-Ardu/
So to summarised my problem, i am trying to get the system to read the opening of the door sensor once so that the alarm will stop and listen to the next alarm regardless if i put it back the door sensor or not
Really hope someone can help me thanks for you kind attention

Please, provide a link to the libraries you are using. There are tons of libraries called “DS3231”, which are not compatible with one another.

As often, the answer to this question is “Implement a ‘Finite State
Machine.’”. In this instance, you need at least three distinct
states:

ARMED: the buzzer is not active, but it is only a matter of time...
ON: bzzzz... bzzzz... bzzzz...
STOPPED: the user has stopped the alarm.

Each of your alarms should have a start time and a stop time (say, two
minutes after the start time). Then, the possible state transitions are:

ARMED → ON: when we hit the start time of an alarm
ON → STOPPED: when the user stops the alarm
ON → ARMED: when we hit the stop time of the alarm
STOPPED → ARMED: when we hit the stop time of the alarm

Notice that, once the user stops the alarm, the only way for the buzzer
to start buzzing again is by going through the transitions STOPPED →
ARMED → ON. The first transition happens at the alarm's stop time,
whereas the second one happens at the next alarm's start time.
You did use a kind of state variable in your code, but the problem is
you failed to realize that ARMED and STOPPED should be distinct
states. If you fuse these states together then, when the user stops
actively “stopping” the alarm, and if it's still start time, the
system transitions immediately back to the ON state.


text:
Custom Classes - Redefinition of void error
I'm getting a redefinition error from my classes, but can't see what I did wrong.
Error: Icon.cpp:3:6: error: redefinition of 'void Icon::setIcon(byte (*)[8])'
Can any help me out on this? Thanks!
MyFile.ino
#include "MyIcon.h"

MyIcon myIcon;

MyIcon.h
#ifndef MyIcon_h
#define MyIcon_h

#include "Arduino.h"
#include "Icon.h"

class MyIcon : public Icon {
  public:
    MyIcon();
};

#endif

MyIcon.cpp
#include "MyIcon.h"

MyIcon::MyIcon() {

  byte _icon[8][8] = {
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 1, 2, 2, 2, 2, 1, 1},
    {1, 2, 1, 1, 1, 1, 2, 1},
    {2, 1, 2, 2, 2, 2, 1, 2},
    {1, 2, 1, 1, 1, 1, 2, 1},
    {1, 1, 1, 2, 2, 1, 1, 1},
    {1, 1, 2, 1, 1, 2, 1, 1},
    {0, 0, 0, 1, 1, 0, 0, 0},
  };
  MyIcon::setIcon(_icon);

Icon.h
#ifndef Icon_h
#define Icon_h

#include "Arduino.h"

typedef struct{
  byte r;
  byte g;
  byte b;
} RGB;

class Icon {
  public:
    Icon();
    inline virtual void setIcon(byte icon[8][8]){};
    inline virtual void setIconColors(RGB colors[3]){};
};

#endif

Icon.cpp
#include "Icon.h"

void Icon::setIcon(byte icon[8][8]) {
  __icon = icon;
}

void Icon::setIconColors(RGB colors[3]) {
  __colors = colors;
}

Edited on 09/11/18
I attempted the following changes, before I realised thanks to KIIV, that I couldn't use array like that.
My idea was to be able to getIcon() and get back the byte array, which is later used to light up specific leds on a NeoMatrix panel.
I thought I would be able to build an icon "library" by extending a base class, setting the correct byte array in the class, and using it as needed (MyIcon, MyOtherIcon, etc...)
Have I completely missed the point?
Icon.h
void setIcon(byte icon[8][8]);
void setIconColors(RGB colors[3]);

Icon.cpp
#include "Icon.h"

Icon::Icon(){ }

void Icon::setIcon(byte icon[8][8]){
  memcpy(__icon, icon, sizeof(icon));
}

void Icon::setIconColors(RGB colors[3]){
  memcpy(__colors, colors, sizeof(colors));
}

Hidden error: You might also what to check the MyIcon constructor. What type of variable (_icon) are you passing to "Icon::setIcon()"?

this is an example of a question for Stack Overflow, not for Arduino SE. https://arduino.stackexchange.com/tour

You should make the Icon pure virtual by virtual void setIcon(byte icon[8][8]) = 0; and same for setIconColors. In Icon.cpp is total nonsense. Even if you define __icon and _colors in MyIcon as members, Icon don't know anything about it. And arrays cannot be assigned like this.

I think I got way lost in my attempts at achieving what I wanted to do. I wanted to be able to extend a base class (Icon) in order to be able to build an icon "library" of sorts.The icons are built from an 8x8 byte array, so I wanted to be able to request getIcon() from a child class like MyIcon in order to retrieve the icon (which is then use to light up a NeoMatrix panel. I didn't realize you couldn't return (or set) a byte array from a function.

I would suggest you don't want to use classes at all for this. You can have an icon as a single array of data in PROGMEM and write a little function to parse it. I'd have something like one byte for the number of colours (N), two bytes for the icon dimensions (W,H) (if needed), N*3 bytes for the colour information, then WxH bytes for the icon image. If the number of colours is always the same, or the dimensions of the icon is always the same then you could omit N and/or W,H values.

Hi Majenko, I am trying to follow your suggestions, and have tried the following gist. It seems to work for the icon byte array, but I'm having an issue in assigning fetching my struct once I place it in PROGMEM, hence why I removed the keyword. This is a very new approach to me, so I'd appreciate any feedback!
https://gist.github.com/Nate1661/0eea9200e9d1c86187c2acf205ba3602

You have bodies for setIcon and setIconColors in both the header file and the cpp file.  You can only have them in one or the other - choose.
Also, as an aside, the way that you are assigning icon data will go out of scope before you use it.  You create a local array variable which you then pass a pointer to to your constructor. That pointer is then saved. But then you go out of scope and the pointer is discarded, and the data will be overwritten.

As Majenko writes, you are having two bodies.
The bodies in the header file are empty and probably you do not want this. It is normal to implement the functions in the cpp file (which you do), so in the header file remove the {} in
inline virtual void setIcon(byte icon[8][8]){};
inline virtual void setIconColors(RGB colors[3]){};

so it becomes
inline virtual void setIcon(byte icon[8][8]);
inline virtual void setIconColors(RGB colors[3]);


text:
Arduino AES128 - CMAC
I'm looking for AES128 library with CMAC for Arduino. Help me to find one

Did you ask Professor Google?

Yes, i search in google but i don't find any library aes128 cmac with example to use it, thank you

I happen to know some libraries which use this. AES128-CMAC is for example used in the LoRaWAN MAC / driver implementation (LoRa is a low-power-wide-range radio technology). For example, the library Arduino-LMIC (LoRa MAC in C) uses this AES-CMAC implementation (has actually 2 built-in, Ideetron is the other one):

https://github.com/matthijskooijman/arduino-lmic/tree/master/src/aes

Other stacks use the mbedtls library with only the AES and CMAC layer activated. The library, written by ARM, is entirely in C and thus easily configrable (config.h) and compilable for the Arduino platform:

https://github.com/ARMmbed/mbedtls
https://github.com/ARMmbed/mbedtls/blob/development/library/cmac.c

Semetech's LoRa stack even has AES and CMAC abstracted in 4 four files:

https://github.com/arduino-org/arduino-library-lora-node-shield/tree/master/src/system/crypto

Another good point would be to search PlatformIO's library index for "AES CMAC". Then this library comes up:

https://platformio.org/lib/search?query=AES%20CMAC
https://github.com/DavyLandman/AESLib

This also offers a CMAC implementation specifically designed for the Atmel AVR MCUs (Arduino Uno and likes) and partially written in Assembler. This should be best suited for you.

https://github.com/DavyLandman/AESLib/blob/master/bcal-cmac.c

Thanks for your answer, I am already working on LoraWan device and a network server .


text:
Stopping / starting DC motor with Limit Switches and on/off button
I have an Arduino UNO with 3 switches attached (2 limit switches, 1 activation switch). I'm trying to make the activation switch turn the motor forwards once hit, then wait for any of the limit switches to be hit and stop the motor. The next step is to wait for the activation switch to be hit again and turn the motor in the opposite direction and wait for the limit switch to be hit and stop the motor.
But the issue I'm facing right now is when i press the activation switch the arduino board and H bridge board restart. The LED's turn on and off and the code restarts. And nothing happens. I know all the switches and motor is working because i have tested them by simplifying the code with just the functions.
(edit) Here is a picture of the schematic:
Can someone please review my code below to see if my logic is correct.
const byte  frontButtonPin = 2;
const byte  backButtonPin = 4;
const byte  onOffButtonPin = 11;
const int   motorPin =  8;
const int   motorPin2 =  7;

boolean  frontButtonState = 0;
boolean  backButtonState = 0;
boolean  onOffButtonState = 0;

/**
    setup inputs for switches and outs for motor pins
    serial begin to read the switches to test for errors
*/
void setup() {
  // initialize the pin as an inputs:
  pinMode(motorPin, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(frontButtonPin, INPUT);
  pinMode(backButtonPin, INPUT);
  pinMode(onOffButtonPin, INPUT);
  Serial.begin(9600);
}

/**
   this function turns motor foward
*/
void drawMovesForward() {
  // turn motor foward:
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, HIGH);
}

/**
   this function turns motor backwards
*/
void drawMovesBackward() {
  // turn motor in other direction:
  digitalWrite(motorPin, HIGH);
  digitalWrite(motorPin2, LOW);
}

/**
   Stop the motor form moving
*/
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}

/**

*/
void loop() {

  frontButtonState = digitalRead(frontButtonPin);
  backButtonState  = digitalRead(backButtonPin);
  onOffButtonState = digitalRead(onOffButtonPin);

  if (onOffButtonState == HIGH) {
    if ( frontButtonState == LOW ) {
      drawMovesForward();

    }

    else if (backButtonState == LOW ) {
      drawMovesBackward();
    }

  }
  else {
    if ( frontButtonState == HIGH ) {
      stopDrawFromMoving();
    }

    else if (backButtonState == HIGH ) {
      stopDrawFromMoving();
    }
  }
}

Welcome to StackExchange. I'm pleased to say you have made an excellent start by formatting your code and giving details in your description of your problem. Your logic looks good to me. To start troubleshooting, I would put println() statements in each of the functions, and try to work out where the program is hanging. When you say the "LEDs turn on and off", what LEDs are you referring to? This is where a schematic might help us troubleshoot, but you have mentioned that the parts are working by themselves.

Presumably you are currently testing with the parts disconnected (not installed in the drawer?). This makes it a lot easier to identify what is going wrong.

Thanks, I had a professional programmer help me program the Arduino but he has never used Arduino stuff before so he recommended using this website to look for other peoples advice. The LED's are the LED's on the arduino board. they turn on and off again and the arduino boards reset (they turn off and off again) when the back limit switch is hit and i hit the on/off switch at the same time.

Can you edit your question to mention whether the circuit is using a "toggle" or push-button activation switch? I presume it is a "toggle" switch as otherwise your code would only work by holding down a pushbutton switch.

Yeah there just momentary push buttons, push the button and let go. Also i actually fixed the code and now it works fine. Should i update the original post to say "problem solved" and then insert the code and how i fixed it? or do i do that somewhere else?

That's brilliant news! If you solved the answer, please post a new answer below with your solution (how you solved it, and your latest code), to help anyone else with the same issue. Your answer will then rise to the top, so people can see what the solution was. Then "mark your answer" (select the check/tick icon), and upvote any other questions or answers you find helpful on the site (you may not have the privileges yet, but you soon will). Well done!

I am currently working on a dumb-waiter project. things seems to go smooth when I made the simulation on the breadboard and using buttons. Once I replaced some of the buttons (the switch for each floor) with limit switches, everything go wrong. and then I read this post, and it saved me. all I need is just "delay(100)" inside the loop . thanks Man.

What is the correct code for this Project that is working right?
I would like to try it thanks.

@andiyunus That may fix the issue for now but it's not the right way to do it, and you may run into issues down the track. The real way to fix that is by using debouncing in your code (google that) as well as pull-up (or down) resistors on your limit switches.

@ChrisBrand I kept adding to this project over the years so it has become a little more complex. You can view the source code here in the repo:

I know this was opened years ago now but I just wanted to add some clarification. When I started this project and created this question I had 0 understanding of software development and didn't understand the code I was writing at the time. Now 3 years later I have revised this project multiple times.
The logic for a project like this is pretty simple, but if you're new to programming and trying to get into the STEM field with Arduino school projects and such, here is what my code now looks like for this same project:
https://github.com/LeehamElectronics/Automated-Cabinet
I have tried to comment it as best I could to help other students understand it. The project is simply a timber cabinet that has an electrically automated draw inside that can be opened and closed at will.
If you are stuck with a similar problem with your own project, I would suggest that you watch a free YouTube video course for C++ programing or even a Arduino programming video course. Even just a few hours of doing that will be enough to get started. That's the one thing I wish someone told me to do when I was starting off 3 years ago, I was wasting hours and hours debugging code that I didn't understand because I just jumped straight into Arduino with little understanding of coding.
I hope this comment helps someone else out there in a similar situation to mine 3 years ago.
Cheers
edit: the answers given about debouncing and pull-up resistors are also important in these types of projects.

Check your switches have pull-up resistors
It would be helpful if your question included a schematic. Do you have pullup resistors in line with your activation and limit switches? If not, you might find the input is "floating" - that is, it will randomly return either HIGH or LOW. This would possibly cause the motor to go forwards and backwards, but because the loop is possibly occurring hundreds of times per second, you might not see anything moving. You need pull-up or pull-down resistors in the circuit so the Arduino can see a definite LOW or HIGH. See https://www.arduino.cc/en/Tutorial/Button for a tutorial with a resistor, or even better, use https://www.arduino.cc/en/Tutorial/InputPullupSerial and use the existing onboard pullup resistors on the Arduino, as suggested by Juraj below.
Potential Logic Error
There might be a logic error in this part of the code:
  if (onOffButtonState == HIGH) {
    if ( frontButtonState == LOW ) {
      drawMovesForward();
    }
    else if (backButtonState == LOW ) {
      drawMovesBackward();
    }
  }
  else {
    if ( frontButtonState == HIGH ) {
      stopDrawFromMoving();
    }
    else if (backButtonState == HIGH ) {
      stopDrawFromMoving();
    }
  }

Loop #1: Let's say the onOffButtonState is HIGH (someone has pressed the switch to ON). The drawer is closed, so the front limit switch is depressed, so frontButtonState is HIGH. So the program will execute stopDrawFromMoving, and do nothing. Currently you are saying nothing is happening, so this might be your issue.
What you will probably need to do is use flags and while loops. For example:
At the start of the loop() declare this
drawerMovingOutFlag = 1;

Then change the loop to contain:
if (onOffButtonState == HIGH) {
    if ( frontButtonState == HIGH ) {
        while(drawerMovingOutFlag == 1)
            drawMovesForward();
            if ( backButtonState == HIGH ) {
                drawerMovingOutFlag = 0;
                stopDrawFromMoving()
            }
        }
    }
    else ...

I'll let you do the rest!

not that button tutorial, please. use the the input_pullup tutorial https://www.arduino.cc/en/Tutorial/InputPullupSerial

Hey thanks for the fast reply. Yes i have resistors going down to GND on all 3 switches. And I've used the serial monitors to check all the switches and they work and are read correctly.

I'm working on the schematic now (:

Schematic is uploaded (: Thanks for your help

I actually had the right code all along but I just had to add delays when reading the limit switches and detecting the activation switches. Here is one of the original programs i wrote that i threw out thinking it doesnt work, but once the delays were added it works fine.
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin3 = 11;     // the number of the pushbutton pin
const int buttonPin2 = 2;     // the number of the pushbutton pin
const int motorPin =  8;      // the number of the LED pin
const int motorPin2 =  7;      // the number of the LED pin

// variables will change:
boolean buttonState = 0;         // variable for reading the pushbutton status
boolean buttonState2 = 0;         // variable for reading the pushbutton status
boolean buttonState3 = 0;   // variable for reading the pushbutton status

int drawPosition = 2;  // Tells progam what position the draw is in

/**
 *  setup inputs for switches and outs for motor pins
 *  serial begin to read the switches to test for errors
 */
void setup() {
    // initialize the pin as an inputs:
    pinMode(motorPin, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);
    pinMode(buttonPin2, INPUT);
    pinMode(buttonPin3, INPUT);
    Serial.begin(9600);
}

/**
 * this function turns motor foward
 */
void drawForward() {
     // turn motor foward:
     digitalWrite(motorPin, LOW);
     digitalWrite(motorPin2, HIGH);
}

/**
 * this function turns motor backwards
 */
void drawBackward() {
     // turn motor in other direction:
     digitalWrite(motorPin, HIGH);
     digitalWrite(motorPin2, LOW);
}

/**
 * Stop the motor form moving
 */
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}

/**
 *
 */
void loop() {
   // read the state of the pushbutton value:
   buttonState = digitalRead(buttonPin);
   buttonState2 = digitalRead(buttonPin2);
   buttonState3 = digitalRead(buttonPin3);

   // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
   if (buttonState == HIGH) {
      drawPosition = 2;
      Serial.println(F("Front button state is high draw is open"));
      stopDrawFromMoving();
   }else if (buttonState2 == HIGH) {
      drawPosition = 1;
      stopDrawFromMoving();
  }

  if (buttonState3 == HIGH) {
    if( drawPosition  == 1 ){
      drawBackward();
      delay(100);
      drawPosition = 2;
      delay(100);
    }else if (drawPosition == 2 ) {
      delay(100);
      drawForward();
      delay(100);
      drawPosition = 1;
    }

  }
}

Please "Mark this as Answer", because this is the real answer to your problem.

That is an excellent project. Great work.
Some suggestions for improvement. You could use a enum class byte instead of a String for the drawer position and the drawer moving direction:
/* Allows the program to keep track of the last known position of the drawer */
enum class DrawerPositions : byte
{
  Closed,
  Open
} drawerPosition = DrawerPositions::Closed;

/* Keep track of what direction the drawer is moving, can one of the following:  Null | Closing | Opening */
enum class DrawerMovingDirections : byte
{
  Null,
  Closing,
  Opening
} drawerMovingDirection = DrawerMovingDirections::Null;
...
if (drawerPosition == DrawerPositions::Closed)
...
else if (drawerPosition == DrawerPositions::Open)
...
if (drawerMovingDirection == DrawerMovingDirections::Opening)
...

It would also be a good idea to add debouncing for all the switch inputs. There are many debouncing algorithms on the internet, but here is a very simple debouncer I put on GitHub which could be implemented something like this:
#include "Debouncer.h"
...
void loop()
{
  static Debouncer limitSwitch0(limitSwitchPin0);
  static Debouncer limitSwitch1(limitSwitchPin1);
  static Debouncer manualToggleButton(manualToggleButtonPin);

  limitSwitch0.Update();
  limitSwitch1.Update();
  manualToggleButton.Update();

  if (drawerIsMoving == true)
  {
    if (drawerMovingDirection == DrawerMovingDirections::Opening)
    {
      if (limitSwitch0.Output() == LOW)  // Get the debounced output of the switch.
      {
        drawerPosition = DrawerPositions::Open;
  ...
  if(manualToggleButton.Rise())   // For rising edge trigger.
  //if(manualToggleButton.Fall())  // For falling edge trigger.
  {
    ...
  }
  ...
}

Here is a debounce demo I put on Wokwi.

Thanks for your advice. I guess some of my laziness from Python crept into my c++ work doing silly things like using reference types to store, effectively 1s and 0s. I definitely should be using a primitive type such as a byte like you mentioned, I will most likely make those changes soon. As for debouncing, I haven't really had the need to use it much but I know I should, I'll add that to the to-do list. Thanks!!


text:
LED blink patterns with multiple LEDs with millis() not using Delay()
I want to make LED blink patterns with multiple LEDs with the millis() function. I researched about it but did not find a perfect solution.
I found one blog, but it is using a LED pin number array; I need a solution without an array. Any help will be appreciated.
This is my code which I have written:
const int Button_code_1 = 2;
const int Button_code_2 = 3;
const int Button_code_stop = 4;

const int LED_one = 6;
const int LED_two = 8;
const int LED_three = 10;
const int LED_four = 12;

int buttonState_code_1 = 0;
int buttonState_code_2 = 0;
int buttonState_code_stop = 0;

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

  Serial.begin(9600);

  pinMode(Button_code_1,INPUT);
  pinMode(Button_code_2,INPUT);
  pinMode(Button_code_stop,INPUT);

  pinMode(LED_Button_one,INPUT);
  pinMode(LED_Button_two,INPUT);
  pinMode(LED_Button_three,INPUT);
  pinMode(LED_Button_four,INPUT);

  pinMode(LED_one, OUTPUT);
  pinMode(LED_two, OUTPUT);
  pinMode(LED_three, OUTPUT);
  pinMode(LED_four, OUTPUT);
}

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

  buttonState_code_1 = digitalRead(Button_code_1);
  Serial.println(buttonState_code_1);
  buttonState_code_2 = digitalRead(Button_code_2);
  Serial.println(buttonState_code_2);
  delay(1000);
  buttonState_code_stop = digitalRead(Button_code_stop);

  if(buttonState_code_1==1)
  {
    pattern_one();
  }
  if(buttonState_code_2==1)
  {
    pattern_two();
  }

}

void pattern_one()
{
  digitalWrite(LED_one, LOW);
  digitalWrite(LED_two, HIGH);
  digitalWrite(LED_three, LOW);
  digitalWrite(LED_four, LOW);
  delay(3000);
  digitalWrite(LED_one, LOW);
  digitalWrite(LED_two, LOW);
  digitalWrite(LED_three, LOW);
  digitalWrite(LED_four, HIGH);
  delay(3000);
  digitalWrite(LED_one, HIGH);
  digitalWrite(LED_two, LOW);
  digitalWrite(LED_three, LOW);
  digitalWrite(LED_four, LOW);
  delay(3000);
  digitalWrite(LED_one, LOW);
  digitalWrite(LED_two, LOW);
  digitalWrite(LED_three, HIGH);
  digitalWrite(LED_four, LOW);
  delay(3000);
}

void pattern_two()
{
  digitalWrite(LED_one, HIGH);
  digitalWrite(LED_two, LOW);
  digitalWrite(LED_three, LOW);
  digitalWrite(LED_four, LOW);
  delay(3000);
  digitalWrite(LED_one, LOW);
  digitalWrite(LED_two, LOW);
  digitalWrite(LED_three, HIGH);
  digitalWrite(LED_four, LOW);
  delay(3000);
  digitalWrite(LED_one, LOW);
  digitalWrite(LED_two, HIGH);
  digitalWrite(LED_three, LOW);
  digitalWrite(LED_four, LOW);
  delay(3000);
  digitalWrite(LED_one, LOW);
  digitalWrite(LED_two, LOW);
  digitalWrite(LED_three, LOW);
  digitalWrite(LED_four, HIGH);
  delay(3000);
}

This is my sample code with four LEDs. I have written this code with delay(), so when I want to change the pattern I can't because delay() is blocking the code.
I researched this and found the millis() function as the solution. How can I implement this code using the millis() function?

Why without an array? Thats a weird requirement. Is it for a school exercise? 2. You didn't give us enough information to help you. What exactly is your goal and what is your problem in inplementing it

I have 9 LEDs and i need to blink one after another with delay of 3s and i have 2 different blink patterns and two buttons to select the pattern and one button to stop the program. so for using different patterns i want that it should not be array otherwise if i will get more patterns then i should take more array one for each pattern.Hope it clears the query

So your pattern are just which LED lights up next and the durations are always the same? Then what is so bad with one array for each pattern, or better one array of arrays (2 dimensional array)? Still seems to be an easy approach. With the 2 dimensional array you can write it in a way that adding a pattern is just adding another pattern to the array.

Please put all the information into the question by editing it. Also please describe in detail where exactly you are stuck. What is the actual problem? What exactly is it that you don't understand. Then we can write a good answer fitting your question

I have edited my question.

This is one of the effects for 3 (sets) of LEDs from my light alarm clock sketch:
void cycleEffect() {

  static unsigned long previousMillis;
  static uint8_t cycleCounter;

  if (millis() - previousMillis > 100) {
    previousMillis = millis();
    digitalWrite(LEDS_CENTRAL_PIN, cycleCounter == 0);
    digitalWrite(LEDS_LEFT_PIN, cycleCounter == 1);
    digitalWrite(LEDS_RIGHT_PIN, cycleCounter == 2);
    cycleCounter++;
    if (cycleCounter == 3) {
      cycleCounter = 0;
    }
  }
}

@Juray: you can replace the last three lines by a more common way to do this: cycleCounter = (cycleCounter + 1) % 3 (although I just realize this might be when performance is more important)


text:
Arduino used as a multi-sensor controller, then sending results to a laptop to post on a web page
We are a non-profit group, we run a salmon rearing pond on Lake Michigan. We are upgrading our equipment that is over 50 years old with monitoring sensors.
We are adding 9 temperature, 5 oxygen, 2 air temperature, and several voltage and current sensors, hooked up to an Arduino. We need to have the results sent to a laptop to post them on a web page, and record values in a log.
We also want to do some simple calculations so that when a value drops below a preset level an output (valve) is activated until the level is corrected. We also want a built-in timer to control different equipment.
The high-voltage part (240 V, 480 V) is my area of expertise. Any help or ideas?

yes .. start with one sensor

Instead of developing your own solution from scratch (which would be a learning experience that might or might not be enjoyable), you might also want to look at a project like Home Assistant.

Tackle this project as any other, divide and conquer.
First learn how to provide a static web site with the Arduino. There are multiple options, so please do your research and follow the inevitable tutorials. Experiment with a few to choose the best alternative for your case.
Then add dynamic values, for example with a simple time-controlled algorithm that alters a value. You can mock up monitored values, it does not matter. Make sure the dynamic web site works as you wish. You have also multiple options here.
Then add a first sensor to measure. First use the raw value to make sure you have the correct results. Only if you succeed, continue to scale the raw value to the physical value you want to use.
Finally extend with the next sensors, one after the other, in the same manner.
Doing "baby steps" helps you identify gaps in your knowledge (fill them) and avoids complex debugging. Never try to develop all at once. To accelerate the development, you can distribute the separate independent steps to multiple developers. This is how professionals do it, and there is no reason why it will not work for you.


text:
Declaring literal strings
When I want to write a literal string in Python, I use r before the string (or @ in C#):
in [1]: print r'\no esca\pe ch\ara\cters'
out [1]: \no esca\pe ch\ara\cters

In straight c++ I can use R, but in the Arduino IDE, this throws the following error:
Serial.begin(9600);
Serial.println(R"\no esca\pe ch\ara\cters");

<output> invalid character '\'in raw string delimiter

So how do I do the same in Arduino c++?

Raw strings in C++11 must have parens within the quotes in order to allow for a custom delimiter. Since your string lacks those parens, it is not valid.
Serial.println(R"(\no esca\pe ch\ara\cters)");


text:
ArduinoISP external programmer produces verification error?
I am using an ArduinoISP external programmer to upload a sketch to an Arduino MEGA.
I set the processor type to MEGA 2560, and use Ctrl-Shft-U to upload using a programmer. My programmer is set to ArduinoISP under tools>Programmer.
So far, I haven't been able to get the sketch to upload without a verification error. Worse, the programmer made it far enough in the upload process to overwrite the bootloader. Trying to re-upload the boot loader ("Burn Bootloader") also fails. The verbose error output is below with the exact error at the bottom.
A previous post suggested that code with a lot of 0xFF statements in it would fail. I have none.
Following a suggestion in the comments, I unsoldered the power over ISP programmer jumper (SJVCC) on my ArduinoISP. I powered the Arduino using the power jack; however, I got the same verification error.
I have also tried updating the software the the latest version (1.6.12), but that also does not seem to work. I may try to downgrade the software, but this all seems a little futile. Other forums don't seem to have a good answer for similar verification problems.
Is this a known problem? What can I do to fix it? What is particularly frustrating is that the problem occurs intermittently, ocassional after a computer reboot, it will upload successfully one time.
avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : usb
     Using Programmer              : arduinoisp
avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x2341-0x0049
     AVR Part                      : ATmega2560
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
       flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : USBtiny
     Description     :
avrdude: programmer operation not supported

avrdude: Using SCK period of 10 usec
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e9801
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be     performed
     To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: Using SCK period of 10 usec
avrdude: reading input file     "C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex"
avrdude: writing flash (9334 bytes):

Writing | ################################################## | 100% 10.71s

avrdude: 9334 bytes of flash written
avrdude: verifying flash memory against     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Te    nsion_wo_Averaging.ino.hex:
avrdude: load data flash data from input file     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex:
avrdude: input file                     C:\Users\Michael\AppData\Local\Temp\builddfc205ae09caa85de62f61bf2adae2c7.tmp/Tension_wo_Averaging.ino.hex contains 9334 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 7.34s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0600
         0xdd != 0x4a
avrdude: verification error; content mismatch

avrdude done.  Thank you.

How is the board powered? 2) Did you try downloading the zip of Arduino IDE 1.5.7 and then trying. (might be waste of time but I hear sometimes older versions work better)

The ArduinoISP provides power to the board, but I have tried it with a USB cable plugged in too.

Haven't tried the older version yet. Will work on that too.

Did you put the jumper back on the ISP when trying external power?

No, the ArduinoISP doesn't have jumper pins, just jumper pads. I didn't change any of the soldering.

https://www.arduino.cc/en/Main/ArduinoISP

By default, my board had the SJVCC jumper soldered over, indicating it should be able to power the board.

I tried desoldering the SJVCC pin, and powering over USB while programming. Same problem.

Yes I read the ISp article on Arduino.cc. It mentions verification errors and says to power via external power so having a soldered power jump on the ISP might be an issue.

I updated my question with the latest tests.

Did you try older arduino ide? The tools have changed. If that doesn't work try using the Device Programming Tools in Atmel Studio to burn the bootloader

Similar to:  https://arduino.stackexchange.com/q/44965/19409 https://arduino.stackexchange.com/q/59837/19409 https://arduino.stackexchange.com/q/52798/19409

I'm having the same problem with my USBtinyISP. It worked great for about a year and then one day it started giving verification errors on every board that I own. I tried a new ICSP cable, a different PC, several Arduino boards and it consistently corrupts flash (verification errors!). The board seems to work fine as far as my PC is concerned. I've ordered another USBtinyISP, hopefully this next one will last longer than the first.

Sounds like you have a bad Arduino ISP board.
I've had limited success restoring bootloaders on some Arduinos with my bad USBtinyISP programmer by connecting a 9V power supply to the Arduino in addition to the 5V that the ICSP cable provides.  Worth a try.
Note that back when my USBtinyISP was working properly I didn't need to attach 9V, the 5V from the ICSP cable was all the power needed.


text:
Interfacing to scale over RS-232
Objective: interface and Arduino MEGA to a Mettler Toledo SB32001 using the RS-232 communication protocol described in the manual.
Equipment Used:

SB32001 Mettler Toledo 32 kg scale
Arduino MEGA
Sparkfun RS232 Shifter - SMD

Background:
I am using the SoftwareSerial library to try to communicate with the scale through MEGA pins 52 and 53. I have the level shifter connected to the scale using a through cable.
So far, I have tried to send the most basic command to the scale, and the command is both not executing, and not causing a status code to be send back (i.e. failure OR success). My Tx light on the level shifter flashes, but the Rx light never does.
Write string to screen:
D "String"
Because I have a through cable, I have tried switching the Tx and Rx pins in code. Neither has worked.
The from the scale has the following options I can set:

Baud Rate: 150, 300, 600, 1200, 2400, 4800, 9600
Parity: 7b-E, 7b-no, 8b-no, 7b-odd

Here is a minimal (non)working example of my code:
#include <SoftwareSerial.h>

const int pinTX = 53;
const int pinRX = 52;

scale = SoftwareSerial(53, 52);

void setup(){
    Serial.begin(9600);
    scale.begin(9600);
    delay(100);
}

void loop(){
    scale.println("D \"Hello!?\"");
    delay(100);

    while (scale.available()){
        Serial.print(scale.read());
    }
    Serial.println()
    delay(100);
}

What I need:
I need help figuring out where I should look next to solve this issue. I have tried switching the transmit and receive pins in software. I have tried using jumpers to switch the Tx and Rx pins in hardware. I have tried 7 and 8-bit settings with no parity. Nothing give me a signal back. Totally perplexed?
Is it my converter chip? Does anyone know of problems with this shifter? I know that it does not contain the industry standard MAX232

"I have tried switching the Tx and Rx pins in code" The drivers are unidirectional.

Did you remember to send the CRLF?

According to my understanding of the documentation, println() automatically applies a CRLF.

I switched the Tx and Rx pins by changing the line scale = SoftwareSerial(52, 53); to scale = SoftwareSerial(53, 52);

Your quote escaping is wrong: "D "\Hello!?\"" should be "D \"Hello!?\""

Why do people insist on trying to use SoftwareSerial on a Mega when the Mega has multiple hardware UART ports?!?! Unless you are wiring lots and lots of UART based things to your Mega there is absolutely no reason to ever use SoftwareSerial!

Because we are naive

Fixed the escape character typo. Unfortunately that was just a transcription error, but even if it wasn't, I would expect to get an error code back from the scale.

Have you tried to connect your computer directly to the Scale serial port and use a terminal (putty for example) to send and received data to the scale?

Indeed, trying to make this work from an embedded system when you haven't first verified your understanding of its requirement by far simpler experiments from a PC is just wasting time.

The solution turned out to be a couple of things, some of which mentioned by others in the comments.
Problems that needed to be fixed:

My level-shifter was a huge part of the problem. I switched to a MAX232-based chip and then I was a least able to get responses shorted lines 2 and 3 (Tx and Rx).
I needed a cross-over cable. I had tried this while troubleshooting, but because that alone didn't fix the problem, I had not idea whether or not that was the problem, or just one of the problems.
I needed to use the onboard UART (Serial1) rather than SoftwareSerial. The problem was that I needed to be able to set the protocol to 8 bits with no parity. This configuration parameter cannot be changed on SoftwareSerial, but is as simple as Serial1.begin(9600, SERIAL_8N2).

Thank you for the help, and hopefully my mistakes make the process easier for others.

Thats 8 bits, no parity and 2 stop bits. The last property is what distinguishes your mode from the usual one, 8N1.

Did my comment get deleted (strange)? I had said that the SERIAL_8N2 configuration is straight from a code example I was using, and that I just went with it because I knew I needed 8-bits and it worked. The manual doesn't specify (or mention) stop bits, but it seemed to work. I get a lot of invalid command codes back from the scale (~70%), so I may try the SERIAL_8N1 configuration to see if that improves the response. Then again, my 'cross-over' cable is a bunch of breadboard jumpers jammed onto the pins to swtich Tx and Rx, so that faulty, unreliable connection could be the problem too.


text:
LCD Display hangs the computer
I'm trying to connect 16x2 LCD screen to clone Arduino UNO via PF8574T backpack. 4 cables are connected to +5V, GND, SDA and SDL pins.
When I tried this I2C scanner code from arduino.cc. It returned strange characters in serial monitor at first couple of tries. And now, when I try computer hangs.
When I use A4 A5 pins on the Arduino instead of SDA and SDL, i2c reported the device is on 0x27. It is ok. But if i keep LCD connected to Arduino, my iMac shutdowns after for a while. In error log i see there was a problem regarding USB serial device. I assume it as a power problem.
I'm on OS X Yosemite. Why this can be happening and how can I fix?
Note: Computer is hanging as soon as the Arduino usb cable connected.

Update: When I removed the LCD, the it connected without error so I could delete I2C scanner sketch.

Update2: I have updated my question. It seems as a power problem.

Sometimes my system hangs in the way you describe  ("hanging as soon as the Arduino usb cable connected")  if I mistakenly connect  the +ve and -ve supply lines to an i2c device the wrong way round.

It seems there is short in the backback circuit. Or may be the pin markings are wrong.


text:
How can I have 2 differents frequency on the 2 DAC outputs on an Arduino Due?
I would like to blink, using specific waveforms, 2 LED controlled by the 2 DAC output of the Arduino Due.
I wrote this :
    #include "Waveforms.h"

    int i = 0;
    int sample;

    void setup()
{
      analogWriteResolution(12);
}

    void test(float fq, int wave1, int wave2)
{

      sample = ((1/fq)*1000000)/120;

      analogWrite(DAC0, waveformsTable[wave1][i]);
      analogWrite(DAC1, waveformsTable[wave2][i]);

      i++;

      if(i == maxSamplesNum)
          {
            i = 0;
          }

      delayMicroseconds(sample);

}

    void loop() {
    // 10 Hz, 0 is a sine wave on DAC0, 3 is a square wave on DAC1

      test(10, 0, 3);

I would like to be able to change the frequency of each output (1Hz - 100 Hz) using differents waveforms. Changing waveforms is ok and it works, but is it possible to also change the frequency so to have two differents output frequency on each DAC output ?
The goal is to have, for example, simultaneously :

1 Hz, sine wave on DAC0.
10Hz, square wave on DAC1.

Thanks a lot.

Properly format the code. It's hard to read.

I don't have experience with this, but what you can do is:

If the frequency of DAC1 is x times faster than DAC2 to calculate the delay time based on the fastest and for DAC1 changing in every loop, while changing DAC2 only every DAC1/DAC2 times.
Vice versa if DAC2 is x times faster than DAC1
However, if there is not a simple ratio between DAC1 and DAC2 than you have to use the fastest speed of the two and use for the slowest an approximation...
Or use a higher significant fixed speed for i use a simple linear approximation between two points of the wavetable.

E.g. assume the speed is 10 times too fast for DAC1.
Suppose i = 100.. you should use the following points in the waveform: wave[100/10] and wave[100/10 + 1], so two consecutive points.
Assume the first is 10.0 and the second is 20.0... for the 10 increases of i (because i is running 10 times too fast) you can calculate for values of
 i     : 10.0 +   0% of (20.0 - 10.0)
 i + 1 : 10.0 +  10% of (20.0 - 10.0)
 ...
 i + 10: 10.0 + 100% of (20.0 - 10.0)

etc.
Note this is called linear interpolation.
You would have to check how many numbers per wave form table you need to get good values for different frequencies/speeds and what 'fixed' frequency you need to use for the delay.


text:
My port is grayed out?
Hello I have a question on why my port is grayed out when I go to upload?
I’ve watched so many YouTube videos on what’s the problem and have been trying to do everything but just nothing seems to work! Also, in device manager under ports (COM & LPT) the ports have an error sign over it. If someone can help me through this that would be fantastic!
The error when uploading:
problem uploading to board.
Sketch uses 2838 bites (8%) of program storage space. Maximum is 32256 bytes . Global variables use 9bites (0%) Of dynamic memory, leaving 2039 bites for local variables. Maximum is 2048 bytes.avrdude: ser_open(): can’t open the voice “\.\COM”: The system cannot find the file specified.

In the device manager you can also open the details windows for that device (don't remember how it is called exactly in the context menu when you right click on the device. Please tells us what error message you can find there. Maybe you need to install the correct driver.

Error : Windows cannot determine the settings for this device. Consult the documentation that came with the device and use the resource tab to set the configuration.(code 34)

Be sure you have the appropriate driver loaded.

Genuine Arduino or CH340 based chinese clone?


text:
Question about using millis for alarm conditions - Arduino
I am new to programming in general and to Arduino as well.
I am working on a small project to improve my ability to write complete and kind of useful programming sketches.
I am facing a problem. I am using a few things in my circuit like 7-segment display and relays and several indicating LEDs and a buzzer.
Let's sat that when a condition occurs I want one LED to  blink while everything still works fine and sends data to the display and controls relays, and I solved that with the millis function.
But the problem came when I tried to implement the same concept to the buzzer (which in my case I want to buzz for a pre-set amount of time, and then stop, without keeping buzzing all the time which might be too long), without using the delay function.
I tried many many code but nothing would work for me so far. Here is the simple code of my sketch. I hope you guys will help me find a solution
const byte buzzer = 13;  // buzzer_PIN
const byte switch1 = 3;  // PUSH-BUTTON PIN

/* please NOTE:
that the switch in my project will actually represent a condition to start the buzzer alarm, then maybe that condition will not exist, and after that the condition might come back and need the buzzer again
*/

unsigned const int delaytime = 500; // delay time needed between on and off states for the buzzer
unsigned long previousBuzz = 0;     // Variable for millis
unsigned long currentTime = millis();
boolean buzzPreState = true;        // Boolean made to avoid repetition for the buzzer when not needed

void setup() {
  pinMode(buzzer,OUTPUT);
  pinMode(switch1,INPUT_PULLUP);
}

void loop() {
  unsigned long currentTime = millis();
  int switchVal = digitalRead(switch1);

  if (switchVal == LOW && currentTime - previousBuzz > delaytime && buzzPreState == true) {
    previousBuzz = currentTime;
    buzzPreState = false;
    buzzerStart(5);
    buzzPreState = true;
  }
}

void buzzerStart(int repeat) {
  for (byte i=0; i<repeat; i++) {
    digitalWrite(buzzer, !digitalRead(buzzer)); // to switch buzzer ON and OFF alternatively
  }
}

active or passive buzzer? for passive buzzer you can use tone() function where you can specify the duration. it doesn't block execution. https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/

@Juraj
Thank you for your replay my friend, actually it is an active buzzer..

Then why are you toggling the buzzer pin multiple times without any time inbetween in buzzerStart()? Doesn't make much sense to me. An active buzzer just has to be turned on and off (via digitalWrite()). So you could replace buzzerStart(5) with a single digitalWrite(buzzer, !digitalRead(buzzer);

You are missing a delay here:
for (byte i = 0; i < repeat; i++) {
    digitalWrite(buzzer, !digitalRead(buzzer));
}

Without the delay, the whole loop terminates so fast that you cannot
hear anything.
Now, if you want non-blocking code, you should instead use the approach
of the Blink Without Delay tutorial:

have the program remember the current state
when it's time to switch states (as determined by millis()), update
the current state.

The difficulty is that, whereas the program state in that tutorial is
trivial (either the LED is off or it's on), in your case it is more
complex. In addition to the time of the last toggle, you have to keep
track of:

whether the buzzer is off or on
whether it is supposed to be making sound
a counter for the buzzing cycles.

The approach I would use is to have a counter (let's call it
buzzer_remaining) telling how many cycles it still has to complete.
The counter would decrement when the pin goes LOW. When it reaches
zero, the buzzing is done. Note that this choice implies that, when the
condition for buzzing becomes true, we will start at the middle of a
buzzing cycle.
Here is a tentative implementation of this approach:
const uint32_t buzzer_half_period = 500;  // 500 ms in each state
const uint8_t buzzer_count = 5;  // buzz for 5 cycles
uint8_t buzzer_remaining;        // remaining buzzing cycles
uint8_t buzzer_state;            // LOW or HIGH
uint32_t buzzer_last_toggle;     // millis() at last toggle time

void buzzer_start() {

    // Ignore request to start if we are already buzzing.
    if (buzzer_remaining > 0)
        return;

    // Initialize the buzzer state.
    buzzer_remaining = buzzer_count;
    buzzer_state = HIGH;
    digitalWrite(buzzer, buzzer_state);
    buzzer_last_toggle = millis();
}

// Call this periodically from loop().
void buzzer_update() {

    // Do nothing if we are not supposed to be buzzing.
    if (buzzer_remaining == 0)
        return;

    // Do nothing if it is too early to switch state.
    uint32_t now = millis();
    if (now - buzzer_last_toggle < buzzer_half_period)
        return;

    // Update the buzzer state.
    if (buzzer_state == LOW) {
        buzzer_state = HIGH;
    } else {
        buzzer_state = LOW;
        buzzer_remaining--;
    }
    digitalWrite(buzzer, buzzer_state);
    buzzer_last_toggle = now;
}

I resisted the temptation to put all this inside a class. It would be
cleaner, but I think this “plain C” style of programming might be easier
on a newcomer.
Note that calling buzzer_start() when the program is already buzzing
has no effect: the request to start the buzzer is ignored. This is not
the only possible choice: one could instead want to reset the counter in
order for the buzzing to last longer. The choice I made is arbitrary,
and I only made it because, in your question, the program requirements
are not fully specified.