message:
How fast should I be able to write to AT45DB321D flash memory?

I checked the [AT45DB321D datasheet](https://www.adestotech.com/wp-content/uploads/doc3597.pdf) and it says it operates at either 66 MHz oder 33 MHz. Both of these speeds are higher than what an Arduino Nano supports (my google fu fails me here, but according to the [Arduino SPI doc](https://www.arduino.cc/en/Reference/SPISetClockDivider) it's probably on the order of 4 MHz).

According to the datasheet

> Data can be clocked in from the input pin (SI) into either buffer 1 or buffer 2. To load data into the standard DataFlash buffer (528 bytes), a 1-byte opcode, 84H for buffer 1 or 87H for buffer 2, must be clocked into the device, followed by three address bytes comprised of 14 don’t care bits and 10 buffer address bits (BFA9-BFA0). The 10 buffer address bits specify the first byte in the buffer to be written. [...] Data will continue to be loaded into the buffer until a low-to-high transition is detected on the CS pin.

Which means to write a single byte I would need

- 1 opcode byte
- 3 address bytes
- 1 data byte

totaling 5 bytes or 40 bits which at 4 MHz yields 10 µs.

My code, as below, yields roughly 48 µs per byte (outputs a duration of ~12380 µs for transfering 256 bytes). I'm using the [DataFlash](https://github.com/BlockoS/arduino-dataflash) library.

```
#include <SPI.h>
#include "DataFlash.h"

static const int csPin    = 10;
static const int resetPin = 8;
static const int wpPin    = 7;

DataFlash dataflash;

void setup()
{
  Serial.begin(115200);

  SPI.begin();

  dataflash.setup(csPin, resetPin, wpPin);
  dataflash.begin();

  long start = micros();
  dataflash.bufferWrite(0, 0);
  for(int i = 0; i <= 255; i++) {
    SPI.transfer(i);
  }
  long afterBuffer = micros();

  Serial.print("Writing 256 values to buffer: ");
  Serial.println(afterBuffer - start);
}

void loop()
{
  // nothing
}
```

It's very likely I'm missing something, but especially if I want to transfer larger chunks of data at once I'd like to speed up that process a bit. Creating a 256 byte buffer and writing it all at once

```
// outside time measurement
uint8_t buffer256[256];
for(int i = 0; i <= 255; i++) {
  buffer256[i] = i;
}
// inside time measurement
SPI.transfer(buffer256, 256);
```
takes roughly the same time.

__tl;dr:__ Is everything working correctly/what am I doing wrong? How can I speed up writing to a flash chip using an Arduino Nano?

body:
> "Data will continue to be loaded into the buffer until a low-to-high
> transition is detected on the CS pin."

The `dataflash.bufferWrite` command writes the opcode and address bytes and then in the `for` loop you write 256 data bytes. The data bytes are written at once, without preceding each single one with the opcode and the address. (So it does already what you want to do.)

It doesn't matter whether you write the byte at once or each with a single SPI write. SPI can only send them sequentially. And the initial opcode and address is only send once with the `dataflash.bufferWrite` command.

BTW: There are two buffers to write to 1 and 2. So I'm curious why the command `dataflash.bufferWrite(0, 0);` works. IMHO that should be `dataflash.bufferWrite(1, 0);` or `dataflash.bufferWrite(2, 0);`.

You also not start the internal writing to the pages. There is no command e.g. `dataflash.bufferToPage(1, 7);`. The data are only transfered into the flash's buffer.

Because data is not written into a memory page, you'll lose it, if you switch off the power.

**UPDATE**

I fear I understood your question not completely. As I now see, you wondered why you need 48 µs in average for 256 Bytes when the SPI Bus is driven with 4MHz.

I looked a little in the codes and docs. And that's what I found:

The DataFlash lib selects a different Clock divider:

    /* Setup SPI */
    SPI.setDataMode(SPI_MODE3);
    SPI.setBitOrder(MSBFIRST);
    SPI.setClockDivider(SPI_CLOCK_DIV2);

`SPI_CLOCK_DIV2` results after some computation to a frequency of Fosc/2. The computation are very difficult to follow, because they use an 8 bit number which is divided into 2 nibbles each of them defines a part of a register content. But I'm quite sure the result is Fosc/2. But that would result in a clock frequency of 8 MHz. That can not explain your observed timings.

BTW: There is also in interesting deprecation note about setting the clock speed this way. ;-)

      // This function is deprecated.  New applications should use
      // beginTransaction() to configure SPI settings.
      inline static void setClockDivider(uint8_t clockDiv) {
        SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK);
        SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK);
      }

But then I saw another thing that could be a problem. There are to single value transfer functions. One for bytes (uint8_t) and one for integers (uint16_t). Your count variable is an integer so the two byte transfer method is used, resulting in two byte per transfer and therefor 512 bytes. But that also no explanation for the observations. And writing buffers works only with uint8_t[] so ??.

What else could have happened?

The MCU could be clocked by a lower frequency then 16MHZ. I think there are fuses that can be configured to reduce the master clock speed for using the MCU with lower voltage (like 3.6 Volt).

The missing beginTransaction / endTransaction (DataFlash doesn't use this) of the SPI bus could have impact on the interrupts which could distort the timing. (But that's a very wild guess ;-))

The observation that, transferring twice the amount of data with the single int transfer method does take roughly the same time than the buffered method gives us a hint, that possibly the SPI speed is not the problem.

In the function `dataflash.bufferWrite(0, 0);` there is e.g. a wait function
`waitUntilReady();` that could cause a long delay of ~12 milli seconds. You can easily try that, by taking the `dataflash.bufferWrite(0, 0);` out of the timing.

    void DataFlash::waitUntilReady()
    {
        while(!isReady()) {};
    }

    uint8_t DataFlash::isReady()
    {
        return status() & AT45_READY;
    }

    uint8_t DataFlash::status()
    {
        uint8_t status;
        reEnable();     // Reset command decoder.
        SPI.transfer(DATAFLASH_STATUS_REGISTER_READ);
        status = SPI.transfer(0);
        disable();
        return status;
    }


sender: user

message:
Get data from Bluetooth scale

I am trying to get data from this type of scale
https://acaia.co/products/pearl. It does not show up under discover-able Bluetooth devices on a computer or phone, but it does have an app which it connects to automatically when turned on; the app can then display the weight in real time. This is my first time working with Bluetooth devices and am unsure as to how it is connecting to the app without showing up on other devices. Any information as to what is going on and possibly steps in the right direction would be greatly appreciated.

sender: assistant

body: What you need to do is do some bluetooth sniffing to find out how the device is communicating with the phone. Here is a good article on doing that : http://nilhcem.com/iot/reverse-engineering-simple-bluetooth-devices


message:
How to split a binary data to form two split binary data?

I want to split a received binary data into two binary data.

Take the following received binary data for instance:

    uint32_t data = 0xFFFF0001;

In binary format it is: 11111111111111110000000000000001

If we need to split this above binary into two new binary data how could it be done?

As an example from the 0xFFFF0001, how can we obtain the first 17-bit as as data1 = 11111111111111110 and then the remaining 15-bit as data2 = 000000000000001 ?

body:
You can use the `bit shift` and `and` operator, like:

    uint32_t data = 0xFFFF0001;

The following line will shift all bits 15 places to the right, meaning the least significant 15 bits will be removed, and the other bits shifted to the right.

    uint32_t dataLeft = data >> 15;

    11111111111111110000000000000001
    >>>>>>>>>>>>>>>11111111111111110000000000000001
    | Bit shift   || orig. bits    ||Removed bits |

For the other 15 bits,  you can use the `and` operator, which just makes all 1's 0's for those bits not in the bit mask (0x7FFF).

    uint16_t dataRight = data & 0x7FFF;

    value:              11111111111111110000000000000001
    bit mask (0x7FFF):  00000000000000000111111111111111
                        -------------------------------- & / AND
                        00000000000000000000000000000001


message:
Arduino L led glows continuously

can someone tell me why my L led on arduino uno glowing continuously I tried restarting my pc, changing USB port
I also tried uploading an empty file and resetting the  Arduino board but nothing seems to work. Does it mean I have to buy a new one?

body:
Don't let that pin float undefined: If undefined (INPUT), pull it to GND to have the led OFF.

If ever possible, try to use the LED_BUILTIN pin as an OUTPUT pin.

And signal some information there. On an UNO (or other 328-based Arduino), this hint might collide with the SPI_SCK pin, which is D13 (PB5 on an atmega328). But as an SPI Master, this pin is at least OUTPUT (and thus will signal SPI activity).


message:
Alternative IDE for compiling and running arduino code?

I am not super experienced with c++ and I know that the syntax for C++ and the code written/compiled by the arduino IDE are slightly different.

----------

I would like to be able to write code, compile it the same way the arduino IDE does, and run it, without uploading it to a board.

----------

I dont need to test any code that interacts with any hardware. I simply want to be able to test basic syntax to make sure my concepts work before integrating with the full program.

I have written a few Arduino programs and I think the most complicated thing I've used were pointer functions, but I'd like to be able to test out code without needing to upload to a board for every change, while relying on Serial.print.

I have found alternatives that help with debugging and although that is helpful, I'd like to avoid the need to upload to a board every time I want to test changes for basic concepts

body:
You can use any C++ IDE you like, best when bundled with a compiler, for example Code::Blocks. Assuming you're using Windows: A combination of a decent editor like Notepad++ and some good compiler chain like MinGW will do, too. If you absolutely have to you could also use MS Visual Studio, I don't bother.

Then create standard console programs with this `main()`:

    void setup();
    void loop();

    int main()
    {
        setup();
        for (;;)
        {
            loop();
        }
    }

And append your hardware-less Arduino code.


body: [PlatformIO](https://platformio.org/platformio-ide) is a plugin for Visual Studio Code that has support for many embedded device, including most Arduinos


message:
What kind of data type can be use store a binary bit-stream which is more than 64-bits?

I'm wondering if one needs to assign a bit-stream of 78 bits to a variable(later on to be processed), what datatype can be used? What is the max bit can be stored into a variable in C?

body:
There is no builtin data type that can store 78 bits. However, it depends a bit what you want to store. Like the following cases:

- If the 78 bits are one 'entity' (e.g. one really big value), you can store it as an array of bytes (10 bytes of 8 bits = 80 bits, leaving 2 bits unused)
- If the 78 bits can be split up in smaller parts, you can:
  - Create a structure or class to contain the sub elements into fields (instance variables), using for each sub type a normal type (e.g. signed/unsigned 8, 16 or 32 bits).
  - Create bit fields to save some memory if there are small items and memory space is an issue.
  - Or a combination of the above

If you have many of these items and you want to save space (thus the 2 unused bits of each 80 bits), you can create a big array that contains many items, and use bit operations to get each item. E.g. the first element will be in the first 10 bytes, where the last 2 bits are not part of the element. The second item will use the remaining 2 bits and the following 78 - 2 = 76 bits, etc. This saves only 2/80 * 100% = 2.5% so only use this when really needed.


message:
How can i connect 4 stepper motors and 3 sensors to an Anduino?

I have an Arduino AT MEGA 2560 circuit. I want to buy 1 Nema-17 bipolar stepper motors, 3 M49SP-2K stepper motors, 3 KY-032 sensors to do my project but i dont know how to connect them to my Arduino.
Is there any Arduino shield for my purpose? Can I use Ramps 1.4 Arduino shield?

body:
Take a look at the Ramps V1.6, it is what I use. It plugs onto the AT Mega board.

https://reprap.org/wiki/RAMPS_1.6

The 1.6 has a few improvements. I like the solder in power connectors rather than the plug in ones. More reliable.

Because I already had the AT Mega board I decided to try the ramps. There are better boards now, with 32 bit processors. But as a starting point the Ramps combo is the simplest to get going and it does the job.

Other boards may work out a little better, but the firmware is a bigger issue. Still in development.


message:
How to run led and buzzer at the same time?

I am making a police light and siren but the delay on light (); affects the buzzers  delay tone

This is the code:
```
//PIN 9 - Buzzers
int f,d;
int t =0;

void setup()
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
}

void loop()
{
    buzzer ();

}

void buzzer () {

  for(f=635;f<=912;f++)
    {
        tone(9, f);
        delay(d);
        d=10;

        light ();
    }

    for(f=911;f>=634;f--)
    {

        light ();
        tone(9, f);
        delay(d);
            d=9;

    }

}

void light() {
 digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  delay(t);

  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);

  delay(t);

  digitalWrite(5,LOW);
  digitalWrite(6,LOW);
  digitalWrite(7,LOW);

  delay(t);

  digitalWrite(5,HIGH);
  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);

  delay(t);

  digitalWrite(5,LOW);
  digitalWrite(6,LOW);
  digitalWrite(7,LOW);

  delay(t);

  digitalWrite(5,HIGH);
  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);

  delay(t);

  digitalWrite(5,LOW);
  digitalWrite(6,LOW);
  digitalWrite(7,LOW);

  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

}

```

body: Don't use `delay()`. You'll need to rewrite your sketch to use the `millis()` function to decide when the desired amount of time has passed. Search on "Arduino Blink Without Delay" for information.


body:
The following Code is not tested. You can take it as an example. If you find errors, it would be nice to report them, so I can correct my prog.

    // here I just guess (10msec), I think you don't want a delay
    // of 0 as in your code.
    int   blinkDelay        = 10;
    long  lastBlinkTime     =  0;
    int   patternSequence[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 1, 2, 1, 2, 1, 2 };

    int   patternSize     = 17;
    int   actPattern      =  0;
    int   delActive       = -1;

    int  frequency     = 635;
    int deltaFreq      =   1;
    int  toneDelay     =  10;
    long lastBuzzTime  =   0;

    void setup()
    {
      pinMode( 5, OUTPUT ) ;
      pinMode( 6, OUTPUT ) ;
      pinMode( 7, OUTPUT ) ;

      ledsOff();
      buzzer( frequency );
    }

    void loop()
    {
      int actTime = millis();

      if ( ( actTime - lastBlinkTime ) > blinkDelay )
      {
        if ( delActive > 0 )
        {
          ledsOff();
        }
        else
        {
          actPattern++;
          if( actPattern > ( patternSize - 1) ) actPattern = 0;
          pattern( patternSequence[ actPattern ] );
        }
        delActive *= -1;

        lastBlinkTime = actTime;
      }

      if ( ( actTime - lastBuzzTime ) > toneDelay )
      {
        frequency += deltaFreq;

        if ( frequency > 911 ) deltaFreq = -1;
        if ( frequency < 636 ) deltaFreq = 1;

        buzzer( frequency );
        lastBuzzTime = actTime;
      }

    }

    void buzzer( int freq )
    {
      //PIN 9 - Buzzer
      tone(9, freq);
    }

    void ledsOff()
    {
      digitalWrite( 5, LOW );
      digitalWrite( 6, LOW );
      digitalWrite( 7, LOW );
    }

    void pattern( int num )
    {
       switch ( num )
       {
          case 0:
            ledsOff();
            break;

          case 1:
            digitalWrite( 5, HIGH );
            break;

          case 2:
            digitalWrite( 7, HIGH );
            break;

          case 3:
            digitalWrite( 5, HIGH );
            digitalWrite( 6, HIGH );
            digitalWrite( 7, HIGH );
            break;
       }
    }

**Update**

I've tested the code at home on my esplora. It worked, but not for a long time. I had to change the timing logic, by using the method `millis()`directly. Now it works. Below is the new code; tested this time. I also introduced some constants on top, because the their names act as documentation ;-). And I experimented with the values. The actual values are my preferences, But I'm by far no Bethoven and can not say if this relly sounds like a police siren. At least, it sounds not like a german police siren which I know better. (No I'm meither a policement nor his/her customer ;-))

Because I tested the code on my Esplora, I had to change the Pin assignments  (now out commented). In this copy I changed back to the original ones.

    int   blinkDelay        = 100;
    long  lastBlinkTime     =  0;
    int   patternSequence[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 1, 2, 1, 2, 1, 2 };

    int   patternSize     = 17;
    int   actPattern      =  0;
    int   clearActive       = -1;

    int  lowerFreq       = 680;
    int  higherFreq      = 840;
    int  deltaFreq       =   2;
    int  toneDelay       =  20;
    int  toneDelayOffset =  -1;
    long lastBuzzTime    =   0;

    int  actFreqStep   = deltaFreq;
    int  actFreq       = lowerFreq;

    // orig pins
    int col1Pin   =  5;
    int col2Pin   =  6;
    int col3Pin   =  7;
    int buzzerPin =  9;

    // esplora pins
    // int col1Pin   =  5;
    // int col2Pin   = 10;
    // int col3Pin   =  9;
    // int buzzerPin =  6;

    void setup()
    {
      pinMode( col1Pin, OUTPUT ) ;
      pinMode( col2Pin, OUTPUT ) ;
      pinMode( col3Pin, OUTPUT ) ;

      // initialize LEDs off
      ledsOff( );

      // and buzzer to the act frequency
      buzzer( actFreq );
    }

    void loop()
    {
      if ( ( millis() - lastBlinkTime ) > blinkDelay )
      {
        if ( clearActive > 0 )
        {
          ledsOff();
        }
        else
        {
          actPattern++;
          if( actPattern > ( patternSize - 1) ) actPattern = 0;
          pattern( patternSequence[ actPattern ] );
        }

        clearActive     *= -1;
        lastBlinkTime  = millis();
      }

      if ( ( millis() - lastBuzzTime ) > ( toneDelay + toneDelayOffset ) )
      {
        actFreq += actFreqStep;

        if ( actFreq >= higherFreq )
        {
          actFreqStep   = -1 * deltaFreq;

          // down sweep is slower
          toneDelayOffset = -1;
        }

        if ( actFreq <= lowerFreq )
        {
          actFreqStep   =  deltaFreq;
          toneDelayOffset =  0;
        }

        buzzer( actFreq );
        lastBuzzTime = millis();
      }

    }

    void buzzer( int freq )
    {
      tone( buzzerPin, freq );
    }

    void ledsOff()
    {
      digitalWrite( col1Pin, LOW );
      digitalWrite( col2Pin, LOW );
      digitalWrite( col3Pin, LOW );
    }

    void pattern( int num )
    {
       switch ( num )
       {
          case 0:
            ledsOff();
            break;

          case 1:
            // red
            digitalWrite( col1Pin, HIGH );
            break;

          case 2:
            // blue
            digitalWrite( col3Pin, HIGH );
            break;

          case 3:
            // white
            digitalWrite( col1Pin, HIGH );
            digitalWrite( col2Pin, HIGH );
            digitalWrite( col3Pin, HIGH );
            break;
       }
    }


message:
How to deep sleep ATtiny/ATmega (to run for years with batteries) but still detect a button press?

**Question (TL;DR): what is the optimal method to deep sleep (to run an ATtiny45 or ATmega on batteries for 1+ year) but still be able to detect a button press?** Is it possible to deep sleep *until* a button is pressed?

I'm using a classic "debounce" method to detect a button press:

~~~
int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;

void setup() {
  pinMode(2, INPUT);
}

void loop() {
  int reading = digitalRead(2);
  if (reading != lastButtonState) { lastDebounceTime = millis(); }
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      if (buttonState == HIGH) {
         // Button pressed, do something here!
         // In my actual code, it sends a packet via RF 433 Mhz
      }
    }
  }
  lastButtonState = reading;
  // snore(20);          // TinySnore here
}
~~~

My ATtiny45 should run during 1 year on 3 AA batteries, so I added a deep sleep using [TinySnore](https://github.com/connornishijima/TinySnore/blob/master/src/tinysnore.cpp). It works, and made the consumption go from more than 1mA to 0.2mA (@1 Mhz).

I know it's possible to go down to 5 µA if I `snore(1000);` but then obviously it won't be able to detect a button press.

I tried various sleep values: `snore(10);`, `snore(20);`, `snore(50);`, etc. but I didn't get consistent results.

Thus the question: **how to deep sleep *until* a button is pressed?**

____

I was thinking about using [`attachInterrupt()`](https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/) but then what kind of sleep should we use? `snore()`? `delay()`?

body:
First I was [unable to make the intterupt work for multiple pins](https://arduino.stackexchange.com/questions/70292/how-to-assign-an-interrupt-to-a-button-press-with-an-attiny-interrupt-not-fire), but finally here is a working code:

~~~
#include <avr/interrupt.h>
#include <avr/sleep.h>

ISR(PCINT0_vect) {
  if (digitalRead(0) == LOW)           // # PB0 = pin 5 pressed => LED on
    digitalWrite(4, HIGH);
  else if (digitalRead(1) == LOW)      // # PB1 = pin 6 pressed => LED off
    digitalWrite(4, LOW);
  else if (digitalRead(2) == LOW)      // # PB2 = pin 6 pressed => LED on
    digitalWrite(4, HIGH);
}

void setup() {
  pinMode(4,OUTPUT); // LED
  pinMode(0,INPUT_PULLUP);
  pinMode(1,INPUT_PULLUP);
  pinMode(2,INPUT_PULLUP);
  ADCSRA = 0; // ADC disabled
  GIMSK = 0b00100000;  // General Interrupt Mask Register, / Bit 5 – PCIE: Pin Change Interrupt Enable / When the PCIE bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt is enabled. Any change on any enabled PCINT[5:0] pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI Interrupt Vector. PCINT[5:0] pins are enabled individually by the PCMSK0 Register. / see https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf
  PCMSK = 0b00000111;
}

void loop() {
  sleep_enable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}
~~~

Note: [PCINTs are handled by a single PCINT_vect](https://arduino.stackexchange.com/questions/70348/pcint0-pcint1-pcint2-etc-on-attiny45-85/70351#70351) here.

PS: as mentioned by Maximilian in a comment, this post gives nice solutions: [Detecting key presses on a keypad whilst asleep](https://www.gammon.com.au/forum/?id=11497&reply=4#reply4).


body:
ATTINY's are designed to easily do this since they can wake from `power down` sleep mode by a pin change...

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

Basically you want to...

1. Connect a normally-open push button between an IO pin and ground.
2. Enable the pull-up on the IO.
3. Enable the pin change interrupt on the IO pin.
4. Enable interrupts.
5. Enter "power down" sleep mode.

When the button is pushed, it will connect the IO pin to ground, which will cause a pin change interrupt, which will wake the chip from sleep.

Note that you do not need to do anything in the pin change ISR (you can use the `EMPTY_INTERRUPT` compiler macro). If the ISR is empty, execution will pick up on the line after the sleep upon waking.

While in deep sleep, the chip will use an astonishingly small amount of power.  For example, an ATTINY25/45/85 running off of a 3V coin cell at room temp will use less than 0.2uA...

[![enter image description here][2]][2]

A typical CR2032 coin cell is rated for 235mAh to 2V, so at this rate we'd expect to be able to wait for a button press like this for [100+ years][3].

IRL the battery will likely self discharge and physically deteriorate long before then (rated at 1% per year), but still not too shabby.

[![enter image description here][4]][4]

  [1]: https://i.stack.imgur.com/8dnWb.png
  [2]: https://i.stack.imgur.com/2BkpN.png
  [3]: https://frinklang.org/fsp/frink.fsp?fromVal=(235 milli amp hours) / (0.2 microamp)&toVal=years#calc
  [4]: https://i.stack.imgur.com/26ahf.png


body: I would put the MCU in deep sleep and then use the reset button.


message:
How to assign an interrupt to a button press with an ATtiny? (interrupt not fired with my code)

*([Here](https://arduino.stackexchange.com/questions/70284/how-to-deep-sleep-attiny-atmega-to-run-for-years-with-batteries-but-still-dete/70289#70289) is finally a solution)*.

I'm using the following code on a ATtiny45 to **assign an interrupt to a button press** (pin #7, PB2, INT0). However the LED doesn't blink when the button is pressed, as if the interrupt is not working. **Why?**

Note: I'd like to use the least power when no interrupt happens, to [have a current in the order of magnitude of ~ 1 µA, to run from batteries for years](https://arduino.stackexchange.com/questions/70284/how-to-deep-sleep-attiny-atmega-to-run-for-years-with-batteries-but-still-dete/70296#70296).

~~~
#include <avr/sleep.h>

void setup()
{
  pinMode(4, OUTPUT);  // LED
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);      // pin #7 = PB2
  digitalWrite(4, HIGH); delay(100); digitalWrite(4, LOW);  // LED blink, working here
}

void wake()
{
  sleep_disable();
  detachInterrupt(0);
  digitalWrite(4, HIGH);  // LED not working here when pressing the button
}

void loop()
{
  sleep_enable();
  ADCSRA = 0;
  attachInterrupt(0, wake, CHANGE);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}
~~~

Note:

* I'm using Arduino IDE with [damellis' attiny](https://github.com/damellis/attiny), I also tried with Spence Konde's ATtinyCore but it's the same

* In my real code, I have 3 buttons, on pin #5, #6, #7, so eventually I'd like to have interrupts for all these three pins.

* I've read https://gammon.com.au/forum/?id=11497 but using `noInterrupts()` / `interrupts()` did not change anything in my case.

* I've tried "Sketch J" from https://gammon.com.au/forum/?id=11497 but `EIFR = bit (INTF0);` gives an `error: 'EIFR' was not declared in this scope` (I'm compiling from Arduino IDE); probably this works on an ATmega but not ATtiny.

---

**Edit: Here is a working code of deep sleep, with an interrupt when the pin #5 (PB0) changes...**

~~~
#include <avr/interrupt.h>
#include <avr/sleep.h>

ISR(PCINT0_vect) {
  if (digitalRead(0) == LOW)
    digitalWrite(4, HIGH);
  else
    digitalWrite(4, LOW);
}

void setup() {
  pinMode(4,OUTPUT); // LED
  pinMode(0,INPUT_PULLUP);
  pinMode(1,INPUT_PULLUP);
  pinMode(2,INPUT_PULLUP);
  ADCSRA = 0; // ADC disabled
  GIMSK = 0b00100000;  // General Interrupt Mask Register, / Bit 5 – PCIE: Pin Change Interrupt Enable / When the PCIE bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt is enabled. Any change on any enabled PCINT[5:0] pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI Interrupt Vector. PCINT[5:0] pins are enabled individually by the PCMSK0 Register. / see https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf
  PCMSK = 0b00000111;  // Pin-change interrupt for PB0, PB1, PB2
}

void loop() {
  sleep_enable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}
~~~

**...but for an unknown reason, if I add this code:**

    ISR(PCINT1_vect) {
      if (digitalRead(1) == LOW)
        digitalWrite(4, HIGH);
      else
        digitalWrite(4, LOW);
    }

the pin-change interrupt for PB0 still works (PCINT0), but not the interrupt for PB1 (PCINT1). Why?

body:
Look at the datasheet of the ATtiny45. In the section “Sleep Modes”,
there is a table that lists the wake-up sources available for each sleep
mode. For the mode “power-down”, INT0 is listed as a possible wake-up
source, but there is a small footnote:

> For INT0, only level interrupt.

This means that the `CHANGE` mode you are trying to use will not wake-up
the MCU out of power-down. You have to instead

```c++
attachInterrupt(0, wake, LOW);
```

> In my real code, I have 3 buttons, on pin #5, #6, #7, so eventually
> I'd like to have interrupts for all these three pins.

You may then have to look into the “pin-change” interrupt. This is
something different from the INT0 you are using here, and is not
generally supported by the Arduino core. You will have to either get
some pin-change-interrupt library, or work with no library using the
information from the datasheet (not that hard). Pin-change interrupt is
also a wake-up source for power-down.

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

**Edit**: Answering extra questions from comments.

> How did you know that "only level interrupt" means only "LOW"?

The [Arduino documentation][arduino-doc] states that the `mode`
parameter of `attachInterrupt()` can be either `LOW`, `CHANGE`, `RISING`
or `FALLING`. A few boards also support `HIGH`, but the ATtinies are not
among them. A “level” can be either `LOW` or `HIGH`, whereas `CHANGE`,
`RISING` and `FALLING` are “edges”.

This is corroborated by the [ATtiny45 datasheet][datasheet]: “The INT0
interrupts can be triggered by a falling or rising edge or a low level.”

> Is pin-change interrupt `PCINT`?

Yes.

> why do you think it isn't supported by the Arduino core?

The `attachInterrupt()` API only really makes sense for INT0, INT1,
etc... not for PCINT. You can also look at [the source code][source].

> Isn't it standard to interrupt when a pin changes states?

If you wish, you can configure INT0 to interrupt on a rising edge, a
falling edge, or any logical change. But this uses an edge-detection
logic which relies on the main clock, and thus does not work in
power-down mode.

For more details on INT0 vs. PCINT, their differences, and how to use
them, please refer to the datasheet, specifically to the “External
Interrupts” section I linked to above.

[arduino-doc]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/#_parameters
[datasheet]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#G1.1738372
[source]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.1/cores/arduino/WInterrupts.c#L69

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

**Addendum**: Extra question:

> why it doesn't work [with `ISR(PCINT1_vect) {...}`]?

Gcc tells me “**warning: ‘PCINT1\_vect’** appears to be a misspelled
signal handler”. And indeed, there is no such interrupt vector on the
ATtiny45: there is only PCINT0\_vect, and this interrupt is shared by
all the pins that can generate a pin change interrupt. If you want to
know which pin triggered the interrupt, you will have to figure that out
within the interrupt handler itself.

This is the single point that makes the PCINTs trickier to work with
than INT0 and co.: each PCINT interrupt is shared by a group of pins. On
the ATtiny45, there is only one such group, and `PCINT0_vect` is the
only interrupt handler. Larger AVRs have more groups (3 on the
Uno/ATmega328P), and `PCINT1_vect` makes sense on them.

Also beware of the somewhat confusing naming scheme. Avr-libc defines
some macros `PCINTn`, where `n` is a number. These macros expand to bit
numbers, and are meant to be used in code like this:

```c++
PCMSK = _BV(PCINT0)   // sense changes in pin PCINT0 = PB0...
      | _BV(PCINT1)   // and PCINT1 = PB1...
      | _BV(PCINT2);  // and PCINT2 = PB2
```

In these macros, the number `n` identifies an _individual pin_. Avr-libc
also defines the macros `PCINTm_vect` for defining interrupt handlers.
In these macros, the number `m` identifies a _pin group_.


message:
How do I change the scope of an object?

I am using the File/Examples/Adafruit MQTT Library/mqtt_ESP8266 example as a model for my code.  In the example, the mqtt object is created as a global variable, and everything works fine.  However, I need to create the mqtt object in setup(), because the constructor parameters are not known until then.  If I move the constructor call

    Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

from the global namespace to inside setup(), I can no longer see it from inside loop().

I have tried declaring a pointer to mqtt in the global namespace, but don't know how to change it to point to the mqtt object that is created in setup().  How can I do this?

David

body:
In general there is several ways to do it, none of them is the perfect one...

 1. pointer to mqtt at global scope `Adafruit_MQTT_Client * mqtt_ptr;` and initialize it by `mqtt_ptr = new Adafruit_MQTT_Client(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);` in setup. Then you have to use arrow operator instead dot to access its methods. Or you can make an alias in loop (or whenever you need it) by `Adafruit_MQTT_Client& mqtt = *mqtt_ptr;` and access it in the same way as before.
 2. returning reference to static variable created inside of function (singleton), but you have to provide parameters every time, even they're needed only for the first time. The static variable gets constructed only for the first call of function.
 3. For esp8266 there might be available `std::optional` template. It's similar to pointer, but you don't have to use arrow `->` operator. But there might be extraneous copy when you assign (create) it's value.
 4. You can also extend 1. or 2. by own class to hold parameters and then return instance of `Adafruit_MQTT_Client`


message:
what will be the sampling frequecy of my arduino Mega 2560 code. How would I calculate it?

<!-- language-all: lang-cpp -->

    void setup() {
        // initialize the serial communication:
        Serial.begin(9600);
        pinMode(10, INPUT); // Setup for leads off detection LO +
        pinMode(11, INPUT); // Setup for leads off detection LO -
    }

    void loop() {
        if ((digitalRead(10) == 1) || (digitalRead(11) == 1)) {
            Serial.println('!');
        }
        else {
            // send the value of analog input 0:
            Serial.println(analogRead(A0));
        }
        //Wait for a bit to keep serial data from saturating
        delay(1);
    }

**EDIT**

This sketch is for plotting raw ECG signal having a baud rate of 9600. but when I use these data for calculating heart rate then I want sampling rate for calculation but I don't get the value by this sketch. How will I calculate the frequency from the coming raw data? As it does not show a clear picture.

body:
The sampling frequency is calculated by the number of samples per time. I think you need to know how fast you're able to do this in your `loop()`.

For this you could fetch the start time, do a number of sampling, fetch the end time, and calculate the frequency.

This is the straight forward and simple way.

Please be aware the the turn-arund time for your sketch will include the transmission time for the result. This will be much longer than the time for the "pure" analog conversion.

---

Alternatively you can lookup the source code of Arduino's library function for `analogRead()`, get the data sheet, learn how the conversion works, and calculate the time.

But this is not at all easy.

---

BTW, `delay(1)` is by far not enough to "saturate" the serial transmission you do. You are using 9600 baud which gives about 960 characters per second. The biggest number you send is "1023" and the sequence "\r\n" is appended due to `println()`. So you are transmitting 6 characters which need 6 characters / 960 characters/s = 0.00625 s. These are a bit more than 6 ms, so you would `delay(7)` at least.

If you don't, the call to `println()` will do the delay if the transmitter's buffer gets full. Therefore your sketch will wait anyway. So you might consider to remove the delay.

---

And please, use the correct formatting the next time. ;-)


body:
On the Arduino Mega, the ADC is clocked at `F_CPU`/128 =
125 kHz (period = 8 µs). Except for the very first one,
each ADC conversion takes 13 ADC clock cycles, i.e. 104 µs. If
you run `analogRead()` in a tight loop, like

```c++
for (;;)
    analogRead(A0);
```

the CPU has to do some work in between the conversions, and since the
ADC always starts by waiting for a rising edge of the ADC clock, you
loose at least one full ADC cycle in between the conversions. You then
get one conversion every 14 ADC cycles, which results in a sampling
period of 112 µs, and the corresponding sampling frequency of about
8.93 kHz.

The code you showed does a little bit more than an `analogRead()` per
iteration: two `digitalRead()`, a test, and a `Serial.println()` that
involves a binary to decimal conversion. I am not sure the CPU will be
able to handle all that in a mere 8 µs. You might end up using
15 ADC clock cycles per iteration (13 for the conversion,
2 for the computation), which would result in 120 µs
(8.33 kHz) sampling period. Maybe even more. You will have to test
if you want to know for sure. The sampling period is not even guaranteed
to be constant: the code will take longer to run whenever it's
interrupted by the timer interrupt, which the Arduino core uses for
timekeeping purposes...

All this applies as long as the serial output buffer is not full. Once
you have 64 bytes waiting to be sent, the buffer will be full, and
`Serial.println()` will start delaying the output, effectively
throttling down your loop to the speed of the serial connection. C.f.
the busybee's answer for the details. Note that the sampling period is
still not constant, as sending a 1-to-4-digit number through the serial
port can take anywhere between 3.125 and 6.25 ms.

If you want a constant sampling period, you have to take control over
the timing yourself. A straightforward example would be:

```c++
const uint32_t SAMPLING_PERIOD = 6500;  // 6.5 ms

void loop() {
    static uint32_t last_sample;
    if (micros() - last_sample >= SAMPLING_PERIOD) {
        last_sample += SAMPLING_PERIOD;
        Serial.println(analogRead(A0));
    }
}
```

You could go faster with a higher baud rate, but you have to always keep
`SAMPLING_PERIOD` consistent with your chosen baud rate. The code above
will still produce some jitter in the sampling, mostly due to the timer
interrupt. If this is not acceptable for your application, you will have
to read the datasheet of the microcontroller and learn how to set the
ADC to be “auto-triggered” from a timer.


message:
What is the best data type to be used through i2C

i'm trying to send multiple commands to multiple slaves controlling motors. Slave Controller(Arduino Nano) will receive the command, and returns the current position of the motors to the Master(Arduino Mega).

What data type would be best to use in this scenario. I am considering, string or byte data type.

body:
I2C works with fixed size byte arrays.

Single bytes for commands should be sufficient. For positions you might need int16_t or even bigger numbers. Unsigned positions relative to (above) zero might make things easier, eventually (?)

As you have the same architecture on both sides, mapping of byte arrays to bigger numbers via `union` will work well.


body:
Strings (aka byte arrays of arbitrary length) are perfect for asynchronous and full duplex protocols like UART, essentially because those are no master-slave protocols. Here, both master and slave can transmit a byte stream independent of each other at any time and with any length.

But using strings on I2C is quite uncommon. As I2C is a master-slave bus where **any** communication (read and write) is initiated by the master generating the bus clock, using strings has the big disadvantage, that the master has to know the number of bytes the slave has to transmit. Of course you could implement it, but as long as you don't need the data to be human-readable, I suggest the more efficient way of transmitting bytes.
Usually, an i2c read transmission is done by

   1. addressing the slave in write mode
   2. Writing the target value's register address
   3. Addressing the slave in read mode
   4. Reading an arbitrary number of bytes (e.g. four bytes for float values)

A write transmission is a bit simpler:

   1. addressing the slave in write mode
   2. Writing the target value's register address
   3. Writing an arbitrary number of bytes (e.g. four bytes for float values)

This is the standard protocol that e.g. I2C sensors use and it's convenient to implement the same behaviour in the ISR when using a microcontroller (you could think of "register addresses" as "variable IDs").

To prepare values of any datatype for transmission (e.g. float to byte[4]) you can use a `union`.


message:
Input current for L293D shield

I am a newbie in arduino working on a bot with L293D shield. But I have a  question as what would be the input current to drive all 4 dc motors and 2 servo motors.  I can see that it can supply 0.6Amp current for the four motors.

I am considering the amount of electrons flowing in per unit time is equal to the electrons flowing out of the circuit, as an simplistic aprach. So practically the input current should be greater than or equal to 2.4Amp.

 As I have 6 motors in total so I was thinking about making a 12V 3Amp DC supply for a better performance. Should I do it like that? will it damage the board or shield?

body:
Here the proper answer:

The vast majority of devices are constant-voltage devices. They need a constant operating voltage to work correctly. Microcontrollers are such devices. When operating, they will try to draw as much current from the power source, as they need, but not more. Much like a simple resistor with an applied voltage will draw a specific amount of current (calculable with Ohm's law), complex devices like microcontrolelrs have something like an overall impedance/resistance, that is depending on their specific operation. So also here the device only draws as much current, as it needs. (I wrote about an overall impedance to emphasize the fundamental principle. No one would really specify an overall impedance for such a device, because this would only be a value calculated by the voltage and current needed, not a real resistance.)

This means, that burning parts are not due to the power supply supplying more amps. They get burnt, because something draw too much power trough them.

Let's look at some examples:

1. Imagine, that you create a short between 5V and ground on your Uno. A short means, that a high current can flow, since the resistance is very low. Now you are drawing a high current from your 5V pin to the ground pin. The Arduino's 5V pin is connected to a voltage regulator (for if you use Vin) and over a diode to USB. Both parts are only rated for a maximum current (depending on the version of the board between 200mA and 1A). The high current, that you draw, will flow through one of these parts, depending on your input source. This part will get fried, because a way to high current will flow through it, just because you **draw** the current.

2. A strong motor, that needs more current, than the board is rated for, would result in a similar problem like the short circuit. Indeed every device, that needs more current, than the board is rated for, might result in frying the mentioned parts.

But what happens, if you draw more power from the power supply itself, than it is rated for? The power supply electronic is similar to the Arduino board. When you draw too much current from the power supply, some parts of it might get fried and stop working. Thus, you should not try to draw more current from it, than it can provide. Often power supplies have a protection circuit, that will either lower or directly cut the voltage, if too much current is drawn. This is for the safety of the supply and should not be used for current limiting your own application normally.

So, you should always calculate, what current you expect to need, and then take a power supply, that can provide more current than that. You should consider a significant headroom, so that you can add more parts, if you want to extent your project. For example, if I calculate 2A for my project, I would use a power supply in the range of 3A.

---

Addition:

Above I wrote about constant-voltage devices. There are also constant-current devices, for example LEDs. An LED has a specific constant forward voltage. Under that voltage it will not conduct current. Over that voltage, the current rises exponentially. The voltage over the LED will always stay the same, as it was designed. This is the reason, why you need to add a current limiting resistor to a LED. But in the vast of devices, LEDs (or in fact every diode) is an exception.


message:
HC06 correct baud rate but missing characters/ no AT commands

I have an issue with the communication between my Serial Monitor and my BT HC06 Module. Iam able to send ascii characters from my phone with BT connection to my local serial monitor. When i send characters from my local serial monitor to my BT module i receive something like this: AT -> U or 3 -> 3

I have this issue since i changed the baud from 9600,0,0 to 9600,0,1

Code:

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(10, 11); // RX | TX

    void setup()
    {
      pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(9, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(9600);  // HC-05 default speed in AT command more
    }

    void loop()
    {

      // Keep reading from HC-05 and send to Arduino Serial Monitor
      if (BTSerial.available())
        Serial.write(BTSerial.read());

      // Keep reading from Arduino Serial Monitor and send to HC-05
      if (Serial.available())
        BTSerial.write(Serial.read());
    }

body:
If I understand you right: You changed the UART settings on the HC05 module and now you are unable to connect to the HC-06.

You use SoftwareSerial  for the connection as on an UNO you have only one HardwareSerial port. SoftwareSerial only allows to configure the baud rate. There are work arounds https://forum.arduino.cc/index.php?topic=251764 , but you can also write a little sketch that reconfigure your HC06 UART to 9600,0,0 using the HardwareSerial which can be setup to the new parity settings to connect to the HC-06.

Something like this

    void setup()
    {
      //Serial.begin( 9600, SERIAL_8O1 );
      Serial.begin( 9600, SERIAL_8E1 );

      // I do not setup to 9600,0,0 but to 9600,1,0
      // Because the Arduino use the stop bit set by default.
      Serial.println( "AT+UART=9600,1,0" );
    }

    void loop() {}

I can not try this program, so it's only an example on hoew to reset your HC-05.

Of cause; before you upload the sketch, you have to connect to HC-05 to the Hardware serial pins (0,1).


body:
Sorry, my question was not easy to understand. Your solution had not worked for me.
I found another libary where its possible to add the parity bit:
https://github.com/ledongthuc/CustomSoftwareSerial

This works fine for me.

Thanks for your help :)


message:
Atmega 328P in Arduino

Does anyone know what it means by the Atmega 328p has 131 instructions? And could you give an example of how any one of these 131 instructions look like?
Thanks in advance!!

body:
A CPU or MCU uses very basic instructions which are executed.

If you write code in a program language (like in Arduino IDE), the sketch is converted into many instructions (by the compiler and linker).

The instruction set can be found [here][1].

An example is:

   `ADC Rd, Rr`: Adds two registers and the contents of the C flag and places the result in the destination register Rd.

A CPU/MCU uses registers, which can be seen as very fast 'variables', mostly there are quite few of them, and all operators (like +, -, *, /) are carried out using these registers.

If you are just starting Arduino, it's not so useful to dive into this, the compiler/linker will take care of these 'details'; just be glad you don't have to write in assembly (anymore).

  [1]: https://www.microchip.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html


message:
Mega ADK connecting to PS3 Controller - OSC did not start error

I have a project that I am working on that uses a PS3 controller to connect to an Arduino Mega 2560 ADK (built-in USB).  I have been trying to test the controller/arduino connection and I cannot get past the "OSC did not start" error via serial monitor.

I started a new thread because all of the threads I read were based on the Mega 2560 plus the USB shield, not the ADK. Theoretically, there should be no difference, but rather safe than sorry.

Here is my hardware:
Arduino Mega 2560 ADK - Controller
TrendNet TWB-106UB - USB dongle
PS3 Move Navigation Controller (only 1)

Libraries:
USB_Host_Shield
USB_Host_Shield_Library_2.0

Sketch:
https://gitlab.com/darren-blum/SHADOW

However, for the sake of testing, I have tried the straight example sketches from the USB Host libraries.  I have tried the PS3USB and the PS3BT examples.  It does not matter what sketch I try, I cannot get past the "OSC did not start".

The code that triggers this error is:

    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
      }

I am not sure what I am missing.  Here is one of the example sketches in its entirety:

    #include <PS3BT.h>
    #include <usbhub.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #endif
    #include <SPI.h>

    USB Usb;
    //USBHub Hub1(&Usb); // Some dongles have a hub inside

    BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
    /* You can create the instance of the class in two ways */
    PS3BT PS3(&Btd); // This will just create the instance
    //PS3BT PS3(&Btd, 0x00, 0x15, 0x83, 0x3D, 0x0A, 0x57); // This will also     store the bluetooth address - this can be obtained from the dongle when running     the sketch

    bool printTemperature, printAngle;

    void setup() {
      Serial.begin(115200);
    #if !defined(__MIPSEL__)
      while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
      if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
      }
      Serial.print(F("\r\nPS3 Bluetooth Library Started"));
    }
    void loop() {
      Usb.Task();

      if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
        if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
          Serial.print(F("\r\nLeftHatX: "));
          Serial.print(PS3.getAnalogHat(LeftHatX));
          Serial.print(F("\tLeftHatY: "));
          Serial.print(PS3.getAnalogHat(LeftHatY));
          if (PS3.PS3Connected) { // The Navigation controller only have one     joystick
            Serial.print(F("\tRightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            Serial.print(F("\tRightHatY: "));
            Serial.print(PS3.getAnalogHat(RightHatY));
          }
        }

        // Analog button values can be read from almost all buttons
        if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
          Serial.print(F("\r\nL2: "));
          Serial.print(PS3.getAnalogButton(L2));
          if (PS3.PS3Connected) {
            Serial.print(F("\tR2: "));
            Serial.print(PS3.getAnalogButton(R2));
          }
        }

        if (PS3.getButtonClick(PS)) {
          Serial.print(F("\r\nPS"));
          PS3.disconnect();
        }
        else {
          if (PS3.getButtonClick(TRIANGLE)) {
            Serial.print(F("\r\nTraingle"));
            PS3.setRumbleOn(RumbleLow);
          }
          if (PS3.getButtonClick(CIRCLE)) {
            Serial.print(F("\r\nCircle"));
            PS3.setRumbleOn(RumbleHigh);
          }
          if (PS3.getButtonClick(CROSS))
            Serial.print(F("\r\nCross"));
          if (PS3.getButtonClick(SQUARE))
            Serial.print(F("\r\nSquare"));

          if (PS3.getButtonClick(UP)) {
            Serial.print(F("\r\nUp"));
            if (PS3.PS3Connected) {
              PS3.setLedOff();
              PS3.setLedOn(LED4);
            }
          }
          if (PS3.getButtonClick(RIGHT)) {
            Serial.print(F("\r\nRight"));
            if (PS3.PS3Connected) {
              PS3.setLedOff();
              PS3.setLedOn(LED1);
            }
          }
          if (PS3.getButtonClick(DOWN)) {
            Serial.print(F("\r\nDown"));
            if (PS3.PS3Connected) {
              PS3.setLedOff();
              PS3.setLedOn(LED2);
            }
          }
          if (PS3.getButtonClick(LEFT)) {
            Serial.print(F("\r\nLeft"));
        if (PS3.PS3Connected) {
          PS3.setLedOff();
          PS3.setLedOn(LED3);
        }
      }

      if (PS3.getButtonClick(L1))
        Serial.print(F("\r\nL1"));
      if (PS3.getButtonClick(L3))
        Serial.print(F("\r\nL3"));
      if (PS3.getButtonClick(R1))
        Serial.print(F("\r\nR1"));
      if (PS3.getButtonClick(R3))
        Serial.print(F("\r\nR3"));

      if (PS3.getButtonClick(SELECT)) {
        Serial.print(F("\r\nSelect - "));
        PS3.printStatusString();
      }
      if (PS3.getButtonClick(START)) {
        Serial.print(F("\r\nStart"));
        printAngle = !printAngle;
      }
    }
    #if 0 // Set this to 1 in order to see the angle of the controller
        if (printAngle) {
          Serial.print(F("\r\nPitch: "));
          Serial.print(PS3.getAngle(Pitch));
          Serial.print(F("\tRoll: "));
          Serial.print(PS3.getAngle(Roll));
        }
    #endif
      }
    #if 0 // Set this to 1 in order to enable support for the Playstation Move controller
      else if (PS3.PS3MoveConnected) {
        if (PS3.getAnalogButton(T)) {
          Serial.print(F("\r\nT: "));
          Serial.print(PS3.getAnalogButton(T));
        }
        if (PS3.getButtonClick(PS)) {
          Serial.print(F("\r\nPS"));
          PS3.disconnect();
        }
        else {
          if (PS3.getButtonClick(SELECT)) {
            Serial.print(F("\r\nSelect"));
            printTemperature = !printTemperature;
          }
          if (PS3.getButtonClick(START)) {
            Serial.print(F("\r\nStart"));
            printAngle = !printAngle;
          }
          if (PS3.getButtonClick(TRIANGLE)) {
            Serial.print(F("\r\nTriangle"));
            PS3.moveSetBulb(Red);
          }
          if (PS3.getButtonClick(CIRCLE)) {
            Serial.print(F("\r\nCircle"));
            PS3.moveSetBulb(Green);
          }
          if (PS3.getButtonClick(SQUARE)) {
            Serial.print(F("\r\nSquare"));
            PS3.moveSetBulb(Blue);
          }
          if (PS3.getButtonClick(CROSS)) {
            Serial.print(F("\r\nCross"));
            PS3.moveSetBulb(Yellow);
      }
      if (PS3.getButtonClick(MOVE)) {
        PS3.moveSetBulb(Off);
        Serial.print(F("\r\nMove"));
        Serial.print(F(" - "));
        PS3.printStatusString();
      }
    }
    if (printAngle) {
      Serial.print(F("\r\nPitch: "));
      Serial.print(PS3.getAngle(Pitch));
      Serial.print(F("\tRoll: "));
      Serial.print(PS3.getAngle(Roll));
    }
    else if (printTemperature) {
      Serial.print(F("\r\nTemperature: "));
      Serial.print(PS3.getTemperature());
    }
      }
    #endif
    }

body: Idiot me.  I thought Mega 2560 = ADK.  It does not.  Once I corrected my board from the Mega 2560 to the ADK, the USB port worked.


message:
Timeout error with Arduino Mega and ESP8266 as the wifi module

I am trying to use the ESP8266 as the wifi module based on this [tutorial][1]. My connections are as follows:

    ESP8266 <-----------------> Arduino Mega
    VCC     ------------------> 3.3V (converted 5V from Mega to 3.3V using LD33V)
    CH_PD   ------------------> 3.3V
    GND     ------------------> GND
    RX      ------------------> TX1(Pin 18)
    TX      ------------------> RX1(Pin 19)

I have checked the baud rate by issuing the AT commands at 115200 baudrate and the ESP is responding. Below is my code which I am trying to use:

    #include "WiFiEsp.h"
    #include <PubSubClient.h>

    const char* ssid = "MySSID";
    const char* password = "MyPassword";
    int status = WL_IDLE_STATUS; //wifi radio's status
    byte* messageBuff;

    //MQTT
    const char* mqtt_server = "192.xxx.x.xxx";
    //const char* mqtt_topic = "Rpi_Master";
    const char* mqtt_username = "username";
    const char* mqtt_password = "password";
    //client Id
    const char* clientID = "A_1";

    //Variables for numbers
    long randNumber1;
    String rn1;
    char rn1_char[50];
    long randNumber2;
    String rn2;
    char rn2_char[50];
    long randNumber3;
    String rn3;
    char rn3_char[50];
    long randNumber4;
    String rn4;
    char rn4_char[50];
    long randNumber5;
    String rn5;
    char rn5_char[50];
    long randNumber6;
    String rn6;
    char rn6_char[50];

    WiFiEspClient wifiClient;
    PubSubClient client(mqtt_server, 1883, wifiClient); //1883 is the listener port for the broker

    void callback(char* topic, byte* payload, unsigned int length) {

        Serial.print("Message Received: [");
        Serial.print(topic);
        Serial.println("]");
        Serial.print("Message is:");
        String message = (char *)payload;
        Serial.println(message);

        Serial.println();
        if (!strncmp((char *)payload, "Start", length)) //Start code can be changed to any string value in place of 1
        {
          randomNumberGenerator();
          client.publish("Arduino_A", "OK");
        }

    }

    void reconnect() {
      //Loop until we are reconnected
      while (!client.connected())
      {
        Serial.print("Attempting MQTT Connection...");
        //Attempt to Connect
        if (client.connect(clientID, mqtt_username, mqtt_password))
        {
          Serial.println("connected");
          //Once connected publish an announcement
          client.publish("Arduino_A", "Please send the pass code to send the values");
          //and resubscribe
          client.subscribe("Rpi_Master"); //This name can be changed
        }
        else
        {
          Serial.print("failed, rc = ");
          Serial.print(client.state());
          Serial.println("Trying again in 5 seconds");
          //Wait for 5 seconds before retrying
          delay(5000);
        }
      }
    }

    void setup() {
      Serial.begin(115200);
      Serial1.begin(115200);

      //initilize the ESP module
      WiFi.init(&Serial1);
      Serial.println("Attempting to connect to WPA network");
      status = WiFi.begin(ssid, password);
      //if you are not connected stop here
      if (status != WL_CONNECTED)
      {
        Serial.println("Couldn't get a wifi network");
        while (true);
      }
      //if you are connected, print out the info about the connection
      else
      {
        Serial.println("Connected to the network");
      }
      //client.setServer(server, 1883);
      client.setCallback(callback);
      //Allow the hardware to sort itself
      delay(1500);
      randomSeed(25);
    }

    void loop() {
      if (!client.connected())
      {
        reconnect();
      }
      //delay(1000);
      client.loop();
      delay(50);
    }

    void randomNumberGenerator()
    {
        randNumber1 = random(10,20);
        Serial.println(randNumber1); // print a random number from 0to 299
        rn1 = String(randNumber1);
        rn1.toCharArray(rn1_char, rn1.length() + 1);
        randNumber2 = random(20, 30);// print a random number from 10 to 19
        Serial.println (randNumber2);
        rn2 = String(randNumber2);
        rn2.toCharArray(rn2_char, rn2.length() + 1);
        randNumber3 = random(30,40);
        Serial.println(randNumber3);
        rn3 = String(randNumber3);
        rn3.toCharArray(rn3_char, rn1.length() + 1);
        randNumber4 = random (40,50);
        Serial.println(randNumber4);
        rn4 = String(randNumber4);
        rn4.toCharArray(rn4_char, rn4.length() + 1);
        randNumber5 = random (50,60);
        Serial.println(randNumber5);
        rn5 = String(randNumber5);
        rn5.toCharArray(rn5_char, rn5.length() + 1);
        randNumber6 = random (60,70);
        Serial.println(randNumber6);
        rn6 = String(randNumber6);
        rn6.toCharArray(rn6_char, rn6.length() + 1);
        client.publish("LC_1", rn1_char);
        client.publish("LC_2", rn2_char);
        client.publish("LC_3", rn3_char);
        client.publish("LC_4", rn4_char);
        client.publish("LC_5", rn5_char);
        client.publish("LC_6", rn6_char);
        client.publish("Arduino_A", "End Transaction");
    }

Currently am using this code to send 6 random values whenever there is a request being sent from the broker over MQTT. I intend to replace this code once the error issue is resolved. The code works fine and the ESP connects to the broker (Raspberry Pi in my case) initially. However after some time I keep getting Timeout Error and the ESP8266 keeps diconnecting from the server.

I read in other forums that ESP8266 will not be handle high baudrates such as 115200 and should be set to 9600. Could this be a reason for the timeout error? Please let me know what changes I need to rectify this issue. Thanks a lot for your time in advance. Attached the screenshot of the error.[![enter image description here][2]][2]

  [1]: https://www.instructables.com/id/Cheap-Arduino-WiFi-Shield-With-ESP8266/
  [2]: https://i.stack.imgur.com/xxVEF.png

body:
The old WiFiEsp by Bruno Poltaruri library can't do much with larger data received. The AT firmware sends all the data at once and the serial RX buffer overflows. It works better with 9600 baud which slows down the AT firmware.

It is hard to receive more data over network with AT firmware without UART hardware flow control and Arduino AVR boards don't have flow control and simple esp8266 modules don't have the flow control pins exposed.

My new WiFiEspAT library uses the new passive receive mode implemented in AT firmware 1.7.0 (SDK 3). The new passive receive mode of the AT firmware is not supported for UDP and secure connection (SSL) yet. For this reason in the new library UDP received message size is limited to configured buffer size and secure connection (SSL, https) is not supported.

With my new library over hardware serial high baud rates can be used. For Arduino Mega 500000 baud works good. For example a WebServer serving web files from SD card requires high baud rate to be able to serve multiple files one after other fast enough.


message:
How to use assembly in Arduino?

I have been assigned a university project to make a sound/audio responsive LED using assembly language. I have already wrote C++ code in Arduino that uses the Fastled library.

How do I write working code for this project in assembly (not restricted  to @rduino IDE, but preferable)? I've already tried converting my code to assembly using an online converter, but it is useless.

body:
You have to use the `asm`  keyword, like:

    asm("sei \n")

In your case it is advised to use defines, e.g.

    #define CLI()          asm("cli \n")
    #define noInterrupts() cli()

    #define SEI()          asm("sei \n")
    #define interrupts()   sei()

See more info at [arduino-inline-assembly-tutorial-1][1].

  [1]: https://ucexperiment.wordpress.com/2016/03/04/arduino-inline-assembly-tutorial-1/


body:
The Arduino IDE is quite idiosyncratic. It won't let you work on a
project that doesn't have a file with the extension “.ino”. On the other
hand, it doesn't care about how much code is in that file, and you can
keep it happy by creating an empty .ino file. I recommend however that
you put at least a comment block in that file, in order to make things
less confusing for other people who could see your project. Then you can
put your assembly code alongside this empty file, in files of their own
ending with the “.S” extension. These files will be preprocessed before
being assembled, so you can `#include <avr/io.h>` and use the macros
defined therein for the IO ports, bits, etc.

The project would look like this:

    my_project/         # containing directory
    ├── my_project.ino  # comments only, to keep the IDE happy
    ├── my_project.S    # main assembly file
    └── some_extras.S   # possibly more assembly files...

If the whole project is pure assembly, one of your assembly files should
define a symbol called `main`, which is the entry point of the program:

```lisp
.global main
main:
    ; code starts here
```

If you are going to mix assembly and C++, then you can define `main()`
in the .ino file, and call from there your assembly routines, which
should be declared as `extern "C"`:

```c++
extern "C" void my_assembly_routine();

int main()
{
    my_assembly_routine();
}
```

Mind the [calling conventions][] when mixing asm and C++ though.

If you are going to use the Arduino core library, then you should define
`setup()` and `loop()` instead of `main()`. The Arduino core will then
provide it's own `main()`, which takes care of its initialization.

If you are going to write mostly C++, with only some assembly sprinkled
here and there, _inline_ assembly could be a better option. C.f. Michel
Keijzers' answer.

[calling conventions]: https://gcc.gnu.org/wiki/avr-gcc


body:
Sorry.

The main learning effect of this exercise is "Don't do it".
You won't beat the c++ compiler regarding performance (speed). But you will run into more errors than you can imagine.

The only purpose of manual assembler language inside c/c++ is to add nanosecond timing by adding some `asm("nop");` statements to wait a controlled small number of cpu clock cycles.
@Michel Keijzers' examples are already implemented. Even in Arduino's convenience environment.

IMO it's more challenging to get beyond Arduino programming by going directly to the MCU's hardware level, dealing with Timers, other MCU components, Registers etc. directly. In C/C++ of course. There you learn that there's much more that can be done beyond the Arduino environment.

Or: Look at compiled results via `avr-objdump` to learn how C++ is compiled to machine code by experts. Very eventually, you might notice how you could help the compiler optimizing.


body:
Re: "The main learning effect of this exercise is "Don't do it". You won't beat the c++ compiler..."
I agree with Edgar Bonet:
(1) Arduino is about learning, including learning Assembler programming, hardware, etc.
And ...
(2) Yes, you can beat the C++ compiler with a little practice. E.g. the GNU tool-chain can input the C++ program and output the corresponding Assembler.
This can be very instructive for learning Assembler. You can then hand-craft any bit of that code...make it faster, or smaller
         --o-0--


message:
Initalizing library object in own library

**EDIT: @Juraj fixed the Issue, changes at the end of the post**

I am developing an application to program OneWire ID Chips. I am using the OneWire library (https://github.com/PaulStoffregen/OneWire) and built my own Library for the DS28EC20 Chip on top of it.

It is working but it's not very elegant. I have issues initalizing the OneWire object in my own library. At the moment it is only working with a fixed pin declared in my own library.

I want to call a function in my code which initalizes the OneWire library aswell as my own library for the DS28EC20.

I am not using the Arduino IDE, I am using Platform.io for VSCode because it's more powerful.

It would be awesome if someone could help me, because I need to use multiple ID Chips in my application.

Because of unkown reasons I need to pass a variable to the constructor of the DS28EC20. Calling the OneWire library in there does not work...

_I excluded the other functions in the DS28EC20.cpp file, I think they are not necessary rn_

Thank you very much in advance!
- pitchbent

main.cpp:
~~~
#include <Arduino.h>
#include <OneWire.h>
#include <DS28EC20.h>

uint8_t scratchpad[32];                                                   // Array for scratchpad
uint16_t location;                                                        //Memory location to store scratchpad in
//uint8_t memory[32];
bool status;                                                              // Status of the crc check

DS28EC20 One(5);

void setup() {

  pinMode(13,OUTPUT);
  Serial.begin(115200);                                                   //begin serial connection 0
  location = 0x460;                                                       //Memory location

  for (uint8_t i = 0; i < 32; i++)                                        //filling array for scratchpad
  {
    scratchpad[i]=0x22;
  }
  Serial.println(scratchpad[2]);

  status = One.write_scratchpad(scratchpad,32,location);                  //write scratchpad
  Serial.println("Status:");                                              //print status
  Serial.println(status);

  // put your setup code here, to run once:
}

void loop() {

  // put your main code here, to run repeatedly:
}
~~~

DS28EC20.cpp:
~~~
#include "Arduino.h"
#include "OneWire.h"
#include "DS28EC20.h"

OneWire Wire(31);

DS28EC20::DS28EC20(uint8_t)
{

}
bool DS28EC20::write_scratchpad(uint8_t *data, uint8_t leng, uint_fast16_t adress)
{
  Serial.println("123");
  uint8_t TA1;                                                            // Var for adress Bytes
  uint8_t TA2;
  uint8_t crc_rec[6];                                                     // Array for recieved CRC Bytes
  uint8_t crc_array[leng+3];                                              // Array for calculation of CRC value

  TA1 = (adress & 0xFF);                                                  // calculation of TA1 & TA2
  TA2 = ((adress >> 8) & 0xFF);
 crc_array[0]=WRITE_SCRATCHPAD;                                            // The CRC sum is computed out of the command aswell as the adress byteys
  crc_array[1]=TA1;                                                         //
  crc_array[2]=TA2;

  for (int i = 0; i < leng; i++)                                            // write data into crc array
  {
    crc_array[i+3]=data[i];
  }
 Wire.reset();                                                             // Reset
  Wire.write(SKIP_ROM);                                                     // Skip ROM
  Wire.write(WRITE_SCRATCHPAD);                                             // write Scratchpad

  Wire.write(TA1);                                                          // send adress bytes
  Wire.write(TA2);

  for(int i=0;i<leng; i++)                                                  // write data
  {
    Wire.write(data[i]);
  }

  Wire.read_bytes(crc_rec,6);                                               // safe CRC values sent from chip

  delay(10);
 Wire.reset();                                                             // Reset
if(Wire.check_crc16(crc_array,leng+3,&crc_rec[0]))                        // CRC Check
  {
    return true;
  }
  else
  {
    return false;
  }

}
~~~

DS28EC20.h
~~~
/*
Library for DS28EC20, built on top of OneWire.h lib
*/

#ifndef DS28EC20_h
#define DS28EC20_h

#include "Arduino.h"
#include "OneWire.h"
#include "DS28EC20.h"

#define WRITE_SCRATCHPAD 0xF                                              // commands für DS28EC20
#define READ_SCRATCHPAD 0xAA
#define COPY_SCRATCHPAD 0x55
#define READ_MEMORY 0xF0
#define EXTENDED_READ_MEMORY 0xA5

#define READ_ROM 0x33
#define MATCH_ROM 0x55
#define SEARCH_ROM 0xF0
#define SKIP_ROM 0xCC
#define RESUME 0xA5

class DS28EC20
{
    public:
     DS28EC20(uint8_t); // Constructor, add DS28EC20 to "pin"
     bool write_scratchpad(uint8_t *data, uint8_t leng, uint_fast16_t adress);
     bool write_memory(uint16_t adress);
     void read_memory(uint16_t adress,uint8_t *data, uint8_t leng);

     private:

};
~~~

**Fix:**

In main.cpp call Object with corresponding pin:
```
DS28EC20 One(31);
```
In DS28EC20.cpp add
```
OneWire Wire;
```
after includes, change the constructor aswell:

```
DS28EC20::DS28EC20(uint8_t pin)
{
  Wire.begin(pin);
}
```

In DS28EC20.h you need to change the class to:

```
class DS28EC20
{
    public:

     DS28EC20(uint8_t pin); // Constructor, add DS28EC20 to "pin"
     bool write_scratchpad(uint8_t *data, uint8_t leng, uint_fast16_t adress);
     bool write_memory(uint16_t adress);
     void read_memory(uint16_t adress,uint8_t *data, uint8_t leng);

     private:
     OneWire Wire;

};
```

body:
Use the constructor without parameter `OneWire wire;` and call `wire.begin(pin);` to set the pin.

And to use more sensors on different pins, make the OneWire instance member of the DS28EC20 class.


message:
Is it possible to run two small motors off an Arduino and have the motors move separately based on a random number generator?

I am a 2nd year design engineering student working on a design project where we are tasked with automating the movement of a rainfall simulator. One of our design ideas consists of two small motors running perpendicular to each other with the movements based on a random number generator. I was told that this would be fairly easy if we used a Siemens Program Logic Controller, but we have a very limited budget so I thought I would check out other options.

I am not familiar with the Arduino or much of anything to do with programming so I thought it would be beneficial to ask for advice from some people who know what they are doing. I attached an initial sketch of the idea and a picture of the rainfall simulator to hopefully clarify what I am hoping to accomplish. The most the device can move from its rested state is only 0.5".

Is this a path worth working towards? Or is this not the proper choice of equipment?

Any advice would be greatly appreciated!

Thanks,

Nick

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

  [1]: https://i.stack.imgur.com/Blb8E.jpg
  [2]: https://i.stack.imgur.com/E0E1M.jpg

body:
Leaving your mechanical equipment uncommented *), an Arduino itself cannot drive 7.4V 1A Stepper Motors. An Arduino itself cannot drive any motor. You need a sufficient power supply and motor driver electronics. And there's a vast amount of different devices to choose from.

But then, the answer to "is it possible (random, two motors, moving independently)" is **yes**.

*) Well, regarding "uncommented" :
200 lbs is quite heavy to simulate/produce a few raindrops. Small motors won't move such gear as in your pic.


message:
What is difference between ATMEGA32 and ATMEGA328?

I'm new in electronics. Just playing with Arduino boards.I just wanted to program ATMEGA328 micro-controller and use it without Arduino for compact design for my personal hobby project. I found there are ATMEGA32 and ATMEGA328 micro controllers in my local store. So, I wanted to know can I use ATMEGA32 instead of ATMEGA328 ? Which one is latest and whats are benefits. Thanks in advance.

body:
To answer this you'd need to study the according data sheets:

[ATmega32][1]
[ATmega32u4][2]
[ATmega328][3]
[ATmega328P][4]
[ATmega328PB][5]

Despite a similar name, the chips are quite different.
32u4 for examle has USB built in.
328PB has more 16-bit Timer/Counters.
... and many more differences.

They only differ on the hardware features and can be programmed in more or less the same way. It is up to you to choose which one you want to use.

  [1]: https://www.microchip.com/wwwproducts/en/ATmega32
  [2]: https://www.microchip.com/wwwproducts/en/ATmega32u4
  [3]: https://www.microchip.com/wwwproducts/en/ATmega328
  [4]: https://www.microchip.com/wwwproducts/en/ATmega328P
  [5]: https://www.microchip.com/wwwproducts/en/ATmega328PB


body:
I cannot tell for sure, but from a cursory look at the datasheets, the
ATmega32 _looks_ older:

* 16 MHz maximum frequency v.s. 20 MHz for the ATmega328
* 4.5 V minimum supply voltage v.s; 1.8 V for the ATmega328
* only one PWN channel per 8-bit timer

From an Arduino-programming point of view, I would prefer the 328, as it
would allow you to prototype your code on an Uno, and then move it to
the bare MCU, knowing it would work identically. The ATmega32 would be
worth consideration if you need more IO than the Uno can provide.


body:
I can't post comments.
One difference is that the ATmega32 has **JTAG**; ATmega328P has not.


message:
ultrasonic sencor give wrong distances

. I used      the inbuilt basic example of measuring the distance to test my ultrasonic sensor. the object is kept at 10 - 15 cm. form the ultrasonic sensor but still the readings show 135 cm only

    #include <Ultrasonic.h>
    int trigPin = 5;
    int echoPin = 6;
    #include <Servo.h>   //servo library
    Servo servo;
    int servoPin = 7;
    long duration, dist, average;
    long aver[3];   //array for average

    void setup() {
        Serial.begin(9600);
        servo.attach(servoPin);
        pinMode(trigPin, OUTPUT);
        pinMode(echoPin, INPUT);
        servo.write(0);         //close cap on power on
        delay(100);
        servo.detach();
    }

    void measure() {
     digitalWrite(100,HIGH);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(100);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(150);
    digitalWrite(trigPin, LOW);
    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);
    dist = (duration/2.0) / 29.1;    //obtain distance
    }
    void loop() {
      for (int i=0;i<=2;i++) {   //average distance
        measure();
       aver[i]=dist;
        delay(100);              //delay between measurements
      }
     dist=(aver[0]+aver[1]+aver[2])/3;

    if ( dist<15 ) {
    //Change distance as per your need
     servo.attach(servoPin);
      delay(1);
     servo.write(0);
     delay(2500);
     servo.write(100);
     delay(500);
     servo.detach();
    }
    Serial.print(dist);
    }

---

    #include <Ultrasonic.h>
    int trigPin = 5;
    int echoPin = 6;
    #include <Servo.h>   //servo library
    Servo servo;
    int servoPin = 7;
    long duration, dist, average;
    long aver[3];   //array for average

    void setup() {
        Serial.begin(9600);
        servo.attach(servoPin);
        pinMode(trigPin, OUTPUT);
        pinMode(echoPin, INPUT);
        servo.write(0);         //close cap on power on
        delay(100);
        servo.detach();
    }

    void measure() {
        digitalWrite(100,HIGH);
        digitalWrite(trigPin, LOW);
        delayMicroseconds(100);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(150);
        digitalWrite(trigPin, LOW);
        pinMode(echoPin, INPUT);
        duration = pulseIn(echoPin, HIGH);
        dist = (duration/2.0) / 29.1;    //obtain distance
    }

    void loop() {
      for (int i=0;i<=2;i++) {   //average distance
        measure();
       aver[i]=dist;
        delay(100);              //delay between measurements
      }
      dist=(aver[0]+aver[1]+aver[2])/3;

      if ( dist<15 ) {
        //Change distance as per your need
        servo.attach(servoPin);
        delay(1);
        servo.write(0);
        delay(2500);
        servo.write(100);
        delay(500);
        servo.detach();
      }
      Serial.print(dist);
    }

body:
You have a lot of redundant code:

1. include Ultrasonic.h is unnecessary.
2. servo.attach and servo.detach without reusing pin is unnecessary
3. The ultrasonic code is not correct.
It should be:
```
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // measure duration of pulse from ECHO pin
    duration_us = pulseIn(echoPin, HIGH);

    // calculate the distance
    distance_cm = 0.017 * duration_us;
```
Refer to the [Ultrasonic sensor tutorial][1] and [Servo motor tutorial][2]

  [1]: https://arduinogetstarted.com/tutorials/arduino-ultrasonic-sensor
  [2]: https://arduinogetstarted.com/tutorials/arduino-servo-motor


message:
PCINT0, PCINT1, PCINT2, etc. on ATtiny45/85

According to the [datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf):

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

we could think that, if we want to have a pin change interrupt for 3 pins, we have to create multiple instances:

    ISR(PCINT0_vect){
       ...
    }

    ISR(PCINT1_vect){
       ...
    }

    ISR(PCINT2_vect){
       ...
    }

    void setup(){
      GIMSK = 0b00100000;
      PCMSK = 0b00000111;
    }

However, this does not work, and I read [here](https://arduino.stackexchange.com/questions/70292/how-to-assign-an-interrupt-to-a-button-press-with-an-attiny-interrupt-not-fire/70330#70330) and [here](https://forum.arduino.cc/index.php?topic=469577.msg3215283#msg3215283) that we have to define **just one** interrupt function:

    ISR(PCINT0_vect){
       if (digitalRead(0) == LOW)
         ...
       if (digitalRead(1) == LOW)
         ...
       if (digitalRead(2) == LOW)
         ...
    }

Why is that so? What is `PCINT1, 2, 3`, ... made for then in this pinout schematics, if we don't have to use it?

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

body:
You can enable/disable Pin Change INTerrupts for individual pins using the Pin Change Mask Register `PCMSK`.

The names on the pins map the bit in `PCMSK` to the physical pin.

You find more information in section 9.3.4 on p. 52 in the [ATtiny85 Data Sheet][1]

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf


body:
That is simply the difference between an external interrupt INTx and a pin change interrupt PCINT. The first is an interrupt for a single pin. The second is an interrupt for a complete group of pins. Normally this group is a complete port. As the Attiny85 only has one port, this is the case here. So the whole group is only 1 single interrupt source. Thus it only has one interrupt vector named `PCINT0_vect`.

A pin change interrupt triggers, when any of the pins under it's supervision changes. You can remove pins from it's supervision by masking them with the `PCMSK` register.

So the interrupt vector `PCINT_vect` will be triggered by every change on any of the pins, that are not masked out. It is up to you to check, which one changed it's level.

---

On bigger microcontrollers, there are more pins and mostly also most of them are connected to a pin change interrupt. Here mostly every complete port is connected to a single pin change interrupt. Thus the corresponding registers are additionally marked with a number (`PCINT0_vect` as the interrupt vector for the first port, ...)


body:
You are confusing Pin Change Interrupt *pins* with Pin Change Interrupt *vectors*. The two are very different.

Many Pin Change Interrupt *pins* are associated with just one Pin Change Interrupt *vector*.

You use the *pin* number (the value shown in the pinout) to decide if you want that pin to respond or not. You use the *vector* to respond any of the pins that are assigned to that vector.

In the ATTiny chips, since there are so few Pin Change Interrupt *pins* (8 or less) you only need one Pin Change Interrupt *vector* to handle them.

You can know if "PCINT4" corresponds to a *pin* or a *vector* by the context. If you see it on a pin then it is a pin. If you see it in code with `_vect` after it then it's a vector.


message:
Determine if Arduino is rapidly pulsed on and off several times

Greetings fellow humans!

I've set myself the task of ascertaining whether an Arduino has been rapidly power cycled to force it into a setup state, a feature common with many IoT devices. So I essentially need to keep a count - of, say, three - prior on/off cycles. I could look at a custom bootloader that stores a power-on count in EEPROM then check if the attempts are >= 3 once the sketch is running (resetting the count), but I'm concerned that the EEPROM data could become corrupted during the cycle, or the the power cycle would be so rapid for even a bootloader to complete the count at all.

So, I figure I need another solution: an external counter, powered by the Arduino, that increments each time the Arduino receives power, but doesn't rely on the Arduino getting so far as running anything of consequence to keep count.

Could some kind soul point me in the direction of a discrete counter solution that would fit the task?  The simpler (fewer discrete components) the better.

Thanks!

SOLVED: less-than-discrete but fully functional solution adopted; noted in comments. Thanks for the feedback.

body:
Normally you wouldn't.

How I would implement it is:

1. Have the MCU monitor the incoming power
2. Provide a large-ish reservoir of power (capacitor) to run the MCU for a short time
3. Isolate the incoming power monitoring from the reservoir with a diode

When the power is removed the MCU runs off the stored power in the capacitor. The MCU then sees that the power is removed (by 1 above) and maybe reduces its power by turning off as much as it can to prolong the runtime. If the power is re-applied before the reservoir runs out then it enters the setup state.  If the reservoir runs out, then not much really happens.

For example:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/GNbb8.png)

<!-- End schematic -->

The size of the capacitor will determine the runtime. You may also choose to replace the capacitor with an "LC PI" filter to give more runtime but at the cost of space:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/SWFNg.png)

<!-- End schematic -->


message:
WS2812 Stair lighting - not all LEDS lighting up

I'm doing a Arduino based stair light project and have a little problem with the code. I have used [Simon Jowett's code from the instructable website][1] which after a couple of tweaks works perfect. Apart from the final section, the waterfall effect. The original project used 117 WS2812 LED's I'm using 188. When the white LED's trigger running up or down the stairs they work fine on all 188, the breathe LED's light up on the first and last LED too. But the waterfall effect stops at LED 117. Can anyone see if there is somewhere else that I need to change the amount of LED's in the code apart from here Adafruit_NeoPixel strip = Adafruit_NeoPixel(***188***, PIN, NEO_GRB + NEO_KHZ800);? Thanks

~~~~~
// "Bling" up your Staircase By Simon Jowett November 2014
// Thanks to the Neopxel Library by Adafruit

#include <Adafruit_NeoPixel.h>
//#define LDRSensor 1
#define PIN 3

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(188, PIN, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

// Set up Variables
 unsigned long timeOut=60000; // timestamp to remember when the PIR was triggered.
 int downUp = 0;              // variable to rememer the direction of travel up or down the stairs
 int alarmPinTop = 5;        // PIR at the top of the stairs
 int alarmPinBottom =7;      // PIR at the bottom of the stairs
 int alarmValueTop = LOW;    // Variable to hold the PIR status
 int alarmValueBottom = LOW; // Variable to hold the PIR status
 int ledPin = 13;           // LED on the arduino board flashes when PIR activated
 int LDRSensor = A0;        // Light dependant resistor
 int LDRValue = 0;          // Variable to hold the LDR value
 int colourArray[350];      // An array to hold RGB values
 int change = 1;            // used in 'breathing' the LED's
 int breathe = 0;           // used in 'breathing' the LED's

void setup() {
   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
   Serial.begin (9600);  // only requred for debugging
   pinMode(ledPin, OUTPUT);  // initilise the onboard pin 13 LED as an indicator
   pinMode(alarmPinTop, INPUT_PULLUP);     // for PIR at top of stairs initialise the input pin and use the internal restistor
   pinMode(alarmPinBottom, INPUT_PULLUP);  // for PIR at bottom of stairs initialise the input pin and use the internal restistor
   delay (100); // it takes the sensor 2 seconds to scan the area around it before it can
   //detect infrared presence.
   for (int i=0 ;i < 350; i++)  { // initilise the colourArray to zero
   colourArray[i]=0;
   }
}

void loop() {

  LDRValue = analogRead(LDRSensor);
  Serial.println(LDRValue);

  if (timeOut+57000 < millis()) {        // idle state - 'breathe' the top and bottom LED to show program is looping

     breathe = breathe + change;
     strip.setPixelColor(0,0,0,breathe);
     strip.setPixelColor(187,0,0,breathe);
     strip.show();
     if (breathe == 100 || breathe == 0) change = -change;      // breathe the LED from 0 = off to 100 = fairly bright
     if (breathe == 100 || breathe == 0) delay (300);           // Pause at beginning and end of each breath
     delay(25);
  }

  if (LDRValue > 1010) {        // only switch on LED's at night when LDR senses low light conditions - you may have to change the number for your circumstances!

    alarmValueTop = digitalRead(alarmPinTop);        // Constantly poll the PIR at the top of the stairs
    alarmValueBottom = digitalRead(alarmPinBottom);  // Constantly poll the PIR at the bottom of the stairs

    if (alarmValueTop == HIGH && downUp != 2)  {      // the 2nd term allows timeOut to be contantly reset if one lingers at the top of the stairs before decending but will not allow the bottom PIR to reset timeOut as you decend past it.
      timeOut=millis();  // Timestamp when the PIR is triggered.  The LED cycle wil then start.
      downUp = 1;
      topdown();         // lights up the strip from top down
    }

    if (alarmValueBottom == HIGH && downUp != 1)  {    // the 2nd term allows timeOut to be contantly reset if one lingers at the bottom of the stairs before decending but will not allow the top PIR to reset timeOut as you decend past it.
      timeOut=millis();    // Timestamp when the PIR is triggered.  The LED cycle wil then start.
      downUp = 2;
      bottomup();         // lights up the strip from bottom up
    }
    if (timeOut+10000 < millis() && timeOut+15000 < millis()) {    //switch off LED's in the direction of travel.
       if (downUp == 1) {
          colourWipeDown(strip.Color(0, 0, 0), 50); // Off
       }
       if (downUp == 2)  {
        colourWipeUp(strip.Color(0, 0, 0), 50);   // Off
       }
      downUp = 0;
      //   for (int i=0 ;i < 350; i++)  {          // Depending on your preference you may want to include this loop to clear out the colourArray
      //    colourArray[i]=0;
      // }
    }

    if (timeOut+15000 < millis() && timeOut+54999 > millis()) waterfall();    // Waterfall effect to play between these times after a PIR trigger.

    if (timeOut+55000 < millis() && timeOut+56999 > millis()) fade();   // Fade/switch off LED's
  }
}

 void topdown() {
    Serial.println ("detected top");                // Helpful debug message
    colourWipeDown(strip.Color(50, 50, 30), 10);    // Warm White
    for(int i=0; i<3; i++) {                        // Helpful debug indication flashes led on Arduino board twice
      digitalWrite(ledPin,HIGH);
      delay(200);
      digitalWrite(ledPin,LOW);
      delay(200);
    }
 }

 void bottomup() {
    Serial.println ("detected bottom");          // Helpful debug message
    colourWipeUp(strip.Color(50, 50, 30), 10);   // Warm White
    for(int i=0; i<3; i++) {                     // Helpful debug indication flashes led on Arduino board twice
      digitalWrite(ledPin,HIGH);
      delay(200);
      digitalWrite(ledPin,LOW);
      delay(200);
    }
  }

 // Fill the dots one after the other with a color
 void colourWipeDown(uint32_t c, uint8_t wait) {
   for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
 }

 // Fill the dots one after the other with a color
 void colourWipeUp(uint32_t c, uint8_t wait) {
   for(uint16_t i=strip.numPixels(); i < -1; i--) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
 }

 // Play the Waterfall effect
 void waterfall(){
    for(int i= 347; i>-1; i--) {            // Shift the RGB colours down in the colourArray[]
        colourArray[i+3]=colourArray[i];
        }
      colourArray[0] = random(0,20);        // Genearate the red component of the 1st LED at the top of the stairs
      colourArray[1] = random(0,40);        // Genearate the green component of the 1st LED at the top of the stairs
      colourArray[2] = random(10,70);       // Genearate the blue component of the 1st LED at the top of the stairs

      for (int k=0; k<351; k=k+3)   {       // Set and send the colours to the strip
       uint32_t c = strip.Color(colourArray[k],colourArray[k+1],colourArray[k+2]);
       strip.setPixelColor(((k+3)/3)-1,c);
       }

      strip.show();      // and display the result
      delay(35);         // delay to simulate running water
 }

 // Play the LED fade out
 void fade(){
 for (int j = 0; j <70; j++) {
   for(int i=350; i>-1; i--) {
     colourArray[i]=colourArray[i]-1;      // reduce intensity of light by 1
     if (colourArray[i] <= 0 ) colourArray[i] = 0;
   }
   for (int k=0; k<351; k=k+3)   {
     uint32_t c = strip.Color(colourArray[k],colourArray[k+1],colourArray[k+2]);
     strip.setPixelColor(((k+3)/3)-1,c);
   }
  strip.show();
  delay(60);
  }
 breathe = 0;
 change = 1;
 }
~~~~~~~

  [1]: https://www.instructables.com/id/How-to-bling-up-a-boring-staircase/

body:
This line in the code:

     int colourArray[350];      // An array to hold RGB values

...contains 3 values for each LED.  But 350 / 3 is 116.67.  This value should likely have been 117 * 3 = 351 for the original code.  And for the posted code using 188 LEDs this likely should be 188 * 3 = 546.

This same problem of indexing into the colourArray repeats several more times in the code where the array is cleared out, assigned random values and used to control the LEDs.  Normally, well written code uses "#define" directive to set such values once at the beginning of the code allowing the compiler to make adjustments when compiling / uploading the Arduino sketch.

The ["#define" used for Arduino sketches][1] is the same as used in C programming.  (As Arduino sketches are actually C programs.) Normally, defines are found at the top of a file.  Defines are a way of substituting an meaningful name for something a bit hard to understand at first.  We can even use a bit of math to keep errors down as the compiler will solve it for us before uploading the code:

    #define LED_NUMBER_OF (3*188)

Later in the code we can use the define:

    int colourArray[LED_NUMBER_OF];      // An array to hold RGB values

Still later in the code we can use the define again:

    for (int i=0 ;i < LED_NUMBER_OF; i++)  { // initilise the colourArray to zero
      colourArray[i]=0;
    }

  [1]: https://www.arduino.cc/reference/en/language/structure/further-syntax/define/