# Question
Title: 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.

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

```
// 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, 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.

# Answer
> 1 votes
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)

---
Tags: arduino-mega, interrupt, timers
---


# Question
Title: 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.

# Answer
> 1 votes
Consider using what is commonly called in programming as a Finite-state machine. 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 or in software. 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.

---
Tags: lcd, button
---


# Question
Title: 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 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
}

```

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

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

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

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

```
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.
> 3 votes

---
Tags: class, isr
---


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

text:
# Question
Title: 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 ???

# Answer
> 2 votes
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.

# Answer
> 1 votes
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.

# Answer
> 1 votes
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)

---
Tags: esp8266, arduino-ide
---


title: Arduino freezing with OLED display

text:
# Question
Title: Arduino freezing with OLED display
I have a 0.96" `OLED` display hooked up to my `Arduino` `Mega` via `SPI`. I installed the `Adafruit` library and GFX library. I can run through the little graphical demo from `Adafruit` just fine as well as display static text with no problem.

However, I am trying to put together a project I thought would be simple and straight forward. I am trying to use a `DHT22` to collect temperature and humidity and then display it on the `OLED`. The problem I am running into is that the `Arduino` freezes after an indeterminate amount of time. The most it has been able to run is about 6 minutes.

Here is the code I am using:

```
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>

#define DHTPIN 7
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// If using software SPI (the default case):
#define OLED_MOSI   8
#define OLED_CLK   9
#define OLED_DC    10
#define OLED_CS    11
#define OLED_RESET 12
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH  16

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

long previousMillis = 0;
long interval = 5000;

    String temperature;
    String humidity;

void setup(){
  dht.begin();

  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC);

  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);

  display.println(" Madgayrah");
  display.display();
  while(millis()<2000);
}

void loop() {

  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;

    float h = dht.readHumidity();
    float f = dht.readTemperature(true);

    if(isnan(h) || isnan(f)){
      int x = 6;
      String dashes = "";
      for(int y=1; y<=x; y++){
        dashes += "-";
      }
      temperature = humidity = dashes;
    }else{
      temperature = String(f)+(char)248;
      humidity = String(h)+"%";
    }

    display.clearDisplay();
    display.setTextColor(WHITE);
    display.setCursor(0,0);

    display.setTextSize(1);
    display.println(String(previousMillis/1000));
    display.println("");

    display.println("Temperature:");
    display.setTextSize(2);
    display.println(temperature);

    display.setTextSize(1);
    display.println("Humidity:");
    display.setTextSize(2);
    display.println(humidity);

    display.display();
  }
}

```

In my attempt at debugging I discovered that NOT printing out the temperature and humidity variables allows the program to run indefinitely. However, for some reason turning on either one of those lines and printing out that variable leads to the issue of the `Arduino` freezing.

ADDITIONAL INFORMATION: I am using a 12 volt external power supply hooked up to the barrel of the `Mega`. The Mega is providing 5 volts and ground to a bread board which powers/grounds both the `OLED` and the `DHT22`.

Any ideas as to what could be causing the freezing issue on what "should be" a simple and straightforward project? Thanks.

# Answer
Because your program uses various `String` objects in several different sizes, there's a good chance that heap memory (in RAM) is getting fragmented to the point that `String` allocation begins to fail, or begins to allocate on top of stack variables. (Typically, heap and stack work toward each other, from opposite ends of memory that is free after static variables are allocated.)

For example, the code `for(int y=1; y<=x; y++){ dashes += "-"; }` with `x=6` creates half a dozen `String` objects, all of different lengths.

To avoid this problem, you could carefully release each heap allocated object when done with it, or more effectively, could avoid using `String` objects, which actually aren't needed in this program.

For example, instead of `display.println(String(previousMillis/1000));` say `display.println(previousMillis/1000);` and instead of building `dashes` a character at a time before using it, just say `"------"` in place of `dashes`.
> 5 votes

# Answer
I had exact same problem and james's answer helped me realize the problem is related to heap memory.

In addition to what he has already commended, I found here that you should also wrap all your constant strings in F() function.

For example instead of

```
display.println(" Madgayrah");

```

You write

```
display.println(F(" Madgayrah"));

```

This will store the string in the flash memory instead of SRAM.

Also if you only use OLED display for printing text, I strongly recommend the more lightweight SSD1306Ascii library

It output text to oled display without buffering which causes slight flickering but massively reduce the amount of memory required to drive the OLED.

Another helpful tip is to use arduino's watchdog. Basically after you enable that you need to constantly call `wdt_reset();` function and if you failed to call it for certain amount of seconds, arduino will automatically reset.
> 1 votes

---
Tags: arduino-mega, temperature-sensor, display
---


# Question
Title: For Arduino Uno it is possible to use the digital pins with PWM to read analog data, is this also possible with the Wemos D1 Mini?
I want to read out data from a load cell, for this I seem to need 2 analog input pins, the Wemos doesn't have this. In the Arduino I was also able to use the digital pint with PWM, there are also Wemos pins who have that. Is it possible to use them to read the data from the load cell?

# Answer
> 1 votes
PWM is quasi-analog **output**, and they have no symmetric analog read function.

The ESP8266 that is the heart of the Wemos D1 Mini has only 1 analog input.

If you need to read 2 analog signals, you can use an analog switch/multiplexer to read one value, and then the other value in quick succession. Or you can purchase an external ADC with multiple inputs -- these often communicate with a host by SPI or I2C connection, which the Wemos supports.

# Answer
> 1 votes
There is one way you *could* measure analogue voltages using a PWM output: Use it as a DAC to build your own Successive Approximation ADC:

* The PWM is filtered through a low-pass filter to create an analogue voltage
* That is compared to an incoming voltage using a comparator
* The output of the comparator is recorded for different reference voltages using a "divide and conquer" method.

You can read more about how Successive Approximation works here.

However, doing that would be overly complex and needlessly expensive. It is far better to just add an ADC chip using I2C or SPI. It's cheaper, easier, and the results will be far superior.

But as a learning exercise to discover how ADCs work, it could be kind of fun.

# Answer
> 1 votes
You can use a capacitor and resistor to build a simple circuit to turn a voltage into a time duration, then precisely measure the timing to get a voltage. This isn't as fast as a direct read, but it can be more precise in some cases, and the sampling might be fast enough for your needs. The cost is great compared with external or home-brew ADCs. I once used this method to build an ohmmeter with an ESP-01, which had a much greater range than a naive voltage divider would have provided.

You feed your voltage through a resistor into a capacitor, and have a digital input pin watching the resistor-cap voltage. You'll need to be generous with the timing because you want the cap to fully drain, and you can't tell from the MCU when that's completed, but a few preliminary DMM measurements will give you that info.

To measure voltage, you switch the GPIO from OUTPUT/low to to INPUT-PULLUP and wait for it to go HIGH. By measuring the time it takes before the pin goes high, you can calculate the voltage expected to fill the cap to the trigger threshold in that amount of time. You will need to do some manual measurements to calibrate it up-front, as different pins have different pull-up values and slightly different schmitt trigger voltage thresholds. Once setup, it can be repeatable to about +/- 5%, maybe more with slower sampling.

ascii schematic: `(vSensor) --- [R1] --- (GPIO) --- [C1] --- GND`

---
Tags: arduino-uno, pins, pwm
---


# Question
Title: Is there any limitation with Arduino Nano serial communication distance?
I am trying to build Project which communicate multiple Arduino Nanos. I wanted to understand if Arudino Nano is capable of doing that, while doing research I came across post where it says communication with nano can be done up to 2-3 meter, where as my goal is up to 30 meter.

Project - I am trying intercom system, I have 4 Ring button at main gate, when user press any one of those 4 the Arduino will understand it and send to one of the 4 Arduino sitting at other place. Each Arduino will read that message if its for them they will perform activity if not they will skip it.

My problem is I am in selection mode and want know if Arduino Nano can handle that, communication is not that complex. It will be just sending 2/3 value max during communication. As I saw post of distance limitation, I just want get inputs from community. If you have any similar examples of serial communication between multiple Arduino Nano please let me know, I found several but it might save my time if I find something more similar.

# Answer
> 7 votes
For that sort of difference you are better using RS-485 instead of UART. UART is really only designed for short-distance communication.

Converting UART to RS-232 will give an improvement, but switching to RS-485 instead will give you the ability to create a multi-drop bus for connecting more than two Arduinos together over a long distance.

* UART uses 5V logic level signalling (on the normal Arduinos - 3.3V on most 32-bit boards). It has a "weak drive" and is highly susceptible to induced noise over longer distances.
* RS-232 uses ±10V "Non Return to Zero" signalling. This gives far greater immunity to noise and a stronger drive for greater distances.
* RS-485 (and the associated peer-to-peer RS-422) use *differential* signalling. This gives the greatest immunity to noise over the longest distances.

In summary:

* RS-232 can be used if you only want to connect two devices together in a low noise environment.
* RS-422 can be used to connect two devices together in a high noise (industrial) environment.
* RS-485 can be used to connect lots of devices together in a high noise environment.

For more information on how they work there are some good Wikipedia pages:

For interfacing any of these to an Arduino you will need extra hardware ("Driver Chips"). For example:

---

There is also "CAN", which is a more modern replacement for RS-485 and is used in many industrial and automotive environments. As this is a newer technology than RS-485 there are fewer resources available and "initial cost to entry" can be higher.

# Answer
> 3 votes
Roughly speaking, for a given protocol and medium (cable) the data rate and the distance are inversely related, that is, a connection with half the data rate can work across twice the distance. You will eventually hit the hard limit when the total capacitance of the cable will become too much for the driver.

RS-232 standard provides this table of maximum cable lengths for standard shielded cables:

```
Data rate (bps) Distance (m)
2400            60
4800            30
9600            15
19200           7.6
38400           3.7
56000           2.6

```

So, 30 meters can be easily achieved even with RS-232, if you don't mind the 4800 bps baudrate. Even longer distances (or higher baudrates) can be achieved by running RS-232 over a twisted pair, e.g. a UTP 5 cable: these cables have lower capacitance and can run at 9600 bps over 100 m or more.

There are other protocols suitable for long-distance communication. There are Arduino shields for CAN, RS-485 and even Ethernet.

# Answer
> 0 votes
Hi please have a look at Nick Gammon's website as he does an Arduino libary for RS485 using cheap driver modules. In particular the non blocking example may well fit your needs. The library also works for ESP8266 and ESP32 modules under the Arduino IDE.

---
Tags: serial, i2c
---


title: Read the value of a register in arduino

text:
# Question
Title: 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?

# Answer
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.
> 3 votes

---
Tags: arduino-uno, programming, shift-register, windows
---


title: Port 0x6F problem

text:
# Question
Title: 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 !

# Answer
> 4 votes
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!

---
Tags: arduino-mega
---


# Question
Title: Modifying normal doorbell to get notification
I'm really not used to Arduino and I would like to know if it would be possible to tweak my doorbell, most specifically the bell itself, to embed a small arduino that would be able to send a notification "somewhere" (well, if it can connect to wifi and send an HTTP request I can handle the rest).

I'm guessing that there will be electricity in the bell itself (to.. ring it I guess) so I could use that to power the Arduino.

My goal is definitelly not to create a "smart" doorbell but to upgrade a tiny bit the one we already have. My biggest problem is that when I am in the office, I can barely hear it and if I turn music on, it becomes impossible.

Before launching myself in this, I'd like to know if it is at all possible. I can (try to) provide more information if needed.

Thanks.

EDIT: I'm guessing that the bell rings when it gets an electric signal when the button at the door is pressed. My goal would be to hook up to that signal to get the arduino to send an HTTP request. Now, my arduino knowledge is very limited and I'd like to see if anyone could give a tiny bit of guidance on how to proceed (which one, which module, ...)

EDIT2: As requested, here is a picture of the bell part: \[!\[bell\]\[1\]\]\[1\]

In the center there is a copper coil so I would guess that when someone presses the button, the little hammer (pointy thing going up) hits the 2 metal plates (up and down). I could also see that there is a third cable (purple) hidden behind that is not currently used but I have no clue what it is for or if there is power at all on this thing...

EDIT3: I realized that I have a Friedland D780 on the fuse box (so right next to all the power I can need for an Arduino). It is unclear if I could get the pulse from here though. Anyone?

I can't upload a picture with my phone but I'll add it ASAP...

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

# Answer
Many (most?) household doorbell systems in the US are powered by a simple transformer that converts 120V AC household electric supply to a lower voltage AC. Often 16V AC or 24V AC.

The coil and hammer form a device called a *solenoid*. When the coil is energized, the hammer (often also called a plunger) is forced in one direction, either up (against gravity) or against a return spring, striking one of the plates. When power is removed, gravity or the return spring pull the plunger back to the rest position, striking the other plate, forming the familiar ding-dong sound.

Power is applied or removed extremely simply -- by the momentary, normally-open pushbutton at your door. When you press the button, the solenoid is energized, and when you release it, the device returns to the normal state.

With regard to powering your Arduino, it is important to understand the difference between AC and DC power. The Arduino requires DC (direct-current) of either a regulated 5V DC into the `5V` pin, or unregulated 7-12V DC into the `VIN` pin, or the regulated 5V DC from a USB device.

I don't know your level of electricity understanding, but there exists quite a bit of information on the difference between AC and DC power. Suffice it to say, you would need some additional circuit to rectify and filter and regulate the 16-24V AC into something between 5V and 12V DC.

Then, there is the issue of the loss of a good power tap while the button is pressed. If you measure the voltage across the contacts of the pushbutton while it is not pressed, you will likely find the full 16V AC or 24V AC, but if you measure those contacts while the button is pressed, you will read 0V AC. This means that tapping off of the pushbutton wires is not a good way to power a device that needs to remain on while reacting to the button press. Whether or not you could tap power off of the solenoid terminals is dependent on the voltage drop across the coil, and still you have the issue to convert the AC to DC at the proper voltage.

If this doorbell is near the ceiling, you will likely find the transformer mounted in the attic space above the ceiling near the doorbell (if there is attic space -- depending on your specific setup). If there is a power outlet in this attic space, you could plug in a good quality AC-DC 5V adapter there to power the Arduino in the attic. The Arduino will need to remain electrically isolated from the doorbell circuit. To detect the pushbutton press, you could use a current transformer measuring the current flow through either of the 16V AC wires coming off of the transformer (measure with one of the the analog inputs of the Arduino), or with an Opto-isolator, with the transmitter connected to the doorbell circuit in a way that delivers a small current (10mA or so normally) to the transmitter side of the opto-isolator, and read the receiver side with a digital input pin on the Arduino.

Unfortunately, interfacing with a doorbell that uses AC power will require some good planning and evaluation of your doorbell system and how much additional circuitry you are willing to apply.

If you aren't careful, working near the transformer can be very dangerous to your life. Working with 16-24V AC will not be as dangerous to your life, but can easily damage the Arduino beyond repair in the flash of an eye. Take great care.
> 2 votes

# Answer
Much as I like Arduinos, it might be easier to just run a wire from your current doorbell to your office and add a 2nd doorbell, or a piezo buzzer that will run on AC. As others have said doorbells in the US are usually powered by AC, and that power is only available while the doorbell is actually ringing. You would need a constant source of power in order to drive your Arduino long enough to connect to a network and send a signal.

You might be able to build a circuit that rectified the AC power to DC and charged a capacitor, then used that capacitor to drive a DC power supply to the Arduino. The capacitor might hold a charge long enough for the Arduino to make a network connection and send a signal, but you'd need a fair amount of electronics knowledge to make that work.
> 1 votes

# Answer
If I could offer a different approach -- to maintain isolation between the doorbell AC and an Arduino, you could have the separately powered Arduino 'listen' for the sound of the gong. A cheap mic feeding an analog input does the trick. Mount it in the same housing to isolate it from household and other noises, or maybe tune it to respond to a narrow range of frequencies.

There are other non-contact, non-wired possibilities too -- sense the motion of the solenoid, or its electrical field, etc.
> 0 votes

---
Tags: power, wifi
---


title: Esp8266 Web based code and real button

text:
# Question
Title: 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<html>\r\n";

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

  s += "<br><br><br>";

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

  s += "<br><br><br>";

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

  s += "<br><br><br>";

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

  s += "<br><br><br>";

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

  s += "</html>\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");
}

```

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

```
> 1 votes

---
Tags: esp8266
---


# Question
Title: 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?

# Answer
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.
> 6 votes

---
Tags: wifi
---


# Question
Title: 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.

```
#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'

```

# Answer
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.
> 5 votes

---
Tags: arduino-uno, c++
---


# Question
Title: 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.

# Answer
> 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.
> 2 votes

---
Tags: esp8266, bootloader
---


# Question
Title: 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!!

# Answer
> 0 votes
> ....\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.

---
Tags: arduino-uno
---


title: RDM6300 continuous RFID tag read

text:
# Question
Title: RDM6300 continuous RFID tag read
I have an RDM6300 connected to an Arduino Mega and code that can read the tag just fine:

```
// Function prototypes
void setup(void);
void loop(void);

// RDM6300 packet details
#define RDM6300_PACKET_SIZE  14
#define RDM6300_PACKET_BEGIN 0x02
#define RDM6300_PACKET_END   0x03

// Globack for reading RFID data
char buff[RDM6300_PACKET_SIZE];
uint32_t tag_id;
uint8_t checksum;

void setup(void) {
  Serial.begin(9600);
  Serial.println("Setting up...");

  // RFID board setup
  Serial1.begin(9600);

  Serial.println("READY. Scanning tags...");
}

void loop(void) {
  while (Serial1.available() > 0) {
    if (Serial1.peek() == RDM6300_PACKET_BEGIN || Serial1.read()) {
      Serial1.readBytes(buff, RDM6300_PACKET_SIZE);
      if (buff[13] != RDM6300_PACKET_END) {
        Serial.println("Bad1");
      }
      else {
        buff[13] = 0;
        checksum = strtol(buff + 11, NULL, 16);
        buff[11] = 0;
        tag_id = strtol(buff + 3, NULL, 16);
        buff[3] = 0;
        checksum ^= strtol(buff + 1, NULL, 16);
        for (uint8_t i = 0; i < 32; i += 8) checksum ^= ((tag_id >> i) & 0xFF);
        if (checksum) {
          Serial.println("Bad2");
        }
        else {
          Serial.println(tag_id);
        }
      }
    }
    else {
      Serial.println("Bad3");
      Serial.println(Serial1.peek(), HEX);
    }
    Serial.println("END");
  }
}

```

However, the output stops after reading the tag around 28 times sometimes (more, sometimes less...) . If I remove the tag from the "read" area and put it back on it start reading again for a number of times and then stop.

I have an LED connect to the RDM6300 board that is supposed to show when it detects a tag and it does blink while I hold the tag over the antenna but also stops when the Arduino stops receiving data.

As the RDM6300 is supposed to be a continuous RFID reader I was expecting to receive data for the duration I kept the tag over the antenna.

Anyone faced this same thing and found a solution ?

Thanks for any hints.

# Answer
Ok, so it seems to be related to the tags. The "standard" keychain and credit-card type cards when used with the RDM360 only emit a single time their ID.

The same tags when used with the RDM3600 module will emit their tags a few times, but at some point the antenna can not provide enough power for the tag to emit again and the flow stops.

Fortunatly the tags I use for this project are very small tags made for birds (https://eccel.co.uk/product/3-3mm-em4102-pit-bird-tag-grey/) and when used with the RDM360 will continuoisly retransmit. I guess they need less power and the antenna is able to provide enough.

If you want to use continuous reading using regular tags, I believe there is still a way... If you "reset" the RDM360 or RDM3600 it forces "re-energize" of the tag and transmission resumes. So one could use a simple transistor to switch on and off the power to the RFID module using an Arduino I/O.
> 0 votes

---
Tags: arduino-mega, rfid
---


# Question
Title: HUZZAH ESP-8266 (by ADAFRUIT): How to use with the ARDUINO R3
I have recently purchased a ESP-8266 HUZZAH by adafruit. I'm kind of new to the whole arduino concept. I would like to know how I would be able to utilise this breakout board with my Arduino to do anything. I have searched on the internet and I know about flashing the board. However, I have no idea how to flash this device. Some help would be appreciated.

I also have no idea where to put my pins. I know that there are RX and TX pins on the UNO, but those are at 0 and 1. Most online guides are using something like 11/12 or 2/3.

Here is the link to the product website

Thanks, Vraj

# Answer
Ok, I'll keep this post open for anyone who got this board and the Arduino and wanted to use them together (it's probably only me, but who cares). Anyway, when looking at this board it's basically it's own controller. The front pins are what you need to communicate with the board itself. It's meant to be used with a FTDI cable to the computer. Anyway, looking further into it we see many pins behind the first 6 or so. To connect it to the computer using the Arduino you need to use this config.

```
Arduino | HUZZAH ESP8266
RX | RX (In the front)
TX | TX (In the front)
5V | V+ (In the front)
GND | GND (In the front)

```

Also, you need to create a thing where the Arduino won't be able to function, making it a communicator port for the HUZZAH itself. To do this simply take one of the GND pins on the Arduino and connect it to the RESET pin on the Arduino. After doing this you need to set up your ESP8266. This is a link to a basic guide on how to do this by ADAFRUIT. Instead of the USB cable, you are using your arduino as a cable essentially (a pretty expensive one). Anyway, the port number should be the port that your arduino is connected to (to the computer). This is if you want to use the ARDUINO IDE.

To use NODEMCU LUA which it comes preloaded with, you need to refer to this guide.

The other thing I wanted to mention was how to utilise a basic board with the controller. I had to use a MFRC522 RFID board with the Arduino, and I wanted to send the info to the internet. Sadly, it seemed as if I couldn't use the arduino itself. To use this board I used many sources. First, was the library github (this one).

The next step was to get the pin layout (from here). However, if you look at it it's in the pin format of a WESMOS D1 MINI board. The final source was to look at the product page (here) and convert the pin format to fit the HUZZAH Board (It's in the PIN section). That took a long time, but now you're done. That's a basic guide on how I used the HUZZAH Board with my arduino.
> -1 votes

---
Tags: arduino-uno, esp8266, adafruit
---


# Question
Title: nRF24L01 6TXA_1RXA network + 6TXB_1RXB network with arduino
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 ?

# Answer
> 3 votes
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.

---
Tags: arduino-uno, nrf24l01+
---


# Question
Title: 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.

# Answer
> -1 votes
First of all, if your Raspberry Pi acts as webserver and mqtt broker, in my opinion you should assign a fixed ip-address, either via configuration in the access point/router or via static ip.

However, if you insist on your approach you could do some hands-on method of pinging all addresses in your LAN-subnet and checking for the MAC-address of the respondents.
If the MAC-address matches to that of your Pi, you have found it.

I have not tested it myself, but this library seems to have what you need for this purpose.
After finding a responsive ip-address via ping, it tries to resolve the corresponding MAC-address using the etharp\_find\_addr function.

This struct field is the reference to a 6 byte character array that you can use for comparing with the Raspberry Pi's MAC address:

```
response.DestMacAddress->addr

```

---

Update:
If you only want to find the IP address of the Raspberry Pi, using mDNS as suggested by @Majenko is the superior choice.
If you are looking for all devices in your LAN, as your title suggests, pinging makes more sense.

# Answer
> 1 votes
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.

---
Tags: esp8266, nodemcu, raspberrypi, iot, mqtt
---


title: arduino LCD help

text:
# Question
Title: arduino LCD help
I am trying to create smart clock with alarm using an Arduino Uno.

My problem is when I set the alarm, I can't set the alarm again. Every time I must power off my Arduino and then power on in order to set the alarm again.

I am using:
Arduino Uno
LCD 16\*2
buttons
buzzer and LED
RTC

My code works like this: At the beginning it will let you to set date and time by buttons and you can set alarm too. When it reaches the alarm time, it turns on the melody of buzzer and LEDs turn on.

but

I want to turn off the alarm so I can set another alarm.

This is my code:

```
#include "RTClib.h"
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int alarmState = 0;
int alarmSnooze = 0;
int btnSet = 0;
int btnSel = 0;
int alarmValue = 0;
int alarmCounter = 0;
boolean turnOffAlarm = false;
boolean settingAlarm = false;
int counter = 0;
boolean initialCount = true;
boolean alarmSet = false;
int timeArray[6]; // 0=Hour, 1=Minutes, 2=day, 3=Day of Week, 4=Month, 5=Year;
int timeCounter = 0;
int alarmArray[2];
char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
RTC_DS1307 rtc;    // Create a RealTimeClock object
DateTime now; // Read data from the RTC Chip

//////////////////////////
 ///difine button////
int  b6=6;
int b7=7;
int b8=8;
int b9=9;
////////////////////

///melody///
#include "pitches.h"

const int piezoPin = 13; //piezo
const int rPin = A0;  //red LED
const int gPin = A1;  //green LED
const int bPin = A2;  //blue LED
const int pPin = 6;  //pushbutton

int ledState = 0;
int ledOn = false;

// notes
int melody[] = {
  NOTE_F5,NOTE_D5,NOTE_AS4,NOTE_D5,NOTE_F5,NOTE_AS5,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_D5,NOTE_E5,NOTE_F5,
  NOTE_F5,NOTE_F5,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_A5,NOTE_AS5,NOTE_AS5,NOTE_F5,NOTE_D5,NOTE_AS4,
  NOTE_D6,NOTE_D6,NOTE_D6,NOTE_DS6,NOTE_F6,NOTE_F6,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_DS6,
  0,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_A5,NOTE_AS5,NOTE_D5,NOTE_E5,NOTE_F5,
  NOTE_F5,NOTE_AS5,NOTE_AS5,NOTE_AS5,NOTE_A5,NOTE_G5,NOTE_G5,NOTE_G5,NOTE_C6,NOTE_DS6,NOTE_D6,NOTE_C6,NOTE_AS5,NOTE_AS5,NOTE_A5,
  NOTE_F5,NOTE_F5,NOTE_AS5,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_F6,NOTE_AS5,NOTE_C6,NOTE_D6,NOTE_DS6,NOTE_C6,NOTE_AS5
};

// durations: 2 = half note, and 8/3,4,6,8,12. It appears that 8/2.9 is more accurate than 8/3.
float noteDurations[] = {
  6,12,4,4,4,2,6,12,4,4,4,2,
  8,8,8/2.9,8,4,2,8,8,4,4,4,4,4,
  6,12,4,4,4,2,8,8,4,4,4,2,
  8,8,8/2.9,8,4,2,8,8,4,4,4,2,
  4,4,4,8,8,4,4,4,4,8,8,8,8,4,4,
  8,8,8/2.9,8,8,8,2,8,8,4,4,4,2
};

// calculates the number of elements in the melody array.
int musicLength=sizeof(melody)/sizeof('NOTE_F5');

//////////////////////////

void setup()
{

  pinMode(pPin, INPUT);
  pinMode(rPin, OUTPUT);
  pinMode(gPin, OUTPUT);
  pinMode(bPin, OUTPUT);

  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(10, OUTPUT);
  rtc.begin(); // Start the RTC library code
  rtc.adjust(DateTime(0, 0, 0, 0, 0, 0));
}
void loop()

{ alarmState = digitalRead(b9);
  alarmSnooze = digitalRead(b6);
  btnSet = digitalRead(b7);
  btnSel = digitalRead(b8);

  if (timeCounter == 0)
  {
    if(initialCount == true){
      counter=0;
      initialCount = false;
    }
    setHour();
  }
  else if (timeCounter == 1)
  {
    if(initialCount == true){
      counter=0;
      initialCount =false;
    }
    setMinute();
  }
  else if (timeCounter == 2)
  {
    if(initialCount == true){
      counter= 1;
      initialCount=false;
    }
    setDay();
  }
  else if (timeCounter == 3)
  {
    if(initialCount == true){
      counter = 0;
      initialCount =false;
    }
    setDOW();
  }
  else if (timeCounter == 4)
  {
    if(initialCount==true){
      counter=0;
      initialCount=false;
    }
    setMonth();
  }
  else if (timeCounter == 5)
  {
    if(initialCount==true){
      counter=0;
      initialCount=false;
    }
    setYear();
  }
  else if (timeCounter == 6)
  {
    rtc.adjust(DateTime(2000+timeArray[5], timeArray[4], timeArray[2], timeArray[0], timeArray[1], 0));
    timeCounter++;
    delay(200);
  }
  else if (timeCounter > 6){
    if(alarmState == LOW&&settingAlarm==false){
      now = rtc.now();
      digitalClockDisplay();
    }
    else if(alarmState == HIGH||settingAlarm==true)
    {
      settingAlarm = true;
      if(alarmValue==0){
        if(initialCount==true)
        {
          lcd.clear();
          alarmCounter=0;
          initialCount=false;
        }
        setAlarmHour();
      }
      else if(alarmValue==1){
        if(initialCount==true)
        {
          alarmCounter=0;
          initialCount=false;
        }
        setAlarmMinute();
      }
      else if(alarmValue>1){
        alarmSet = true;
        settingAlarm = false;
      }
    }
    if(alarmArray[0]==now.hour()&&alarmArray[1]==now.minute()&&turnOffAlarm==false&&alarmSet==true&&alarmSnooze==LOW){
       for (int thisNote = 0; thisNote < musicLength; thisNote++) {
      // blink the three LEDs in sequence
      if (thisNote%3==0){
        digitalWrite(rPin, HIGH);
        digitalWrite(gPin, LOW);
        digitalWrite(bPin, LOW);
      }
      else if (thisNote%3==1){
        digitalWrite(rPin, LOW);
        digitalWrite(gPin, HIGH);
        digitalWrite(bPin, LOW);
      }
      else if (thisNote%3==2){
        digitalWrite(rPin, LOW);
        digitalWrite(gPin, LOW);
        digitalWrite(bPin, HIGH);
      }

      // calculate the note duration. change tempo by changing 2000 to other values
      int noteDuration = 2000/noteDurations[thisNote];
      tone(piezoPin, melody[thisNote],noteDuration);

      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well
      float pauseBetweenNotes = noteDuration * 1.30;

      //split the delay into two parts and check to see
      //whether the pushbutton is pressed to turn off
      //the sound and light
      delay(pauseBetweenNotes/2);
      if(digitalRead(pPin)==HIGH) {
        break;
      }
      delay(pauseBetweenNotes/2);
      if(digitalRead(pPin)==HIGH) {
        break;
      }

    }
      digitalWrite(13, HIGH);

    }

    else if(alarmArray[0]==now.hour() && alarmArray[1]==now.minute()&&turnOffAlarm==false&&alarmSet==true&&alarmSnooze==HIGH){
      noTone(13);
      digitalWrite(13, LOW);
      digitalWrite(rPin, LOW);
    digitalWrite(gPin, LOW);
    digitalWrite(bPin, LOW);
      turnOffAlarm = true;
    }
  }
}

void nextValue(){
  btnSel=LOW;
  // Update array value with counter
  timeArray[timeCounter] = counter;
  counter=0;
  initialCount = true;
  timeCounter++;
  delay(200);
  lcd.clear();
}
void nextAlarmValue(){
  btnSel=LOW;
  // Update array value with counter
  alarmArray[alarmValue] = alarmCounter;
  alarmCounter=0;
  initialCount = true;
  alarmValue++;
  delay(200);
  lcd.clear();
}

void setAlarmHour(){
   if(alarmCounter==24){
    alarmCounter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set alarm hour");
  lcd.setCursor(7,1);
  lcd.print(alarmCounter);
  if (btnSet==HIGH)
  {
    alarmCounter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextAlarmValue();
 }
}

void setAlarmMinute(){
  if(alarmCounter==59){
  alarmCounter=0;
  lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set alarm minute");
  lcd.setCursor(7,1);
  lcd.print(alarmCounter);
  if (btnSet==HIGH)
  {
    alarmCounter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextAlarmValue();
 }
}

void setDOW(){
  if(counter==7){
    counter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set day of week");
  lcd.setCursor(7,1);
  lcd.print(days[counter]);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}
void setHour()
{
  if(counter==24){
    counter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set hour");
  lcd.setCursor(7,1);
  lcd.print(counter);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

// Function to set minutes
void setMinute()
{
  if(counter==60){
    counter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set minute");
  lcd.setCursor(7,1);
  lcd.print(counter);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

// Function to set date
void setDay()
{
  if(counter==32){
    counter=1;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set day");
  lcd.setCursor(7,1);
  lcd.print(counter);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

// Function to set month
void setMonth()
{
  if(counter==12){
    counter=0;
    lcd.clear();
  }
  lcd.setCursor(0,0);
  lcd.print("Set month");
  lcd.setCursor(7,1);
  lcd.print(months[counter]);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

// Function to set year
void setYear()
{
  lcd.setCursor(0,0);
  lcd.print("Set year");
  lcd.setCursor(7,1);
  lcd.print(counter);
  if (btnSet==HIGH)
  {
    counter++;
    delay(200);
  }
 else if(btnSel==HIGH)
 {
  nextValue();
 }
}

void digitalClockDisplay(){
  // digital clock display of the time
  long hours;
  String amOrPm = "";
  if(now.hour() > 12){
    hours = now.hour() - 12;
    amOrPm = "PM";
  }
  else if(now.hour()==0){
    hours=12;
    amOrPm = "AM";
  }
  else{
    hours = now.hour();
    amOrPm = "AM";
  }
  lcd.setCursor(0,0);
  lcd.print(days[timeArray[3]]);
  lcd.print(" ");
  lcd.print(months[timeArray[4]]);
  lcd.print(" ");
  lcd.print(now.day());
  lcd.print(" ");
  lcd.print(now.year());
  lcd.setCursor(0,1);
  lcd.print(hours);
  printDigits(now.minute());
  printDigits(now.second());
  lcd.print(" ");
  lcd.print(amOrPm);
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  lcd.print(":");
  if(digits < 10)
    lcd.print('0');
  lcd.print(digits);
}

```

# Answer
> 1 votes
It looks like you haven't reset your state variable *turnOffAlarm* after you turn off the alarm.

# Answer
> 0 votes
Since the question is tagged \[code-review\]

1. ```
char* days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

```

This should be a `const` array of `const char *`, not of `char *`.

```
const char *const days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

```

Same goes for `months`.
2. ```
int  b6=6;
...
const int piezoPin = 13;
...

```

Why some of your pins are `const` and others are not? I don't see any attempts or reasons to change the value of `b6` in the code. Why is it not `const`?
3. ```
int melody[] = { ... };
float noteDurations[] = { ... };

```

Both are supposed to be be `const`, apparently.
4. ```
// calculates the number of elements in the melody array.
int musicLength=sizeof(melody)/sizeof('NOTE_F5');

```

Really? What is `'NOTE_F5'`? What did your compiler tell you about it? Did you just ignore the compiler's message?

Should be

```
const int musicLength = sizeof melody / sizeof *melody;

```

I'd prefer `unsigned` or `size_t`, but let's not open this can of worms.
5. In a single-file sketch all global variables (i.e. the ones that really need to be global) should be declared either `const` or `static` (or placed in an anonymous namespace). Declaring a global variable that is not `const` or `static` requires a good reason for doing so.

---
Tags: lcd, code-review
---


title: ISR definition causing boot loop?

text:
# Question
Title: 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:

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

# Answer
> 2 votes
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

```

---
Tags: arduino-uno, interrupt, isr, avr-toolchain
---


# Question
Title: 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

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?

# Answer
> 9 votes
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)

---
Tags: avr, bootloader, isp
---


# Question
Title: OV2640 with 18 Pins - No XLCK System Clock
I'm trying to connect an OV2640 camera module to a microcontroller.

This camera module has only 18 pins as seen in this schema: https://i.stack.imgur.com/wVBwV.jpg

Here an image of the module: https://i.stack.imgur.com/tUVg0.jpg

These pins are on the module:

* 3.3V
* GND
* VSYNC
* SCL
* SDA
* HREFF
* D0 - D7
* DCLK
* PWDN
* NC

Maybe I could set XLCK and PLCK via the DCLK pin but I don't know how.

I am pretty new to camera modules and searched the net a lot of times. Most examples are for the OV7670. This module has also 18 Pins but all are used quiet contrary to the OV2640.

Could anybody help me connect and get a signal?

# Answer
> 1 votes
In this specific OV2640 module, it's supposed to have a 12MHz oscillator in the board connected to XLCK pin (you can all time adjust the PLL trough SCCB interface as usual). Remove the plastic lens and see near the CMOS. Regards

# Answer
> 0 votes
I also bought one of these to use with an esp32, not realizing that there was an on-board oscillator and no system clock pin. I just left the pin on the esp that's supposed to connect to XCLK hanging, and set the frequency to 12000000 in my code. It seems to work alright!

---
Tags: camera
---


# Question
Title: 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...

# Answer
> 1 votes
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.

---
Tags: rgb-led
---


# Question
Title: 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.

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

```

# Answer
> 1 votes
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.

---
Tags: arduino-uno, button, stepper-motor
---


# Question
Title: error: espcomm_upload_mem failed when uploading a sketch
I am new to the whole arduino scene. I have connected my wifi module (esp8266 v01) to my arduino Uno like this:

http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/

And have downloaded the arduino ide framework so that I may be able to use the arduino IDE as opposed to sending AT commands through the serial monitor.

When trying to upload an example sketch that sends a http request that I found on github, I get the following error:

```
    Arduino: 1.8.4 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Archiving built core (caching) in: C:\Users\Yasmeen\AppData\Local\Temp\arduino_cache_354217\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____9d1d735445f8d7bf19746e2177d24e71.a
Sketch uses 285417 bytes (65%) of program storage space. Maximum is 434160 bytes.
Global variables use 38688 bytes (47%) of dynamic memory, leaving 43232 bytes for local variables. Maximum is 81920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

After looking online and researching, I can see that it has something got to do with flashing the firmware or something. I came across this question:

ESP8266 error: espcomm\_upload\_mem failed while uploading sketch

and the answer did say that he bought a converter.. what does this mean? Does it mean buying this?: https://www.amazon.co.uk/gp/product/B06Y3FNGJF/ref=oh\_aui\_detailpage\_o00\_s00?ie=UTF8&psc=1

I really need help, been stuck on this for the past few days now and seriously contemplating whether to get the arduino wifi shield since it comes prebuilt with wifi.. even though it costs quite a lot!

# Answer
The ESP8266 has two "modes". "Run" mode and "Flash" mode. In "Run" mode the firmware installed onto the ESP8266 executes. The default firmware is the AT firmware that allows you to control the device with AT commands through serial.

Note that the site you link to has erroneous information about CH\_PD that should be talking about GPIO0.

In "Flash" mode you get to upload new firmware (AKA a "sketch") to make the device do something different.

The basic programming sequence is:

1. Switch the device to Flash mode (connect GPIO0 to GND)
2. Upload the sketch using the IDE
3. Switch the device to Run mode (connect GPIO0 to 3.3V).

Because of these extra steps many people choose to invest in a small USB interface board designed specifically for programming the ESP8266 to make their life easier. These generally have a switch on them to set whether GPIO0 is connected to GND or 3.3V.
> 1 votes

# Answer
By default, the ESP8266 runs the program in flash memory. To upload new firmware over UART, you have to change the boot mode by connecting GPIO0 to ground during reset. GPIO15 should be low and GPIO2 should be high during boot in both cases. GPIO needs an external pull-down resistor, the internal pull-up resistor for GPIO2 is enabled during boot, so you don't need to add an external one.
To prevent from shorting GPIO0 if it's used as an output in your sketch, it's recommended to add a series resistor to limit the current.

**To upload a sketch**:
1. press and hold the reset button
2. press and hold the program button
3. release the reset button, the ESP will boot in program mode
4. release the program button
5. upload the sketch

If your USB-to-Serial breaks out the RTS and/or DTR lines, you can automate the reset and programming mode procedures.
> 1 votes

# Answer
I had the same issue while uploading to the NodeMCU.

The issue was that the mode was not selected to `program mode` even after doing the below steps:

1. press and hold the reset button
2. press and hold the program button
3. release the reset button, the ESP will boot in program mode
4. release the program button
5. upload the sketch

To solve the issue, do this:

1. short the pin GPIO 0(D3) to ground using a jumper wire.
2. press reset button
3. upload the sketch
4. remove the jumper wire

Done!!!!
> 1 votes

# Answer
This is one of the simple solutions that worked for me:

1. Plug out the USB connection with the computer;
2. Hold the flash button on the nodemcu/esp8266;
3. Plug in the usb connection and quickly release the flash button;
4. Now try uploading the sketch.

Thank you.
> 0 votes

# Answer
depending on the USB speed cable that you are using, sometimes this problem often occurs if I use a cable that is not suitable. if your com setting is 9600 then you have to set up upload speed in the tools menu -\> upload speed faster than 9600 ... for exp: 57600. this is should be work!!
> 0 votes

---
Tags: arduino-uno, esp8266, arduino-ide
---


# Question
Title: Sending a text message through a arduino wifi shield
I am using an Arduino uno and need to send text messages and email messages from the device based on certain events occurring. I have the logic figured out of when to send the text message or email but don't know what shield I need to send these messages.

# Answer
> 1 votes
Sending an email you need a network connection of some form. Options include:

* Ethernet Shield
* WiFi Shield
* GSM Shield (can be expensive, but will work almost anywhere)

To send a text message you need access to a text message service. That can either be directly through a mobile phone operator or through an on-line SMS gateway service. For an on-line service the options are as above, since it's almost the same as sending an email (in fact, some gateways offer an email-to-SMS gateway option). For direct mobile provider access you can only use a GSM shield.

So really it boils down to how mobile you need it to be, and how much you are willing to spend (both on the initial hardware outlay and service provider fees and charges).

# Answer
> 1 votes
In one of project I had seen recently, they used esp8266 for home automation and used TEMBOO.com to send SMS. I am sorry I can't help u further than this, but i am sure, Google will..

You can also refer this tutorial from adafruit on sending an sms with Temboo

https://learn.adafruit.com/sending-an-sms-with-temboo/

# Answer
> 0 votes
If you are trying to send `test messages` and `emails` over INTERNET using ETHERNET or WIFi you might need some REST API. There are two ways to get that part done.

1. You might create your own REST API that contains some AUTHENTICATION KEYS, USER ID, RECEIVER ID etc for emails and same for test messages.
2. You can use third part REST API that provides these functionality.

I am attaching some link you for help that will tell you how to send emails and text messages over internet.for emails For Text Messages

**NOTE :-** Email api might get expired, don't get stuck over it found some other ways or third party API for that.

---
Tags: arduino-uno, shields
---


title: Receive Signal from different circuit

text:
# Question
Title: 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

# Answer
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:

simulate this circuit – Schematic created using CircuitLab

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

# Answer
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
> 0 votes

---
Tags: arduino-uno, led
---


# Question
Title: 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?

# Answer
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, 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.
> 0 votes

---
Tags: arduino-uno
---


title: Code to control servo with shield

text:
# Question
Title: Code to control servo with shield
I recently bought an Arduino MEGA2560 and a SainSmart InstaBots Robot Controller Shield for Arduino MEGA2560 R3 Robot Arm Control.

I understand how to control a servo in the method described in Sweep. However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

Please help me I am a beginner in robotics and I need this for a project.

# Answer
> However, I want to control six servos using the shield area circled in red below. Could anyone provide the code to setup and control servos from the area circled in red?

With the limited amount of info you have provided about the shield this will have to be a wild guess. I am assuming that the pins are S(ignal), V(cc) and G(nd) for pins 8-13. On an Arduino Mega these can be used for PWM and therefore Servo control.

Include the Servo library, attach the pin and set the angle.

```
#include <Servo.h>

Servo servo[6];

void setup()
{
  ...
  for (int i = 0; i < 6; i++)
    servo[i].attach(8 + i);
  ...
}

void loop()
{
   ...
   servo[i].write(pos);
   ...
}

```

Cheers!

NB: Do not forget to provide the correct power supply. If USB Port is left, then the upper pin is positive and the lower pin negative.
> 1 votes

# Answer
Sainsmart STILL refuses to supply documentation for this board.Supposedly, it can control 6 servos and two motors, up to 4 Amps, with digital encoder inputs. There is NO documentation on the hardware or the software for the mega to drive this.
> 1 votes

# Answer
The SVG connectors on your board appear to be lacking header pins:

These should have been supplied with the board. If not you will need to source some. Either way, you will need to solder them on. I don't understand why they are not already attached.

If you look at the other images of the board on the SainSmart web page, the header pins are clearly visible:

The S pin of each SVG is the same as the output pins, near the green light, but for ease of use, they are replicated in the SVG pins, so that a servo plug can be easily, and conveniently plugged in, with out the user having to wire up power and ground separately. If you look at the plug attached to the end of the cable coming from your servo, you will see the servo connector, like so:

As the board has arranged the pins in the SVG order, that means that it will support the Futaba J type connectors (but not the Airtronics, as the power and ground pins are reversed):

Also, Hitec and JR Radio connectors are supported by your board, as they have the same pin out:

.

For more information, take a look at Choosing RC Servos.

In addition, as Mikael says, you will also need to attach an external power supply to the green terminals

as the on board power regulator of the Arduino can not supply enough power to the servos, via the shield, by itself, neither with the USB, nor an external wall wart PSU, supplying power to the Arduino. So, use a bench power supply, battery pack, or otherwise and supply that power directly to the board via the Green power terminals at the end of the board.

Once you have done all of that, and got the hardware out of the way, then the software provided in Mikael's answer will work perfectly.
> 0 votes

---
Tags: servo
---


title: How to read this hmackey for arduino?

text:
# Question
Title: 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.

# Answer
> 1 votes
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);

```

---
Tags: arduino-uno
---