text:
Can't figure out source of interference reading 10k POTs with 74HC4051
I realize this gets asked a lot, but I feel like I've applied the most common fixes without success. I have 10 10k potentiometers plugged in to an arduino via a custom shield. 2 are wired directly to the MC via A2 and A3. The other 8 are plugged in via a 74HC4051 multiplexer. The 2 plugged in directly work great. The other 8 show a ton of cross talk and don't seem to vary as much as they should. Here is some example output on the arduino serial plotter:

Things I have tried:

I put a delay between the pin selection and the read.
I'm reading twice (with a delay in between) and discarding the first read.

I'd use an MCP2308 if I were doing this again, but in the mean time is there anything else I can try?
Here is my schematic:

Each pot is plugged in to 5V and ground, with the wiper wired directly to the pin, all via jumper cables to the shield. Here's a picture of how this works (apologies for the mess):

The pin blocks have, per row, one pin each feeding in to a multiplexer input, and another attached to the GND and +5V planes on the PCB. These are attached to +5V and GND on the arduino:

Here is my code:
const int selectPins[3] = {8, 12, 13}; // S0, S1, S2
const int zInput = A1; // Connect common (Z) to A1 (analog input)
const int DIMp = A2;
const int bDIMp = A3;
void setup()
{
  Serial.begin(9600); // Initialize the serial port
  // Set up the select pins as outputs:
  for (int i=0; i<3; i++)
  {
    pinMode(selectPins[i], OUTPUT);
    digitalWrite(selectPins[i], HIGH);
  }
  pinMode(zInput, INPUT);
  pinMode(DIMp, INPUT);
  pinMode(bDIMp, INPUT);
}

// The selectMuxPin function sets the S0, S1, and S2 pins
// accordingly, given a pin from 0-7.
void selectAMuxPin(byte pin)
{
  for (int i=0; i<3; i++)
  {
    if (pin & (1<<i))
      digitalWrite(selectPins[i], HIGH);
    else
      digitalWrite(selectPins[i], LOW);
  }
}

void loop()
{
  // Loop through the hard wired dimmers
  Serial.print(String(analogRead(DIMp))+" ");
  Serial.print(String(analogRead(bDIMp))+" ");
  // Loop through all eight pins.
  for (byte pin=0; pin<=7; pin++)
  {
    selectAMuxPin(pin); // Select one at a time
    delayMicroseconds(500); // delay after pin select
    int inputValueb = analogRead(zInput); // read Z
    delayMicroseconds(150); //delay after first read
    inputValueb = analogRead(zInput); // read Z again
    Serial.print(String(inputValueb) + " ");
  }
  Serial.println();
}

"Z1" is connected to A0 but you are reading from A1?

it is difficult to guess the anything else I can try because you did not say what you already tried

Sorry - the Z1 is a mistake because I removed some code related to the second chip. I tried adding a delay between reads, and I tried reading twice and throwing out the first read.

Please [edit] your question, informations in the comments are very hard to find.

I'd start with decoupling capacitor for 4051. Next step would be reading 0V channel before reading analog input channel (but that's not possible by analogRead), to remove charge of sampling capacitor.

Where does the 5V used on Poties come from? Is it the same voltage you use as the reference voltage for the Arduino ADCs?  Do the Arduino and the poties have the same GND? It would be easier to find someting, if we could see a picture of your setup. Schematics say nothing about what you have really done. ;-)

Thanks everyone for your helpful comments. I've edited the post with cleaned up code and added my (no doubt shameful) PCB layout and a picture of the actual setup.
@PeterPaulKiefer : The poties are plugged in to the arduino Gnd and +5V pins via copper fills on the PCB - I'm guessing that's not the way to go?

Have you tried to connect only one poti to the muxer? Setting the other 1st over a resistor to GND (Just for safety, if there is a short circuit) and 2nd leave them open. I think the program works fine. But there seems to be a problem with the wiring of the poties or PCB. There is an influence of the potis on each other and/or on the ref voltage. And the graph show also a voltage offset. That's a hint that the feeding voltage of the poties and the reference do not match.

Have you a multimeter to measure the voltages before the muxer. Perhaps that gives you a hint.

And one thing, but it might be nonsense: I saw in the layout that the chips are oriented in different ways.  But on the picture it seems as if they are inserted in the same way. If they use different marker to indicate pin 1.

They are pointing in different directions! Too bad - that would have been an easy fix. I'll compare the ref voltage when I can get back to the shop. Per @KIIV I'll also try putting a .1 uf capacitor between the IC VCC and gnd. Not sure how to read 0V.

There is an internal ADC channel connected directly to the ground. But as i wrote, it's not reachable by analogRead. So unless you have free analog input that can be grounded, you'll have to try to read it directly by setting ADC registers. (that's for elliminating crosstalk caused by too big input impedance that can't charge/discharge sampling capacitor enough - causing crosstalk with previous reading)


text:
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 ?

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

source: Stack Exchange

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

sort: votes


text:
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?

What happens if you upload the example blink sketch? And what, if you try to blink an LED on another pin (you need an extra LED for this)

… and a resistor

Some Arduino boards drive that LED through an op-amp. If pin 13 is set to INPUT Then the input to the op-amp will be effectively floating. That can cause the LED to glow since it lacks further instruction on what to do.

I ran a blink code using pin 13 and an LED both L and LED is now blinking. But if I ran an empty code the L led is on continuously  also if I connect an LED with the empty code uploaded both the L Led and external LED goes out

Does L LED glowing continuously mean something? bcuz the programs that I run seem to do the work

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).

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


text:
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

google arduino emulator

Thats a reasonable option, but i still would need to upload to a board, just an emulated one, I could just use a throwaway board I have and skip the hassle of dealing with the emulator. I appreciate the suggestion though

it is now unclear what you are asking ... you want to compile and run  Arduino code without any hardware, real or virtual ... what would the program do? ... it would have no way to interact with you

Use proteus with arduino library.

similar to using repl.it - I would like to be able to write code, that gets compiled and ran similar to what the arduino ide does. I am trying to test out different syntax for concepts I dont understand. I dont need to test working with hardware.

sorry if this is a stupid question. I was just hoping to reduce some steps in the process so I could learn the language quicker. I am a web developer but for some reason c++ is harder for me than id like to admit

"... syntax for C++ and the code written/compiled by the arduino IDE are slightly different." The Arduino IDE accepts standard C++. What it does differently, to assist learners, is to notice when you've referred to a library (that it know about!) and provides it even if you forgot to '#include" it, and forward declarations for functions, if you forgot those. If you write correct C++, it will compile in any standard C++ environment, including the Arduino IDE.

The difference of C++ and higher level (script) languages is that C++ is really near to the hardware. So running compilations on a PC, can be different from running it on a raspi or an Arduino.  And there are differences even then you don't use Hardware function directly. e.g an int on a Arduino can have another size then on a PC. And beside that, what is the purpose of learning Arduino C++ without Hardware functions? This language is designed for a MCU, that's pure hardware. You can learn how pointers work (and so on), by using plain C++.

Thank you for clarifying the difference, I suppose I can just use repl.it or even visual studio. I appreciate everyone's input!

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.

Need to get rid of Serial.print at least :) :-)
But alas, with a debugger, you don't need that Serial.print at all.

One could write a simple Serial class with a minimal interface that prints to stdout or the native debugger channel.

PlatformIO is a plugin for Visual Studio Code that has support for many embedded device, including most Arduinos

The principle question seems to be about testing their code, in some capacity, without having to upload to an Arduino on each test.  It would probably help to say how PlatformIO enables this.


text:
Arduino cat feeder
My cat feeder works like that:

LCD shows real time clock
Press a push button
LCD shows you to put the feeding time
You put the feeding time through a matricial keyboard
When feeding time is reached, a servo motor open the food container

The problem with my project is when the feeding time is reached, the servo motor doesn't open the food container! I'll put my code below, can you guys help me!! It's a project for college!!
#include  DS3231.h>
#include  Servo.h>
Servo microservo9g;
#include  LiquidCrystal.h>
#include  Keypad.h>
#include  Wire.h>

const byte ROWS = 4; // Four rows
const byte COLS = 4; // Three columns

// Define the Keymap

char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.

byte rowPins[ROWS] = {2, 3, 4, 5};

// Connect keypad COL0, COL1 and COL2 to these Arduino pins.

byte colPins[COLS] = {6, 7, 8, 9};

//  Create the Keypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS );
DS3231  rtc(A4, A5);
LiquidCrystal lcd(A0, A1, A2, 11, 12, 13); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)
Time t;

 //int angle = 0;
// int potentio = A0;      // initialize the A0analog pin for potentiometer
 int t1, t2, t3, t4, t5, t6;

boolean feed = true; // condition for alarm

 char key;
 int r[6];

 void setup()
 {
  microservo9g.attach(10);
  lcd.begin(16,2);
  microservo9g.write(0);
  Serial.begin(9600);
  rtc.begin();
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
 }

 void loop()
 {
lcd.clear();
lcd.setCursor(0,0);
int buttonPress;
buttonPress = digitalRead(A3);

if (buttonPress==1)
 setFeedingTime();
 char customKey = customKeypad.getKey();

//Serial.println(buttonPress);

 lcd.print("Time:  ");
 String t = "";
 t = rtc.getTimeStr();
 t1 = t.charAt(0)-48;
 t2 = t.charAt(1)-48;
 t3 = t.charAt(3)-48;
 t4 = t.charAt(4)-48;
 t5 = t.charAt(6)-48;
 t6 = t.charAt(7)-48;

 lcd.print(rtc.getTimeStr());
 lcd.setCursor(0,1);
 lcd.print("Date: ");
 lcd.print(rtc.getDateStr());

 if (t1==r[0] && t2==r[1] && t3==r[2] && t4==r[3]&& t5<1 && t6<3 && feed==true)
 {
  microservo9g.write(90);
 //command to rotate the servo to the specified angle

  delay(400);
  microservo9g.write(0);
  feed=false;
 }
 }

void setFeedingTime()
{
  feed = true;
   int i=0;

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Set feeding Time");
  lcd.clear();
  lcd.print("HH:MM");
  lcd.setCursor(0,1);

  while(1){

key = customKeypad.getKey();

  char j;

 if(key!=NO_KEY){

  lcd.setCursor(j,1);

  lcd.print(key);

   r[i] = key-48;
    i++;
    j++;

 if (j==2)
    {

  lcd.print(":"); j++;
    }

   delay(500);
  }

 if (key == '*')

 {key=0; break; }
  }
}

Align your code (select code, press ctrl-k)

Your code still looks messy with al the parenthesis not aligned (very hard to see which code belongs to an if/while statement). Did you try the servo motor in an example? Also it will help to add Serial.print statements to show exactly the values around the places where you want the motor to start (and all other relevant places), to rule out if it is a software problem or hardware problem. At least check all values for t1 to t6, r[0] to r[3] and feed.

This code would not compile: Look at the #include statements. Each of them is missing an  beginning  <.  And also your poor cat has only 400 milli sec to eat.  :-( .i.e Perhaps the door is closed before you can see it open.


text:
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?

How about an array ob bytes? also 78 is not divisible by 8. no matter what type you take, you will have fractional parts.

But I can still store 78 into anything multiple of 8. Its not a problem rest of the bits can be zero.

Would in 64 can store 64 bits? How about if more than 64 and less than 128 bits are to assigned? Is it impossible?

FWIW, sizeof(intmax_t) == 8, at least on the AVR-based boards.

Here is a template class that handles this, https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/BitSet.hh.

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.


text:
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?

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.


text:
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);

}

There are 2 ways.  1) State machine. 2) Use the PWM hardware to create buzzer sound.  I would use both.  Comment is you need an more complete answer.

As t=0 you can safely remove the delay(t) lines ;-) And why do you set d=10 after you used it. Wouldn't it be better to set it before the for loop?  You need nearly 300 steps to sweep up and ~ 300 steps to sweep down and for each step you let the LEDs flicker with a patern your eays are not fast enough to see. It that really your intention? I would expect you liked to see the sound sweeps and the LED blinking in parallel. The best way to achieve that is to remove the for loops, and do the things in parallel. See my answer.

@st2000, how do you want to make a siren with hardware PWM?

My bad @Juraj,  the tone() function is already being used.  So all this question needs is a state macing.  Using the mills() function is a step in the correct direction if not a simple state machine already.  A more general state machine solution might benefit the OP as it gives them the bases for more complex software challenges.

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;
   }
}

It's working just like what I want to happen. Thanks

You're welcome. Please do not just copy and paste the prog. Try to understand why and how it works. The world needs more skilled people and you seems to be interested in the subject. I used some things, I learned in 25 years as a developer and they might be difficult for a beginner. If some of the code is unclear, please fell free to ask me here. I would be happy the help you understand and perhaps you find a hidden error, I've overseen.

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.


text:
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. 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() but then what kind of sleep should we use? snore()? delay()?

#include <avr/sleep.h> with sleep_cpu and friends, woken up by an interrupt. Nick Gammon has a pretty extensive forum post on this: https://www.gammon.com.au/forum/?id=11497 (https://github.com/connornishijima/TinySnore/blob/master/src/tinysnore.cpp uses the same functions but only seems to be able to do timer-wakeups)

Thank you @MaximilianGerhardt. In this example: https://www.gammon.com.au/forum/?id=11497&reply=4#reply4, why is there no use of attachInterrupt? Are there different methods?

Instead of attachInterrupt(), the interrupt service routine (ISR) for the necessary vectors are hooked directly, e.g. ISR (PCINT0_vect) { .. }. An example with attachInterrupt is in the first post with the code labeled Waking from sleep with a signal, which matches your button better. When an interrupt is configured for a pin, a change event will automatically wake the CPU from sleep. See datasheet (http://www.farnell.com/datasheets/1698186.pdf) section 7.1 "Sleep Modes", "INT0 and pin change"

Just a caution that putting a standard ATMEGA. Board into sleep mode leaves the supporting circuitry (USB interface etc) drawing power so you would be better to go for the ATTINY.

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

Basically you want to...

Connect a normally-open push button between an IO pin and ground.
Enable the pull-up on the IO.
Enable the pin change interrupt on the IO pin.
Enable interrupts.
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...

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.
IRL the battery will likely self discharge and physically deteriorate long before then (rated at 1% per year), but still not too shabby.

Thank you for this great answer! Linked question: https://arduino.stackexchange.com/questions/70292/how-to-assign-an-interrupt-to-a-button-press-with-an-attiny-interrupt-not-fire

First I was unable to make the intterupt work for multiple pins, 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 here.
PS: as mentioned by Maximilian in a comment, this post gives nice solutions: Detecting key presses on a keypad whilst asleep.

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


text:
Can only program Pro Mini board once then error getsync()
I am 100% new to Arduino.  I am using the Pro Mini 328P 3.3v 8mhz board.  I can successfully write to the board once with the Blink program. I set the FTDI to 3.3v jumper. It works.  Then if I try to upload again (I changed the timing on the blink) I get the getsync error.  I tried two boards they both fail after the first upload.  I am using Win 10.
This is the error I see:
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xaf

Can you add a screenshot of the used Arduino IDE settings and how you connect your FTDI (I assume, not FTDL) to the target board?

I can successfully write to the board once with the Blink program ... how do you know this? ... the blink program may have been previously loaded onto the board

Because I have 5 of these 328P boards and I uploaded another program to one of them and it works monitoring a voltage on a FRSky S6R receiver.  But once I upload a program I can no longer upload to the board.

https://imgur.com/zSFHVQt
https://imgur.com/zqdw9Td
It's DTR to DTR, TX to RX, RX to TX, VCC to VCC, GND to GND

Bad link in the previous comment:  IDE screen shot:
https://imgur.com/gallery/zqdw9Td

Have you reconnected the FTDI adapter? Then it could happen that windows choose a new PORT. In that case you have to reset the port to the new one. I've also heard of others, they had problems with the usb driver of the FTDI mod. Could you look into the device manager to see if the USB device FTDI i still working?

The COM port has not changed.  (I confirmed in the device manager) I can take a new unprogrammed Mini Pro and it works fine.  I bought a total of 5 of them.  Does the upload wipe the boot loader?

I got an UNO R3 board.  I was able to take those Pro Mini boards that would not accept a 2nd upload and got them working.  Something on that FTDI board must be wiping the bootloader.


text:
Motor keeps spinning crazily after UNO board reset
I'm using a NEMA 17 stepper motor with A4988 motor driver and Arduino Uno board. I have used full microstepping (1/16th, so one revolution = 3200 steps).
I'm coming across this strange problem. Whenever I upload any code, for example
void loop()
{  delay(20);
   digitalWrite(stepPin, HIGH);
   delayMicroseconds(100);
   digitalWrite(stepPin, LOW);
   delayMicroseconds(100);
}

the motor spins rapidly for about 1000 steps clockwise (before "avrdude done. Thank you." appears), and then executes the code. When a similar code is placed in void steup() with an empty void loop (), the same thing happens - motor spins rapidly, executes what's written and then stops. The initial rapid spinning is always the same speed and direction, no matter what code is uploaded.
When I upload empty code -
void setup() {}
void loop() {}

the motor continuously spins rapidly with the same speed, same direction. If I add a delay(1000) anywhere in the above program, same thing happens. When I long/short press the reset button on the board, same thing happens. When I upload programs unrelated to the motor, like the example Blink program, same thing happens. Buddy of mine told me to upload the eeprom_clear program from Examples, same thing happened.
I tried uploading this program -
void setup(){
for (int i=0; i<=13; i++)
  {pinMode(i,OUTPUT);
  digitalWrite(i,LOW);

  }

}
void loop(){}

and motor spun like crazy while uploading (same ~1000 steps, clockwise direction) and then stopped. Uploading any program after this has same behaviour. If it an empty/delay only program, motor spins crazily forever. If it is a specific program (example - run for 1000 steps), it spins crazily while uploading, executes the main program, then stops.
As I'm typing this, the motor is spinning like a crazed maniac even though I just uploaded an empty void setup() {} void loop() {} program.
I've tried changing the computer that the Arduino is connected to, I've changed the motor driver and plugged in a brand new one, I've changed the USB cable, I've changed the motor and I've reset all Arduino and breadboard connections. I went to Device Manager > Ports (COM & LPT) > USB-SERIAL CH340(COM5) and updated driver. Current Arduino IDE is Arduino 1.8.10 on Windows 10.
No change in outcome. This problem has been spoiling my sleep for the past few nights as I can't upload anything to the board without the Arduino either spinning crazily endlessly or spinning crazily just while uploading and then behaving properly.
Any solutions? Thanks a lot!
Edit - Added schematic of the electronics connections. Original image from www.lastminuteengineers.com

How do you have it connected to the Arduino?  You aren’t using pins 0 or 1 are you?

Maybe the pins are floating during programming and the motor driver sees this as valid input? An exact schematic would help.

Pins 9,10,11 are for microstepping (all HIGH for 1/16 stepping). Pin 2 for direction, pin 3 for Step mode. Also using 5V pin and GND pin from the POWER section of the Arduino Uno board, connected to the appropriate pins of A4988 motor driver.

@MaximilianGerhardt - I've added the schematic of the connections.

Most pins are floating while programming. Do some pull-up or pull-down resistors help?

You should try to use the EN (enable) pin of the motor driver. The driver is only active when EN is low. You should connect EN to a digital I/O of the microcontroller, and add a pull-up resistor (e.g. 10K) to +5V on the line. In the sketch then pull the EN line low. This should protect against "I/O line is floating", if that is the problem.

@thebusybee Can you explain in more detail? What resistors do you want me to use and where?

So you don't know what a pull-up/down resistor is, do you? Then please show some effort and learn that. See @MaximilianGerhardt's comment: one end of the resistor belongs on the connection that will float otherwise, the other end connects to VCC for pull-up or GND for pull-down. The value depends on the input impedance of the circuit to be controlled; in your case the motor driver. As a rule of thumb make it 1/10 of that input impedance.


text:
How to assign an interrupt to a button press with an ATtiny? (interrupt not fired with my code)
(Here 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.
#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, 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?

the reason is bad code ... do not use delays in the ISR ... set a flag variable only ... do the blink inside the loop() block

Without having an Arduino at hand: Don't you need to enable interrupts in general? Like calling sei() or so?

@Basj - Sorry, I can't help you. I don't have an ATtiny to use for testing.

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

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
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 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: “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.

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.

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:
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.

Thank you for your answer, and for the update!

I edited my question and added some working code of interrupt for PCINT0. Do you know why it doesn't work for PCINT1?


text:
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

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

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.
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.
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.
You can also extend 1. or 2. by own class to hold parameters and then return instance of Adafruit_MQTT_Client


text:
How to parse data most efficiently coming through mqtt with ESP8266
I am writing a program that is currently set up like so:
Python script running on my computer.
Raspberry pi is the broker for the mqtt data transmission
An ESP8266 is programmed to listen to/subscribe to data coming through on a specific channel.
The data comes through with this format: "255,255,255" for example.
It is parsed on the "," saving the values to apply to the red green and blue channel of an led.
I can manually type colors to send from my python program and the led updates correctly. When I update the python script to send a stream of values that produce an effect of fading through the rainbow, that also works for the most part BUT, the data gets sent so quickly and it seems to get backed up. This causes the LED to continue running through the loop even after I stop the python program. The longer the program runs before I stop, the longer the led continues fading after stopping.
This is a problem because I was hoping to scale this up greatly to control many led strips throughout my house. I imagine I could slow down the rate at which I send values, I would need to find the sweet spot of how fast I could send values without them getting backup (because if I change the pattern I want the change to happen immediately, and to not need to wait for all the values of the previous pattern to complete) This gets harder with the more individual strips I try to control at once.
Is there a more efficient way to parse the incoming values?
callback() and splitAndSaveRGBValues() handle parsing the values
The esp8266 code is:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define CLIENT_NAME "ESP8266_1" // just a name to identify this client
WiFiClient wifiClient;
PubSubClient mqttClient("10.0.0.131", 1883, wifiClient);

//set rgb led pins
int pinGreen = 4;
int pinBlue = 14;
int pinRed = 12;

void setup()
{
  Serial.begin(9600);
  //set rgb led pins to output

  pinMode(pinRed, OUTPUT);
  pinMode(pinGreen, OUTPUT);
  pinMode(pinBlue, OUTPUT);
  digitalWrite(pinRed, HIGH);
  digitalWrite(pinGreen, HIGH);
  digitalWrite(pinBlue, HIGH);

  mqttClient.setCallback(callback);
  WiFi.begin("partyHouse", "whatsthepassword");
  connectToWiFiAndBroker();
}

void connectToWiFiAndBroker()
{
  Serial.print("\nConnecting to WIFI");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("Connected to WIFI!");

  Serial.println("Connecting to broker");
  while (!mqttClient.connect(CLIENT_NAME))
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("Connected to broker!");

  mqttClient.subscribe("InterestingTopics/#");
}

//savaing for use when sending data

//#define MILLISEC_DELAY_BETWEEN_PUBLISH 10000
//unsigned long lastTime = 0;
//unsigned long currentValue = 1;
//char msg[50];

void loop()
{
  if (!mqttClient.connected())
  {
    connectToWiFiAndBroker();
  }

  mqttClient.loop();
  //Savaing as a refernce for how to send data

  //  if(millis() - lastTime > MILLISEC_DELAY_BETWEEN_PUBLISH)
  //  {
  //    lastTime = millis();
  //    Serial.println("Publishing a new value");
  //    snprintf (msg, 75, "%ld", currentValue);
  //    Serial.println(currentValue);
  //    mqttClient.publish("ESP8266/CurrentValue", msg);
  //    currentValue++;
  //  }
}
int red;
int green;
int blue;

//the topic is the path based on the subscription
void callback(char* topic, byte* payload, unsigned int length)
{
  char colorCommand[length+1];
  for (int i = 0; i < length; i++)
  {
    colorCommand[i] = (char)payload[i];
  }
  colorCommand[length+1] = '\0';
  splitAndSaveRGBValues(colorCommand);
  updateRGBFromIncomingValues();
}
void splitAndSaveRGBValues(char *colorCommand) {
  char *color;
  color = strtok (colorCommand,",");
  red = atoi(color);
  int increment = 1;
  while (color != NULL)
  {
    color = strtok (NULL, ",");
    if (increment == 1) {
      green = atoi(color);
    } if (increment == 2) {
      blue = atoi(color);
    }
    increment ++;
  }
}

void updateRGBFromIncomingValues() {
  analogWrite(pinRed, red);
  analogWrite(pinGreen, green);
  analogWrite(pinBlue, blue);
}

I have considered changing the approach from streaming values constantly, to coding patterns that could be called from functions saved on each device, but I would need to upload need code (containing the additional patterns for use) to each device each time I think of a new pattern.
Current approach would allow patterns to be created on my computer  and the path used with the MQTT would control which chip to send values to.
The con of my current approach is that leds would only work if I was running the program on my computer to control them (Id like the leds to be able to run their previous pattern if freshly turned on).
I am completely open to suggestions on different ways I can attempt to accomplish my goals if my current approach is insufficient: many nodes/arduinos that have X number of led strips that could be controlled individually, or sync'd up. That would run the previous pattern if turned on, and could be controlled from a single interface

you need to identify the data bottleneck ... if you have to throttle the python script on your computer, then the bottleneck may be between the computer and the MQTT server ... until then, the post is not about the arduino

I thought the bottle neck was the parsing of the data, due to the symptoms from sending data quickly. Is that not right?


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

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.

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
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:
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.

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. ;-)

THANKS...But still, I didn't get my answer. I want to calculate sampling frequency by calculation method not by just rough idea. So if you have any better method please share with me. Thanku

Well, my answer targets real-world aspects. For the detailed alternative see @EdgarBonet's answer. My hint in the second part is just a pointer to start with. -- It is not clear, for which situation you need to know the frequency. You should elaborate on this issue in your question. As your sketch is written, the frequency is by far determined by the serial transmission, not by the sampling itself.


text:
AT commands not working on arduino uno with A7 gsm gprs module
After all connections have been made, I tried to verify my sketch to the arduino
#include <SoftwareSerial.h>

// RX, TX
SoftwareSerial mySerial(2, 3);

void setup()
{
  Serial.begin(9600);
  mySerial.begin(9600);

  while (mySerial.available())
  {
    mySerial.read();
  }
}

void loop()
{
  if (Serial.available())
  {
    mySerial.write(Serial.read());
  }

  if (mySerial.available())
  {
    Serial.write(mySerial.read());
  }
}

After uploading this code to arduino, I tried to confirm.
But it was constantly displaying
¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿
If I set the baud to 9600
But if I set it to 115200, I will not get anything
..
Please help me.
I will be defending my project tomorrow and I am stock here...

You start your project one day before you have to present it. That's funny ;-)) .... OK, now seriously: In order to get quick help, you should add all information you have, and provide links to the used boards and modules. Your could at least format your code example. Have you seen it, how could someone read it? I've done that for you. "But if I set it to 115200, I will not get anything .. " Which one have you set to 115200? The hardware serial, the software serial, the serial terminal in the IDE, all of them? How did you wire the board? Show a picture of your setup.

BTW: Formatting code is easy. Just highlight it and then press the {} button in the menu bar of the online editor.

Have you tried all the other common baud rates? The module might work on one of them. Do you have dicumentation about your module, that states the baudrate?


text:
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.

Why are you considering string? Is it going to be read by humans? I hav not heared of I2C to human interfaces. - Imagine there was an image file format based on XML. Do you think that would be efficient?

I2C is usually a one byte register address and one to four bytes of binary data (interpreted by the I2C device as a 8-bit to 32-bit bitstring). The interface is designed as a high speed, low volume, low cost command and control (master-slave) system. You should read the details at https://i2c.info/i2c-bus-specification

i plan on using string, to make the command unique. but i get your point, thankyou for pointing that out.

String as in array of characters makes sense. Using a C++ String does not make sense. I'd suggest using fixed length arrays of characters without null terminators vs. null-terminated C strings however. That might make your commands easier to read. You can also use integer enum values. That would likely make for shorter byte counts, but make the data a little harder to read if you log it to the console.

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.

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

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

A write transmission is a bit simpler:

addressing the slave in write mode
Writing the target value's register address
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.


text:
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?

Buying a power supply with more amps doesn't hurt the circuit

But there should be a limiting current, right? otherwise it can burn it or parts of the shield? isn't it?

No, the circuit will draw as much current, as it needs. Nothing ever burns, because you provide too much current. It burns, because you draw too much power. If you draw more current, than your power supply can supply, the power supply might get fried. If you draw more current through a  motor driver, than it can handle, it might get fried.

That is great! I completely mised it. Thanks @chrisl

In fact you should buy a power supply that provides 20% - 50% more than you think you need, to allow for surprises.

@chrisl you should post your response as an answer. You might want to state it a little more broadly. Something like: "If you feed a device the correct voltage, it won't draw more current than it needs unless it is faulty. Having a power supply that is able to provide more current than you need should not damage anything (except for components like LEDs that require external current limiting, but that's the exception.) On the other hand, if you try to draw more current from a power supply or other current source that it is designed to provide, you can damage the current source.

I will write an answer, when I'm home again, with a computer. Writing a longer answer on the smartphone is really annoying >.<

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:

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.
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.

That is a great explanation and very eleborate one. Thanks for the time and effort. But I have some doubts. So I can use a 10 amp source with anything? as long as the circuit is not drwaing any more than its limit it should be okay. is that correct?

That's correct. The amperage doesn't matter, as long, as it is more, than needed. You could connect a source, that can provide 100A and it would be the same. But of course you should be careful, when changing your circuit. Providing enough power to drive motors does also mean, you are providing enough power, that the circuit can destroy itself, if you do something wrong.

Think about how a smartphone is charged. These days you can find many  different standards like Quick Charge etc. These are only ways to tell the smartphone, that it can draw more current from the charger, than normal. So the charger always provides the higher power, but the smartphone also has to actually use it. Otherwise you would still charge the slow way, with lower current. And the smartphone never breaks with chargers, that have different amperage output.

Yes I got it. The transformer in the hand made DC supply does not generally get damaged but other components like diodes, capacitors get burned as they are not capable of hadling the current over their rated values. As the transformer can supply as much current as the load draws but the components are not able to tolerate the heat over the specified value.

This entire comment answer made the loading effect much clear. I forgot it too.


text:
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());
}

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 :)

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).


text:
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!!

chapter 31 in http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf

and https://en.wikipedia.org/wiki/Assembly_language

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.
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).

Thanks so much for your explanation!! It's very clear and just what I was looking for!

You're welcome!


text:
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
}

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.

It's OK to accept your own answer as the solution to the problem.


text:
(Firebase and NodeMCU) How to reduce the delay time when control led?
My project consists of NodeMCU controlling led from Firebase's RealTime Database (Using Esp8266Firebase library)
The problem is that the delayed time is too long ( about 6 seconds from when I change the value on the server until the led is turn ON or OFF)
My code on NodeMCU 1.0
#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>

#define FIREBASE_HOST "-6c5d7.firebaseio.com"
#define FIREBASE_AUTH "hYIBAaJYb8nGPuo8Q9EfZuAIfV"

//define ledPin
int ledPin = 2; //D4

void setup(){
    //setup pinLed
    pinMode(ledPin, OUTPUT);

    //setup general
    Serial.begin(115200);
    delay(1000);
    WifiConnect();
    Serial.begin(115200);
}

void getConfirmDataForLed() {

    int controlValue;
    Firebase.getInt(firebaseData,"/Control/ControlValue",controlValue);

    switch(controlValue) {

        case 1:
            digitalWrite(ledPin, HIGH);
            break;
        default:
            digitalWrite(ledPin, LOW);
            break;
    }

}

void WifiConnect(){
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Connecting to WiFi..");
    }

    Serial.println("Connected to the WiFi network");
    Serial.println(WiFi.localIP());
    Serial.println(WiFi.macAddress());

    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
    Firebase.reconnectWiFi(true);
    //Set database read timeout to 1 minute (max 15 minutes)
    Firebase.setReadTimeout(firebaseData, 1000 * 60);
    //tiny, small, medium, large and unlimited.
    //Size and its write timeout e.g. tiny (1s), small (10s), medium (30s) and large (60s).
    Firebase.setwriteSizeLimit(firebaseData, "tiny");
    delay(1000);
}

void loop(){
    getConfirmDataForLed();
    delay(500);
}

Firebase's Structure
Control
    |
    |--ControlValue : 0

what is the average response time of firebase in your area?

When I use my android phone to send data to firebase, It changes very quickly, but it only slows on the Node

@Thang Do not reveal your Firebase auth details publicly like this. It may be misused.


text:
ESP8266 connected to a HIGH pin and DPDT only works sometimes. Works everytime if connected to 3V3 pin
I have a Wemos D1 Mini hooked up to a DS2Y-S-DC3V DPDT switch.
When I have the coil ends are hooked up to a pin (D2) and ground, it will click when I set the pin HIGH. It should click again when it goes low, and then again with high, etc. But after while, it stops responding. Measuring the voltage while hooked up to the DPDT is 1.7 V.  When disconnected from the DPDT, the D2 pin and Ground voltage is as expected, 3.3V.
However, if I connect the DPDT terminals to the ESP's 3V3 pin and G, it works all day as many times as I wish.
I have multiple DPDTs. And two of the 6 don't work as expected. Why does it work when I directly hook it up to 3v terminal but not a HIGH pin? Shouldn't both be 3v?
Any ideas?

please add a schematic diagram of the connections ... it is unclear what is happening when you press the switch

you damage the pin. it can't supply the current for the coil


text:
Arduino GPIB control
I want to control a scientific instrument with an Arduino through GPIB. I have a USB-GPIB adapter, so I would want to do it through the USB. There are tutorials on the Internet on how to connect Arduino to a GPIB instrument through pins, but I did not fid any explanation of how to do it though USB. Is there a software package I can use?

an arduino can interface to something simple like a USB keyboard or mouse ... it may have problems with interfacing GPIB through the USB ... you would be better off using something like a Raspberry Pi ... it uses Linux as an operating system ... it has the necessary hardware to make use of the USB-GPIB adapter .... the necessary software may also be available .... google linux gpib instrument to see if there is any scientific software that you could use

Is there a reason, why you want to use the USB-GPIB adapter? When there are tutorials on how to directly interface GPIB, why do you want to involve the USB interface? USB is a rather complex interface and the possible capabilities of Arduinos (depending on which version you use) regarding USB are limited.


text:
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. 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.

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.

Thanks Juraj. Will try it out.

@Prashant, did the answer help?


text:
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.

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:
.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":
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.

Upvoted, much new info for me too.

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.

By learning assembly, you learn a lot more than “don't do it”: you get an intimate understanding of what the compiler and the hardware do, and you learn what kind C/C++ constructs compile to efficient machine code. Also, you must have written at least a little bit of assembly to really appreciate the compiler's job (the output of avr-objdump). 2. It is not rare that avr-gcc produces sub-optimal code, easily beaten by hand-crafted assembly. I guess this flavor of gcc has not been fine-tuned as much as the ARM or x86_64...

@Edgar Bonet : Sure, you learn a lot more. And only after you've learnt that you can 1. appreciate what the compiler is doing for you 2. interpret its results 3. decide whether you'll continue with assembly programming. BTW: I came from assembly programming, because FORTRAN was not really optimal for small machines, and I'm happy since someone invented C and others built cross-compilers.

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--

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.

Which IDE do we have to use for this? Also, are these definitions for inline assembly? We are restricted to have the main working code of our program in assembly language.

Afaik the default Arduino IDE can be used for this. You probably have to put the code inside the setup and loop functions. Note however, the Arduino IDE creates some code around the setup and loop (like interrupt handling).

Wait a minute here. You can use #define for functions/methods? Well, that's new to me.