body:
For my product, I went from an [Arduino Uno][1]:

[![Arduino Uno R3][2]][2]

to the [Arduino Pro Mini][3]:

[![Arduino Pro Mini][4]][4]

Yes you will need a  [FTDI cable][5] for programming and serial coms to the PC, but providing you don't need coms all the time, you will only need the one cable to upload the program to each device. They can be found pretty cheap too.

However I notice that the Arduino Pro Mini is retired now, so it may be a bit harder to source (it is [still available on AliExpress][6]). So for this reason, I suggest that you instead try the [Arduino Nano][7]:

[![Arduino Nano][8]][8]

which has the added advantage of onboard USB, meaning you no longer need the FTDI cable for programming or coms.

The ATMega328P that is the processor of these 3 boards does not have native USB, which means that the board also needs to include the [FTDI FT232RL IC][9] that is used in the FTDI cable. Having this IC can add additional costs to your bottom line.

For a few dollars cheaper per device, you can use a microcontroller (such as the ATMega32U4) that has native USB coms (and hence you save on the FTDI IC). One such product is the [Arduino Micro][10]:

[![Arduino Micro][11]][11]

All of these boards mentioned are native within the Arduino Ecosystem and (apart from the retired Pro Mini) should be easy to source online or at your local electronics shop. Your Arduino Uno program will work for all of these alternatives - you just have to change the board in the Arduino IDE:

[![Arduino Board Selection][12]][12]

There is one more board that I would like to mention - the [DigiSpark][13]:

[![Digispark][14]][14]

It is only suitable for smaller programs, is limited in some of its features and is not an oficial Arduino board. Having said that, [there is plenty of Arduino support][15] - and its cheap!

  [1]: https://store.arduino.cc/usa/arduino-uno-rev3
  [2]: https://i.stack.imgur.com/WhBC7.jpg
  [3]: https://store.arduino.cc/usa/arduino-pro-mini
  [4]: https://i.stack.imgur.com/jKRqF.jpg
  [5]: https://www.ftdichip.com/Products/Cables/USBTTLSerial.htm#TTL-232R-5V
  [6]: https://www.aliexpress.com/item/Pro-Mini-atmega328-Mini-ATMEGA328P-5V-16MHz-Module-With-Crystal-Oscillator-Pins-Replace-ATMEGA128-for-Arduino/32828645889.html
  [7]: https://store.arduino.cc/usa/arduino-nano
  [8]: https://i.stack.imgur.com/88aGT.jpg
  [9]: https://www.arduino.cc/en/uploads/Main/Arduino_Nano-Rev3.2-SCH.pdf
  [10]: https://store.arduino.cc/usa/arduino-micro-without-headers
  [11]: https://i.stack.imgur.com/v4exX.jpg
  [12]: https://i.stack.imgur.com/9Edtp.jpg
  [13]: http://digistump.com/products/1
  [14]: https://i.stack.imgur.com/rdgIh.jpg
  [15]: https://digistump.com/wiki/digispark/tutorials/connecting


sender: user

message:
Smaller and cheaper alternative to Arduino Uno for permanent projects

I have played a bit around with a Arduino Uno that came in a kit with a breadboard and components. Soon I would like to make some more permanent things.

I would prefer a smaller and cheaper unit than the Arduino Uno but that is almost as easy to use as the Arduino Uno, and very similar to use.

Is the Arduino Pro Mini 328 - 5V/16MHz a logical next step?
At 1/6 of the size of the Arduino Uno it is plenty small.
At 10 $ a piece the price is also good.

I understand that I must solder to get it to work. That should not be a problem.

Will I also need a USB serial board to program the unit?

sender: assistant

body:
I think the first best choice is to remove the ATMega328p-pu chip from your Arduino UNO and incorporate it into your final circuit.
The chips are only about $1.50.

That way, you can just use your UNO as a programmer instead of the final device that you deploy.

I'm not sure why there isn't more documentation about the proper way to remove the ATMega328p-pu chip and using it on your breadboard, after completing your programming.

I explain exactly how to do this on my blog: [http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone][1]

But, here are the basics.
First you remove the chip.  It will look like the following after you do so.  (Note: I'm using the Elegoo clone of an UNO).

[![atmega328p-pu chip removed][2]][2]

Next, you apply power to pin 7 and connect pin 8 to GND.

**Need A 16MHz Crystal**

But, the chip won't seem to run your sketch at this point.
That's because you actually need a crystal to run at 16MHz.

The UNO board has that chip installed and that is why it works.
You can see it here:

[![16MHz crystal on UNO][3]][3]

Finally you add the 16MHz crystal and a couple of 22pF caps and your chip will run standalone (no UNO).

You add the crystal to pins 9 & 10.  You can see all the details by reading my blog entry or reading the [atmega328 datasheet][4].

[![crystal on breadboard][5]][5]

**Finally, Just Wire Everything Else Up**

After that, just wire the rest of your circuit up to the proper pins and you can run your ATMega328p-pu standalone.

It's actually a nice learning experience too.
Just buy replacement atmega328p-pu chips for your UNO and you can create all the projects you want to for very cheap.

  [1]: http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone
  [2]: https://i.stack.imgur.com/jyZb2.png
  [3]: https://i.stack.imgur.com/zzrxr.png
  [4]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf
  [5]: https://i.stack.imgur.com/RMKe4.png


body:
Arduino Pro Micro clones are super cheap and all you need to program them is a normal micro USB cable. You will probably have to solder the headers to do anything useful. They are available in a 3.3V/8MHz and a 5V/16Mhz version.

[![Pro Micro][1]][1]

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


message:
How to concatenate a part of a string and convert then to a int?

Lets say I have

    String myString="AR0236";

I wish to extract the number 236 and assign it to an `int`. How can this be done?

P.S: I'me new to programming and I tried searching the forums for similar problems but surprising none of them worked for me!

body:
There's multiple ways.

The String class (which TBH you should avoid) has some useful methods:

* [substring](https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/substring/) - extract part of a string as a new string
* [toInt](https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/toint/) - convert a string to an integer

So you can join them together:

    int val = myString.substring(3).toInt();

That's the *easy* way.  Grab the string content from the 4th character (it's zero-based, so 3 is the 4th character) onwards, and convert it to an integer.

If you are avoiding String, as you should, then you are working with pointers.  For instance:

    char myString[10]; // This is where your data gets stored
    strcpy(myString, "AR0236"); // Let's put in some dummy data

    int val = atoi(myString + 3);

`myString + 3` gives you a new string pointer to a location that is 3 bytes further up in memory from `myString` - which equates to where the start of your number is.  Then convert that portion of the string to an integer.

The "easy" way consumes and makes a mess of your heap, since it's having to make a new String object and copy data into it. The "better" (second) way uses no more memory. It just converts a subset of the existing string directly.


message:
ESP32 not seen by a network analyzer application in server mode

I have used the **scan wifi** and **blink** examples provided by Espressif,
they are both working on the ESP32 using arduino ide.

However, I can not see my ESP( the SSID and signal strength) in the list of detected wifi when searching for it using a network analyzer app  ( Net analyzer on android)

This was solved when I used the ESP as Access point.
In Client mode the ESP is using the WIFI capability. But why it can not be seen by others?

why is the ESP32 Lolin getting hot only when it is in AP mode?

Thanks in advance

body:
> In Client mode the ESP is using the WIFI capability. But why it can
> not be seen by others?

The app is looking for access points. (if it is looking for SSID) And if you do not have the ESP set as an access point it will not be seen.

> why is the ESP32 Lolin getting hot only when it is in AP mode?

Because the radio is on all the time. It has to be available for a connection. When it is not an access point, the ESP goes into a sleep mode when it does not have any need to communicate.


message:
How to convert hex to ASCII

I am receiving bytes, converting them into hex and now I need to convert the hex to ASCII. Can it be done on an Arduino? Or do I need something else?
I am new to programming with Arduino.

body:
If you have a byte variable `b`, you can

 - `write(b)` it as it is. if it is ASCII code of a readable character, the Serial Monitor will display it as that character, for example for 65 it will printt 'A'
 - print it as decimal number with `print(b)`. for 65 it will print "65"
 - print it as hexadecimal number with `print(b, HEX)`. for 65 it will print "41"
 - print it as a number in other base with `print(b, base)`, for example `print(b, 2)` will print 1000001 if b is 65 in decimal


message:
Assigning array variables to int variables

I need to control thousands of rgb leds.To make animations I want to assign led numbers(addressable led strip) to arrays.For example `floor[2]room[14]=106` 106 is the number of led,there are many floors and rooms.I want to change floor or room numbers with that way I will make animations.
  We can say its 92x30 pixel monitor.I tried to create list of floor and rooms but I couldnt make it.
  I'm new to programming,help please!

**Solved with this way `#define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))`**

body:
You really don't need to maintain a list.

Just calculate the LED index from the location:

    int room = 14;
    int floor = 2;

    const int rooms = 92;

    int led = room + (floor * rooms);

That is, each floor below the current one (floors and rooms count from 0) is a full row of rooms (92 * floors), and there are "room" extra rooms on this floor to add to it.

You could make a macro:

    #define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

Then your LED number is just:

    int led = LEDNO(2, 14);

Here's an example taken from your code:

    void floorsup(){

      FastLED.setBrightness(brightness);

      for(int a=1;a<255;a+=40){
        for (int floor = 0; floor < 30; floor++) {
          for (int room = 0; room < 92; room++) {
            leds[LEDNO(floor, room)].setHSV(a, 255, 255);
          }
          FastLED.show();
          delay(300);
        }
        for (int floor = 0; floor < 30; floor++) {
          for (int room = 0; room < 92; room++) {
            leds2[LEDNO(floor, room)].setHSV(a, 255, 255);
          }
          FastLED.show();
          delay(300);
        }
        for (int floor = 0; floor < 30; floor++) {
          for (int room = 0; room < 92; room++) {
            leds3[LEDNO(floor, room)].setHSV(a, 255, 255);
          }
          FastLED.show();
          delay(300);
        }
      }
    }


body:
Something like this would work:

    #define MAX_FLOORS  92
    #define MAX_ROOMS   30

    struct floor_str {
      int Room[MAX_ROOMS];
    } Floor[MAX_FLOORS];

You would then access an individual LED address like:

Floor[2].Room[14] = 106;


message:
Cannot compile code from Arduino WIFI shield example

I'm trying to launch the piece of code in this Wifi example:
https://www.arduino.cc/en/Reference/WiFiConfig
via Arduino.cc online editor, but I'm getting those errors:

    /home/ubuntu/opt/libraries/latest/wifinina_1_2_0/src/utility/spi_drv.cpp:87:24: error: 'PINS_COUNT' was not declared in this scope

and

    /home/ubuntu/opt/libraries/latest/wifinina_1_2_0/src/utility/spi_drv.cpp:97:15: error: 'NINA_GPIO0' was not declared in this scope

Do someone has an idea of how to solve this?

body:
Those kinds of errors are usually caused by the selection of an incorrect hardware in the IDE.

Choosing a correct board in the IDE will solve the compilation issue.

Since you said that you used the Arduino.cc online editor, I pasted your code into the editor.

You did not say which Arduino board or which WiFi module you are using, so I chose `Arduino Uno WiFi` board as a starting point.

Compiling the code produced the same errors as in the post.

Next I chose `Arduino Uno WiFi Rev2` board, and compiled without errors.


message:
Can I use arduino to generate 8mhz frequency ultrasonic pulses in piezo discs?

void setup()
    {
        pinMode(freqOutputPin, OUTPUT);
        Serial.begin(9600);

        // Set Timer 2 CTC mode with no prescaling.  OC2A toggles on compare match
        //
        // WGM22:0 = 010: CTC Mode, toggle OC
        // WGM2 bits 1 and 0 are in TCCR2A,
        // WGM2 bit 2 is in TCCR2B
        // COM2A0 sets OC2A (arduino pin 11 on Uno or Duemilanove) to toggle on compare match
        //
        TCCR2A = ((1 << WGM21) | (1 << COM2A0));

        // Set Timer 2  No prescaling  (i.e. prescale division = 1)
        //
        // CS22:0 = 001: Use CPU clock with no prescaling
        // CS2 bits 2:0 are all in TCCR2B
        TCCR2B = (1 << CS20);

        // Make sure Compare-match register A interrupt for timer2 is disabled
        TIMSK2 = 0;
        // This value determines the output frequency
        OCR2A = ocr2aval;

        Serial.print("Period    = ");
        Serial.print(period);
        Serial.println(" microseconds");
        Serial.print("Frequency = ");
        Serial.print(freq);
        Serial.println(" Hz");
    }

    void loop(){}

I am working on a project where i need an ultrasonic pulse of 8Mhz every one second and emitter is piezo disc. Please help me with the code.

body:
With 8 Mhz pulse, I assume you mean a pulse of 0.125 µs duration every second. "Frequency" may be misleading here.

Since the ATmega328 in the Arduino Uno is only clocked at 16 Mhz, you only have one extra cycle before having to turn it back off. Debugging and developing at this sort of speed absolutely requires a good oscilloscope.

I would attempt setting your output pin via register, and then turning it off again right after. Use `cli()` to prevent interrupts during your desired pulse.

    void setup() {
      DDRC |= (1 << DDRC0);   //Set PC0 as output (Analog Pin 0)
    }
    void loop() {
      cli();                  //Disable interrupts
      PORTC = 0b00000001;     //Set Analog Pin 0 HIGH
      PORTC = 0b00000000;     //Set Analog Pin 0 LOW
      sei();                  //Enable interrupts again
      delay(1000);            //Delay for 1000ms until next pulse
    }

Beware that this would also set all other pins on Port C (Analog Pins 1 through 5) LOW.

This

      PORTC |= (1 << PORTC0);     //Set Analog Pin 0 HIGH
      PORTC &= ~(1 << PORTC0);     //Set Analog Pin 0 LOW

would be cleaner and only affect Analog Pin 0, but it may take more than one clock cycle to execute.
Unfortunately, I don't have a quick enough oscilloscope to try this out.
If it is too fast (e.g., you get a pulse of duration 0.06125 µs, you may want to insert another `PORTC = 0b00000001;` before turning it off again. It is not unlikely that compiler optimization might just remove this when compiling, so you may have to set some other register to waste that one clock cycle.


message:
If a condition is ever met I want to run a loop permanently

I am trying to run an LED to do SOS in morse code if a temperature is over 20 C and motion is detected, but I want it to continue doing SOS even after the motion goes away or the temperature comes down.

Right now it simply does SOS 1 time and stops.

(sorry if coding is messy)

       int counter;
       int motion = 0;

       void setup()
      {

        {Serial.begin(9600);
         pinMode(4, INPUT);
         pinMode(0, OUTPUT);
         pinMode(2, OUTPUT);
         pinMode(1, INPUT);
         digitalWrite(0, HIGH);

         }
      }

        void loop()
       {

       int sensorA0Value = analogRead(A0);
       float voltage = sensorA0Value * (5.00 / 1023.00);
       Serial.print("Voltage: ");
       Serial.print(voltage);

       float temp = (voltage -.5)*100;
       Serial.print("| Temp: ");
       Serial.print(temp);
       Serial.println(" Celcius|");

       motion = digitalRead(4);

       if(motion == HIGH)
        {Serial.println("Motion Detected");}
       if(motion == LOW)
         {Serial.println("No Motion");}

       if(motion == HIGH && temp > 30)
         {
         digitalWrite(2, HIGH);
         delay(300);
         digitalWrite(2, LOW);
         delay(300);
         digitalWrite(2,HIGH);
         delay(300);
         digitalWrite(2, LOW);
         delay(300);

         digitalWrite(2, HIGH);
         delay(600);
         digitalWrite(2, LOW);
         delay(600);
         digitalWrite(2, HIGH);
         delay(600);
         digitalWrite(2, LOW);
         delay(600);
         digitalWrite(2, HIGH);
         delay(600);
         digitalWrite(2, LOW);

         delay(600);
         digitalWrite(2, HIGH);
         delay(300);
         digitalWrite(2, LOW);
         delay(300);
         digitalWrite(2,HIGH);
         delay(300);
         digitalWrite(2, LOW);
         delay(300);
         digitalWrite(2,HIGH);
         delay(300);
         digitalWrite(2, LOW);
         delay(1000);

       }
         else {
         digitalWrite(2, LOW);

         }
       delay(1000);
        }

body:
You could use a `while`-loop like this:

    if(motion == HIGH && temp > 20) {
      while(true){
       SosMethod();
       }
    }

to clean everything up, then outside your `void loop()` you declare your `SOSMethod()`

    void loop() {
     ... .
     }

     void SosMethod(){
     your-led-code-with-delays
     }


body:
It seems this is your SOS code:

    if(motion == HIGH && temp > 30)
    {
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);

     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);

     delay(600);
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(1000);
    }

Step 1: I think you want to send the first S (.-.-.-.-) as 3 sequences instead of 2 sequence, so the code is:

    if(motion == HIGH && temp > 30)
    {
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);

     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);

     delay(600);
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(1000);
    }

Step 2: Reduce the duplicate code (each 6 sequences of digitalWrite and delay), you will get:

    if(motion == HIGH && temp > 30)
    {
      send(300);
      send(600);
      send(300);
      delay(1000);
    }

    void send(int delayTime)
    {
       for (length = 0; length < 3; length++)
       {
          digitalWrite(2, HIGH);
          delay(delayTime);
          digitalWrite(2, LOW);
          delay(600);
       }
    }

Than you want to fix your problem to keep it sending
Instead of

    if(motion == HIGH && temp > 30)
    {
      send(300);
      send(600);
      send(300);
      delay(1000);
    }

Use

    while ((motion == HIGH) && (temp > 30))
    {
      send(300);
      send(600);
      send(300);
      delay(1000);
    }

For easy reading, I always use parenthesis around equal conditional operator (like ==, >).
The variables motion and temp will not be changed in the while loop, so you can use a while here. It is assumed that the variables are not changed in an interrupt.


body:
This may be unrelated to the actual question but... your Morse timings
are completely messed up. The standard timings are:

    element         duration
    ------------------------
    dot                 1
    dash                3
    interelement gap    1
    intercharacter gap  3
    interword gap       7

where the time unit is the duration of a dot. A correctly timed SOS can
be implemented as follows:

    const uint32_t DOT_TIME = 150;  // 8 words per minute

    void dot() {
        digitalWrite(2, HIGH);
        delay(1 * DOT_TIME);
        digitalWrite(2, LOW);
        delay(1 * DOT_TIME);
    }

    void dash() {
        digitalWrite(2, HIGH);
        delay(3 * DOT_TIME);
        digitalWrite(2, LOW);
        delay(1 * DOT_TIME);
    }

    void send_sos() {
        dot(); dot(); dot();
        dash(); dash(); dash();
        dot(); dot(); dot();
        delay(6 * DOT_TIME);  // interword gap
    }

Notice that there are no intercharacter gaps within SOS, as this is a
[procedural signal][prosigns], transmitted with no letter boundaries. It
is _not_ a three-letter word. The last delay is written as
`6 * DOT_TIME` as there is already a one `DOT_TIME` delay at the end of
the function `dot()`.

[prosigns]: https://en.wikipedia.org/wiki/Prosigns_for_Morse_code


message:
how to use arduino to detect an 8Mhz ultrasonic pulse using piezo disc as receiver?

i need a code to detect an 8MHz ultrasonic pulse and show its properties eg wave pattern and amplitude on serial plotter( like an oscilloscope)

body:
In a word: no.

Let's crunch some numbers...  You want detail like an oscilloscope.  Okay...

My scope is 50MHz bandwidth and runs at 1 giga samples per second.

Drop that down to 8MHz with the same kind of resolution, and you get (1,000,000,000 * (8/50)) = 160,000,000 samples per second.

That's 10 times more samples per second that the clock speed of the Arduino, and it takes at least 1664 clock cycles to take one sample.

So, no.  You need a board with an ADC which can run in the hundreds of millions of samples per second. The Arduino can only run at just under 10 thousand samples per second.

A slight discrepancy.

Even the Arduino Due can only get as good as 1Msps. I have seen MCUs with 15Msps theoretical maximum, but for the kind of output you want you would need considerably more.

So no, there won't be a cheap development "Arduino-like" board around that will do what you want. There may be an expensive one with a very fast CPU, DSP, ultra-high-speed ADC, etc, but you won't be programming it with Arduino, and you most likely won't be able to afford it to just play with.


message:
I can send on software serial, but not read?

I've been cracking my head over this for a long while.

Like many before me, I'm trying to send and receive data from a HM-10 bluetooth module, arduino mega adk and the app called BLE Scanner. I've figured out receiving alright. Whatever I write into the serial monitor, shows up on the app. Whatever I write into the software serial, shows up. However, I haven't figured out how to read from the software serial. The available function never gets triggered, and always printing out the software serial read is always -1

[![This is my connection][1]][1]

The app supports sending data over bluetooth as well. However, using:

        #include <SoftwareSerial.h>
    SoftwareSerial blueSerial(14, 15); //RX, TX
      blueSerial.begin(9600);
      Serial.begin(9600);
    while (1)
      {
        blueSerial.listen();
        if (Serial.available()) {
          Serial.println("Writing");
          blueSerial.write(Serial.read());
          Serial.println(Serial.read());
          Serial.println(blueSerial.available());
        }
        if (blueSerial.available()) {
          Serial.println("Blueserial writing");
          Serial.write(blueSerial.read());
        }
    }

The listen function is used out of pure desperation.

How do I fix this? This should be working right? Since I want to be sending AT commands to the bluetooth modules at some time and read their output, getting this to work is really important.

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

body:
If SoftwareSerial is not working then simply do not use it.

You shouldn't be using it anyway.

You have a Mega with 4 UARTs. You are using a pair of the UART pins, and yet you are using SoftwareSerial.

Don't.

instead use the `SerialX` object (where X is the number by the TX and RX for the pins) to communicate.

SoftwareSerial is only for those times when you *don't* have enough hardware UARTs, and you have plenty.


body:
Possibly the built-in UART (Hardware Serial) assigned to the same pins is interfering with SoftwareSerial? If you really want to us SoftwareSerial, try it on a pair of pins that has no hardware UART attached.

And/or try SoftwareSerial (again, on a non-UART pair of pins) to connect to your PC (after uploading; you can't upload with it), and use Serial1 to connect to your device. This isn't the recommended or easiest way but it might help debug the problems you're seeing.


body:
On Mega you don't need to use SoftwareSerial. Mega has 4 Serials. Connect the module to RX3/TX3 like on the Fritzing in your question and use Serial3 in sketch.

    void setup() {
      Serial.begin(9600);
      Serial3.begin(8600);
    }

    void loop() {

      while (Serial.available()) {
        Serial3.write(Serial.read());
      }
      while (Serial3.available()) {
        Serial.write(Serial3.read());
      }
    }


message:
The servo sweep library code - "delay" versus "in steps of"

This is a pretty basic question - essentially I want to know the difference between adjusting the basic sweep code (from the library) in terms of the "delay" instruction and the "pos += 1" (in steps of 1 degree) instruction.

For my project I want my servo to move 60 degrees at the same frequency as a heart beating relatively fast (lets say two beats a second). I.e., the servo moves from zero to 60 degrees twice in one second. Should I adjust the 'delay' or the 'position' instruction from the library? What's the difference? Does it matter which one I adjust as long as it does what I need it to?

Thanks for your time!

body:
Changing the delay and leaving the increment to one generally gives a "smoother" movement. In fact, if you want for instance to move (roughly) five times faster than the example you can either move the delay to 3ms or increment the position by 5. This is what happens at the position request:

    Time   0  3  6  9 12 15 18 21 24 27 30 33 ...
    Delay  0  1  2  3  4  5  6  7  8  9 10 11 ...
    Incr.  0  0  0  0  0  5  5  5  5  5 10 10 ...

Now, usually I try to use the delay approach as much as I can; the limitations on that approach are that it becomes more CPU consuming if you should also perform other actions between two movements (which is not your case, since you are using delays).

In order to perform four 60° movements in one second you should wait roughly 4ms between calls.

In any case, even if the single increment is the best solution, as long as you perform one movement every 10-20ms you won't be able to see any differences, so even increasing the position by 3 every 12ms or by 5 every 20ms is fine. If you start hearing a "pulsed" noise or see the motor going "jerkily" reduce the increments and the delay.

Note: You can also use multiple increments in order to have "fractional" delays. For instance, if you want to have one increment every 3.5ms, instead of using delayMicroseconds you can perform two increments every 7ms.


body:
Servo send out command pulse about 50 Hz. that mean no point to update servo position more frequent than that.
Servo.write() give resolution of 1 degree. if you need more resolution you can use servo.writeMicroseconds()
For my approach I calculate position trajectory as function of time and update servo position in while loop using millis() as time base.
Anyway I finish it and implement to library called accServo
https://github.com/Menginventor/accServo


message:
Need some help in coding a "timer" in an if else statement

I want to code something like a "timer" (don't know what to call it) in an if else statement in my arduino uno.

Basically I have 2 buttons. If the button1 is pressed and button2 is also pressed in a certain amount of time (let's say 3 seconds), the code will execute. If button1 is pressed but button2 is not pressed within 3 seconds then it will loop back up. How do I go about writing this code?

I've included a flowchart to make my question clearer.

Thanks all :)

    if(digitalRead(button1) == LOW)       // this is where I need help
    {
      if(digitalRead(selectbutton) == LOW)
      {
        for(x=1; x<=30; x++)
        {
          digitalWrite(dir, HIGH);
          delayMicroseconds(10);
          time_now = millis();
          digitalWrite(led, HIGH);
          while(millis() < time_now + 50)
          {
          }

          time_now = millis();
          digitalWrite(led, LOW);
          while(millis() < time_now + 50)
          {
          }
        }
        x=0;
      }
    }

    else if(digitalRead(button2) == LOW)    //same here >_<
    {
      if(digitalRead(selectbutton) == LOW)
      {
        for(x=1; x<=10; x++)
        {
          digitalWrite(dir, LOW);
          delayMicroseconds(10);
          time_now = millis();
          digitalWrite(led, HIGH);
          while(millis() < time_now + 150)
          {
          }

          time_now = millis();
          digitalWrite(led, LOW);
          while(millis() < time_now + 150)
          {
          }
        }
        x=0;
      }
    }
}

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

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

body:
A flowchart is not bad, but it's not really the most appropriate kind of
diagram for this sort of problems. You should try to think in terms of
[finite state machines][FSM] instead, which is a very useful concept
whenever you try to implement “reactive” systems, i.e. systems that have
to react to some kind of input.

Here is your problem, as I understand it, translated into a state
diagram:

[![state diagram][diagram]][diagram]

This system has two states:

- “waiting”, when it waits for the first button to be pressed
- “stand by” when the first button has been pressed and it waits for the
  second.

Pressing button 1 makes a transition from “waiting” to “stand by”. The
transition back to the initial “waiting” state can be triggered by two
distinct events:

- 3 seconds spent in the “stand by” state
- the user pressing button 2.

Note that in the second case, the system runs your code while making the
transition.

Once you have the state diagram, and assuming you have read (and
understood) the finite state machine tutorial I linked to, translating
the diagram into code is almost trivial.

[FSM]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/
[diagram]: https://i.stack.imgur.com/HJicg.png


body:
Your flowchart seems to be in conflict with the code.
`button1` and `button2` are self-explainatory, but what is the `selectButton`?

Here's some code which may accomplish what you're trying to do:

    uint8_t bool_waitforbutton2 = 0;
    uint32_t num_timeatbutton1 = 0;
    void loop() {
      //your other looping code here
      if(digitalRead(button1) == LOW) {
        num_timeatbutton1 = millis();
        bool_waitforbutton2 = 1;
      }
      if(bool_waitforbutton2 == 1 && digitalRead(button2) == LOW){
        bool_waitforbutton2 = 0;
        //Your code here
      }
      if (millis() > (num_timeatbutton1 + 3000)) {
        bool_waitforbutton2 = 0;
      }
    }

This would give you 3000 ms to press `button2` after you've let go of `button1` to execute your code, otherwise the "readyness-flag" `bool_waitforbutton2` is reset.


message:
How to solve this "xpected primary-expression before ',' token"

I'm new in this arduino world, and I'm having some trouble. I am programming something for a school assignment. The program gives an error, and my teacher also doesn't know how to solve it. Maybe someone can help me?

    #include <CapacitiveSensor.h>
    #define speaker

    CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);
    CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);
    CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);
    CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);
    CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);
    CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);
    CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);
    CapacitiveSensor   cs_2_10 = CapacitiveSensor(2,10);

    int s1;
    int s2;
    int s3;
    int s4;
    int s5;
    int s6;
    int s7;
    int s8;

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

    void loop()
    {

      s1 =  cs_2_3.capacitiveSensor(3000);
      s2 =  cs_2_4.capacitiveSensor(3000);
      s3 =  cs_2_5.capacitiveSensor(3000);
      s4 =  cs_2_6.capacitiveSensor(3000);
      s5 =  cs_2_7.capacitiveSensor(3000);
      s6 =  cs_2_8.capacitiveSensor(3000);
      s7 =  cs_2_9.capacitiveSensor(3000);
      s8 =  cs_2_10.capacitiveSensor(3000);

      Serial.print("s1: ");
      Serial.println(s1);
      Serial.print("s2: ");
      Serial.println(s2);
      Serial.print("s3: ");
      Serial.println(s3);
      Serial.print("s4: ");
      Serial.println(s4);
      Serial.print("s5: ");
      Serial.println(s5);
      Serial.print("s6: ");
      Serial.println(s6);
      Serial.print("s7: ");
      Serial.println(s7);
      Serial.print("s8: ");
      Serial.println(s8);

      if (s1 > 500){
        tone(speaker,131);
       }
      else if (s2 > 500){
        tone(speaker,147);
       }
      else if (s3 > 500){
        tone(speaker,165);
       }
      else if (s4 > 500){
        tone(speaker,175);
       }
      else if (s5 > 500){
        tone(speaker,196);
       }
      else if (s6 > 500){
        tone(speaker,220);
       }
      else if (s7 > 500){
        tone(speaker,247);
       }
      else if (s8 > 500){
        tone(speaker,262);
       }

      if (s1<=500  &&  s2<=500  &&  s3<=500 && s4<=500  &&  s5<=500  &&  s6<=500 &&  s7<=500 &&  s8<=500){
        noTone(speaker);
      }
    }

body:
This:

    #define speaker

defines "speaker" as nothing, an empty string. Then:

    tone(speaker,131);

is translated into

    tone(,131);

which makes no sense. The compiler expected to find an expression before the comma.


message:
Controlling stepper motor direction with push buttons

I'm trying to control the direction of three 28byj-48 stepper motors using the ULN2003 drivers. I am using 6 push buttons, 2 for each motor. what I want is for each motor to be stationary by default and rotate forward when I press on one button and reverse when I press the other.

You can find my code below. When I use the same approach for coding for one motor, it works fine with a suitable speed. But once I add all 3 motors, motor A and C perform fine but with low speed, motor B keeps rotating forward from the start, stops while I'm pushing its forward button and nothing happens when I push its reverse button. I have checked my circuit several times and there's nothing wrong with it.

    #include <Stepper.h> //including stepper motor library

    //defining pins section

    // pins for motor A:
    int stepAIN1Pin = 5;
    int stepAIN2Pin = 4;
    int stepAIN3Pin = 3;
    int stepAIN4Pin = 2;

    // pins for motor B:
    int stepBIN1Pin = 9;
    int stepBIN2Pin = 8;
    int stepBIN3Pin = 7;
    int stepBIN4Pin = 6;

    // pins for motor C:
    int stepCIN1Pin = 13;
    int stepCIN2Pin = 12;
    int stepCIN3Pin = 11;
    int stepCIN4Pin = 10;

    int stepsPerRevolution = 2048; // amount of steps per revolution for the 28BYJ48 motor

    int buttonA1Pin = A5;  // pushbutton 1 pin for clockwise rotation of motor A
    int buttonA2Pin = A4;  // pushbutton 2 pin for counter clockwise rotation of motor A

    int buttonB1Pin = A3;  // pushbutton 1 pin for clockwise rotation of motor B
    int buttonB2Pin = A2;  // pushbutton 2 pin for counter clockwise rotation of motor B

    int buttonC1Pin = A1;  // pushbutton 1 pin for clockwise rotation of motor C
    int buttonC2Pin = A0;  // pushbutton 2 pin for counter clockwise rotation of motor C

    Stepper myStepperA(stepsPerRevolution, stepAIN1Pin, stepAIN3Pin, stepAIN2Pin, stepAIN4Pin); // stepping sequence for motor A

    Stepper myStepperB(stepsPerRevolution, stepBIN1Pin, stepBIN3Pin, stepBIN2Pin, stepBIN4Pin); // stepping sequence for motor B

    Stepper myStepperC(stepsPerRevolution, stepCIN1Pin, stepCIN3Pin, stepCIN2Pin, stepCIN4Pin); // stepping sequence for motor C

    void setup()
    {
      // Setting up the pushbutton pins to be an input:
      pinMode(buttonA1Pin, INPUT);
      pinMode(buttonA2Pin, INPUT);

      pinMode(buttonB1Pin, INPUT);
      pinMode(buttonB2Pin, INPUT);

      pinMode(buttonC1Pin, INPUT);
      pinMode(buttonC2Pin, INPUT);

    myStepperA.setSpeed(15); // Setting the speed for motor A

    myStepperB.setSpeed(15); // Setting the speed for motor B

    myStepperC.setSpeed(15); // Setting the speed for motor C
    }

    void loop()
    {

    int buttonA1State, buttonA2State, buttonB1State, buttonB2State, buttonC1State, buttonC2State;

      buttonA1State = analogRead(buttonA1Pin);
      buttonA2State = analogRead(buttonA2Pin);

     if ((buttonA1State != 0) && !(buttonA2State != 0))  // if we're pushing button 1 and NOT button 2
      myStepperA.step(stepsPerRevolution/8);

     if (((buttonA2State != 0) && !(buttonA1State != 0)))  // if we're pushing button 1 and NOT button 2
      myStepperA.step(-stepsPerRevolution/8);

      buttonB1State = analogRead(buttonB1Pin);
      buttonB2State = analogRead(buttonB2Pin);

     if (((buttonB1State != 0) && !(buttonB2State != 0)))  // if we're pushing button 1 and NOT button 2
      myStepperB.step(stepsPerRevolution/8);

     if (((buttonB2State != 0) && !(buttonB1State != 0)))  // if we're pushing button 1 and NOT button 2
      myStepperB.step(-stepsPerRevolution/8);

      buttonC1State = analogRead(buttonC1Pin);
      buttonC2State = analogRead(buttonC2Pin);

     if (((buttonC1State != 0) && !(buttonC2State != 0)))  // if we're pushing button 1 and NOT button 2
      myStepperC.step(stepsPerRevolution/8);

     if (((buttonC2State != 0) && !(buttonC1State != 0)))  // if we're pushing button 1 and NOT button 2
      myStepperC.step(-stepsPerRevolution/8);

      }

body:
Try using `digitalRead()` for button presses. Chances are your buttons, especially when on a breadboard, don't return exactly 0 for `analogRead()`.

IMHO, simple On-Off switches should always connect your pin to either Vcc or GND, with either the internal pullup turned on (if connected to GND), or an external pulldown resistor in place.

To debug this, you might want to `Serial.println()` the values of your button states to your Arduino IDE and observe if their values are like you'd expect.


message:
Trying to use a 7 segment display to count 0/9 with a potentiometer

im trying to switch number on the display using a
    potentiometer, it is just counting from 0/9.
    All help is much appreciated!

    int SegmentA = 6;
    int SegmentB = 7;
    int SegmentC = 8;
    int SegmentD = 9;
    int SegmentE = 10;
    int SegmentF = 11;
    int SegmentG = 12;

    const int PP = A0;

    void setup()
    {
      pinMode (SegmentA, OUTPUT);
      pinMode (SegmentB, OUTPUT);
      pinMode (SegmentC, OUTPUT);
      pinMode (SegmentD, OUTPUT);
      pinMode (SegmentE, OUTPUT);
      pinMode (SegmentF, OUTPUT);
      pinMode (SegmentG, OUTPUT);

    }

    void loop() {

      int POD = analogRead(PP);
      int SM = map(POD, 0, 1023, 0 , 8);
      switch (SM) {

        case 0:
          digitalWrite (SegmentA, HIGH);
          digitalWrite (SegmentB, HIGH);
          digitalWrite (SegmentC, HIGH);
          digitalWrite (SegmentD, HIGH);
          digitalWrite (SegmentE, HIGH);   //0
          digitalWrite (SegmentF, HIGH);
          digitalWrite (SegmentG, LOW);

          delay(1000);

        case 1:
          digitalWrite (SegmentA, LOW);
          digitalWrite (SegmentB, HIGH);
          digitalWrite (SegmentC, HIGH);
          digitalWrite (SegmentD, LOW);
          digitalWrite (SegmentE, LOW);   //1
          digitalWrite (SegmentF, LOW);
          digitalWrite (SegmentG, LOW);

          delay(1000);

        case 2:
          digitalWrite (SegmentA, HIGH);
          digitalWrite (SegmentB, HIGH);
          digitalWrite (SegmentC, LOW);
          digitalWrite (SegmentD, HIGH);
          digitalWrite (SegmentE, HIGH);   //2
          digitalWrite (SegmentF, LOW);
          digitalWrite (SegmentG, HIGH);

          delay(1000);

        case 3:
          digitalWrite (SegmentA, HIGH);
          digitalWrite (SegmentB, HIGH);
          digitalWrite (SegmentC, HIGH);
          digitalWrite (SegmentD, HIGH);
          digitalWrite (SegmentE, LOW);   //3
          digitalWrite (SegmentF, LOW);
          digitalWrite (SegmentG, HIGH);

          delay(1000);

        case 4:
          digitalWrite (SegmentA, LOW);
          digitalWrite (SegmentB, HIGH);
          digitalWrite (SegmentC, HIGH);
          digitalWrite (SegmentD, LOW);
          digitalWrite (SegmentE, LOW);   //4
          digitalWrite (SegmentF, HIGH);
          digitalWrite (SegmentG, HIGH);

          delay(1000);

        case 5:
          digitalWrite (SegmentA, HIGH);
          digitalWrite (SegmentB, LOW);
          digitalWrite (SegmentC, HIGH);
          digitalWrite (SegmentD, HIGH);
          digitalWrite (SegmentE, LOW);   //5
          digitalWrite (SegmentF, HIGH);
          digitalWrite (SegmentG, HIGH);

          delay(1000);

        case 6:
          digitalWrite (SegmentA, HIGH);
          digitalWrite (SegmentB, LOW);
          digitalWrite (SegmentC, HIGH);
          digitalWrite (SegmentD, HIGH);
          digitalWrite (SegmentE, HIGH);   //6
          digitalWrite (SegmentF, HIGH);
          digitalWrite (SegmentG, HIGH);

          delay(1000);

        case 7:
          digitalWrite (SegmentA, HIGH);
          digitalWrite (SegmentB, HIGH);
          digitalWrite (SegmentC, HIGH);
          digitalWrite (SegmentD, LOW);
          digitalWrite (SegmentE, LOW);   //7
          digitalWrite (SegmentF, LOW);
          digitalWrite (SegmentG, LOW);

          delay(1000);

        case 8:
          digitalWrite (SegmentA, HIGH);
          digitalWrite (SegmentB, HIGH);
          digitalWrite (SegmentC, HIGH);
          digitalWrite (SegmentD, HIGH);
          digitalWrite (SegmentE, HIGH);   //8
          digitalWrite (SegmentF, HIGH);
          digitalWrite (SegmentG, HIGH);

      }

    }

body:
You miss the break statement at the end of each case. e.g.:

      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

      break;

    case 4:

This causes each case to perform, and continue with the next case. However, since there is a delay of 1 second, it looks like it is counting.

Actually, I would expect it counts from a certain value depending on the pot meter to 7, since there is no digit 9 implemented, and the delay for the 8 digit is missing too.

To further improve your code, you can add the delay not in every case but at the end, since I assume there always will be one digit selected.

Also you can make a function void showDigit with a parameter for each of the possible segment states and replace all (almost) duplicated code by that function call, or send the digit and use showDigit to set internally the states of each segment (by using a boolean array[nr_of_digits][nr_of_segments], somewhat like Nic Hartley proposes below.


body:
You'll want a single delay (if any) at the bottom of the loop() function. You may not need it since it will keep displaying the current digit until you move the potentiometer. Exception: if the pot is near the edge between 2 digits, you could see some dithering.

Replace the delay-calls in the `case`s with `break;` statements. Otherwise whichever case you call will fall through into the case below it, and so on, displaying subsequent each digit in turn, which isn't what you wanted (and is what you are already seeing).

Change the map() call to `map(POD, 0, 1024, 0 , 10)`. Otherwise there will be no '9' band on potentiometer and the '8' band will be only 1 value wide (out of 1023): exactly the value "1023". You'd like the '9' band to be about as wide as all of the others. It's even possible that a given potentiometer won't get close enough to zero resistance for you to get a 1023 reading.


message:
Arduino baud rate 8 times too high?

I'm having a strange issue where in order to get the expected serial output on my serial monitor, I have to set the baud rate on my serial monitor to be 8 times higher than the rate that i set in my Serial.begin(). For example, Serial.begin(4800) works with a serial monitor baud rate of 38400.

The setup is an atmega328P and an atmega8u2 built up on a breadboard similar to an UNO R1. I followed Nick Gammon's tutorial and his scripts to flash the 328P with the bootloader (http://www.gammon.com.au/forum/?id=11637), and I used the DFU programmer (on OS X) to flash the 8u2. When I plug my computer into the USB connector on the breadboard, the device correctly shows up as an Arduino Uno in my computer's devices list using lsusb. I can also flash sketches to the 328P using the breadboard tutorial (https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard).

The fact that I get the expected results on my serial monitor (even though it's at the wrong baud rate) leads me to believe my hardware is set up correctly. I'm thinking that it could be a bit/byte confusion in the firmware, has anyone encountered something like this or have ideas? I currently can't flash sketches over the USB connector and I believe it is due to the baud rate mismatch.

body:
There are two baud rates you need to diagnose.  One is the baud rate the ATMega8U2 runs at, and the other is the baud rate the ATMega328P runs at.

You need to work out which one is being calculated wrong:

* The ATMega8U2's baud rate is set by the USB connection when you open the port
* The ATMega328P's baud rate is set by your sketch

Obviously, the two have to match.  However, a baud rate isn't just set as a number, it's calculated as a fraction of the CPU clock.

If the CPU clock on just one of the chips is different to what the firmware or sketch expects then the calculation for the baud rate will be wrong.

An example:

Your ATMega328P is expected to be running at 1MHz - however, the fuse settings have it set to run from the internal 8MHz clock.  That means everything on that chip will run 8× faster than expected, so you have to compensate with a lower baud rate.

Another example:

Your ATMega8U2 is expected to be running at 16MHz - however, the fuse settings have it set to run at 2MHz.  That means everything on that chip (except the USB which is clocked separately) will run 8× slower than expected, so you have to compensate on the ATMega328P with a lower baud rate.

So check the fuse settings on both chips. Make sure they are set to the right speeds for your firmware and boards.txt file settings.

Also, you should look at getting a cheap oscilloscope or logic analyser. That would allow you to monitor precisely what is going on with the communication between the two chips and work out if the baud rate is actually 8× faster than expected (ATMega8U2 at fault), or the normal speed but you have to specify it as a lower number (ATMega328P at fault).


message:
How do I connect an accelerometer (GY-521) to a SparkFun Thing Dev (ESP8266)?

All of the wiring diagrams I've found for wiring up a GY-521 accelerometer to an Arduino have looked something like this:

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

I've read in several places that it needs to be connected to `A4` and `A5`. I want to connect one to a SparkFun ThingDev, which unfortunately only has a single analog input:

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

Is this possible?

I only need it for a very simple application (finding out if a machine is vibrating or not).

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

body:
A4 and A5 on the Arduino double as the I2C pins SDA and SCL.  You are communicating with I2C, not analog.

The ESP8266 doesn't have I2C in hardware, but there is a software-based I2C implementation which can work on any pins.  The pinout you show has I2C labeled on pins 2 and 14. While you *can* use those you could use any two pins of your choosing.

Note that I2C on the ESP8266 has a slightly different begin function:

    Wire.begin(2, 14);

That is where the pins you want to use are assigned - in this case, pin 2 for SDA and pin 14 for SCL.


message:
How can I simulate an accelerometer?

I am new to Arduino. I want to simulate a circuit which uses an accelerometer ADXL335 and a DC motor. If any deviation observed in the accelerometer readings, I want the motor to rotate. Is there any way I can simulate its working in software without implementing it?

body:
Your sensor supplies an analog signal, ranging from 0V for -3g to 3.3V for +3g.
This means you have a signal averaging at "338" when read using Arduino's `analogRead()` function, with spikes in either direction when acceleration changes.

You would want some code which gives you a variable hovering around "338", with random acceleration spikes injected in either direction. This could look something like this:

    int16_t num_zerog = (3.3 / 5) * 512;
    int16_t num_xaxis = num_zerog;
    uint8_t num_random = 0;

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

    void loop() {
      // put your main code here, to run repeatedly:
      num_random = random(256);
      if (num_random == 255) {
        num_xaxis += 200;
      }
      else if (num_random == 0) {
        num_xaxis -= 200;
      }
      else if (num_random < 100) {
        num_xaxis += 1;
      }
      else if (num_random > 155) {
        num_xaxis += 1;
      }
      else {
        num_xaxis += (num_zerog - num_xaxis) / 4;
      }
      if(num_xaxis < 0 || num_xaxis > 675) {
        num_xaxis = num_zerog;
      }
      Serial.println(num_xaxis);
      delay(10);
    }

Explanation: First, the value for 0g is determined from the voltage difference.
A random value is generated, ranging from 0 to 255.
If the random value is 0, a negative value is added to your "signal". If it's 255, a positive spike is added.
If any other value is obtained, it goes back to it's 0g level with 1/4th of the difference between the current value and the 0g value per loop.

The serial commands only serve to let you watch the result in Arduino IDE's serial plotter.
If you need the spike to occur less frequently, adjust the `delay()`, or let the counter run to higher numbers.
If the CPU-blocking `delay()` command is an issue in your project, you could run the randomization code using a timer and an interrupt.

Please note that real acceleration sensors exhibit a lot more noise than this. This could be implemented by adding smaller spikes at a broader range of random values (like -1 if num_random is below 100 and +1 if it is above 155).
[![Graph][1]][1]

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


message:
Tx Rx Arduino uno

first of all let me thank you all , you have been of great help.
So, my problem is the next , i have note counter machine i need to read the data from the machine to the arduino , as bytes or ascii , just some readble data .
The machine is connected on the arduino via 2 pins , tx and rx and the data i am getting is not readble and kind of wierd , and one more question do i need some kind of serial shiled or no ?Because right now it is connected with just 2 wires . Thank you

    #include <AltSoftSerial.h>

    // AltSoftSerial always uses these pins:
    //
    // Board          Transmit  Receive   PWM Unusable
    // -----          --------  -------   ------------
    // Teensy 3.0 & 3.1  21        20         22
    // Teensy 2.0         9        10       (none)
    // Teensy++ 2.0      25         4       26, 27
    // Arduino Uno        9         8         10
    // Arduino Leonardo   5        13       (none)
    // Arduino Mega      46        48       44, 45
    // Wiring-S           5         6          4
    // Sanguino          13        14         12

    AltSoftSerial altSerial;

    void setup() {
      Serial.begin(9600);
      while (!Serial) ; // wait for Arduino Serial Monitor to open
      Serial.println("AltSoftSerial Test Begin");
      altSerial.begin(9600);
    }
    byte rx_byte =0 ;
    char text ;
    char hex;
    void loop() {
      if (altSerial.available()) {
        // get the byte from the software serial port

       rx_byte = altSerial.read();
        // send a byte to the software serial port
        //altSerial.println(text);
      Serial.print(rx_byte, HEX);

    }
         //Serial.println("TUKA SUM");
          //text = altSerial.read();

        //hex=(text);

      //Serial.print(text);
        //Serial.write(text);
      // Serial.println(text);

body:
The 9-pin port is designed for connecting to a printer. It uses the RS-232 protocol, not UART.

You cannot connect it directly to an Arduino - you must connect it via a MAX232 adaptor board.

**Disconnect the cable immediately - the voltage levels of RS-232 are likely to do permanent damage to the Arduino.**


message:
ESP8266WebServer how to parse Json payload in post request that is bigger than the ram

I need to post a big json to the nodemcu server which would be bigger than the ram's size

I am using esp8266werserver and arduinojson libraries. I know how to use arduinojson to parse huge json response from other servers by parsing the response as a stream using response.getstream() . I can reuse a small static buffer in the stack to parse the whole json in a loop which performs really well.

But when I use nodemcu as a server, I can't find any similar method in the ESP8266WebServer to allow me to process json response as a stream. All I can only do is to read the string file in server.arg("plain") which may crash as the string may get bigger than the ram.

Is there a quick and dirty workaround? I look at the source in parsing.cpp there is a readBytesWithTimeout method that seems to be responsible to actually parsing the response stream. I am wondering if I may override this function to do what I need but I don't know how.

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/src/Parsing.cpp

body:
The ESP8266WebServer library can process only a HTML-Form POST request of application/x-www-form-urlencoded or mulripart/ content type.

You could sent the JSON as multipart 'upload' to save it to file, but it would require to build the multipart format of the POST body.

If you want to process POST with application/json content type, you could make a simple web server implemented with WiFiServer.


message:
expected ')' before executarAcao

here is the code:

    #define pinSom 7
    #define pinRele1 2
    #define pinRele2 3
    #define tempoMaximoDeUmaPalma 150 //milisegundos
    #define tempoMaximoEntrePalmas 500 //milisegundos

    int contaPalmas = 0;
    long tempoEspera = 0;
    long tempoEsperaEntrePalmas = 0;

    void setup() {
      // put your setup code here, to run once:
        pinMode(pinSom, INPUT);
        pinMode(pinRele1, OUTPUT);
        pinMode(pinRele2, OUTPUT);
    }

    void loop() {{
      // verifica o estado do sensor de som (ele fica normalmente com
      int sensorSom = digitalRead(pinSom) ;

      //se o sensor detectou palmas
      if (tempoEspera == LOW) {

          //espera um tempo para não detectar a mesma palma mais de uma vez
        tempoEspera = tempoEsperaEntrePalmas = millis();
        contaPalmas++;
      }else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma)
         tempoEspera = 0;
      }

        //caso exceda o tempo maximo entre palmas, zera o contador de palmas

        {

        if ( (contaPalmas != 0) && ((millis() - tempoEsperaEntrePalmas)
        (i get the error here) executarAcao();
        contaPalmas = 0;
        TempoEsperaEntrePalmas = millis();

     }
    }
    void executarAcao()
    {
       switch (contaPalmas) {
        case 2:
          digitalWrite(pinRele1, !digitalRead(pinRele1));
          break;
       }

body: This error means you did not close a pair of brackets, either `{}` or `()`.  The solution is to check through your code to make sure brackets are always in pairs.


body:
You're missing closing brackets in the line above your error.

It compiles now, but I have no idea whether it works as you intend.
Try forcing yourself to always open and close brackets when you begin one, and making sure to indent properly.

Also, Arduino code is case-sensitive.

    #define pinSom 7
    #define pinRele1 2
    #define pinRele2 3
    #define tempoMaximoDeUmaPalma 150 //milisegundos
    #define tempoMaximoEntrePalmas 500 //milisegundos

    int contaPalmas = 0;
    long tempoEspera = 0;
    long tempoEsperaEntrePalmas = 0;

    void executarAcao()
    {
      switch (contaPalmas) {
        case 2:
          digitalWrite(pinRele1, !digitalRead(pinRele1));
          break;
      }
    }

    void setup() {
      // put your setup code here, to run once:
      pinMode(pinSom, INPUT);
      pinMode(pinRele1, OUTPUT);
      pinMode(pinRele2, OUTPUT);
    }

    void loop() {
      // verifica o estado do sensor de som (ele fica normalmente com
      int sensorSom = digitalRead(pinSom);

      //se o sensor detectou palmas
      if (tempoEspera == LOW) {
          //espera um tempo para não detectar a mesma palma mais de uma vez
        tempoEspera = tempoEsperaEntrePalmas = millis();
        contaPalmas++;
      }
      else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma) {
         tempoEspera = 0;
      }
        //caso exceda o tempo maximo entre palmas, zera o contador de palmas
      else {
        if ((contaPalmas != 0) && (millis() - tempoEsperaEntrePalmas)) {
          executarAcao();
          contaPalmas = 0;
          tempoEsperaEntrePalmas = millis();
        }
      }
    }


message:
Problem with modbus communication between two arduinos when writing more than 27 registers

I have the following problem:
I want send 200 registers from a modbus master to a slave. Both are arduinos.
I can't send more than 27 registers. When I send more i get the Errorcode `255` which means `timeout`. I know that the modbus message is limited to 253 bytes (256 bytes - server address (1 byte) - CRC  (2 bytes)). Listed here: [MODBUS APPLICATION PROTOCOL SPECIFICATION page.5](http://www.modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf)

**My setup:**

- I use two Arduino Mega 2560. One as a master and the other as the slave. If that works I want to use more than one slave. They are connected via Serial1 master TX1 (pin18) to slave RX1 (pin19) and master RX1 (pin19) to slave TX1 (pin18).

- The modbus library I'm using is [ModbusRtu.h](https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino) from smarmengol.

- Because i want to ultimately communicate with more than one slave device I use RS-485. To send the message as a broadcasat but thats not relevant now because first I want to send to one slave to test it out.

I know that the array is much bigger as the registers I want to send. Thats because I wanted to know when the the timeout happens. Sending 27 registers works fine and the slave recieves all of the 27. But when sending more than 27 registers I get the timeout and nothing will be send.

**Master code**

<!-- language: c -->

    #define SERIAL_BUFFER_SIZE 256
    #include "ModbusRtu.h"

    #define Timeout 150
    #define QUERYINTERVALL 50

    /* Defined the buffersize as stated in
     * C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h
    */

    modbus_t telegram;

    // Test sending large array
    uint16_t sendLargeArray[200] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
                                    18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
                                    33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
                                    48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
                                    63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
                                    78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
                                    93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
                                    106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
                                    118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
                                    130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
                                    142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
                                    154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
                                    166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
                                    178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
                                    190, 191, 192, 193, 194, 195, 196, 197, 198, 199};

    Modbus master;

    void dataSend();

    void setup()
    {

     /**
     *  Modbus object declaration
     *  u8id : node id = 0 for master, = 1..247 for slave
     *  u8serno : serial port (use 0 for Serial)
     *  u8txenpin : 0 for RS-232 and USB-FTDI
     *               or any pin number > 1 for RS-485
     */
        master = Modbus(0, 1, 8); // this is master with RS-485 config
        master.begin(9600, SERIAL_8N2);
        master.setTimeOut(Timeout);
        Serial.begin(9600); // setup Serial for USB debugging
    }

    void loop()
    {
        uint8_t error = master.getLastError(); //get errorcode
        uint8_t state = master.getState();     // get state from master 0 = idle 1 = waiting

        dataSend(); // function for sending array

        // Error Code
        Serial.print("Error code: ");
        Serial.print(error);
        Serial.println();

        // Print master state
        Serial.print("Master State: ");
        Serial.print(state);
        Serial.println();
    }

    void dataSend()
    {
        uint8_t slaveId;
        uint8_t u8state;
        unsigned long u32wait;
        slaveId = 1;
        u32wait = millis() + QUERYINTERVALL;
        bool staywhile = true;

        // telegram for sending sendLargeArray
        telegram.u8id = 1;
        telegram.u8fct = 16;
        telegram.u16RegAdd = 0;
        telegram.u16CoilsNo = 28; // 27 or less works fine
        telegram.au16reg = sendLargeArray;
        u8state = 0;

        // Master broadcasts data
        while (staywhile)
        {
            switch (u8state)
            {
            case 0:
                if (millis() > u32wait)
                    u8state++; // wait state
                break;
            case 1:
                master.query(telegram); // send query (only once)
                u8state++;
            case 2:
                master.poll(); // check incoming messages
                if (master.getState() == COM_IDLE)
                {
                    u8state = 0;
                    u32wait = millis() + QUERYINTERVALL;
                    staywhile = false;
                }
                break;
            }
        }
    }

**Slave code**

<!-- language: c -->

    #define SERIAL_BUFFER_SIZE 256
    #include "ModbusRtu.h"

    /* Defined the buffersize as stated in
         * C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h
        */

    // data array for modbus network sharing

    uint16_t recieveLargeArray[200] = {};

     /**
      *  Modbus object declaration
      *  u8id : node id = 0 for master, = 1..247 for slave
      *  u8serno : serial port (use 0 for Serial)
      *  u8txenpin : 0 for RS-232 and USB-FTDI
      *               or any pin number > 1 for RS-485
     */
    Modbus slave(1, 1, 8); // this is slave @1 and RS-485

    void setup()
    {
      Serial.begin(9600);
      slave.begin(9600, SERIAL_8N2); // baud-rate at 9600
    }

    void loop()
    {
      uint8_t error = slave.getLastError();
      slave.poll(recieveLargeArray, 28); // receiving 27 or less registers works fine

      // print every 5th element of the recieved array
      // no spamming console that way
      Serial.print("Recieve: ");
      for (int i = 0; i < 200; i += 5)
      {
        Serial.print(recieveLargeArray[i]);
        Serial.print(",");
      }
      // Error Code
      Serial.println();
      Serial.print("Error code: ");
      Serial.print(error);
      Serial.println();

      memset(recieveLargeArray, 0, 200 * sizeof(uint16_t)); // recieveLargeArray = {}

    }

**Questions**

- Does anyone know why I cant send more than 27 registers?
- Did anyone made a simillar project and can share the code?
- Has anyone a fix for that?

Help is very appreciated.

Cheers ueberBrot

[Link issuepage on ModbusRTU.h GitHub](https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino/issues/40)

**Edit**

- Forgot to mention that I increased the buffer size inside the `ModbusRTU.h` library aswell. I did it like that `#define MAX_BUFFER 256` as mentioned in [this comment from Juraj](https://arduino.stackexchange.com/a/57819/50966)

- Changed the define location of `#define SERIAL_BUFFER_SIZE 256` in both sketches to the top.

body:
In ModbusRtu.h:

`#define MAX_BUFFER 64 //!< maximum size for the communication buffer in bytes`

27*2=54 bytes for registers and 10 for header and crc.

Change the MAX_BUFFER define. On Mega you have enough RAM.

btw: RS485 doesn't imply mandatory use of Modbus. You could use your own protocol.


body:
I did change the `MAX_BUFFER` inside `ModbusRTU.h` from 64 to 256. As you stated before in there its only the size for the used array. What I also did was move the `#define SERIAL_BUFFER_SIZE 256` inside both my sketches to the top. That did nothing, After that I found a way to increase the RX and TX buffer size with the help of [this post](https://forum.arduino.cc/index.php?topic=399751.msg2749597#msg2749597). I changed it from 64 to 256. maybe I could have changed those with a `#define` in my sketches aswell?.

Now I can send a max of 59 registers at once. Im not sure why I cant send more because the max should be 123 registers at once and the buffer is 256 bytes so  123 registers x 2 bytes = 246 is enough space in the buffer.


message:
Adding POE to Ethernet Board

If I was to use the [Arduino A000024][1], would I be able to add a [POE MODULE][2] to the board to get a Ethernet board with POE to run my arduino project?

  [1]: https://media.digikey.com/pdf/Data Sheets/Arduino PDFs/A000024_Web.pdf
  [2]: https://cdn-shop.adafruit.com/product-files/3847/C11556-001+WC-PD13C050S.pdf

body: If the pinout is what the Ethernet shield expects, then yes. The rows of holes at an odd angle are designed for a POE board similar to that. I can't vouch for whether the pinout is correct though.  It *looks* ok, but it depends on the dimensions of the board whether it fits the existing pinout.


message:
How can I have code in a project that won't compile for Arduino?

I want to test the algorithms in my code without needing to send it to an actual Arduino board. I figured I could lay out my project like:

    project/
        core.cpp      # core algorithms
        core.h        # header for core.cpp
        project.ino   # Arduino setup() loop() calling into core
        pc-main.cpp   # main(argv) calling into core

**However, when I do this, the Arduino IDE wants to compile `pc-main.cpp`, which won't work since it uses stdio and all that. What can I do instead?**

Is there a way to hide a file from the build, other than changing the extension which would inconvenience other editors and compilers? Is there a different standard approach to this kind of problem?

---

What I've thought of:

* I could put `pc-main.cpp` in another directory and have the build for it refer to the files in the Arduino project directory, but that seems awkward and I'd like a more elegant solution.

* I could symlink the `core.*` files into the Arduino project directory from elsewhere, but that would also be inelegant, and inconvenience Windows users should one want to compile the project.

* I could put an `#ifdef` around the contents of `pc-main.cpp`, but I haven't found a suitable `#define` to check for, other than board-specific ones.

I don't want a solution which requires extra steps for each build; the whole point of trying to do this is fast and easy development.

I would also prefer one which does not bring in a whole additional build system, testing framework, or IDE; for example, I found [arduino_ci](https://github.com/ianfixes/arduino_ci) and [PlatformIO](https://platformio.org/) while researching this question. I'll switch to looking at such options if there _isn't_ a good solution to the problem as I've stated it here.

---

[My question is arguably the same as https://arduino.stackexchange.com/questions/47812/project-structure-to-build-for-pc-and-arduino at a high level, but the question and answer there are broad and about organizing modules and not how to make the build actually work.]

body:
I would use conditional compilation, like this:

<!-- language: lang-c++ -->

    #ifndef(ARDUINO)
    // Non-Arduino code.
    #endif


message:
How to upload a sketch to Arduino if it goes to deep sleep mode quickly

I have created sketch where Arduino goes to powerdown mode in about 1s after boot. Now I can not upload other sketch, because programmer does not get proper response. I tried to hold reset and release it at various stages during compile/upload, but it does not help. I suspect the programmer needs to communicate with Arduino for several seconds. Any advice how to erase the sketch without programmer, or how to ban the sleep mode? It is Pro Mini 168. Thanks

body:
Hold the reset button while you start the upload. Wait until you upload first tries to connect to the Arduino, then release the reset.

If you can't get that to work, the next option is to load another Arduino with the ArduinoISP example sketch, connect the two as described in the comments, and use the 2nd Arduino to program yours.

Update:

> Would another Arduino overcome this problem?

Ok, then it's time for plan B. Using a programmer (real, or simulated by another Arduino) doesn't depend on the 'failing' Arduino's bootloadloader but uses a direct (SPI) interface to program it. [This article has more information.][1]

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP


body:
Turn on Verbose output (Under File:preferences).
Press & hold the Reset button. After the compilation ends, you will see a message like:

"Compiled xxx of 32xxx bytes".
That's when the download starts - release reset.
It make take a few tries to get the timing of the release correct.

If you can't get the reset to take hold, then it's time to reburn the bootloader using a Programmer connected to the ICSP pins.


message:
Hot Swap Sensor

Is there a way to have a sensor be hot swappable, as in it can be disconnected and reconnected without locking up the Arduino? I have an I2C sensor that I want to be able to disconnect and reconnect without having to restart the board.

body:
The I2C bus is not blocking the operation, if the sensor isn't there. Also the `Wire` library will not block in this case. It will just return an error code, which you should handle in your code.

But this doesn't mean, that every library, which wraps the I2C workload for a specific sensor, is doing the same. Depending on the sensor and the used library you will have to check yourself, if it is blocking in any way. (This part is not better answerable without information on what sensor and what library will be used)

So: Yes, this is totally possible, but you will have to deal with the errors from disconnecting the sensor and handle them in your code. By polling the sensor in a regular fashion (like Jot mentioned in the comments) will give you the information, if there is a sensor with this address on the bus. The `Wire.endTransmission()` method will return `2` (received NACK on transmit of address), if no device with the specified address is reachable on the bus.

Depending on the used sensor, you might have to initialize the sensor correctly after every reconnect. Especially, if the disconnect happend during a transmission. Refer to the datasheet of the sensor to find out, what happens in this case with the sensor.

If you plan to use different sensors, you have to check for their specific addresses (since different types of sensor often have different hardwired addresses/address spans) and - if the sensors are controlled differently - determine, what sensor is actually connected. The least may be possible by reading their status registers, which can work for many sensor types.


message:
Turn infrared LED on and off in order to simulate an infrared signal

**Note I am able to send and recieve IR signals. This question is only for purposes of learning.**

When using the existing library `#include <IRremote.h>` it is very simple to read and transmit infrared signals. **However I will like to send the signals myself with `digitalWrite(pin, HIGH);`**

1) Receive an infrared signal from a remote control in order to clone it and send it later with Arduino.
----

For this to work I have purchased an [infrared LED][1].

I connect the left leg of the IR LED to pin 11, the middle leg to the ground and the right leg to 5 volts.

Then I upload the following sketch to arduino:
<!-- language-all: lang-cpp -->

    #include <IRremote.h>

    int receiverpin = 11; // left leg of IR receiver is connected to this pin

    IRrecv irrecv(receiverpin);
    decode_results results;

    void setup() {
      pinMode(receiverpin, INPUT);
      Serial.begin(9600);
      irrecv.enableIRIn();
    }

    void loop() {
      if (irrecv.decode(&results))
      {
        Serial.println(results.value, HEX);
        irrecv.resume();
        delay(150);
      }
    }

When I run that and press the power button of my samsung remote control this is what I capture through serial:

    Encoding  : SAMSUNG
    Code      : E0E040BF (32 bits)
    Timing[67]:
     +4500, -4500     + 550, -1650     + 550, -1700     + 550, -1700
     + 550, - 600     + 500, - 550     + 550, - 550     + 550, - 600
     + 550, - 550     + 550, -1700     + 550, -1650     + 550, -1700
     + 550, - 550     + 550, - 550     + 550, - 600     + 550, - 550
     + 550, - 550     + 550, - 600     + 550, -1650     + 550, - 600
     + 550, - 550     + 550, - 550     + 550, - 550     + 550, - 600
     + 550, - 550     + 550, -1700     + 550, - 550     + 550, -1700
     + 500, -1700     + 550, -1700     + 550, -1650     + 550, -1750
     + 500, -1650     + 550
    unsigned int  rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};  // SAMSUNG E0E040BF
    unsigned int  data = 0xE0E040BF;

**What is this supposed to mean. How can I conver this to 0s and 1s?**

2) Sending cloned signal from arduino.
----

Now if I want to power on my TV with arduino I will need a [Infrared LED][2]. I will connect pin 3 to the long leg of my LED and ground to the short leg. Once I pefrom that connection I will run this sketch:

    #include <IRremote.h>

    IRsend irsend;

    void setup() {}

    void loop() {

      irsend.sendSAMSUNG(0xE0E040BF, 32); //Power Code
      delay(1000); // try again in 1 second

    }

**Note this code works and my TV powers on with my Arduino!**

3) Now my question
----

It was very simple to read and transmit infrared signals using `IRremote.h` header.The only thing I had to do was capture 0xE0E040BF that I got when reading the infrared signal and use that hex code on part 2. From reading on the internet I have researched that sending an IR signal is just turning and IR LED on and off very fast (38khz). How can I tranlate what I read:

     rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};

To 0s and 1s and then send that hard coded for puposes of learning.

Acording to this link: http://www.remotecentral.com/cgi-bin/codes/samsung/tv_functions/

The infrared code to power on a samsung tv is:

    0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015
    0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015
    0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015
    0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f
    0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015
    0015 0015 0e6e

I have converted that to binary and it comes to be:

    000000000000000000000000011011010000000000100010000000000000001100000000101010010000000010101000000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000010000000000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000011100000010000000001010100100000000101010000000000000010101000000000001010100000000000101010000111001101110

**Now every time I see a 0 I will power off the LED and every time I see a 1 I will power on the LED waiting about 10 microseconds in order to have a frequency of 38khz** This is how my sketch looks like:

    int pinSend=3;
    char data[1248] = "000000000000000000000000011011010000000000100010000000000000001100000000101010010000000010101000000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000010000000000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000011100000010000000001010100100000000101010000000000000010101000000000001010100000000000101010000111001101110";
    int waitTimeInMicroseconds = 5; // counter to try with different wait times in order to see what frequency works best

    void setup() {
      Serial.begin(9600);
      pinMode(pinSend,OUTPUT);
    }

    void loop() {

      Serial.print("Starting sending IR signal waiting ");
      Serial.print(waitTimeInMicroseconds);
      Serial.println(" microseconds");

      int len = sizeof(data);

      for(int i=0; i<len; i++)
      {
        if( data[i] == '0') // if 0 turn off LED
        {
          digitalWrite(pinSend,LOW);
        }
        else // else turn ON LED
        {
          digitalWrite(pinSend,HIGH);
        }

        delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds
      }

      Serial.println("Done! Is TV on??????");
      delay(1000); // wait 1 second for next atempt

      waitTimeInMicroseconds++; // next time try with different wait time

    }

**When I run that code the TV does not turn on why? How can I hard code the 0s and 1s for purposes of learning?**

  [1]: https://www.amazon.com/Infrared-Receiver-Controlled-Electronic-Circuits/dp/B006OAHKEE/ref=sr_1_8?ie=UTF8&qid=1542244406&sr=8-8&keywords=infrared receiver arduino
  [2]: https://www.amazon.com/Infrared-Lighting-Electronics-Components-Emitting/dp/B01BVGIZGC/ref=sr_1_3?ie=UTF8&qid=1542244967&sr=8-3&keywords=infrared LED

body:
Finally managed to figure it out without using any library. This is how I turn on my TV:

    int pinSend=3;
    int waitTimeInMicroseconds = 33; // counter to try with different wait times in order to see what frequency works best
    unsigned int  rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};

    int isOn =1;

    void setup() {
         Serial.begin(9600);
         pinMode(pinSend,OUTPUT);
    }

    void loop() {

        Serial.print("starting with ");
        Serial.println(waitTimeInMicroseconds);

        for(int jj=0; jj<16; jj++)
        {
        for(int i=0; i<67; i++)
        {
            if(isOn==0)    {
              isOn=1;

              int x=0;

              while(true)
              {
                digitalWrite(pinSend,HIGH);
                delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds
                digitalWrite(pinSend,LOW);
                delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds

                x=x+waitTimeInMicroseconds+waitTimeInMicroseconds;

                if(x > rawData[i])
                {
                  break;
                }
              }

            }
            else{
              isOn=0;
              delayMicroseconds(rawData[i]);
            }

        }
        }

        delay(2500);
        //waitTimeInMicroseconds++;

    }


message:
Eclipse Arduino Leonardo Pro Micro ATMega32U4 Programming Issue

Help Needed as I am little bit lost. I've procured a Pro Micro Board from sparkfun. Great little board and it work like clock work when using the standard Arduino Programming IDE.

Well Copied the code thru to the Eclipse Project, Hit compile and all seems well. But Trying to write the code to the device the following happens.
____________________________________________________________________________
avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:/Users/vente/.arduinocdt/packages/arduino/tools/avrdude/6.3.0-arduino14/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = "F"; type = @
    Software Version = �.u; Hardware Version = �.
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

avrdude done.  Thank you.
_____________________________________________________________________________

I've setup the Programming interface a as a Leonardo Board. AVR ISP.

For some reason It seems as if and it might be me that the usb does not reset? and go into programming mode.

Please Help

body:
I assume you use Eclipse Sloeber plugin for Arduino. For serial upload over USB using bootloader choose programmer `Default`. All other programmers are for flashing over ICSP.

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

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


message:
How to set time for 15 seconds

When user used one password after close the servo the password will valid for 15 seconds then it will not work. Other 9 will be same process

Here is code I need just this to set

    int locker = 13;
    int lockerState = 0;
    const int buzzer = 49;
    String readString;

    #include <Servo.h>
    Servo myservo;
    int pos = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(locker, OUTPUT);
      pinMode(buzzer, OUTPUT);
      myservo.attach(9);
    }

    void loop() {
      lockerState = digitalRead(locker);
      while (Serial.available()) {
        delay(3);
        char c = Serial.read();
        readString += c;
      }

      if (readString.length() >0) {
        Serial.println(readString);
        if ((readString == "2028") || (readString =="1234") || (readString =="1294") || (readString =="4795") || (readString =="5651") || (readString =="7616") || (readString =="5648") || (readString =="1487") || (readString =="7095") || (readString =="2554"))
        {
          digitalWrite(locker, HIGH);
          for (pos = 0; pos <= 180; pos += 1) {
          myservo.write(pos);
          delay(30);
          }
          delay(5000);
          digitalWrite(locker, LOW);
          /* for (pos = 180; pos >= 1; pos -= 1) {
          myservo.write(pos);
          delay(30);
          } */
          readString="";
        }
          /* else if (readString == "proceed") {
            digitalWrite(locker, HIGH);
            for (pos = 0; pos <= 180; pos += 1) {
            myservo.write(pos);
            delay(30);
            }
          digitalWrite(locker, LOW);
          readString="";
          } */
          if (readString == "decline") {
             digitalWrite(locker, HIGH);
             for (pos = 180; pos >= 0; pos -= 1) {
             myservo.write(pos);
             delay(30);
             }
          digitalWrite(locker, LOW);
          readString="";
          }

        else {
          tone(buzzer, 500);
          delay(1000);
          noTone(buzzer);
          delay(1000);
          readString="";
      }
     }
    }

body:
In programming, there are many cases where designing data structures is
more important than the code itself. Once you have a data structure that
makes sense, the code flows very naturally. I think this is one of those
cases, so let's start by looking at what data you have to store for each
of your passwords:

* the password itself (let's call it the _code_)
* whether it has ever been used and, if so, whether it has expired
* if it has been used but has not expired yet: when it was used for the
  first time

This can be saved in an object with the following data fields:

<!-- language-all: lang-c++ -->

    const char * const code;
    enum { UNUSED, USED, EXPIRED } status;
    uint32_t first_use;  // valid if status == USED

Now think about what kind of _actions_ you want to perform on such a
password:

* you want to be able to test whether it matches some user entry
* you want check whether it can be used and, if so, take note that it is
  being used

Based on these requirements, I propose the following class:

    const uint32_t PASS_LIFE_TIME = 15000;

    class Password {
    public:
        Password(const char *c)
            : code(c), status(UNUSED) {}
        bool matches(const char *entry) {
            return strcmp(code, entry) == 0;
        }
        void update() {  // expire if it needs to be
            if (status == USED && millis() - first_use > PASS_LIFE_TIME) {
                status = EXPIRED;
            }
        }
        bool use() {  // returns true on success
            if (status == UNUSED) {
                status = USED;
                first_use = millis();
            }
            update();
            return status != EXPIRED;
        }
    private:
        const char * const code;
        enum { UNUSED, USED, EXPIRED } status;
        uint32_t first_use;  // valid if status == USED
    };

Now you need to store all the passwords in an array, and a couple of
functions to operate on the password collection as a whole:

    const int PASS_COUNT = 10;

    Password passwords[PASS_COUNT] = { "2028", "1234", "1294",
        "4795", "5651", "7616", "5648", "1487", "7095", "2554" };

    void update_all_passwords()
    {
        for (int i = 0; i < PASS_COUNT; i++)
            passwords[i].update();
    }

    // Returns true on success, and uses the matching password.
    bool try_entry(const char * entry)
    {
        for (int i = 0; i < PASS_COUNT; i++)
            if (passwords[i].matches(entry))
                return passwords[i].use();
        return false;  // no match found
    }

The function `update_all_passwords()` is meant to be called on each
iteration of `loop()`. It may seem superfluous, as a password is updated
whenever you try to use it. However, without regular updating, a used
password could be reused 49.7 days later, because of the `millis()`
rollover.

Now, in your program, you just need to:

1. Put a call to `update_all_passwords()` at the beginning of `loop()`
2. Replace the big condition that tests for a valid password by
   `if (try_entry(readString.c_str()))`


message:
Not receiving data from NRF24L01

I'm trying to send data from one Arduino board to another using **NRF24L01** connect to the two ends of the two Arduino boards. The **Tx** blinks in the transmitting end(Arduino board 1) but the receiving end(Arduino board 2) is not getting any value from it. Here is my code.

Transmitting end (Arduino board 1)

    #include <SPI.h>
    #include "RF24.h"

    RF24 myRadio(0, 1);
    byte addresses[][6] = {"0"};

    struct package
    {
        int id = 1;
        float longitude = 0.0;
        float latitude = 0.0;
        char text[100] = "Geographic coordinates";
    };

    typedef struct package Package;
    Package data;

    void setup()
    {
        Serial.begin(115200);
        delay(1000);
        myRadio.begin();
        myRadio.setChannel(115);
        myRadio.setPALevel(RF24_PA_MAX);
        myRadio.setDataRate(RF24_250KBPS);
        myRadio.openWritingPipe(addresses[0]);
        delay(1000);
    }

    void loop()
    {
        myRadio.write(&data, sizeof(data));

        Serial.print("\nPackage:");
        Serial.print(data.id);
        Serial.print("\n");
        Serial.println(data.longitude);
        Serial.println(data.latitude);
        Serial.println(data.text);
        data.id = data.id + 1;
        data.longitude = data.longitude + 0.1;
        data.latitude = data.latitude + 0.1;
        delay(1000);
    }

Receiving end (Arduino board 2)

    #include <SPI.h>
    #include "RF24.h"

    RF24 myRadio(7, 8);
    struct package
    {
        int id = 0;
        float longitude = 0.0;
        float latitude = 0.0;
        char text[100] = "empty";
    };

    byte addresses[][6] = {"0"};

    typedef struct package Package;
    Package data;

    void setup()
    {
        Serial.begin(115200);
        delay(1000);
        myRadio.begin();
        myRadio.setChannel(115);
        myRadio.setPALevel(RF24_PA_MAX);
        myRadio.setDataRate(RF24_250KBPS);
        myRadio.openReadingPipe(1, addresses[0]);
        myRadio.startListening();
        delay(1000);
    }

    void loop()
    {

        if (myRadio.available())
        {
           while (myRadio.available())
           {
               myRadio.read(&data, sizeof(data));
           }
            Serial.print("\nPackage:");
            Serial.print(data.id);
            Serial.print("\n");
            Serial.println(data.longitude);
            Serial.println(data.latitude);
            Serial.println(data.text);
        }

    }

This is how i connected the Arduino and NRF24L01
[![enter image description here][1]][1]

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

Any reason why im not getting the the data from the transmitting end?

body:
Check the reading and writing pipe addresses.

First, the default is `0xE7E7E7E7E7` for pipe 0 (RX_ADDR_P0) and `0xC2C2C2C2C2` for pipe 1 (RX_ADDR_P1), see the [data sheet][1].  Check that the transmitter (TX) address is the same as the receiver
(RX) pipe address.

Secondly, you should not set the pipe address to `0x0` even if that's common between the TX and RX.  This note comes from the data sheet:

> Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in
noise and can give a false detection, which may give a raised Packet Error Rate. Addresses
as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate

  [1]: https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf


message:
Capturing interrupt on both edges when it's set on RISING or FALLING

I've been trying to capture rising edge of an IR sensor output. This sensor's Vcc connected to Arduino 5V and it has a digital output pin. I've observed the digital output pin on an Oscilloscope. It's not noisy.

When I attach a rising edge interrupt on digital pin 2. It somehow captures both rising and falling edges. This response is the same for when it's set for FALLING or CHANGE.

I've tried code at below both on Arduino Uno and

    volatile bool caughtAnInterrupt = false;

    void setup() {

      Serial.begin (19200);

      pinMode(2, INPUT);

      attachInterrupt(digitalPinToInterrupt(2), test, RISING);
    }

    void loop() {

      if (caughtAnInterrupt){

        Serial.println("Rising edge detected");

        caughtAnInterrupt = false;
      }
    }

    void test() {

      caughtAnInterrupt = true;
    }

body:
I've solved the issue with the reply by [eventHandler][1] to [another post][2]. Here it is;

> The problem you are having is because the button glitches are
> producing many interrupts on each button press. You can find a good
> description and a way of solving it using hardware here.
>
> Let me explain, when you press the button, the mechanical contact will
> have a transcient state in which it will fluctuate ON-OFF for a short
> period of time. The same effect might happen when you release the
> button.
>
> One way of solving this problem is using a capacitor parallel to the
> load. Another "easier" way would be done by software. The idea is to
> set a fixed arbitrary time in which you don't allow new interrupts.
> You could use the millis() or micros() library to set this time. The
> code would look something like this.
>
>     unsigned long lastInterrupt;
>
>     void ngt()
>     {
>
>       if(millis() - lastInterrupt > 10) // we set a 10ms no-interrupts window
>         {
>
>         state = !state;
>
>         lastInterrupt = millis();
>
>         }
>     }
>
> This way you don't process new interrupts until 10ms have elapsed.
>
> Note: adjust the time to your requirements.

  [1]: https://stackoverflow.com/users/3443596/eventhandler
  [2]: https://stackoverflow.com/questions/29756145/arduino-attachinterrupt-seems-to-run-twice/29758314