message:
Arduino Mega - Enabling CTC mode disables timer

I'm trying to use timer3 on an Arduino Mega 2560 in CTC mode. However, enabling CTC disables the code entirely.

Here is the function I call in setup() to setup the times.

```cpp
void SetupInterrerupt() {
  cli(); // Disable interrupts

  // Setup timer
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // Setup compare match register
  OCR3B =  CMP_FAST; // CMP_FAST = 40

  // turn on CTC mode:
  TCCR3B |= (1 << WGM32); // Commenting out this line makes the code work
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  sei(); // Enable interrupts

  Serial.println("Timers enabled");
}
```

And the interrupt vector.

```cpp
// Timer 3 Interrupt
ISR(TIMER3_COMPB_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
  // do stuff...
}
```

As is, the interrupt doesn't execute at all. As noted in the code, commenting out "TCCR3B |= (1 << WGM32);" actually executes the interrupt, except the frequency is more like 1Hz instead of 720.

I'm using the [arduino-lmic library][1], as well as some other data structure libraries. I don't think they use any timers, but since lmic is designed for Uno's, I figured that using timers 3 and up would be fine.

I'm a little rusty on my timers unfortunately. Is anyone able to spot my mistake?

Thanks.

  [1]: https://github.com/matthijskooijman/arduino-lmic

body:
I think your problem is that you are using the wrong "TOP" counter value register.

    OCR3B =  CMP_FAST; // CMP_FAST = 40

should be:

    OCR3A =  CMP_FAST; // CMP_FAST = 40

I am not too familiar with the workings of the AVR times, but according to the datasheet:

> In Clear Timer on Compare or CTC mode (WGM22:0 = 2), the OCR2A Register is used to manipulate the counter resolution. In CTC mode the counter is cleared to zero when the counter value (TCNT2) matches the OCR2A. The OCR2A defines the top value for the counter, hence also its resolution.

(Note: it only mentions the register for timer 2, but the same holds true for all the timers in the same class, including timer 3).

Since OCR3A is zero it never triggers a match.  And since there is only one counter (TCNT3) which gets reset to 0 on a match, there can only be one register to compare to, and that is the "A" register. The "B" register appears to be redundant in CTC mode.

You may also need to switch to the COMPA vector (I am not sure on this one TBH)


sender: user

message:
SR505 PIR sensor Time Delay Using Ticker Library NodeMCU

I am trying to make the value of PIR sensor value HIGH for certain time using code. SR505 have a default time delay of 8 seconds. But I want to increase it to 20 seconds.

I am thinking of increasing it using `TICKER` library. I have tried and tested a basic code and seems to be working fine. But I want to implement it with Ticker which will keep the value HIGH for 20 seconds as soon as the timer goes above 20 seconds and PIR is not detecting the motion then it will go set again the timer to 0.

Here is how my code looks like:

    #include <Ticker.h>

    #define SIGNAL_PIN D2

    Ticker flipper;

    void setup()
    {
      Serial.begin(9600);
      pinMode(SIGNAL_PIN, INPUT);
      digitalWrite (SIGNAL_PIN, LOW);

    }

    void flip(){
      Serial.println("From callback");
      digitalWrite (SIGNAL_PIN, HIGH);
    }

    void loop() {
      if(digitalRead(SIGNAL_PIN)==HIGH) {
        Serial.println("Movement detected.");
        flipper.attach(1, flip);
      } else {
        Serial.println("Did not detect movement.");
        flipper.detach();
      }
      delay(1000);
    }

Thank you!

sender: assistant

body:
You really don't need the Ticker library. Just maintain a timestamp of the last time the PIR was seen to be HIGH:

    void loop() {
        static uint32_t lastSeenHigh = millis();
        static bool pirState = false;

        // If it's active then record that fact along with the time
        if (digitalRead(SIGNAL_PIN) == HIGH) {
            lastSeenHigh = millis();
            pirState = true;
        } else {
            // otherwise, if it's been 12 seconds since last seen
            // active, record that it's inactive.
            // 20 seconds, minus the 8 second active time, times 1000 is
            // 12000 milliseconds to extend the time by
            if ((millis() - lastSeenHigh) > 12000) {
                pirState = false;
            }
        }

        if (pirState == true) {
            // Do whatever you want in here when the PIR is active
        }
    }

With that (untested) code:

* Any time the PIR is active the current time is recorded and the state is set true
* When the PIR is LOW and at least 12 seconds have passed since the last activation, set the state to false.


message:
ESP8266 print DNS address (obtained via DHCP)

I've set up an ESP8266 (Wemos D1 Mini) to get IP-information via DHCP.
Everything works fine and I can print the information :

Serial.print(WiFi.macAddress());
Serial.print(WiFI.localIP());
Serial.print(WiFi.subnetMask());
Serial.print(WiFi.gateway.IP());

But how do I print the DNS-address ??

I cant find a function for this ???

/Kind regards : Gurra

body:
    Serial.println(WiFi.dnsIP());

If you have more than one DNS server you can specify the index:

    Serial.println(WiFi.dnsIP(1));


message:
Arduino stopped working: avrdude: ser_open(): can't set com-state

I'm playing with my first Arduino device (Arduino Leonardo). It worked fine but at some point it failed. **I'm getting this error**:

> avrdude: ser_open(): can't set com-state for "\\.\COM6"

> An error occurred while uploading the sketch

The error came out of nowhere because I didn't change the port or cable or anything. Everything seems to be in order: the port, the driver, the IDE, the cable. And everything worked just an hour ago.

1) I've tried to change the port
2) I've reinstalled IDE
3) I've tried different cable

What else can I do?

And another thing: after manual reset of Arduino (with button) device disappears.

body:
The thing to remember with the Leonardo and other ATMega32U4 based boards is that there is no actual serial connection.

What there is, is a USB connection which is controlled by the sketch (and independently by the bootloader) to provide a "CDC/ACM" connection over USB.  This emulates a serial connection, but it's not a *real* serial connection.

This actually has a huge number of benefits, because you can be other things besides a serial port, such as a keyboard or a mouse. However, it comes at a cost:  the serial port is at the mercy of the sketch that's running at the time.

If your sketch crashes for any reason then the serial port can no longer be used. That's bad. It can cripple your Arduino. Since it's the sketch that is providing the driving force for the CDC/ACM serial emulation, if that sketch dies, so does the control of the USB and thus the CDC/ACM.

So while the port may be created initially by the sketch, if it then subsequently crashes the port is still there, but unresponsive.  Or the port can vanish completely.

So how do you fix it?  Well, there's a couple of strategies:

1. Some people have had success by pressing the RESET button twice in quick succession. This depends on the version of the bootloader in use though, and it's not something I have ever tried.
2. Pressing RESET at just the right moment to get the bootloader to run *just before* `avrdude` runs and catch it at the right time to accept a new sketch, or
3. Using a hardware programmer (e.g., USBASP) or another Arduino to wipe the chip and reinstall the bootloader

My preferred method is 3, since it is certain to always work - however it requires either a hardware programmer or another Arduino. However you can pick up a USBASP on eBay / AliExpress / Amazon etc for next to nothing, and when you're working with AVR chips they're always good to have to get you out of tight spots like this.


message:
Convert byte* to int in Arduino

I am trying to convert `byte*` value to `int` here is how I have it.

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

      String topicStr = topic;
      int* payload_value;
      int updates_cal;

        payload_value = (int*)payload;
        //updates_cal = *payload_value;

        Serial.print((int)payload_value);

      delay(1);

      Serial.println();
      Serial.println("-----------------------");

    }

I am getting MQTT payload as Integer value. Which I want to receive in my NodeMCU (ESP8266).

Is there any way to do this?

Thank you!

body:
`byte*` means "pointer to byte(s). It is usually used to point to a byte buffer, and usually will also have a length value so you know how many bytes are in the buffer. It looks like your function does have a length value.

If you're certain that the data in the `payload` parameter is a single int, and the length is correct for an int (2 bytes on Arduino I believe) then you should be able to cast the pointer to `int*` type and then fetch the value from the buffer:

    void mqttCallback(char* topic, byte* payload, unsigned int length) {
      String topicStr = topic;
      int payload_value;
      int updates_cal;

      if (length >= 2) {
        //Cast payload to an int pointer and fetch the value
        intValue = *((int*)payload);
      }
    }


body:
Judging by the comments, you are actually receiving your integer data as text, as a sequence of ASCII characters. This is what you send yourself using `mosquitto_pub`. The buffer is apparently not zero-terminated.

If these characters represent an integer value, then the way to retrieve it as an integer value would be

    char buffer[128];

    // Make sure here that `length` is smaller than the above buffer size.
    // Otherwise, you'd need a bigger buffer

    // Form a C-string from the payload
    memcpy(buffer, payload, length);
    buffer[length] = '\0';

    // Convert it to integer
    char *end = nullptr;
    long value = strtol(buffer, &end, 10);

    // Check for conversion errors
    if (end == buffer || errno == ERANGE)
      ; // Conversion error occurred
    else
      Sterial.println(value);

---

Another approach, which avoids using a separate large[ish] buffer just for the purposes of zero-termination, would be

    // Build a `scanf` format string that will read no more than `length`
    // characters without relying on zero-termination of the payload
    char format[16];
    snprintf(format, sizeof format, "%%%ud", length);

    // Convert the payload
    int payload_value = 0;
    if (sscanf((const char *) payload, format, &payload_value) == 1)
      Serial.println(payload_value);
    else
      ; // Conversion error occurred

However, this approach is less protected from integer overflow than the previous one.

---

Note that most of the above "jumping through the hoops" is dedicated to adding a zero-terminator to the input buffer. If instead you opt for ensuring zero-termination on the sender's side, then it would all reduce to a simple

    // Convert C-string to integer
    char *end = nullptr;
    long value = strtol((const char *) payload, &end, 10);

    // Check for conversion errors
    if (end == buffer || errno == ERANGE)
      ; // Conversion error occurred
    else
      Sterial.println(value);

No extra buffers required.


body:
Don't know if you found an answer yet, but I had the exact same issue and eventually came up with this:
```
   payload[length] = '\0'; // Add a NULL to the end of the char* to make it a string.
   int aNumber = atoi((char *)payload);
```

Pretty simple in the end!


message:
AttachInterrupt - fail to initiate inside a class

I'm trying to create a class that uses `attachInterrupt`, but get this error msg:

     In member function 'void ledDoor::attach()':
    ClosetLedStrip:31:82: error: invalid use of non-static member function
             attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
                                                                                ^
    exit status 1
    invalid use of non-static member function

I found few [answers][1] regarding `static member`, but it was not clear for my needs.

Appreciate help,

    #define USE_SLEEP true

    #if USE_SLEEP
    #include <avr/sleep.h>
    #endif

    #define sensorPin_1 2
    #define sensorPin_2 3
    #define RelayON HIGH
    #define doorOpen HIGH

    #define pwrdown_timeOut 10*(1000*60) // mins to powerdown

    // volatile boolean detectDoor_1_Open = false;
    //volatile boolean detectDoor_2_Open = false;
    const int relayPin1 = 4;
    const int relayPin2 = 5;

    class ledDoor {

    private:
    int _sensorPin;
    int _interruptPin;
    int _relPin;

    void  attach(){
            attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
    }

    void detection_door(){
        #if USE_SLEEP
            sleep_disable();
        #endif

            detachInterrupt(digitalPinToInterrupt(_sensorPin));
            if (digitalRead(_sensorPin) == doorOpen) {
                    _doorOpen = true;
            }
            else {// trun off
                    _doorOpen = false;
            }
            attach();
    }

    public:
    bool volatile _doorOpen;
    ledDoor(int sensorPin, int relPin){
            _sensorPin=sensorPin;
            _relPin=relPin;

            pinMode(_relPin, OUTPUT);
            pinMode(_sensorPin, INPUT); // sensor io
            attach();
    }
    void go2sleep() {
      #if USE_SLEEP
            sleep_enable();
            set_sleep_mode(SLEEP_MODE_PWR_DOWN);
            sleep_cpu();
      #endif

    }
    void switchLeds(){
            if (_doorOpen == true) {
                    digitalWrite(_relPin, RelayON);
            }
            else{
                    digitalWrite(_relPin, !RelayON);
            }
    }

    };

    ledDoor door1(sensorPin_1, relayPin1);
    ledDoor door2(sensorPin_2, relayPin2);

    void setup() {
            Serial.begin(9600);
            Serial.println("UP");
    }

    void loop() {
            door1.switchLeds();
            door2.switchLeds();

      #if USE_SLEEP
            door1.go2sleep();
            door2.go2sleep();
      #endif
    }

  [1]: https://stackoverflow.com/questions/41443720/how-to-create-an-isr-in-an-arduino-class

body:
Firstly, if `detection_door` is a non-static member function, then C++ simply has no such expression syntax as just `detection_door`. Such functions have to either be called (with `()` operator) or be taken address of (with `&` operator). You can't just say `detection_door`. That's meaningless, which is what the compiler is telling you.

Secondly, as you already realized, regardless of the syntax a non-static class member function cannot be used as an interrupt handler. You need a freestanding ("ordinary") function as a handler or a static class member. Non-static class methods are beasts of completely different and incompatible nature.

I see that you have multiple `ledDoor` objects that you want to attach to interrupts independently.

At the level of `attachInterrupt` and `void (void)` handlers you will not be able to use a single interrupt handler function and then properly dispatch the handling to multiple individual objects. The high-level `attachInterrupt` mechanism is insufficient to work around this limitation in a proper way. (At ISR level you can do that, the same way `Servo.h` handles multiple servos, but it is more complicated.)

For this reason, in your case, as long as you want to stay at `attachInterrupt` level, it is better to just implement two separate interrupt handlers as external functions that will call your class methods for your existing global objects

```cpp
ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

void handler_door1()
{
  door1.detection_door();
}

void handler_door2()
{
  door2.detection_door();
}
```

and then just attach these handlers to your desired pins in a regular way.

`static` in this case can only change things in a purely cosmetic way.

---

On the second thought one can wrap the above into a quasi-elegant implementation that might look as follows
```cpp
constexpr unsigned N_PINS = 16; // Range of attachable pin numbers

class ledDoor
{
  // ...

  static ledDoor *self[N_PINS];
  static void (*const HANDLERS[N_PINS])();

  template <unsigned PIN> static void handler()
  { // This is the actual interrupt handler that will dispatch the call to
    // the `detection_door` method of the proper class object
    self[PIN]->detection_door();
  }

  // ...

  void attach()
  {
    self[_sensorPin] = this;
    attachInterrupt(digitalPinToInterrupt(_sensorPin), HANDLERS[_sensorPin], CHANGE);
  }

  void detection_door()
  {
    // Your code
  }
};
```
And somewhere in one of the `.cpp` files
```cpp
// Definitions and initializers for static members

ledDoor *ledDoor::self[N_PINS] = {};

void (*const ledDoor::HANDLERS[N_PINS])() =
{
  ledDoor::handler<0>,
  ledDoor::handler<1>,
  // ...and so on...
  ledDoor::handler<15>
};
```
This uses a dedicated callback for each pin. Maybe a better idea would be to use interrupt number (i.e. the result of `digitalPinToInterrupt`) for indexing instead of pin number.

The same thing can be rewritten through lambdas instead of a template. I.e. one can get rid of `ledDoor::handler<>` template and instead initialize the `HANDLERS` array as
```cpp
void (*const ledDoor::HANDLERS[N_PINS])() =
{
  [](){ ledDoor::self[0]->detection_door(); },
  [](){ ledDoor::self[1]->detection_door(); },
  // ...and so on...
  [](){ ledDoor::self[15]->detection_door(); }
};
```
Note that this approach is a bit more memory wasteful that it could have been, since it uses a number of static tables of pre-determined size. In essense this is a slightly different implementation of the same "gluing" approach as described [here][1].

  [1]: https://arduino.stackexchange.com/questions/20608/pass-classs-public-function-as-an-argument-to-external-command


message:
Make one button print different sentences on LCD

I am very new to arduino and I've been scratching my brain on how to make one button print out three different sentences. When I press it the first time, a " I am " is suppose to appear, when I press it the second time " very" and then the third time " late". I can't have three different buttons because a tone follows this button as well.

body:
Consider using what is commonly called in programming as a [Finite-state machine][1].  Advance to the next state each time the button is pressed.  Start out with 3 states and advance to the next after pressing the button.  You many need to double the number of states after adding your message to the program.  This is because you will want to press the button and only print the message once then advance to a new state where all you do is wait for the next button press.

Note, a mechanical device such as a button will need to be de-bounced either in [hardware][2] or in [software][3].  This is because the processor may see individual makes and breaks as the button is closed and opened causing it to advance to the next state in unexpected ways.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: http://www.labbookpages.co.uk/electronics/debounce.html
  [3]: https://www.arduino.cc/en/tutorial/debounce


message:
Arduino-IDE "while (!Serial)"

I have a Question regarding Arduino IDE:

Many old Arduino setup examples states that the Serial.begin() function always should begin with :

    Serial.begin(9600); // (or 115200)

    while (!Serial)
     {
       ; // Wait for serial to connect
     }

Now I have read a lot of comments saying that this "Wait-function" is no longer necessary ??

Is this an old routine, that's no longer necessary, or is it still important ???

body:
Microcontrolers with native USB interface create an USB connection. It takes a little time. The serial prints right after begin() would be lost without waiting or the connection.

For Uno, Mega, Nano, esp8266/32 boards and other boards with a MCU without native USB support, an external USB-to-TTL-Serial converter chip handles the USB connection.

Leonardo, Micro, MKR have an MCU with built-in USB port. Some boards with Zero or M0 in name have only the native USB port, some have a debugger chip which can serve as USB-to-TTL-Serial converter too.

`!Serial` is a C++ construct using bool() operator. Then implementation is a function which checks if the USB connection is ready.

The waiting for native USB Serial (called SerialUSB for some boards) is used in examples to see the debug prints from setup(). But if USB is not connected, it waits and the sketch doesn't continue. It can be very confusing. So I rather use a `delay(500)` after `Serial.begin()` on boards with native USB.


body:
This is for the Arduino boards that have native USB to ensure that the serial port is ready before progressing. The while loop is not needed for Arduino boards where the USB is not native to the processor (such as the Arduino Uno).

> Indicates if the specified Serial port is ready.
>
> On the boards with native USB, if (Serial) (or if(SerialUSB) on the Due) indicates whether or not the USB CDC serial connection is open. For all other boards, and the non-USB CDC ports, this will always return true.
>
> Ref: [Arduino Reference > communication > serial > if(serial)][1]

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/ifserial/


body:
That function is not obsolete. However, there is gratuitous use of it where it's not really needed.

The usage of the function that you alude to grew from the desire to make ATMega32U4-based boards (such as the Leonardo) which have a *native* USB interface act similar to the ATMega328P etc boards.

When you open the serial port on an Uno, for example, the main MCU is reset and the sketch runs from the start.  When you do the same on a Leonardo that doesn't happen. So by adding that code snippet to the beginning the sketch is paused until the serial port is opened.  This makes it appear that the board has been reset and the sketch is running afresh, like an Uno - but it isn't.

Placing that `while` loop at the start of your sketch without thinking about the consequences means that your sketch may never run. If a serial connection is *required* for your program then that's not such a problem. However, if all you're using the serial for is debugging, then as soon as you try and use your sketch *without* the computer opening the serial port it will fail.

So I would recommend *not* using that `while` loop unless you know that you want the effects that it provides.  That is, stalling the sketch until the serial port is opened by the computer.


message:
Port 0x6F problem

When I disassemble an Arduino IDE created pjoject I see in the created code ("disassembled code actually"), the it uses IN / OUT instruction on port 0X6F.

Like this (part of disassembled list):

    00E3     4FFF                SBCI      R31,0XFF                 ; .O
    00E4     91A5                LPM       R26,Z+                   ; ..
    00E5     91B4                LPM       R27,Z                    ; ..
    00E6     B79F                IN        R25,0X6F                 ; ..
    00E7     94F8                CLI                                ; ..
    00E8     1161                CPSE      R22,R1                   ; a.
    00E9     C004                RJMP      L00EE                    ; ..

    00EA     918C                LD        R24,X                    ; ..
    00EB     9530                COM       R19                      ; 0.
    00EC     2338                AND       R19,R24                  ; 8#
    00ED     C002                RJMP      L00F0                    ; ..

    00EE     91EC      L00EE:    LD        R30,X                    ; ..
    00EF     2B3E                OR        R19,R30                  ; >+
    00F0     933C      L00F0:    ST        X,R19                    ; <.
    00F1     BF9F                OUT       0X6F,R25                 ; ..
    00F2     9508      L00F2:    RET

Anyway the ATMEGA328 Datasheet says that port 0x6F is memorymapped and as such should be accessed through LDS/STS instructions.  This problem really confuses me.  Can anyone give me an explanation ??  Thanks !

body:
The AVR operation code for the IN instruction is:

    Loads data from the I/O Space (Ports, Timers, Configuration Registers, etc.) into register Rd in the Register File.

    Operation:
    (i) Rd ← I/O(A)
    Syntax: Operands: Program Counter:
    (i) IN Rd,A 0 ≤ d ≤ 31, 0 ≤ A ≤ 63, PC ← PC + 1
    16-bit Opcode: 1011 0AAd dddd AAAA

The disassemble of the operation code `B79F (hex) = 1011 0111 1001 1111 (bin)` is `IN R25,$3F` which is actually `SREG`.

The block of code with the `IN, CLI` and `OUT` instruction is a critical section where the flags in `SREG` are saved, interrupts are turned off, and later the `SREG` is restored.

Cheers!


message:
Read the value of a register in arduino

I want to read the value of the register (8-bit). In particular I want to read the values of:

 1. The Timer/Counter - TCNT0 ( **Adress** 0x26 (0x46) )
 2. The output compare registers - OCR0A and OCR0B.

Is there a way to read them with the Arduino program?

body:
To convert my comments to an answer:

You can use the register names directly. They are defined in the boards/chips core. To read them, simply use the names in your calculations. Write to the registers by setting the value of the registers name (like a variable: `TCNT0 = 0;`). Be sure to look into the datasheet, to check the behavior of that register.


message:
Esp8266 Web based code and real button

0

I wrote a code in the Arduino IDE. With this code, i can control 4 leds on and off from the web page. In the web page 9 buttons.

2 buttons for led-1 on and off. 2 buttons for led-2 on and off. 2 buttons for led-3 on and off. 2 buttons for led-4 on and off. 1 button for toggle all leds on and off.

I want also add a real button to the circuit. When i press this button, i want to run that toggle code. How can i do that?

This is my code;

    #include <ESP8266WiFi.h>

    const char* ssid = "UnderSpeed";
    const char* password = "q1w2e3r4t5__";
    const char* host = "192.168.1.185"; //it will tell you the IP once it starts up
                                            //just write it here afterwards and upload
    int r0 = D0;
    int r1 = D1;
    int r2 = D2;
    int r3 = D3;
    int btn0 = D5;

    WiFiServer server(301); //just pick any port number you like

    void setup() {
      Serial.begin(115200);
      delay(10);
    Serial.println(WiFi.localIP());
      // prepare GPIO2
      pinMode(r0, OUTPUT);
      pinMode(r1, OUTPUT);
      pinMode(r2, OUTPUT);
      pinMode(r3, OUTPUT);
      pinMode(btn0, INPUT_PULLUP);
      digitalWrite(r0, HIGH);
      digitalWrite(r1, HIGH);
      digitalWrite(r2, HIGH);
      digitalWrite(r3, HIGH);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.println(WiFi.localIP());
    }

    void loop() {
      // Check if a client has connected

      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      while (!client.available()) {
        delay(1);
      }

      // Read the first line of the request
      String req = client.readStringUntil('\r');
      client.flush();

      // Match the request
      if (req.indexOf("") != -10) {  //checks if you're on the main page

        if (req.indexOf("/r0-OFF") != -1) { //checks if you clicked OFF
          digitalWrite(r0, HIGH);
          Serial.println("Relay-0 OFF");
        }
        if (req.indexOf("/r0-ON") != -1) { //checks if you clicked ON
          digitalWrite(r0, LOW);
          Serial.println("Relay-0 ON");
        }

        if (req.indexOf("/r1-OFF") != -1) { //checks if you clicked OFF
          digitalWrite(r1, HIGH);
          Serial.println("Relay-1 OFF");
        }
        if (req.indexOf("/r1-ON") != -1) { //checks if you clicked ON
          digitalWrite(r1, LOW);
          Serial.println("Relay-1 ON");
        }

        if (req.indexOf("/r2-OFF") != -1) { //checks if you clicked OFF
          digitalWrite(r2, HIGH);
          Serial.println("Relay-2 OFF");
        }
        if (req.indexOf("/r2-ON") != -1) { //checks if you clicked ON
          digitalWrite(r2, LOW);
          Serial.println("Relay-2 ON");
        }

        if (req.indexOf("/r3-OFF") != -1) { //checks if you clicked OFF
          digitalWrite(r3, HIGH);
          Serial.println("Relay-3 OFF");
        }
        if (req.indexOf("/r3-ON") != -1) { //checks if you clicked ON
          digitalWrite(r3, LOW);
          Serial.println("Relay-3 ON");
        }

        if (req.indexOf("/btn0") != -1) { //checks if you clicked OFF
          buton_islemi();
        }

      }

      else {
        Serial.println("invalid request");
       client.stop();
        return;
      }

      // Prepare the response
      String s = "HTTP/1.1 200 OK\r\n";
      s += "Content-Type: text/html\r\n\r\n";
      s += "<!DOCTYPE HTML>\r\n\r\n";

      s += "
<input type=\"button\" name=\"rly0-on\" value=\"Relay-0 ON \" onclick=\"location.href='/r0-ON'\">";
      s += "
";
      s += "
<input type=\"button\" name=\"rly0-off\" value=\"Relay-0 OFF\" onclick=\"location.href='/r0-OFF'\">";

      s += "

";

      s += "
<input type=\"button\" name=\"rly1-on\" value=\"Relay-1 ON \" onclick=\"location.href='/r1-ON'\">";
      s += "
";
      s += "
<input type=\"button\" name=\"rly1-off\" value=\"Relay-1 OFF\" onclick=\"location.href='/r1-OFF'\">";

      s += "

";

      s += "
<input type=\"button\" name=\"rly2-on\" value=\"Relay-2 ON \" onclick=\"location.href='/r2-ON'\">";
      s += "
";
      s += "
<input type=\"button\" name=\"rly2-off\" value=\"Relay-2 OFF\" onclick=\"location.href='/r2-OFF'\">";

      s += "

";

      s += "
<input type=\"button\" name=\"rly3-on\" value=\"Relay-3 ON \" onclick=\"location.href='/r3-ON'\">";
      s += "
";
      s += "
<input type=\"button\" name=\"rly3-off\" value=\"Relay-3 OFF\" onclick=\"location.href='/r3-OFF'\">";

      s += "

";

      s += "
<input type=\"button\" name=\"btn0\" value=\"Button-0 \" onclick=\"location.href='/btn0'\">";
      s += "
";

      s += "\n";

      client.flush();

      // Send the response to the client
      client.print(s);
      delay(1);
    }

    void buton_islemi() {
      digitalWrite(r0, !digitalRead(r0));
      delay(500);
      digitalWrite(r1, !digitalRead(r1));
      delay(500);
      digitalWrite(r2, !digitalRead(r2));
      delay(500);
      digitalWrite(r3, !digitalRead(r3));
      Serial.println("Button Pressed");
    }

body:
Just add your button check into the section where you're not handling a client. For example:

    static uint8_t buttonState = LOW;
    if (!client) {

      uint8_t bs = digitalRead(BUTTON_PIN);
      if (bs != buttonState) {
        buttonState = bs;
        if (buttonState == HIGH) {
          buton_islemi();
        }
      }

      return;
    }


message:
HMAC SHA256 in Arduino use case?

I am doing a school project and wanted to implement HMAC on a arduino UNO like board. I have been testing the Cryptosuite, but none of the examples work for me. Such as this one: https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde

This one https://github.com/simonratner/Arduino-SHA-256, a trimmed-down version, which sounds good but there's none working example.

Can any one point me to the right direction? Thanks a lot!!

body:
When you are asking a question, here or on a forum, then please tell what you did and what the result was. When you say that it is not working, then we have not enough information and your question might not get answered.

I have tested the first link that you gave to [Cryptosuite][1]. It is outdated and needs to be fixed.
I renamed "hmacsha256test.**pde**" to "hmacsha256test.**ino**".
The compiler errors and warnings are in the lower part of the Arduino IDE. Scroll up to find the first problem and fix that. Repeat it until it works.

The `PROGMEM` requires that the 'const' keyword is used. For example in "sha256.cpp":

    const uint32_t sha256K[] PROGMEM = {

The 'write' function should return a `size_t` value.

In sha256.h:

    // virtual void write(uint8_t);
    virtual size_t write(uint8_t);

In sha256.cpp:

    size_t Sha256Class::write(uint8_t data) {
      ++byteCount;
      addUncounted(data);
      return 1;
    }

Then it compiles and runs on a Arduino Uno, although there is a warning for low memory because 75% of the sram is used.

The [second link][2] is a changed version of the same Cryptosuite. It should be able to use the examples of the Cryptosuite, but it does not.
I can make that work as well.

Using the same example of the Cryptosuite "hmacsha256test.**pde**" (I renamed it to "hmacsha256test.**ino**"), create a object 'sha' after including the "sha256.h":

    #include "sha256.h"
    Sha256 sha;

In the example, replace all "Sha256" function calls with "sha" function calls:

    sha.initHmac(hmacKey1,20);
    sha.print("Hi There");

Then it works as well.

  [1]: https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde
  [2]: https://github.com/simonratner/Arduino-SHA-256


body:
I have used the [https://github.com/Cathedrow/Cryptosuite/][1] on ESP8266. For that in addition to the changes desribed by Jot it is enough to remove

    #include <avr/io.h>
    #include <avr/pgmspace.h>

from the header files. Then it is working fine.

  [1]: https://github.com/Cathedrow/Cryptosuite/


message:
How would I give an Arduino-based product WiFi credentials?

Let's imagine I create this cool little Arduino-based (replace Arduino with any embedded system that's not a Raspberry Pi) object that does some interesting things but it needs an internet connection to retrieve some information. The object doesn't have an input interface for the user because it would be meaningless if not for the WiFi credentials insertion procedure. In my testing instance, I can just hardcode the credentials before flashing the firmware, but what if I wanted to make it a product and have every user set it up on his own network?

How was such a task handled in some commercial products with similar challenges? Or what would the best way of handling it be?

body:
Most WiFi chips/modules these days worth paying for can function both as a WiFi client or as an AP.

So, what you would do is when the device is unconfigured, put your WiFi module into AP mode, and serve up a lightweight webpage hosted from your device. The owner connects to the devices WiFi network, and accessing the device through that webpage, they can setup their wifi information. Once configured, you switch the WiFi back to client mode, and connect to the provided Wi-Fi network.


message:
Motor code for the "Pirate: 4WD Arduino Mobile Robot Kit with Bluetooth 4.0", will not work

The board is the RoMeo BLE V 1.0 and I have set the board to Arduino UNO on the board part of the arduino IDE, as I cannot find the RoMeo Board.

This is the code for the motors.

    ``int speedPin_M1 = 5;     //M1 Speed Control
    int speedPin_M2 = 6;     //M2 Speed Control
    int directionPin_M1 = 4;     //M1 Direction Control
    int directionPin_M2 = 7;     //M1 Direction Control

    void setup(){

    }

    void loop(){
        carAdvance(150,150);
        delay(1000);
        carBack(150,150);
        delay(1000);
        carTurnLeft(150,150);
        delay(1000);
        carTurnRight(150,150);
        delay(1000);
    }

    void carStop(){                 //  Motor Stop
      digitalWrite(speedPin_M2,0);
      digitalWrite(directionPin_M1,LOW);
      digitalWrite(speedPin_M1,0);
      digitalWrite(directionPin_M2,LOW);
    }

    void carTurnLeft(int leftSpeed,int rightSpeed){         //Turn Left
      analogWrite (speedPin_M2,leftSpeed);              //PWM Speed Control
      digitalWrite(directionPin_M1,LOW);
      analogWrite (speedPin_M1,rightSpeed);
      digitalWrite(directionPin_M2,HIGH);
    }

    void carTurnRight(int leftSpeed,int rightSpeed){        //Turn Right
      analogWrite (speedPin_M2,leftSpeed);
      digitalWrite(directionPin_M1,HIGH);
      analogWrite (speedPin_M1,rightSpeed);
      digitalWrite(directionPin_M2,LOW);
    }

    void carBack(int leftSpeed,int rightSpeed){             //Move backward
      analogWrite (speedPin_M2,leftSpeed);
      digitalWrite(directionPin_M1,LOW);
      analogWrite (speedPin_M1,rightSpeed);
      digitalWrite(directionPin_M2,LOW);
    }
    void carAdvance(int leftSpeed,int rightSpeed){          //Move forward
      analogWrite (speedPin_M2,leftSpeed);
      digitalWrite(directionPin_M1,HIGH);
      analogWrite (speedPin_M1,rightSpeed);
      digitalWrite(directionPin_M2,HIGH);
    }

After I upload the code, nothing happens. The boards light blinks and then after that nothing occurs. How do I get the Motors moving according to the code in the loop?

body:
To formulate my comments as answer:

Your board has some features involving the motors/servos:

1. Since the PCs USB port cannot provide enough current for the motors, they can be switched off wit the Motor Power Switch. It has to be set to OFF, when you connect the board to an USB port. For operating the motors the board needs it's own power supply (a battery in your case), which can provide enough current. So in this case, you have to switch the Motor Power Switch to ON, to enable the motor drivers. **Attention:** If you turn on the motors while being connected to the USB port, you can damage your board and also your USB port.

2. The motors are connected to the pins 4, 5, 6 and 7. If you don't need the motors, you can use these pins for other purposes. For this, the board let's you disconnect the motor driver from these pins. If the jumpers, that are marked with "Motor Control Terminal Jumpers" in the image on [this documentation page][1], are inserted onto the jumper pin pairs (in the image they are already inserted), the motor drivers will be connected to the mentioned pins. If the jumpers are not inserted there, the motors will not work, since they are not connected to the controlling pins.

---

Note, that you need to use `pinMode(pin_number, OUTPUT);` in the `setup()` function for all pins, that you want to use `digitalWrite()` on, because only this way, the corresponding pin will be set to an output (can only then output a digital signal on `digitalWrite()`). `analogWrite()` will configure the corresponding pin for you, but it is a good practice to set it as OUTPUT in setup anyway, to make it clear for readers, that this pin is an output.

  [1]: https://wiki.dfrobot.com/RoMeo_BLE__SKU_DFR0305_


message:
ESP8266 Bootloader Firmware (on the ESP8266)

It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.  If that firmware is corrupted, the ESP8266 is dead.  I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.  Does anybody know how to do that?  Thank you.

body:
> It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.

Indeed there is.

> If that firmware is corrupted, the ESP8266 is dead.

Well, if that firmware gets corrupted, then yes indeed the chip is dead. That's because the firmware is in ROM, not flash - and the only way it can get corrupted is for the chip to be physically damaged internally.

> I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.

No. They are SPI. SPI has nothing to do with flashing firmware. It just *happens* that AVR chips share the same pins as SPI for their debug protocol.

You cannot replace the bootloader on an ESP8266. It is in ROM. It's unchangeable - except as mentioned earlier by physical trauma to the silicon itself.


message:
I've gotten an error telling me, "expected initializer before 'digitalWrite'"

I should mention that I didn't write this code but got it from [HERE][1].
```
#include<Servo.h>
Servo myservo; // create a servo object
int redled=13; // declare the pins
int greenled=12;

int servopin=9;
int trigpin=6;
int echopin=5;
float distance;
float duration;
int datapin=7;
int clockpin=8;
int latchpin=3;

void setup(){
  Serial.begin(9600);
  pinMode(redled,OUTPUT); // declare the pinmode
  pinMode(greenled,OUTPUT);

  pinMode(servopin,OUTPUT);
  pinMode(trigpin,OUTPUT);
  pinMode(echopin,INPUT);
  pinMode(datapin,OUTPUT);
  pinMode(clockpin,OUTPUT);
  pinMode(latchpin,OUTPUT);
  myservo.attach(servopin); // declare servo object is connected to servo pin

}

int ping() // create a function {
  digitalWrite(trigpin,LOW);
  delayMicroseconds(10);

  digitalWrite(trigpin,HIGH);
  delayMicroseconds(20);
  digitalWrite(trigpin,LOW);

  duration= pulseIn(echopin,HIGH);
  distance= duration*0.034/2; // distance is in cm
  return(distance);
  }

void loop() {
  myservo.write(90); // set servo at 90 degree angle
  float value;
  value=ping(); // call the ping function
  Serial.println(value);
  delay(100);
  if(value>20) {
      digitalWrite(redled,LOW);
      digitalWrite(greenled,HIGH);

      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B01010000); // move the car in forward direction
      digitalWrite(latchpin,HIGH);
  }
  if(value<20&& value>15) {
      digitalWrite(redled,HIGH);
      digitalWrite(greenled,HIGH);

      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B01010000);
      digitalWrite(latchpin,HIGH);
  }
    if(value<15) {
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00000000); // stop the car
      digitalWrite(latchpin,HIGH);
      delay(1000);
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00101000); // first back the robo car
      digitalWrite(latchpin,HIGH);
      delay(1000);
      digitalWrite(latchpin,LOW);
      shiftOut(datapin,clockpin,LSBFIRST,B00000000); // then again stop
      digitalWrite(latchpin,HIGH);
      delay(100);

      go(); // call go function
      delay(2000);
  }

  myservo.write(90);

}

void go() {
  int a;
  int b;
  myservo.write(0);
  delay(1000);
  a=ping();
  myservo.write(180);
  delay(1000);
  b=ping();

  if(a>b) {
   digitalWrite(redled,HIGH);
   digitalWrite(greenled,LOW);

   digitalWrite(latchpin,LOW);
   shiftOut(datapin,clockpin,LSBFIRST,B00010000); // move to the right side
   digitalWrite(latchpin,HIGH);
} else if(a<b) {
    digitalWrite(redled,HIGH);
    digitalWrite(greenled,LOW);

    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B01000000); // move to the left side
    digitalWrite(latchpin,HIGH);
} else if(a=b) {
    digitalWrite(redled,HIGH);
    digitalWrite(greenled,LOW);

    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B00101000); // first back the robo car
    digitalWrite(latchpin,HIGH);
    delay(4000); // wait for 4 seconds
    digitalWrite(latchpin,LOW);
    shiftOut(datapin,clockpin,LSBFIRST,B01000000); // then move to right direction
    digitalWrite(latchpin,HIGH);
    delay(2000);
  }
}
```
The error in full is:
```
sketch_may02a:31:3: error: expected initializer before 'digitalWrite'

   digitalWrite(trigpin,LOW);

   ^

sketch_may02a:32:20: error: expected constructor, destructor, or type conversion before '(' token

   delayMicroseconds(10);

                    ^

sketch_may02a:34:15: error: expected constructor, destructor, or type conversion before '(' token

   digitalWrite(trigpin,HIGH);

               ^

sketch_may02a:35:20: error: expected constructor, destructor, or type conversion before '(' token

   delayMicroseconds(20);

                    ^

sketch_may02a:36:15: error: expected constructor, destructor, or type conversion before '(' token

   digitalWrite(trigpin,LOW);

               ^

sketch_may02a:38:3: error: 'duration' does not name a type

   duration= pulseIn(echopin,HIGH);

   ^

sketch_may02a:39:3: error: 'distance' does not name a type

   distance= duration*0.034/2; // distance is in cm

   ^

sketch_may02a:40:3: error: expected unqualified-id before 'return'

   return(distance);

   ^

sketch_may02a:41:3: error: expected declaration before '}' token

   }

   ^

exit status 1
expected initializer before 'digitalWrite'
```

  [1]: https://create.arduino.cc/projecthub/Aritra_B/obstacle-avoiding-robot-car-b38334?ref=search&ref_id=robot car&offset=23

body:
Your function definition starts:

    int ping() // create a function {

Notice that the comment is inserted **before** the open curly brace. That means the curly brace is commented out. Move the comment to the end of the line, or move the curly brace to a line on it's own.


message:
MD5 hash for Arduino Uno [-Wshift-count-overflow]?

I tried to test out this MD5 library (https://github.com/tzikis/ArduinoMD5 ) as a hash function on arduino uno.

What I have done is that I placed the MD5.cpp and MD5.h to the folder below:
C:\Program Files (x86)\Arduino\libraries\MD5

And launched arduino IDE 1.8.9 to test the example provided (https://github.com/tzikis/ArduinoMD5/blob/master/examples/MD5_Hash/MD5_Hash.ino):

```
#include <MD5.h>
/*
This is en example of how to use my MD5 library. It provides two
easy-to-use methods, one for generating the MD5 hash, and the second
one to generate the hex encoding of the hash, which is frequently used.
*/
void setup()
{
  //initialize serial
  Serial.begin(9600);
  //give it a second
  delay(1000);
  //generate the MD5 hash for our string
  unsigned char* hash=MD5::make_hash("hello world");
  //generate the digest (hex encoding) of our hash
  char *md5str = MD5::make_digest(hash, 16);
  free(hash);
  //print it on our serial monitor
  Serial.println(md5str);
  //Give the Memory back to the System if you run the md5 Hash generation in a loop
  free(md5str);
}

void loop()
{
}

```
However when run verify and compile, it works but got the warnings below:

```
...\sketch_may02a_MD5_test.ino.ino: In function 'void setup()':

sketch_may02a_MD5_test.ino.ino:15:51:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

   unsigned char* hash=MD5::make_hash("hello world");

                                                   ^

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:
In static member function 'static void MD5::MD5Update(void*, const void*, size_t)':

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21:
warning: right shift count >= width of type [-Wshift-count-overflow]

  ctx->hi += size >> 29;

                     ^
```

I know little of c++, can anyone help to fix this? Thanks a lot!!

body:
> ....\sketch_may02a_MD5_test.ino\sketch_may02a_MD5_test.ino.ino:15:51: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

That is a flaw in the library. The author defined the function as taking a `char *` instead of a `const char *`.  You can ignore it, it's just a warning - however maybe raising the issue with the author could be a good idea.

> C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21: warning: right shift count >= width of type [-Wshift-count-overflow]

This one is a little more awkward.  The `size` variable is defined as type `size_t`.  That varies in length depending on the architecture the software is compiled on.  On the 8-bit Arduinos that's a 16 bit variable. On 32-bit Arduinos, like the Due, it's a 32-bit variable.

It is probable that the author developed the library using a 32-bit Arudino (or Arduino-compatible) device - in which case he would never see that warning (since 29 is less than 32).  However anyone that then uses an 8-bit Arduino gets the warning, and probably a corrupt hash.

However, it looks like it should only be a problem if `size` is too big - and it can't be on an 8-bit Arduino. So again you can ignore it, but the author should really be made aware of the issue.


message:
How to increase the serial port's data throughput

I have an array of numbers that will be subtracted from the ADC readings
of a 50 Hz sine wave. Using `Serial.begin(57600);`, I can only
output 25 samples per sine wave cycle, or about 1,250 samples per
second. my questions are:

 1. how fast the increent of array number moves with y++ in my int sinus[]? because when i see on serial monitor with 52700 baudrate it can only show about 25 numbers per cycle (50Hz)
 2. how to increase the speed the increment of y++ in my array?

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

    int sinus[] = {
        70, 72, 83, 92, 108, 132, 157, 182, 207, 230, 243, 255, 255,
        255, 250, 238, 217, 193, 169, 143, 118, 98, 88, 77, 72, 80
    };
    int dataSensor;
    int hasil[26];
    int datasensor2;
    int dataBaru;
    int x;
    int y;
    int intPin = 2;
    int output;
    int output2;
    int toggle;
    int toggle2;
    int z;

    void setup() {
        TCCR1A = 0b00000010;
        TCCR1B = 0b00011100;
        TCCR0A = 0;  //disable millis, delay and mciros
        TCCR0B = 0;
        ICR1 = 3200;

        Serial.begin(57600);

        pinMode(A1, INPUT);
        pinMode(A0, INPUT);
        pinMode(A2, INPUT);
        pinMode(intPin, INPUT);
        pinMode(9, OUTPUT);
        pinMode(10, OUTPUT);

        attachInterrupt(0, genJeah, RISING);
    }

    void genJeah() {  //intrupsi rising
        y = 5;
    }

    void loop() {
        dataSensor = analogRead(A0);
        toggle     = digitalRead(A1);
        toggle2    = digitalRead(A2);
        dataBaru = map(dataSensor, 0, 1023, 0, 255);

        for (x = 0; x < 25; x++) {
            hasil[x] = sinus[x];
        }
        // for (x=0; x<100; x++){

        output = sinus[y] - dataBaru;
        Serial.println(output);
        y++;
        if (y > hasil[26]) {
            y = 0;
        }
    }

body:
If you are looking for throughput then stop sending the ASCII conversion of numbers and just send the numbers.
In other words, use `Serial.write()` rather than `Serial.print()`: you can send ~25k integers per second with a 52k baudrate.

As you are actually remapping the ADC output to a single byte, that means you can easily achieve a 48k/s throughput with this simple change.

If you are also looking for low latency please consider the USB connection is actually packet based, not stream based, which means you will receive the data in chunks, no matter how frequently you write. You can speed it up a bit flushing the channel, at the cost of throughput.


body:
> how fast the increment of array number moves with y++ in my int
> sinus[]?

Incrementing an `int` is fast enough. Even on a slowish Uno, `y++` will
take less than one microsecond to execute, so you can do it a million
times per second if you want...

> when i see on serial monitor with 52700 baudrate it can only show
> about 25 numbers per cycle (50Hz)

Your `loop()` is doing _more_ than `y++`, no it's no wonder it takes
more time!

There are two slow functions there:

* `analogRead()` takes about 110 µs

* `Serial.println()` is initially fast, but once the output buffer is
  full, it runs at the speed of the serial port.

The limiting factor here is `Serial.println()`. You are printing
4.6 bytes on average per sample (2.6 printable characters,
plus CR and LF). Each byte is worth 10 bits on the wire (one start
bit, 8 data bits and one stop bit). That is 46 bits per sample
at 57,600 bits per second. The ratio of these numbers gives the
1,250 samples per second you experienced.

> how to increase the speed the increment of y++ in my array?

It's very hard to answer this question because you did not explain what
you are actually trying to achieve. If I naively take the question at
face value, the simplest option is to just repeat `y++` several times
per loop iteration:

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

    y++;
    y++;
    y++;
    y++;

This can obviously be optimized into

    y += 4;

and the compiler may even be able to figure out this optimization by
itself.

But maybe what you don't care so much about speeding up `y++`, and
instead you want to process more data samples per second? If this is the
case, then you can speed up the loop by speeding up the serial port:

    Serial.begin(115200);

by printing only every other sample (or one sample every _N_):

    static bool print_this_sample;
    if (print_this_sample) {
        Serial.println(output);
    }
    print_this_sample = !print_this_sample;

by printing one sample every so often:

    static uint32_t last_print_time;
    if (millis() - last_print_time >= PRINT_PERIOD) {
        last_print_time += PRINT_PERIOD;
        Serial.println(output);
    }

by printing the samples in binary (first make sure they fit in a byte):

    Serial.write((byte) output);

Now, what _I_ suspect, is that you actually want to get your processing
synchronized with the 50 Hz mains. If this is the case, you will
have to completely rethink your program, and reason about the timings:
at what specific time do you want to take each sample? The Arduino
timing functions (`millis()` and `micros()`) should help.

As you see, half of this answer is me making guesses about what you may
want to achieve. This is a sign of a _very badly_ written question.
Normally it is your job to explain that in detail. Please, rewrite the
question and provide all the necessary background to help us understand
your project, and the difficulties you are facing.


message:
Mega code not compiling on Wemos Mega board

Hi I have some code that I'm trying to port from a Mega 2560 R3 to a Wemos Mega.

    #include "SoftPWM.h"
    #include ESP8266WiFi.h

    // Outputs to PWM & H bridge direction
    // PWMs:
    // DC_pwm, left_pwm, right_pwm = 3, 4, 5
    int pwm_out[] = {3, 4, 5};
    const int num_pwm = sizeof(pwm_out) / sizeof(pwm_out[0]);

    // H bridge direction control:
    // dc_1, dc_2, left_1, left_2, right_1, right_2 = 6, 7, 8, 9, 10, 11
    int dir_pins[] = {6, 7, 8, 9, 10, 11};
    const int num_dir_pins = sizeof(dir_pins) / sizeof(dir_pins[0]);

    // Variable for reading pin inputs
    int from_r_pi_pwm = 0;
    int from_r_pi_dir = 0;

    void setup() {

      // Inputs from Raspberry Pi
      Serial.begin(38400);

      // Set up PWM pins
      SoftPWMBegin();
      for (int i = 0; i < num_pwm; i++)
      {
        SoftPWMSet(pwm_out[i], 0);
      }

      // Set up H bridge direction pins
      for (int i = 0; i < num_dir_pins; i++)
      {
        pinMode(dir_pins[i], OUTPUT);
        digitalWrite(dir_pins[i], LOW);
      }
    }

    void loop() {

      // Check input from R Pi & send it to the H bridges
      while (Serial.available() < 2){}

      if (Serial.available()) {
          // read the incoming bytes:
          from_r_pi_dir = Serial.read();
          from_r_pi_pwm = Serial.read();
          Serial.print("Serial in: directions - ");
          Serial.print(from_r_pi_dir);
          Serial.print(" PWM - ");
          Serial.print(from_r_pi_pwm);
          Serial.println();
      }

      // Set direcions on H bridges
      for (int i = 0; i < num_dir_pins; i++)
      {
        digitalWrite(dir_pins[i], bitRead(from_r_pi_dir, i));
        Serial.print("pin ");
        Serial.print(dir_pins[i]);
        Serial.print(" : ");
        Serial.print(digitalRead(dir_pins[i]));
        Serial.println();
      }

      // PWM to motors
      for (int i = 0; i < num_pwm; i++)
      {
        analogWrite(pwm_out[i], from_r_pi_pwm);
        Serial.print("pin ");
        Serial.print(pwm_out[i]);
        Serial.print(" : ");
        Serial.print(digitalRead(pwm_out[i]));
        Serial.println();
      }
    }

This compiles and runs fine on a Mega & is my go to code for setting up pwm & h bridges.

So when I was playing with WiFi I selected the Wemos R1 board from the programmer & everything worked fine but if I try that with this code I get,

    #include <avr/io.h>
                        ^
    compilation terminated.

    exit status 1 Error compiling for board WeMos D1 R1.

So after a bit of searching I found that I should be selecting `Arduino/Genuino Mega 2560` but now the upload keeps timing out,

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer
    An error occurred while uploading the sketch

Anybody come across this before?

**Edit #1:**  As per the comment below I tried setting DIP switches 1 & 2 ON and all the rest OFF (I also tried 1, 2, 3 & 4 ON and the rest OFF) but still the same compliation error if I select Wemos board.

If I select the Mega 2560 I get `ESP8266WiFi.h: No such file or directory` which is a new error!

body:
The Wemos/Mega board and IDE setup is complex and not for the faint hearted. Here is the table for the DIP switch setting:

    1=ON  2=ON  3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (ATmega2560<->ESP8266)
    1=OFF 2=OFF 3=ON  4=ON  5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)
    1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=ON  8=OFF (USB<->ESP8266 (Update firmware or sketch))
    1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=OFF 8=OFF (USB<->ESP8266 (communication))
    1=OFF 2=OFF 3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (All independent)

Table DIP switch Special Solution:

    1=ON 2=ON 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <-> ATmega2560<-> ESP8266)
    USB converter CH340G connect to RX0/TX0 of ATmega2560
    ESP8266 connect to RX3/TX3 of ATmega25

https://arduino-esp8266.readthedocs.io/en/latest/index.html for ESP8266 documentation.

Set the Additional Boards URL to http://arduino.esp8266.com/stable/package_esp8266com_index.json in preferences

Under Tools select Board then Board Manager, then install the esp8266 by ESP8266 Community

The Arduino IDE setup requires understanding what board setting and communication setting to use to build and upload a sketch.

Under Tools select Board then select the "Arduino/Genuino Mega or Mega 2560"

Set the DIP switches on the actual board to `1=OFF 2=OFF 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)`

That was the DIP switch and USB setup.

Ref. https://forum.arduino.cc/index.php?topic=578430.0

The error `ESP8266WiFi.h: No such file or directory` is easy. The file name should be a string: `#include "ESP8266WiFi.h"`.


message:
No headers (.h) found in Documents\Arduino\libraries\arduino_144469 with demo code

I followed [this][1] tutorial for a demo code for the SR04 ultrasonic distance sensor (without the LCD display). I've installed the Arduino IDE and wrote the code in it and saved it in some location. Compilation of the code is successful. However when I try to upload the code, I get the message:

    Invalid library found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469: no headers files (.h) found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469

There are no header files in the directory and I'm wondering if I need to download additional header files or if I should configure something else.

  [1]: https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/

body:
If the folder is not needed then delete it.

The Arduino IDE uses the folders in the `library` folder to search for library header files (ie. `.h` files). It expects one library in each folder. When it see's a folder without any header files in it, it will count this as an invalid library.


message:
How to get a list of IPs in a LAN using NodeMcu?

I'm going to create an IoT system. I use a Raspberry Pi as a MQTT broker and as a webserver. Every day, the Pi gets a new IP address, so I need to find its new IP address via ESP8266 to use this information in my code. I know that I can use a fixed IP, but I don't want to, so it is better if I can find a solution.

body:
You should use mDNS.  Install (if it isn't already) `avahi-daemon` on your Raspberry.

Then check out the ESP8266mDNS library and the examples it has. Especially the mDNS-SD_Extended example, which performs a query for a service on the network.


message:
nRF24L01 6TXA_1RXA network + 6TXB_1RXB network with arduino

[![nRF24L01 6TXA_1RXA network + 6TXB_1RXB network with arduino][1]][1]

How to build nRF24L01 network shown above with arduino ?
SPI pins are shared between RXA,RXB and separate pins for both CE, CSN, IRQ.

Which nRF24L01 library supports my requirements ?

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

body:
You can use the RF24 library that you can install right away from the Arduino IDE. It provides you all you need. Just use two instances of `RF24` with different CSN and CE pins assigned to get started.

```
RF24 radioA(7, 8); // CE, CSN
RF24 radioB(5, 6); // CE, CSN
```

Use the simple ping sketch as a starting point and add a second radio to it.


message:
ISR definition causing boot loop?

I am trying to compile and upload code to an Arduino Uno from the command-line, however I seem to be experiencing an odd issue.

When I compile this code:

```C
#include <avr/interrupt.h>
#include <stdbool.h>

ISR(TIMER0_OVF_vect) {
}

int main() {
  while (true);
}
```

With these commands:

```
$ avr-gcc -mmcu=atmega328p -DF_CPU=16000000 -std=c17 -O3 -Wall -Wextra -c boot_loop.c -o boot_loop.o
$ avr-gcc boot_loop.o boot_loop.elf
$ avr-objcopy -j .text -j .data -O ihex boot_loop.elf boot_loop.hex
$ avrdude -p atmega328p -c arduino -P /dev/ttyUSB0 -U flash:w:boot_loop.hex
```

My Arduino ends up in a boot loop, flashing the LED 3 times every second or so (similarly to when you press the reset button or the device powers up).

I've tried it without an empty ISR and also with different interrupt vectors (e.g. `TIMER0_COMPA_vect`) but to no avail. Completely removing the ISR definition stops the boot loop.

body:
Your problem is not with your code. It's with how you're linking your elf file.

You haven't specified the chip to link for.

    $ avr-gcc -mmcu=atmega328p boot_loop.o -o boot_loop.elf


message:
Using LDR and RGB Led to get R,G,B values

Has anyone tried using a setup of RGB LED directed to cuvette and the LDR on the opposite side? using arduino to and get the RGB values..

Currently having problems with calibration... I was able to get R,G,B values of colored papers... however with colored liquids inside a cuvette I'm not getting any good results (i.e the Red/Blue/Green values goes way up like 5000++)

Used white and black paper for callibration..

No idea for liquid...

body:
Your are probably doing the white calibration with some clear liquid,
like water. The LDR is then lit directly by the LEDs, and is getting too
much light. It's resistance is then very low compared to the pull-down
resistor in series with it. You end up measuring something very close to
5 V.

You should try to reduce the amount of light hitting the LDR. A neutral
density filter (the kind used in photography) would be ideal.
Alternatively, you could increase the distance between the LEDs and the
LDR, and put some translucent paper in between. You could also add a
diaphragm (a small hole). Then, you can also lower the resistance of the
pull-down in order to get lower voltage readings, but beware not to draw
too much current.

A comment about the instructable you linked to: owing to the highly
non-linear characteristic of the readings you get, it is quite likely
that you get unequal RGB vales from a neutral grey. Some kind of
linearization (estimating actual light fluxes) would be needed if you
want neutral greys to be measured as neutral greys.


message:
Can I program a factory fresh Atmega328P through UART pins without burning a bootloader?

Can I program a factory fresh ATMega328P using the UART pins without burning a bootloader? These pins are TX, RX, VCC, GND, and DTR pins in the schematic below. They are *not* the ISP/SPI pins 10-13.

[Arduino Pro Mini schematic][1]

For example, if you program an Arduino Pro Mini (which requires an ICSP programmer) with a programmer, you're not connected to the ISP pins (basically the SPI interface: MOSI, MISO, SCLK, SS), but rather to the serial i/o and reset pins.

My understanding is that a bootloader *is* required if you want to program through these pins, because the Arduino bootloader looks for UART traffic at these pins upon startup and hands off operation to the user's code if no attempt at programming happens during this time.

That said, I also understand burning a bootloader is done through the ISP/SPI pins, and my PCB is already manufactured, which makes burning a boatloader somewhat of a hassle. So...

Can I program an ATMega328P through the UART pins fresh off the reel, or will I need rig up a way to burn a bootloader through the ISP pins first?

[1]: https://cdn.sparkfun.com/assets/0/7/5/5/1/51eec304ce395f104c000000.png

body:
No, the ATmega's ISP does not operate over the UART pins but only the ISP pins.

To program it via a UART, you need to first load a bootloader, unless your chip was pre-programmed by the vendor, something some offer as a value-added service (or even as an essential stock item, with an Arduino type bootloader)


message:
Arduino not responding to macbook pro

When I try to upload my code onto the Arduino it just gives me the error message: "avrdude: ser_open(): can't open device "/dev/cu.usbmodem14201": No such file or directory
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions."

My Arduino used to function just fine. Now when a plug it in, the lights on the Arduino do not blink like they used to, and the only pins that do anything are the ones to power. It also said something like: Arduino is not optimized for mac os. It seems that the Arduino is taking in the power but not the code. here's the code:

    int led = 13; // the pin the LED is connected to
    void setup() {
      pinMode(led, OUTPUT); // Declare the LED as an output
    }

    void loop() {
      digitalWrite(led, HIGH); // Turn the LED on
    }

body:
I had this issue and it was because the port was not set in my Arduino IDE.

I fixed it by going to Tools -> Port, and selecting my usb device.  In my case it was called /dev/cu.SLAB_USBtoUART


body:
I fixed it by plugging it into my other USB port (which I had previously been using)

So possibly this is caused by switching USB ports


message:
Connecting a push button to a stepper motor problem

I can't get this code to work. The button code and the step motor code works separately. However, when I code using an if statement saying when the button is pressed the motor will move or else it won't. PLEASE HELP.

```c++
const int buttonPin = 7;

int buttonState = 0;
int serialData = 0;

#define IN_1 8
#define IN_2 9
#define IN_3 10
#define IN_4 11
#define DELAY_TIME 30

int i = 0;

void setup() {
  Serial.begin(9600);
  pinMode(IN_1, OUTPUT);
  pinMode(IN_2, OUTPUT);
  pinMode(IN_3, OUTPUT);
  pinMode(IN_4, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.print ("start");
}

void loop() {
  buttonState = digitalRead (buttonPin);
  if (buttonState == HIGH) {
    //delay(1000);
    for (i=0; i<4; i++)
      Serial.println ("pressed");
    switch (i) {
      case 3: // ASCII value for '1'
        digitalWrite(IN_1, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_1, LOW);
        break;
      case 1: // ASCII value for '2'
        digitalWrite(IN_2, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_2, LOW);
        break;
      case 0: // ASCII value for '3'
        digitalWrite(IN_3, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_3, LOW);
        break;
      case 2: // ASCII value for '4'
        digitalWrite(IN_4, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_4, LOW);
        break;
      default:
        Serial.println("Not a valid case");
        break;
    }
    if (i == 4) {
      i = 0;
    } else {
      i = 5;
    }
  }
}
```

body:
Your code makes no sense at all.  Let's break it down. First we'll reformat the code using the auto-formatter (AStyle) in UECIDE:

    const int buttonPin = 7;

    int buttonState = 0;
    int serialData = 0;

    #define IN_1 8
    #define IN_2 9
    #define IN_3 10
    #define IN_4 11
    #define DELAY_TIME 30
    int i = 0;

    void setup()

    {
     Serial.begin(9600);
     pinMode(IN_1, OUTPUT);
     pinMode(IN_2, OUTPUT);
     pinMode(IN_3, OUTPUT);
     pinMode(IN_4, OUTPUT);
     pinMode(buttonPin, INPUT);
     Serial.print("start");
    }

    void loop()

    {
     buttonState = digitalRead(buttonPin);

     if (buttonState == HIGH) {
    //delay(1000);
      for (i = 0; i < 4; i++) {
       Serial.println("pressed");
      }

      switch (i) {
       case 3: // ASCII  value for '1'
        digitalWrite(IN_1, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_1, LOW);
        break;

       case 1: // ASCII  value for '2'
        digitalWrite(IN_2, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_2, LOW);
        break;

       case 0: // ASCII  value for '3'
        digitalWrite(IN_3, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_3, LOW);
        break;

       case 2: // ASCII  value for '4'
        digitalWrite(IN_4, HIGH);
        delay(DELAY_TIME);
        digitalWrite(IN_4, LOW);
        break;

       default:
        Serial.println("Not a valid case");
        break;
      }

      if (i == 4) {
       i = 0;
      } else {
       i = 5;
      }
     }
    }

Now that we have fixed the formatting we can see some very strange things:

    if (buttonState == HIGH) {

First we're doing this for every loop iteration where the button is pressed. That means we're doing it over and over again until you release the button.

        for (i = 0; i < 4; i++) {
            Serial.println("pressed");
        }

Now we're printing the word "pressed" four times.  After this `i` will be set to 4.

The `switch` will now take an input value of 4, which is "Not a valid case". So nothing will happen.

Then:

        if (i == 4) {
            i = 0;
        } else {
            i = 5;
        }

`i` is always 4, so it will always set it to 0.  Quite what this block is supposed to achieve I have no clue. If it were supposed to be inside the `for` loop above then it would just kill the loop on the first iteration, since `i`, when 0, would not be 4, so would be changed to 5, which is > 4. It makes no sense and can achieve nothing of value.

As for the `switch`: if it were inside the `for` loop and able to get some varying values of `i`, it would just make each output briefly activate in turn. If that's what you need to drive your motor, then fine. However, it's never going to run since the rest of the program is just nonsense.


message:
Receive Signal from different circuit

I am an mid experienced Programmer but I have no clue about electronic circuits. I want my Arduino to do sth if he gets a signal from an external source. The external source has 5V and is 0V or 5V and when it has 5V I want my Arduino to send me a Message, the Code for the Message is no problem, but please help me with the circuit:
The external source is independent and runs on battery and the device has a 2.5mm jack, normally there is an LED attached that lights up, but I want my Arduino to receive the signal. Are there any opportunities for realising this?
Thank you for your help

body:
Unless there are exceptional circumstances you can just connect the two ground connections together. Then the 5V of your other circuit will be the same voltage as the 5V of the Arduino and you can just connect your signal direct to an input.

However, if there are exceptional circumstances (ground isn't really ground, for example) then you can use an opto-coupler to act like an optically-controlled button:

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

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

<!-- End schematic -->

R1 can be replaced by the internal pullup resistor of the Arduino by setting the pinMode to INPUT_PULLUP.

Note that this inverts the logic of the input: a HIGH input signal is detected on the Arduino as a LOW logic level, and vice versa.


body: the external source is an indicator that sends a 5V signal via a 2.5mm mono jack, I think this just has +&- so no ground. But I only need to measure if it is on or off, not the intensity


message:
PIR motion sensor (HC-SR501) false results with NodeMCU

I have a PIR sensor which I use to detect the motion and turn ON and OFF the lights on the basis of it.

I have PIR connected with NodeMCU (ESP8266) based board. I find that sometimes it trigger false positive value. Even when there is no motion. As per my understanding I think any of the following reasons can be there:

 1. I have NodeMCU close to it. So may be because NodeMCU heatness triggers it.
 2. Some hot air blow near it. But I don't know. It trigger the false positive even in mid-night.
 3. It can be trigger by mosquitoes.
 4. I have my other electric wires going from near by.

I am considering these scenarios correct? If yes then how can I prevent from them?

I tried to put it in a box and make it tightly pack. but still its false trigger. I checked even with multiple sensors and have same problem.

**Any suggestions to protect this?** I also check people put capacitor to smooth it. And put some resistance on Vin.

My Vin of PIR is connected to 5v and OUTPUT pin to D2.

For reference I am having this code for checking.
<!-- language-all: lang-cpp -->

    #define SIGNAL_PIN D2

    void setup()
    {
      Serial.begin(115200);
      pinMode(SIGNAL_PIN, INPUT_PULLUP);
    //  digitalWrite (SIGNAL_PIN, LOW);
    }

    void loop() {

        static uint32_t lastSeenHigh = millis();
        static bool pirState = false;
        Serial.println(digitalRead(SIGNAL_PIN));

        // If it's active then record that fact along with the time
        if (digitalRead(SIGNAL_PIN) == HIGH) {
            lastSeenHigh = millis();
            pirState = true;
        } else {
            if ((millis() - lastSeenHigh) > 10000) {
                pirState = false;
            }
        }

        if (pirState == true) {
            Serial.println("Pir Is active");
        }
    //
        if (pirState == false) {
          Serial.println("PIR sensor inactive");
        }
        delay(1000);
    }

body: I had the same issue. PIRs have very sensitive circuitry and can be triggered by the WiFi signal from the ESP8266. The answer is to move them apart and with some decoupling of the power supply lines you should see much better performance. My PIR and ESP are now a couple of metres apart and I use shielded cable to connect them together.


body:
I had the same issue. I tried various solutions on the net. Finally i solved my issue like this.

- Supplied the PIR sensor 3.3 v (from the NodeMcu board) instead of 5v (my main PS is 5V)
- Connected VCC (3.3v) cable to "HIGH PIN" of trigger pins instead of main (+) pin.
- It's not generate false positive signals about 2 hours.

Actually, I'm applied that solution -> https://www.youtube.com/watch?v=2HbbQIqJHoE


body:
I was also going through the same issue. But finally, the issue got resolved.

The issue is the PIR sensor that comes with ESP8266 can work with 3.3V as well as 5V.
By default, the wiring is connected to the 5V which may work fine for the Arduino device but not for ESP8266.

I just removed the red cable (power cable) from the connector and connected to the other side where you can see H. That side also there are 3 pins.
Remove the jumper completely and connect to the first PIN from top.

Just make sure you leave the GND and OUTPUT as it is, but only the RED wire will be connected to the first pin on the other side of the PIR sensor[![please see the attached image][1]][1].

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


body: I glued some aluminum foil onto a piece of a cereal box and folded it around the PIR sensor. Works like a charm!


message:
How can I run the arduino IDE 1.8.9 on debian testing as regular user?

When I start the arduino IDE as regular user from my debian testing system, I get a crash right after the splash screen:

```
Temp/arduino-1.8.9/arduino                                                              :)
Picked up JAVA_TOOL_OPTIONS:
java.lang.NullPointerException
        at processing.app.BaseNoGui.onBoardOrPortChange(BaseNoGui.java:679)
        at processing.app.Base.onBoardOrPortChange(Base.java:1317)
        at processing.app.Base$12.actionPerformed(Base.java:1544)
        at processing.app.Base.rebuildBoardsMenu(Base.java:1494)
        at processing.app.Base.<init>(Base.java:275)
        at processing.app.Base.main(Base.java:151)
Temp/arduino-1.8.9/arduino  7,28s user 0,50s system 183% cpu 4,243 total
```

When I start it with `sudo` I can use everything regularly. There are quite a few bug reports mainly in the archlinux community about a similar issue, where they suggest to install a package `arduino-avr-core` to solve it. But I assume, the reason why it happens for me, is different, since it runs fine with root privileges, and we do not have such a package in debian. Debians arduino IDE from the repos is way to old to use it these days with modern boards.

My Groups: `tty uucp dialout cdrom floppy sudo audio dip video plugdev systemd-journal netdev bluetooth lpadmin scanner docker`

The file permissions are fine for the ide and the arduino data directory.

The permissions for the usb device are also correct, just in case:`crw-rw----+ 1 root dialout 188, 0 Mai  4 11:42 /dev/ttyUSB0`

My Java environment:

```
java --version                                                                          :)
openjdk 11.0.3 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+1-Debian-1)
OpenJDK 64-Bit Server VM (build 11.0.3+1-Debian-1, mixed mode, sharing)
```

Maybe someone ran into the same problem as well?

body: It turned out, that the current Arduino IDE is using a directory `~/.arduino15` for data. I was not aware of the existence of it. The comments to my question made that clear. I tried to delete the `~/Arduino` and `~/.arduino` direcory several times, but to no avail. Deleting `~/.arduino15` indeed fixed the issue.


message:
How to read this hmackey for arduino?

I understand the HMAC with SHA256 example provides a set of keys:
(https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde)

```
#include "sha256.h"
uint8_t hmacKey1[]={
  0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,
0x0b,0x0b,0x0b,0x0b,0x0b,0x0b,0x0b
};
uint8_t hmacKey2[]={
  0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,
0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19
};
...
```

I did a bit research and have a sense that these keys are in hexadecimal form with 0x added as prefix. If I like to use my own key, like a string, abece123*, do I just convert the key string to hex?

I tried to use this site below to convert above hmacKey2 to see what the key may look like. But the result is not recognizable. Here's what I did: copy and past
```
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,
0x0f,0x10,0x11,0x12,0x13,0x14, 0x15,0x16,0x17,0x18,0x19
```
to the site below to convert to string.
https://codebeautify.org/hex-string-converter

I am very new to this field. Please help me understand how these key works and and the steps needed to replace one of the preset hmac keys with my own key string (e.g. abece123*). Thanks.

body:
Those are examples for keys. You need one key and you can choose any text with any length.

Did you see this line in the example:

    sha.initHmac((uint8_t*)"Jefe",4);

It uses the key "Jefe" with a length of 4.
You can use your own key, but you also need the length.

    char myKey[] = "abece123*";
    int length = strlen(myKey);
    sha.initHmac((uint8_t*)myKey, length);


message:
Serial input help

Hey guys I have a LED strip with 6 LEDS
(I control these through Kinect & processing. It sends 1,2,3,4,5,6 to Arduino. This seems to work fine.)

In Arduino LED0,LED1,LED2,LED3,LED4 work perfectly but the last one don't work. it doesn't light up at all.

Anyone know what's going on?

```

#include <FastLED.h>

#define LED_PIN     13
#define NUM_LEDS    6

CRGB leds[NUM_LEDS];

void setup() {

  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  Serial.begin(9600);

}

void loop() {

  if (Serial.available() > 0) {
int incomingByte = Serial.read();

  //1
if(incomingByte=='1'){
  leds[0] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[0] = CRGB(0, 0, 0);
  FastLED.show();}

 //2
 if(incomingByte=='1'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[1] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
  if(incomingByte=='4'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[1] = CRGB(0, 0, 0);
  FastLED.show();}

  //3
   if(incomingByte=='1'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[2] = CRGB(255, 0, 0);
  FastLED.show();}
   if(incomingByte=='4'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[2] = CRGB(0, 0, 0);
  FastLED.show();}

  //4
   if(incomingByte=='1'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
    if(incomingByte=='4'){
  leds[3] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[3] = CRGB(0, 0, 0);
  FastLED.show();}

  //5
   if(incomingByte=='1'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='2'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[4] = CRGB(255, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[4] = CRGB(0, 0, 0);
  FastLED.show();}

  //6
   if(incomingByte=='1'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();
if(incomingByte=='2'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='3'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='4'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='5'){
  leds[5] = CRGB(0, 0, 0);
  FastLED.show();}
if(incomingByte=='6'){
  leds[5] = CRGB(255, 0, 0);
  FastLED.show();}

}
  }
}

```
here's the processing code:

```
float x = 100;
float y = 50;
float w = 150;
float h = 80;

import org.openkinect.freenect.*;
import org.openkinect.processing.*;
import processing.serial.*;

// The kinect stuff is happening in another class
KinectTracker tracker;
Kinect kinect;
Serial myPort;

void setup() {
  size(512, 424);
  kinect = new Kinect(this);
  tracker = new KinectTracker();
  String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}

void draw() {

  tracker.track();
  tracker.display();

  PVector v1 = tracker.getPos();
  fill(50, 100, 250, 200);
  noStroke();
  ellipse(v1.x, v1.y, 50, 50);

   //1
    if (v1.x > 0 && v1.x < 50 ){
    println('1');
    //rect(0,200,200,200);
    myPort.write('1'); }
    //println('0'); }

    //2
  if (v1.x > 50 && v1.x < 100){
    println('2');
    myPort.write('2'); }
 //3
   if (v1.x > 100 && v1.x < 150 ){
    println('3');
    myPort.write('3'); }

    //4
   if (v1.x > 150 && v1.x < 200 ){
    println('4');
   myPort.write('4'); }

    //5
   if (v1.x > 200 && v1.x < 250 ){
    println('5');
    myPort.write('5'); }

    //6
   if (v1.x > 250 && v1.x < 300 ){
    println('6');
    myPort.write('6'); }

}

```

body:
Your problem lies in the position of the closing bracket of the first if statement for LED 6:

    //6
    if(incomingByte=='1'){
      leds[5] = CRGB(0, 0, 0);
      FastLED.show();         // here the closing bracket is missing
    if(incomingByte=='2'){
      leds[5] = CRGB(0, 0, 0);
      FastLED.show();}
    if(incomingByte=='3'){
      leds[5] = CRGB(0, 0, 0);
      FastLED.show();}
    if(incomingByte=='4'){
      leds[5] = CRGB(0, 0, 0);
      FastLED.show();}
    if(incomingByte=='5'){
      leds[5] = CRGB(0, 0, 0);
      FastLED.show();}
    if(incomingByte=='6'){
      leds[5] = CRGB(255, 0, 0);
      FastLED.show();}

    } // this is the missing closing bracket
      }
    }

This means, that this whole block will only be executed, when `incomingByte` has the value `'1'`. This also means, that the last if statement will never be executed. Correct the position of the marked closing bracket and it should work.

---

Besides that, your code is a very complicated way of doing this. Why not simply switching the `incomingByte`? Also, to write less code and making it more understandable, use a function to turn all LEDs to off ("resetting" them):

    void reset_LEDs(){
        for(int i=0;i<NUM_LEDS;i++){
            leds[i] = 0;
        }
    }

    void loop(){
    if (Serial.available() > 0) {
        int incomingByte = Serial.read();

        switch(incomingByte){
            case '1':
                reset_LEDs();
                leds[0] = CRGB(255, 0, 0);
                break;
            case '2':
                reset_LEDs();
                leds[1] = CRGB(255, 0, 0);
                break;
            ...
        }
        FastLED.show();
    }
    }

When you stay with such easy conditions, you can even optimize more:

int incomingByte = Serial.read() - '0'; //Convert ASCII character value to decimal int value, by subtracting the ASCII value of zero

    if(incomingByte > 0 && incomingByte <= NUM_LEDS){ //Test, if the incomingByte lies between 1 and NUM_LEDS including
        reset_LEDs();
        leds[incomingByte - 1] = CRGB(255, 0, 0); // -1 because array counting starts with 0, we start counting with 1
        FastLED.show();
    }

For both versions, you save time, because you we only call `FastLED.show()´ once, when a change happens, not multiple times.


message:
Generating variable frequency of 3 phase SPWM

I got a sample of program to generate 3 phase SPWM from this https://arduino.stackexchange.com/questions/59925/controlling-output-frequency-of-3-phase-spwm-inverter. As far as I understood, the frequency generated is constant. My question is how can I make it a variable frequency generated? I am using Arduino mega right now.

body: I've edited the code in that post to my latest code! I suggest you take a look at the signal on proteus scope, but first try to filter all signals with 1K ohm resistor and 0.37uF capacitor connected in series. Put your scope probe at the end of resistor. Hope that will help!


message:
Using Servo on Timer3 on a Leonardo

I would like to use the Radiohead library and control a servo from the same Leonardo board.

Now the Radiohead library occupies `timer1` and therefore cant be used together with the `servo` library. (It does offer to use `timer2` which the Leonardo does not have.)

Are there any other Servo libraries that use `timer3` or `timer4` which the Leonardo has?

I have already tried:

* https://github.com/nabontra/ServoTimer2  does not compile
* https://www.pjrc.com/teensy/td_libs_TimerOne.html does not work (calling function blocks)

body:
I wonder if you could use this PWM version of the Servo library written for the Arduino MEGA? Looking at the code, it looks like you would have to remove the "else if (pin == 44)" and "else if (pin == 45)" blocks of code in the attach() and detach() functions in Update Servo_Hardware_PWM.cpp. Just guessing here. I haven't tried it out.

https://github.com/dadul96/Arduino-Servo-Hardware-PWM-Library


body:
You could try manually sending the servo pulses with something like:

    digitalWrite(SERVOPIN,HIGH);
    delayMicroseconds(pulseWidth);
    digitalWrite(SERVOPIN,LOW);

As long as the duration of the pulses is consistent, it doesn't matter if they don't occur regularly.

Downsides will be that there may be jitter if there are interrupts running, although there is the advantage that this will work on just about any pin.

If you are looking for a simple proof of concept, this may enough to test it out.


body:
In file `ServoTimers.h`in standard Arduino Servo library change the timer

    #elif defined(__AVR_ATmega32U4__)
    #define _useTimer3
    typedef enum { _timer3, _Nbr_16timers } timer16_Sequence_t;

on Windows the file `ServoTimers.h` is located in `C:\Program Files (x86)\Arduino\libraries\Servo\src\avr`


message:
There's an error I don't know how to fix

I basically have a bread board with an rgb led and a peizo buzzer with a photocell.

I have the codes for both. If I put a code for the rgb, it works. If I put the code for the peizo, it works. Once I paste both codes onto it it says there's an error because "void setup" and "void loop" are already defined. What do I do to get both things to work?

rgb led code:

    /*
    Adafruit Arduino - Lesson 7. RGB Fader
    */
    int redLEDPin = 11;
    int greenLEDPin = 10;
    int blueLEDPin = 9;
    int redSwitchPin = 7;
    int greenSwitchPin = 6;
    int blueSwitchPin = 5;
    int red = 0;
    int blue = 0;
    int green = 0;

    void setup()
    {
      pinMode(redLEDPin, OUTPUT);
      pinMode(greenLEDPin, OUTPUT);
      pinMode(blueLEDPin, OUTPUT);
      pinMode(redSwitchPin, INPUT_PULLUP);
      pinMode(greenSwitchPin, INPUT_PULLUP);
      pinMode(blueSwitchPin, INPUT_PULLUP);
    }

    void loop()
    {
      if (digitalRead(redSwitchPin) == LOW)
      {
        red ++;
        if (red > 255) red = 0;
      }
      if (digitalRead(greenSwitchPin) == LOW)
      {
        green ++;
        if (green > 255) green = 0;
      }
      if (digitalRead(blueSwitchPin) == LOW)
      {
        blue ++;
        if (blue > 255) blue = 0;
      }
      analogWrite(redLEDPin, red);
      analogWrite(greenLEDPin, green);
      analogWrite(blueLEDPin, blue);
      delay(10);
    }

peizo code:

    int speakerPin = 12;
    int photocellPin = 0;

    void setup()
    {
    }

    void loop()
    {
      int reading = analogRead(photocellPin);
      int pitch = 200 + reading / 4;
      tone(speakerPin, pitch);
    }

body:
Putting all other possible issues aside such as pin and timing conflicts.

Rename the sketch `setup()` and `loop()` functions, for instance, `rgb_led_setup()` and `rgb_led_loop()`, and `peizo_setup()` and `peizo_loop()`, then rewrite:

    void setup() {
      rgb_led_setup();
      peizo_setup();
    }

    void loop() {
      rgb_led_loop();
      peizo_loop();
    }

Cheers!


message:
Motor isnt spinning when using L298N motor controller

[![enter image description here][1]][1]I have a L298 motor controller connected to a motor with a 6 volt power sources. the motor however isn't spinning any ideas I'm using a esp 8266 node mcu board. I would like to use pwm but for right now I'm just trying to get it to work so I disabled the pwm.

    //int d0 = 16;
    const int d0 = 16;
    const int d4 = 2;

    //=======================================================================
    //                    Power on setup
    //=======================================================================
    void setup() {
      Serial.begin(115200);
      pinMode(d0,OUTPUT);
      //pinMode(d1,OUTPUT);
      pinMode(d4,OUTPUT);
    }

    //=======================================================================
    //                    Main Program Loop
    //=======================================================================
    void loop() {
      //PWM Value varries from 0 to 1023
      Serial.println("10 % PWM");
      //analogWrite(d0,102);
      digitalWrite(d0,HIGH);
      digitalWrite(d4,LOW);
      delay(2000);

      Serial.println("20 % PWM");
      //analogWrite(d0,205);
      digitalWrite(d0,HIGH);
      digitalWrite(d4,LOW);
      delay(2000);

      Serial.println("40 % PWM");
      //analogWrite(d0,410);
      digitalWrite(d0,HIGH);
      digitalWrite(d4,LOW);
      delay(2000);

      Serial.println("70 % PWM");
      //analogWrite(d0,714);
      digitalWrite(d0,HIGH);
      digitalWrite(d4,LOW);
      delay(2000);

      Serial.println("100 % PWM");
      //analogWrite(d0,1024);
      digitalWrite(d0,HIGH);
      digitalWrite(d4,LOW);
      delay(2000);

    }

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

body:
You need two supply voltages for this board to work: motor supply, which goes directly to your motor (up to 35V for this L298N board, depends on what your motor needs), and logic supply of 5V, which powers the board's logic chips. If the motor supply voltage is between 7V and 12V, you can derive 5V logic supply from motor supply by enabling this board's built-in linear regulator.

* The actual motor power supply should be connected to the `VCC` terminal of the L298N board you have in your picture. This is the **leftmost** terminal in the block of 3 in the picture (sometimes it is labeled `+12V` instead of `VCC`). In your case it is not connected to anything at all. This is already wrong.

* It is not clear what the purpose of the red wire is in your picture.

 In your comments you mention different voltages of motor power supply (6V in one place, 9V in another...). If you are feeding this board 9V through the red wire, you are doing it wrong. The rightmost terminal in the block of 3 is the `5V` pin. Don't attempt to feed more than 5V to that pin.

 If you'll be using the red wire to supply 5V logic power **to** the L298N board from an external source, then you need to disable this board's own linear regulator - remove the jumper that is shown above the 3-terminal block.

 If you'll decide to use it to supply 5V logic power **from** the L298N board (e.g. to your Arduino), then you have to keep the jumper.

 In any case, the leftmost terminal has to be connected to motor power supply.


message:
ESP8266 I2C datasheet pins not the same as several examples

According to espressif datasheet of the ESP8266 it uses
MTMS (I2C_SCL) and GPIO2(I2C_SDA) for I2C.

However in several examples I've seen the typically use is GPIO(4&5) or GPIO(0&4) to connect to the I2C.
I guess all method works? but what is the real difference?

body:
Many modules don't have the right pins for I2C available. Thus it was decided that the sensible option would be to use a bit-banged implementation of I2C using software only.

Also GPIO2 has a special meaning for booting, and using it is risky at best, and should be avoided.

Doing it 100% in software has the advantage that any pin combination can be used for I2C.


message:
Nodemcu ESP12-E (ESP8266), Can I reprogramming when the UART pins are defined as GPIO?

I wonder if there may be any problems using the pins that the UART are using as GPIOs, if now I want to be able to reprogram the circuit?
(Of course I will detach the ESP12-E from the mainboard before so)

body:
Sure, you *can* use the UART pins as general purpose IO pins - however, it's far from ideal - for one simple reason:

* The ROM issues messages on the UART at boot time.

This means that when you power the chip up whatever is connected to the UART TX pin will receive pulses of HIGH and LOW.

That may or may not be a problem, depending on what is connected. It's something you need to bear in mind though.