title: SIM800L HTTP request is not reliable

text:
# Question
Title: SIM800L HTTP request is not reliable
I have a question regarding SIM800L and HTTP GET request. I'm using this https://exploreembedded.com/wiki/Setting\_up\_GPRS\_with\_SIM800L simple code to communicate with SIM800l with AT commands. To perform the HTTP request, I use the following set of AT commands:

```
AT+CFUN=1
OK

AT+CSTT="internet","",""
OK

AT+CIICR
OK

AT+CIFSR
10.180.xxx.xx

AT+CIPSTART="TCP","84.42.xxx.xx",80
OK

CONNECT OK

AT+CIPSEND=52
>
GET /bakalarka.php/? HTTP/1.1
Host:84.42.xxx.xx

SEND OK
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2019 16:20:27 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Vary: Accept-Encoding
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

10
time201908191820
0

CLOSED

```

The problem is that sometimes. Or every other time, I don't get the whole HTTP answer. I usually get only the beginning. Something like this:

```
AT+CIPSEND=52
>
GET /bakalarka.php/? HTTP/1.1
Host:84.42.xxx.xx

SEND OK
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2019 16:20:27 GMT
Server: Apac

```

and then after a couple of seconds, the connection closes.

```
CLOSED

```

Do you know what could cause that? It's literally random. I need the information from the webpage (it's the current time) and currently, it's really unreliable.

Another question. What does the "10" and "0" mean in the HTTP request? The "time201908191820" is the current time from printed from PHP.

Thank you very much!

# Answer
> 1 votes
Thank you for your answer. The code is as follows:

```
#include <SoftwareSerial.h>

String Arsp, Grsp;
SoftwareSerial gsm(12, 8); // RX, TX

String GET = "GET /bakalarka.php/? HTTP/1.1\r\nHost:84.42.xxx.xx\r\n\r\n";

void setup() {

  Serial.begin(115200);
  Serial.println("Testing GSM SIM800L");
  gsm.begin(19200);

}

void loop() {

  AT("AT+CFUN=1");
  AT("AT+CSTT=\"internet\",\"\",\"\"");
  AT("AT+CIICR");
  AT("AT+CIFSR");
  AT("AT+CIPSTART=\"TCP\",\"84.42.xxx.xx\",80");

  int get_length;
  get_length = GET.length();

  AT("AT+CIPSEND=" + String(get_length));
  AT(GET);
}

void AT(String AT){

  gsm.println(AT);

  if(gsm.available()){

    Grsp = gsm.readString();
    Serial.println(Grsp);
  }
}

```

I was thinking about a couple of things that could cause this. 1. Hardware design - some noise could cause a freeze of the GSM module while getting the answer from the server. After thinking through I don't think it's likely to be that. The power supply is made to be really beefy and there are enough bypass caps to reduce the noise and provide enough energy during current spikes. Also, the module doesn't freeze. It's still connected to the server, after a couple of seconds it closes the connection exactly as it should be.

2. Serial buffer gets somehow full. This was just a quick thought. The buffer of Arduino could get somehow full so it's not able to save any more incoming data. I think it's nonsense, but...

Thank you for your answers.

Krystof

# Answer
> 1 votes
I've figured it out. The answer to HTTP GET request was read as a string. The string has aroud 284 bytes. Since it's so big, string gets to be saved fragmented, which is apparently a problem. The solution is to create a buffer and save the characters there from the Serial.

# Answer
> 0 votes
> Do you know what could cause that? It's literally random.

Could be your code, could be your network provider / signal. It's impossible to tell without you providing your code for us to inspect.

> Another question. What does the "10" and "0" mean in the HTTP request? The "time201908191820" is current time from printed from PHP.

Those look to be part of the response body - so they are printed by whatever the PHP script is that you are requesting. Either that or they are generated by your undisclosed Arduino program.

---
Tags: arduino-uno, gsm, http
---


# Question
Title: Arduino Ultrasonic Sensor and LCD - Help Needed-
I just recently purchased an Arduino Uno 3 and I wanted to make an ultrasonic distance sensor that outputs the readings to a 16x2 LCD. I followed this guide: http://www.mertarduino.com/using-ultrasonic-distance-sensor-hc-sr04-with-lcd-display-and-arduino/2018/11/22/ but it gave an error when I uploaded the code. The error was: a function definition is not allowed here before '{' token. I don't know too much about Arduinos, so I need help. Thanks to whoever responds!

Here is the code:

```
// put your setup code here, to run once:
#include <LiquidCrystal.h> //Please replace the single quote characters ('') with the parenthesis character (<>)

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

const int trigPin = 9;
const int echoPin = 10;
long duration;
int distanceCm, distanceInch;

void setup() {

lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

}

void loop() {

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;
distanceInch = duration*0.0133/2;

lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor
lcd.print("  cm");
delay(10);
lcd.setCursor(0,1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print("inch");
delay(10);
}

```

# Answer
The root of your problem is this bit:

```
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

```

I think in copying-and-pasting you ended up with a line split across two giving you an error. It should read:

```
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)

```

You have a similar problem here:

```
lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display

```

Again that has split across two lines and should read:

```
lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display

```

And a third:

```
lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed

```

which should be:

```
lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed

```

When those three are corrected the code compiles properly.
> -1 votes

---
Tags: arduino-uno, sensors, lcd
---


# Question
Title: SD Card store struct: force big-endian / little-endian?
Following MAJENKO's tutorial on sd card file optimization and data integrity, can I force the SDCard to read and write in either big-endian or little-endian?

I need this in order to maintain backup data integrity across a wide array of IoThings, using various boards (Arduino UNO, MEGA, Nano, NodeMCU, etc) for future parsing.

# Answer
Many full C libraries have an `sys/endian.h` header file. This defines a number of macros so you can find out what the endianness of your device is. It also usually defines a number of handy macros that can convert the endianness for you.

```
htobe16(x)
htobe32(x)
betoh16(x)
betoh32(x)

```

These convert **H**ost **to** **B**ig **E**ndian values and back again.

```
htole16(x)
htole32(x)
letoh16(x)
letoh32(x)

```

And these convert **H**ost **to** **L**ittle **E**ndian values and back again.

Not many embedded C libraries provide it, though, and not all that do provide the handy macros.

It's not too hard to implement yourself, but it does mean you deciding what to do depending on the target architecture. Which kind of negates the handiness of the endian.h file.

So really you want to re-implement the functionality in a form you can include in all your sketches.

Fortunately the compiler provides a set of macros defining the endianness that you can use though:

```
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __ORDER_PDP_ENDIAN__ 3412
#define __ORDER_BIG_ENDIAN__ 4321
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__

```

So you can examine the `__BYTE_ORDER__` macro to see what byte order it equates to and use that to select whether `htobe32(x)` has to do anything to the byte order or not.

In the PIC32 compiler it's done as a set of macros that either call `swap32` / `swap16`, or pass the value unchanged:

```
#if __BYTE_ORDER__ == __LITTLE_ENDIAN__

#define htobe16 swap16
#define htobe32 swap32
#define betoh16 swap16
#define betoh32 swap32

#define htole16(x) (x)
#define htole32(x) (x)
#define letoh16(x) (x)
#define letoh32(x) (x)

#endif /* __BYTE_ORDER__ */

#if __BYTE_ORDER__ == __BIG_ENDIAN__

#define htole16 swap16
#define htole32 swap32
#define letoh16 swap16
#define letoh32 swap32

#define htobe16(x) (x)
#define htobe32(x) (x)
#define betoh16(x) (x)
#define betoh32(x) (x)

#endif /* __BYTE_ORDER__ */

```

So now depending on the byte order it will either swap the bytes around, or leave them unchanged. It's now just a matter of implementing `swap16` and `swap32` \- which I'll leave to you (hint: it just returns the value with the bytes in the reverse order - bit shifting and masking is good for that).

Then you need to decide on an endianness for your file. Maybe choose little-endian since that is probably the most common. So whenever you place a value into a struct for writing you pass it through either `htole32(...)` or `htole16(...)` depending on the data type. Then whenever you read from a struct that has been read you pass the value through either `letoh32(...)` or `letoh16(...)` to get it in the host's endianness.
> 1 votes

---
Tags: arduino-uno, arduino-mega, nodemcu, sd-card
---


title: control 3 relays with 1 button

text:
# Question
Title: control 3 relays with 1 button
Is there a way to control 3 relays with 1 button?

My idea is: There are 3 modes; mode 1 for relay 1, mode 2 for relay 2 and mode 3 for relay 3.

With a long press you switch between modes (After 3 comes 1) and with a short press you activate the relay which is in the activated mode.

I need this for my wheelchair so please help me.

Thank you, Michael

---

Further question:
Does the relays really need a external power supply?
Because I have a small amount of power to control with the relays.

# Answer
> 1 votes
Sure you can. This site isn't a great place for open-ended questions like this though. Since you have a serious real-world need I'll give you some guidance anyway.

You'd need to break it into pieces and solve each one in turn.

First create code that recognizes long and short presses (not using `delay()`.) You'll probably want to respond on releasing the button, since at that point it's easy to tell if it was a long or a short press.

The pseudo-code might look something like this:

```
void loop()
   if button_is_pressed
      if !press_in_progress
         press_in_progress = true
         start = millis()
   else
      if press_in_progress //Button has been released
         elapsed = millis() - start
         press_in_progress = false
         if elapsed > long_press_threshold
            long_press_function()
         else
            short_press_function()

```

For controlling the relays, I suggest getting "digital" relays that are made to be controlled with 5V logic signals. Relays **like this** work well. (Link). Since you need to control 4 relays, a 4 channel model like this one would be a better choice. Note that you'll need a fairly high current power supply. A 2A 5V regulated supply should be plenty for both your Arduino and your relays, although it's more of a sure thing if you use separate power supplies for the arduino and the relays (that way the voltage to the arduino doesn't bounce around as the relays energize and de-energize.

You'll need a global variable for the currently active relay. The long press would increment that value modulo 4: (going from 0 to 3 and then back to 0)

```
relay_index = (relay_index + 1) % 4;

```

You'd need an array of 4 bools for the states of each relay:

```
bool relay_states[4];

```

The short press would toggle the state of the current relay

```
relay_states[relay_index] = !relay_states[relay_index];

```

Note that if you're more interested in solving your wheelchair problem cost-effectively than tinkering, this is the sort of thing that a maker space would be ideal for. There are lots of tinkerers there who love a challenge, and would likely pitch in and help you.

# Answer
> 0 votes
Yes, it is possible to do that and there are libraries for that purpose. Check for example ObjecButton library, which supports click, press and double click action. It is well documented and comes with many examples...

And does the relays really need a external power supply? It depends, what kind of relays you want to use, what kind of power supply is available on wheelchair, what is the load switched by these relays and so on...

---
Tags: timers, button, relay
---


title: Callback functions when using a class

text:
# Question
Title: Callback functions when using a class
This question is somewhat similar to How to pass non-static class member to callback?, but there are a few differences, especially since a lot of my uses have "interesting" additional complexities. I'd like to understand better my options in using them, since I have not gained enough understanding from other answers (and I need to write both the callback and the function that calls it).

I have a number of libraries that produce "events" that I'd like to be able to write separate classes or functions to respond to (so I don't need to customize every library every time I develop something). The annoying part is that I've long-since discovered the `this` pointer that's hidden in class method calls, which prevents me from passing `currentgui.leftbutton` as a function to `menu.leftbuttonpressed(void (*callbackfuncptr)(void))`.

I'm **also** using the ESP8266 web server library, which needs a callback in the context of the server object that can call the server as a global to actually get the data sent to it! (Unless the server passes its *own* `this` as a parameter to the callback, *which I don't know* since the documentation consists almost solely of a small number of "examples" which don't show the majority of the actual features of the web server, rather than a real explanation.)

I could use some variant of a pointer to a class method, but the syntax for that is eye-gouging and I'm using more than one class to provide callbacks to (especially for the task scheduler), so this would require customizing the library to handle pointers to every class I use again. **I can't use polymorphism, either**, since some classes contain *multiple* scheduler callbacks to be done on different times/conditions.

*How do I handle these callbacks?* My current method is to write a function that wraps the method's function, but that relies on a specific instance of that method, so it can't be reused. It's also really awkward since I'm now dealing with multiple functions/methods that are now very similar.

I would **also** like to be able to have a class, that when passed a web server object, registers itself as a callback to a particular page event (I want to write a network connection manager similar to the WiFiManager library, but with the ability to integrate with an existing webpage. I have all the code, but it currently can't be nicely integrated into a standalone class because of this issue). It needs to store a pointer to the server object to get the data once the callback's called, but it also needs to be attached to the callback of the class that holds that particular pointer AND the other handler functions once the data's retrieved. There is already a library that does something similar, but I can't figure out at all how this works, since I was under the impression that this is not possible. Can someone help me understand how the following class operates? https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266HTTPUpdateServer/src

# Answer
> 1 votes
The ESP8266WebServer uses callback functions to handle HTTP request by your code. This callback functions can't be members of a class. But you can use anonymous functions to implement this callbacks. And if you like you can implement them as 'redirects' to functions of your objects.

```
server.on("/leftbutton", []() {
  currentgui.leftbutton(server);
}

```

Note: this anonymous functions are called lambda functions and they can do some tricks with parameters too

# Answer
> 0 votes
> They call the same instance of the class' member functions to get data back.

Yes, but if they eventually call the class' member function to get data, other than static data, then the need to know what *instance* of the class to get the data from.

> I'd like to know how to get a class I wrote (nothing special about it, but how do I connect it?) to register itself as a callback so IT gets data and I don't need a bunch of disconnected non-class functions around

If function X (not a member of this class) needs to be able to access the data from instance A or instance B then clearly X needs to know which instance it is looking at (the `this` pointer). This is not a syntax thing, you need to have a way of solving this problem.

In fact, when you say "a class I wrote" then that would also have instance data (its own `this`) so now you are trying to connect two instances of two classes.

How many server objects do you have? If just one in this particular case you might be able to fudge your way around it by storing its `this` somewhere, or making some glue routines.

---
Tags: class, callbacks
---


# Question
Title: Multiple buttons on single interrupt, how to debounce?
Buttons on separate interrupt pins work fine (triggered on *FALLING*), bouncing is handling by forcing a 80ms lockout period during which further presses are ignored. I like that solution for being lightweight.

My goal is to have 1 interrupt handle all events (buttons and other digital inputs). I don't want to depend on *loop()*, I wish to be free to use *delay* often rather than timer interrupts.
Most buttons execute an action when pressed, some, while pressed.

What I have now (just 2 buttons for now):

simulate this circuit – Schematic created using CircuitLab

```
void setup() {
  pinMode(17, INPUT_PULLUP);
  pinMode(16, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(3), wotHappnd, CHANGE);
}

boolean isDebouncing(){
  unsigned int now = millis();
  if(now - time_lastPressed > time_debounceLockout){
    time_lastPressed = now;
    return false;
  }
  return true;
}

void wotHappnd(){
  boolean interruptFalling = digitalRead(3) == LOW;
  if(interruptFalling && isDebouncing()) return;
  // digitalRead the pins; do stuff
}

```

Internal pullups on all used pins.

My problem is that often (~4%), on interrupt, the interrupt pin is *LOW* all button pins are *HIGH* ("not pressed" - likely bouncing just as I read it). How to fix that?

Can't use *delay* during an interrupt; *delayMicroseconds* to wait for stable readout still feels inappropriate; a cap-based delay on the interrupt pin induces a period of floating. Prefer solutions in software or with no more than 1 extra component per input.

**\[edit\]** here's a claim that pin interrupts do some filtering already, which, if true, may make some solutions unreliable.

# Answer
In the Isr, read the two pins and maintain their current status (UN debounced), and reset a counter.

In the main loop, increment that counter. If it is more than a certain number, it means that the current state of the key has been stable for a while - bounce no more.

Or Google Kuhn debounced. I wrote a blog page about that. If you want, I can post it later. The basic idea is the same.
> 1 votes

# Answer
As ever I am the voice of dissent: never write software to solve a hardware problem.

For a double-throw switch the classic solution is an SR latch.

Single throw is actually harder. On the face of it, debounce is a trivial matter done with a capacitor and a pull-down (or pull-up) resistor. This will certainly stop floating and false positives from induced current from spikes. However, microprocessors switch pretty fast and will recognise the edges of microsecond oscillations around the switching voltage as changes of switch state. To prevent this you need the hysteresis of a Schmitt Trigger such as an LM7414 (TTL) or LM7417 (suitable for 3V3).

Here is the debounce circuit suggested in Understanding Schmitt Triggers. Unfortunately, it doesn't behave correctly under all conditions, for reasons explained on the Ganssle page referenced later.

You can fix the problem with a diode. For TTL, R1 = 82kΩ, R2 = 18kΩ, C = 1µF

Larger values of C will absorb slower bounces. One of my projects has a relay that bounces for so long I needed 470µF.

Here's what I regard as the last word on the subject — the Ganssle page. There's even a solution for multiple buttons on a single input. This is not quite the same as multiple buttons on a single interrupt but I think the approach may be applicable.

Note that on the Ganssle page a software solution is touted as cheaper than hardware. That's irrelevant for a one-off, true for mid sized runs and potentially false for mass produced items. Debugging software has its own costs and so does product recall. Make your decision in context. Arduino projects are usually one-off.

One objection to a hardware solution is cost, in assembly time, component count and board size. For hobby work that's a personal choice, and for commercial work it's a trade-off between simplicity and reliability. Reliability of *software* hinges on deterministic behaviour and the management of complexity. The Atmel chip doesn't have a *lot* of DRAM or program space, and moving this problem out of the software will make it smaller, simpler and more predictable.

That's not to say there aren't *other* ways to deal with the problem.

If you really want to do it in software you need to measure the pulse width and compare it to a threshold. Since you need both falling and rising edges for this, bind to CHANGE and test for state. The primary difference between this and the Kuhn method mentioned by others is it uses the clock instead of a counter allowing you to specify millisecond duration rather than iterations.

In the excerpt below, the `listen` flag is a simple alternative to noInterrupt() or unbinding the handler. My loop code evaluates a state machine transition function for current state and inputs, and not all states want input.

```
void isr_change()
{
    if (listen)
    {
        unsigned long now = millis();
        int d2 = digitalRead(2);
        if (d2 == LOW || fall_time == 0)
        { // FALLING
            fall_time = now;
        }
        if (d2 == HIGH)
        { // RISING
            command_pending = now - fall_time > MIN_PULSE_MS;
        }
    }
}

```

The state machine doesn't look at digital inputs, it looks at the `command_pending` flag, which is reset after the transition function finishes.

This is one of those things that looks simple, isn't, but does have a stock solution. It beats me why there isn't a mass produced debouncer component the way you can get op-amps.

Thank you to kaay in comments for referring me to the MC14490 which is a DIP16 or SOIC16 with six diode protected debouncers. Kaay thinks it's expensive but consider the cost of the time to code and debug debounce of six inputs. What about the cost when the program doesn't quite fit and you have to rewrite it to shrink it? And then regression test *everything*. Would you pay someone $5 for an instant guaranteed result that doesn't complicate or bloat your software? The economics change with production scale of course, but in very small runs I think it's well worthwhile.

I found the MC14490 DIP16 for 5USD and the SOIC for 9AUD online. Local shops didn't carry it.
> 2 votes

---
Tags: pins, interrupt, button
---


title: Delay stops execution forever sometimes

text:
# Question
Title: Delay stops execution forever sometimes
I have an arduino to control an irrigation system, consisting on one pump (called "bomba" on the code) and 5 12V water valves.

Each valve controls one irrigation circuit and the idea is to open each one sequentially during one minute and then move on to the next one.

The code is this:

```
const int TIEMPO_RIEGO = 64; // seconds

const int TRIGGER = 5;

const int BOMBA = 6;
const int CIRCUITO_1 = 8;
const int CIRCUITO_2 = 9;
const int CIRCUITO_3 = 10;
const int CIRCUITO_4 = 11;
const int CIRCUITO_5 = 12;

const int CIRCUITOS_ACTIVOS[] = {
  CIRCUITO_1,
  CIRCUITO_2,
  CIRCUITO_3,
  CIRCUITO_4,
  CIRCUITO_5,
};

void _abrirValvula(int circuito, int t) {
    digitalWrite(circuito, HIGH);
    digitalWrite(BOMBA, HIGH);
    unsigned long waitTime = t * 1000L;
    delay(waitTime);
    digitalWrite(BOMBA, LOW);
    digitalWrite(circuito, LOW);
}

void cicloRiegoCompleto() {
  int numeroDeCircuitos = sizeof(CIRCUITOS_ACTIVOS) / sizeof(CIRCUITOS_ACTIVOS[0]);
  for (int i=0; i<numeroDeCircuitos; i++){
    _abrirValvula(CIRCUITOS_ACTIVOS[i], TIEMPO_RIEGO);
  }
}

void setup() {
  pinMode(BOMBA, OUTPUT);
  pinMode(CIRCUITO_1, OUTPUT);
  pinMode(CIRCUITO_2, OUTPUT);
  pinMode(CIRCUITO_3, OUTPUT);
  pinMode(CIRCUITO_4, OUTPUT);
  pinMode(CIRCUITO_5, OUTPUT);
  pinMode(TRIGGER, INPUT);
}

void loop() {
  if (digitalRead(TRIGGER) == HIGH) {
   cicloRiegoCompleto();
  }
}

```

On the pin 5 (TRIGGER) I have a raspberry pi connected that is connected to the internet also, so, when I send it a message from mi phone, it puts 3.3V on that pin and starts the process.

It has been working great for like a month or so but, a few days ago, the pump didn't stop when it should, and was still working hours after it started.

I pull the plug and, when I turn it on again, it worked correctly again for another 2 or 3 days.

But today it hasn't stop again. I have check that the pump has been working for around 15 minutes until I pulled the plug, and the first valve (CIRCUITO\_1) has been opened the whole time, looks like the `for` loop is stuck in the first iteration.

So can it be some problem with the `delay` function?

For some reason it is waiting way more than it should?

It works sometimes and sometimes it doesn't so it makes me think: can it be some weird overflow issue?

# Answer
Based on your experience with the system and the source of the Nanos, the best and quickest test I can think of is to swap in a another Nano to find out whether if the problem remains or disappears.
> 1 votes

# Answer
Do you have 10k resistors between gate and ground on your MOSFETs? You might be suffering from residual charge on your MOSFET gate keeping it on when it should be off.
> 1 votes

# Answer
> It has been working great for like a month or so ... it makes me think: can it be some weird overflow issue?

It's hardly a software issue then. Nothing in your code would change after a month of operating. And if you turn the power off and on again then it would "forget" about the previous month.

> So can it be some problem with the delay function?

No.

---

I suggest looking at the hardware, or the code on the Pi.
> 0 votes

# Answer
You may have a problem in the casting of the variable t vs the variable waittime. t is an int and waittime is a long so when you multiply t by 1000L you may be picking up a couple of extra bytes used by other parts of the code:

For instance if t is stored at location 0x100:0x101 in RAM, and some other variable or random data is stored at 0x102:0x103, you pass 100 to the function in variable t which you expect multiplies into waittime as 100,000mS or 100S, but if the data stored at 0x102:0x103 for instance is randomly 0xFFFF, the multiplication into waittime actually works out to (100\*65536)+65535 = 6,619,135mS or 1.83 hours.

The way around this is to either pass a long in the function or recast t to match waittime:

waittime = (long) t * 1000L;

Note that the order of the bytes depends on how the compiler handles variable storage.
> 0 votes

---
Tags: c++, arduino-nano
---


# Question
Title: can I check if why my motor isn't working?
I am currently using the arduino Uno connected with L298N(green pcb) connected to a dc motor rated 12V. I provided dedicated 12v power supply to the dc motor and the arduino board's power is supplied by usb connected to my pc. I connected Pin 9 of arduino uno to 'ENA' on L298N , Pin 7 & 8 (UNO) to 'INA' & 'INB' of L298N. Connected '-' polarity of Motor power supply to GND of L298N, while also connecting the 'GND' of L298N to the GND of Arduino UNO. Last but not least, connecting the 'OUT B'to the dc motor. This is the picture of how L298N(green) look like https://sea.banggood.com/Green-Board-L298N-DC-Motor-Driver-Board-Stepper-Motor-p-974549.html?cur\_warehouse=CN

Can i check why my motor isn't running? Thanks in advance.

```
char data = 0;
int enB = 9;
int InC = 8;
int InD = 7;

void setup()
{
    Serial.begin(9600);
    Serial.println("Motor test !");
  pinMode(enB, OUTPUT);
   pinMode(InC, OUTPUT);
  pinMode(InD, OUTPUT);

}

void loop()
{Serial.println("Entered loop, should start moving now !");
  digitalWrite(InC, HIGH);
  digitalWrite(InD, LOW);
   digitalWrite(enB, HIGH);
   analogWrite(enB, 255);
 }

```

# Answer
Well, your wiring is OK, but I think the

'digitalWrite(enB, HIGH);

in the loop() code is causing your problem. You don't want to try to use the same pin for both digital and analog functions.

I wired up a Uno here with your setup and a L298N, and got a motor to run fine with the following sketch that doesn't use the loop() at all - it does everything in setup().

```
char data = 0;
int enB = 9;
int InC = 8;
int InD = 7;

void setup()
{
    Serial.begin(9600);
    Serial.println("Motor test !");
    pinMode(enB, OUTPUT);
    pinMode(InC, OUTPUT);
    pinMode(InD, OUTPUT);

    Serial.println("motor should start moving now !");
    digitalWrite(InC, HIGH);
    digitalWrite(InD, LOW);
    //digitalWrite(enB, HIGH);

    for (size_t i = 0; i < 10; i++)
    {
        analogWrite(enB, 20*i);
        Serial.print("motor speed = "); Serial.println(20 * i);
        delay(2000);
    }

    Serial.println("quitting!");
    while (true)
    {

    }

}

void loop()
{
    //Serial.println("Entered loop, should start moving now !");
    //digitalWrite(InC, HIGH);
    //digitalWrite(InD, LOW);
    //digitalWrite(enB, HIGH);
    //analogWrite(enB, 255);
}

```

If you can't get your motor working with the above program, then you most likely have a connection or power supply or component problem that you'll need to troubleshoot.

Hope this helps,

Frank
> 1 votes

---
Tags: arduino-uno, motor, l298n
---


title: LCD shield submenu

text:
# Question
Title: LCD shield submenu
I need to make an app that does various functions regarding IR signals (remote-like) I need to create a sub menu in order for me to access multiple functionalities.

Arduino-Uno-Menu-Template

I used the link above to create a menu and it works great! The problem is I can not do a sub menu without messing with the loop that display the original one. Any ideas?

This is the code I got so far:

https://pastebin.com/Vh5R2JVp

I'm trying in menuItem1() function to add a routine to create the submenu. I tried to use a variable that changes when the menu does but it didn't work.

# Answer
What you can do (but there are many solutions):

* Keep a variable (e.g. `subMenu` that has the state of the current menu option selected (make this an `enum`).
* Whenever a sub menu is entered, assign the `subMenu` variable with the current sub menu value.
* Use a `switch` around the current `switch` statement for first switching subMenu (make different functions for clearity).

So the pseudo code would look like

```
enum ESubMenu { MainMenu, Page1, Page2 };
ESubMenu subMenu;

void setup()
{
  subMenu =  MainMenu;
}

void loop()
{
   switch (subMenu)
   {
   case MainMenu : showMainMenu() ; break;
   case Page1Menu: showPage1Menu(); break;
   case Page2Menu: showPage2Menu(); break;
   }
}

void showMainMenu()
{
   if (`sub menu 1 selected`)
   {
      subMenu = Page1Menu;
   }
   else if (`sub menu 2 selected')
   {
      subMenu = Page2Menu;
   }
   else
   {
      // Show/handle main menu
   }
}

void ShowPage1()
{
   if `back'
   {
     subMenu = MainMenu;
   }
   else
   {
      // Show/handle page 1 menu options
   }
}

```
> 0 votes

---
Tags: arduino-mega, lcd, shields
---


# Question
Title: Why is observed clock rate < 3MHz on Arduino Uno?
I wrote a simple loop to test the processor speed on my Arduino Uno. The numbers I'm getting are much worse than the 16MHz advertised, by a factor of ~5. Trying to figure out what I'm missing.

```
long counter = 0;
int sum = 0;
uint32_t t = 0;

void setup() {
  Serial.begin(9600);
  t = micros();
}

void loop() {
  sum += counter;

  if (counter == 10000) {
    float usecsPerIteration = (micros() - t) / (counter * 1.0);
    Serial.print(usecsPerIteration);
    Serial.println(" microseconds per iteration");

    // Print result to avoid loop getting optimized away
    Serial.println(sum);
  }

  ++counter;
}

```

The output is:

```
3.77 microseconds per iteration

```

Here's how I'm estimating clock rate from this. The body of the loop involves two additions and an equality check. Even if we assume that these simple operations take 10 clock cycles, the implied clock rate is still just (1 iter / 3.77 us) * (1e6 us / sec) * (10 cycles / iter) = 2.65 MHz.

What am I missing?

# Answer
> 8 votes
As Michael says there is a lot more going on than you think.

Firstly there are interrupts triggering which can slow things down (used to calculate milllis()).

Secondly you vastly under estimate the number of instructions that are being called. For a start the `loop` is being called from a `for(;;)` loop in `main()`:

```
    for (;;) {
        loop();
4   572:    0e 94 73 00     call    0xe6    ; 0xe6 <loop>
        if (serialEventRun) serialEventRun();
2   576:    20 97           sbiw    r28, 0x00   ; 0
2   578:    e1 f3           breq    .-8         ; 0x572 <main+0x10>
-   57a:    0e 94 1d 01     call    0x23a   ; 0x23a <_Z14serialEventRunv>
2   57e:    f9 cf           rjmp    .-14        ; 0x572 <main+0x10>
10 total

```

Then for the call to `loop()` the registers used get pushed to the stack, then your code executed, and the registers popped off again before returning. This is the code for loop when disassembled:

```
000000e6 <loop>:
    // Save the registers to the stack
2   e6:     cf 92           push    r12
2   e8:     df 92           push    r13
2   ea:     ef 92           push    r14
2   ec:     ff 92           push    r15
8 total

    // Add to the sum
2   ee:     40 91 44 01     lds r20, 0x0144 ; 0x800144 <counter>
2   f2:     50 91 45 01     lds r21, 0x0145 ; 0x800145 <counter+0x1>
2   f6:     60 91 46 01     lds r22, 0x0146 ; 0x800146 <counter+0x2>
2   fa:     70 91 47 01     lds r23, 0x0147 ; 0x800147 <counter+0x3>
2   fe:     80 91 42 01     lds r24, 0x0142 ; 0x800142 <sum>
2   102:    90 91 43 01     lds r25, 0x0143 ; 0x800143 <sum+0x1>
1   106:    84 0f           add r24, r20
1   108:    95 1f           adc r25, r21
2   10a:    90 93 43 01     sts 0x0143, r25 ; 0x800143 <sum+0x1>
2   10e:    80 93 42 01     sts 0x0142, r24 ; 0x800142 <sum>
18 total

    // Check the value to see if it's time to print
1   112:    40 31           cpi r20, 0x10   ; 16
1   114:    57 42           sbci    r21, 0x27   ; 39
1   116:    61 05           cpc r22, r1
1   118:    71 05           cpc r23, r1
2   11a:    d1 f5           brne    .+116       ; 0x190 <loop+0xaa>
6 total

    // From here on is the "IF" section - skipped by the BRNE above
-   11c:    0e 94 f5 04     call    0x9ea   ; 0x9ea <micros>
-   120:    c0 90 3e 01     lds r12, 0x013E ; 0x80013e <__data_end>
-   124:    d0 90 3f 01     lds r13, 0x013F ; 0x80013f <__data_end+0x1>
-   128:    e0 90 40 01     lds r14, 0x0140 ; 0x800140 <__data_end+0x2>
-   12c:    f0 90 41 01     lds r15, 0x0141 ; 0x800141 <__data_end+0x3>
-   130:    6c 19           sub r22, r12
-   132:    7d 09           sbc r23, r13
-   134:    8e 09           sbc r24, r14
-   136:    9f 09           sbc r25, r15
-   138:    0e 94 68 06     call    0xcd0   ; 0xcd0 <__floatunsisf>
-   13c:    6b 01           movw    r12, r22
-   13e:    7c 01           movw    r14, r24
-   140:    60 91 44 01     lds r22, 0x0144 ; 0x800144 <counter>
-   144:    70 91 45 01     lds r23, 0x0145 ; 0x800145 <counter+0x1>
-   148:    80 91 46 01     lds r24, 0x0146 ; 0x800146 <counter+0x2>
-   14c:    90 91 47 01     lds r25, 0x0147 ; 0x800147 <counter+0x3>
-   150:    0e 94 6a 06     call    0xcd4   ; 0xcd4 <__floatsisf>
-   154:    9b 01           movw    r18, r22
-   156:    ac 01           movw    r20, r24
-   158:    c7 01           movw    r24, r14
-   15a:    b6 01           movw    r22, r12
-   15c:    0e 94 c7 05     call    0xb8e   ; 0xb8e <__divsf3>
-   160:    ab 01           movw    r20, r22
-   162:    bc 01           movw    r22, r24
-   164:    22 e0           ldi r18, 0x02   ; 2
-   166:    30 e0           ldi r19, 0x00   ; 0
-   168:    88 e4           ldi r24, 0x48   ; 72
-   16a:    91 e0           ldi r25, 0x01   ; 1
-   16c:    0e 94 a9 04     call    0x952   ; 0x952 <_ZN5Print5printEdi>
-   170:    60 e0           ldi r22, 0x00   ; 0
-   172:    71 e0           ldi r23, 0x01   ; 1
-   174:    88 e4           ldi r24, 0x48   ; 72
-   176:    91 e0           ldi r25, 0x01   ; 1
-   178:    0e 94 0b 03     call    0x616   ; 0x616 <_ZN5Print7printlnEPKc>
-   17c:    60 91 42 01     lds r22, 0x0142 ; 0x800142 <sum>
-   180:    70 91 43 01     lds r23, 0x0143 ; 0x800143 <sum+0x1>
-   184:    4a e0           ldi r20, 0x0A   ; 10
-   186:    50 e0           ldi r21, 0x00   ; 0
-   188:    88 e4           ldi r24, 0x48   ; 72
-   18a:    91 e0           ldi r25, 0x01   ; 1
-   18c:    0e 94 b0 03     call    0x760   ; 0x760 <_ZN5Print7printlnEii>

 // All this is just counter++
2   190:    80 91 44 01     lds r24, 0x0144 ; 0x800144 <counter>
2   194:    90 91 45 01     lds r25, 0x0145 ; 0x800145 <counter+0x1>
2   198:    a0 91 46 01     lds r26, 0x0146 ; 0x800146 <counter+0x2>
2   19c:    b0 91 47 01     lds r27, 0x0147 ; 0x800147 <counter+0x3>
2   1a0:    01 96           adiw    r24, 0x01   ; 1
1   1a2:    a1 1d           adc r26, r1
1   1a4:    b1 1d           adc r27, r1
2   1a6:    80 93 44 01     sts 0x0144, r24 ; 0x800144 <counter>
2   1aa:    90 93 45 01     sts 0x0145, r25 ; 0x800145 <counter+0x1>
2   1ae:    a0 93 46 01     sts 0x0146, r26 ; 0x800146 <counter+0x2>
2   1b2:    b0 93 47 01     sts 0x0147, r27 ; 0x800147 <counter+0x3>
20 total

 // Get the registers back and return
2   1b6:    ff 90           pop r15
2   1b8:    ef 90           pop r14
2   1ba:    df 90           pop r13
2   1bc:    cf 90           pop r12
4   1be:    08 95           ret
12 total

```

That's more than 10 instructions. I make it 74 clocks to run one full iteration. (`counter++` alone is 20 clock cycles - double your estimation for the total...)

You have to remember two important things:

* AVR is a RISC CPU - that means that seemingly simple operations can take multiple instructions to perform.
* AVR is an 8-bit CPU - that means that working with any variables bigger than 8 bits in size require far more complex code, and you work with 32-bit variables (and floats, but that's outside the timing loop section of your code).

# Answer
> 0 votes
The loop function is called within the framework of the Arduino IDE. Beyond the code you write, also an interrupt check is done, which also cost time, and explains the difference.

The following function CAN be called after every loop call. See Majenko's answer about the details.

```
/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

```

See SerialEvent for more info.

However, as Kwasmich's comment says, you can easily circumvent this by performing your test inside a `while` loop.

---
Tags: arduino-uno
---


# Question
Title: How to choose alternate I2C pins on ESP32?
I'm a begginer with Arduino and this may be a basic question but I'm facing an issue.

I'm using a HTU21D sensor with an ESP32. This sensor use I2C communication. Inside the Arduino library, there is this function to start to collect data:

```
//Start I2C communication
void HTU21D::begin(TwoWire &wirePort)
{
  _i2cPort = &wirePort; //Grab which port the user wants us to use

  _i2cPort->begin();
}

```

As you can see, we can set in this function which port we want to use. Perfect. But my probleme is that I don't know how to use the type TwoWire. I checked some documentation but I was still unable to find a solution. I want to use GPIO\_16 as SDA and GPIO\_17 as SCL. So I tried something like that without result: `htu21d.begin(Wire(16, 17));`

**How to set SDA and SCL pin in TwoWire type ? (in my case GPIO\_16 and GPIO\_17)**

# Answer
> 7 votes
I was able to resolve my issue thanks to Juraj comment. I did :

```
Wire.begin(16, 17);
htu21d.begin(Wire);

```

# Answer
> 2 votes
Here is the example of how you can change esp8266 i2c pins. I used it for my ESP8266 and bme280, but the same for Arduino and other sensors.

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

void setup() {
  Wire.pins(12,2); //new SDA SCL pins (D6 and D4 for esp8266)

  Serial.begin(115200);
  delay(100);

  bme.begin(0x76, &Wire); //here is the address for my bme280 and instance of TwoWire object
}

```

For my ESP8266 I tried to use GPIO0 for SDA and GPIO2 for SCL, but no luck. Probably because GPIO0 is a Flash pin. Changing SDA to GPIO12 (or D6 pin) helped me.

---
Tags: i2c, wire-library, esp32
---


# Question
Title: Slave to Send Data after Receiving Command using I2C
I want to have my Slave Arduino to send signal to Master after the command was made. But the Slave Arduino does not proceeds to sending the signal after doing the command. What is wrong with my code?

**Slave**

```
void receiveEvent(int bytes) {
  dir = Wire.read();    // direction
  dis = Wire.read();    // distance
  spe = Wire.read();    // speed
  eStop = Wire.read();    // 1 or 0
  Serial.println(dir);
  Serial.println(dis);
  Serial.println(spe);
  mov = true;
}
void loop() {
    Wire.onReceive(receiveEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
       Wire.onRequest(requestEvent);
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
      Wire.onRequest(requestEvent);
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}
void requestEvent(){
    Wire.write(1);
    fin = false;
    Serial.println("sent");
}

```

**Master**

```

#include <Wire.h>

const byte interruptPin = 2;
byte dir = 0;
byte dis;
byte spe;
bool upd;

bool state= false;

void setup() {

  Wire.begin();
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), emergencyStop, CHANGE);
  Serial.begin(9600);

}
void loop() {
       if( state == false ){
       dir = 1;
       dis = 30;
       spe = 2;
       Wire.beginTransmission(9); // transmit to device #9
       Wire.write(dir);
       Wire.write(dis);
       Wire.write(spe);
       Wire.write(0);
       Wire.endTransmission();    // stop transmitting
       state = true;
       }
       if (state == true){
        if(Wire.available() > 0){
       Wire.requestFrom(9,2);   //6bytes from slave 9
          bool upd = Wire.read();
          Serial.println(upd);
        }
      }
}
void emergencyStop(){ // not working
  Wire.beginTransmission(9); // transmit to device #9
       Wire.write(0);
       Wire.write(0);
       Wire.write(0);
       Wire.write(1);
       Wire.endTransmission();    // stop transmitting

}

```

# Answer
found my solution for this. although not verified yet, but i removed Serial print and moved the Wire.onRequest outside of the if loop. and uses a ledPin for checkups

```
void loop() {

        Wire.onReceive(receiveEvent);
        Wire.onRequest(requestEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}

void requestEvent(){
    if ( fin == true){
      Wire.write(1);
     fin = false;
    digitalWrite(ledPin, HIGH);
    }

}

```
> 1 votes

---
Tags: arduino-mega, i2c, signal-processing
---


# Question
Title: Set PWM by period? And have it variable?
In this other stack QA I'm asking about generating a pulse signal with a period ranging from 63 ms to 6.5 ms. There is a popular PWM library however it doesn't compile and also since 63 ms is 15.8 Hz, that library's integer Hz setting isn't of help.

Is there a definitive process that isn't waving incense bundles in the corners of the room? There is an over abundance of "how tos" on the internet, however, none seemed to get me to a solution.

I've got a Mega and am using TIMER5. It's "just like" TIMER1 in that it is a 16 bit timer.

# Answer
> 2 votes
I stumbled upon a solution via trial and error coupled with watching the results on an o'scope.

The best guidance came from a Stack Exchange QA. Setup isn't particularly special, however the combination of WGM bits here worked and I didn't investigate further. Of the biggest importance are the prescaler divider bits, the least three significant bits of TCCRxB. `001` means no dividing or prescaling of the clock.

It all boiled down to 4 registers and the `pinMode()` call. Ultimately, seven lines of code:

```
#define PULSE_PIN 45
void setup() {
    // IMPORTANT: Clear Timer/Counter Control Registers
    TCCR5A = 0;
    TCCR5B = 0;

    // Set Timer/Counter Control Registers
    TCCR5A = B00101001; // Phase and frequency correct PWM change at OCRA
    TCCR5B = B00010010; // least sig bits sets "carrier frequency" by dividing CPU clock
    //  Observation:
    //  TCCR5B = B00010010 and OCR5A = 16667 results in period of 16.70 mSec
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    //  TCCR5B = B00010001 : OCR5A = 20000 results in period = 2.5 mSec 399.3Hz

    pinMode(PULSE_PIN, OUTPUT);
}

```

In the sketch, I watch an analog pin with a potentiometer on it and map its sweep to an effective RPM range of 950 to 9000 RPM. Hence the arbitrary range of periods I want to handle. When `loop()` sees the ADC change, the below code adjusts the PWM accordingly.

Note that no floating point data types are used. The magic numbers below were chosen by trial and error in a spreadsheet with values rounded to whole numbers.

```
void setRpm(){
    //  Getting to period in uSec from rpm the long way to keep
    //  the answer in range of the data type:
    unsigned int rpm = map(pot_adc, 0, 1023, RPM_MIN, RPM_MAX);
    unsigned long period = rpm/50;
    period = 24000/period;
    period = period*50;
    //  The trigger lasts 26°, so the PW is 26/360 * period.
    dwell = period/36;
    dwell = dwell*26;
    dwell = dwell/10;

    //  OCR5A is a counter the carrier frequency counts up to,
    //  which sets output period / frequency
    //  meaning OCR5A is period in uSec when TCCR5B = B00010010
    OCR5A = period; //  OCR5A is period in uSec when TCCR5B = B00010010
    //  OCR5B is the width of the pulse. If we used floats,
    //  we could use duty cycle * period.
    OCR5B = dwell;
}

```

Obviously, this code will have limitations to the range of frequencies it can handle, but the Internet has plenty of means for higher frequency PWM, especially when the desired PWM is fixed and doesn't need varying.

The most helpful way to see the control registers is as binary positions and not to rely upon macros, masks, and bit shifting. This comment block helped greatly:

```
 // WGM modes:
 // TCCR1A
 // Bit              7      6      5      4      3     2     1     0
 // Bit Name         COM1A1 COM1A0 COM1B1 COM1B0 ----- ----- WGM11 WGM10
 // Initial Value    0      0      0      0      0     0     0     0
 // changed to       1      1      1      1      0     0     0     1

 // TCCR1B
 // Bit            7      6      5       4        3        2        1        0
 // Bit Name       ICNC1  ICES1  -----   WGM13    WGM12    CS12     CS11     CS10
 // Initial Value  0      0      0       0        0        0        0        0
 // changed to     0      0      0       0        1        0        0        1
 // CS12,CS11,CS10 = (0,1,1) = prescaler divide by 64

```

---
Tags: pwm, timers, atmega2560
---


# Question
Title: How to detect V-SYNC on the SparkFun MicroView?
Is there a way to detect the start of the OLED screen refresh cycle (V-SYNC) on the SparkFun MicroView? There is no code for this functionality in the Arduino library; in fact it looks like the Arduino library is only set up to *send* data over SPI to the display, and not *receive* any data/status back.

Do you know how to access the internal state of the OLED screen directly, by polling some kind of status bit over SPI?

The only datasheet I can find of this OLED screen does not have SPI command details.

Update: here's a movie taken with an iPhone on "slo-mo" video, showing a full screen (all pixels on). There is clearly a screen refresh going on, which interlaces with the video frame rate.

# Answer
> 1 votes
The scenario you describe is called the *Tear Effect*. On the SSD1306, which the device you are interested in is based around, a Frame Synchronisation pulse can be emitted on the FR pin.

However it would appear that the specific SSD in use by SparkFun does *not* provide this pin from the SSD1306 on the external FPC connector, so there is no way of getting it. Probably owing to the small size of the display a reduced size connector without extra pins like FR was used.

So no, you can't combat the Tear Effect with that display.

There is nothing you can do over SPI, either. That is simply because SPI is just too slow for such things. You would use the FR pin because it's instantaneous. With SPI you would have to make a request to read a register, then read that register's value back. In that time, coupled with the question of exactly *when* would the register say it was at the start of a frame, the information would be completely meaningless anyway.

---
Tags: display
---


# Question
Title: Running out of GPIO & looking for suggestions
I'm working on a project using a NodeMCU and am quickly running out of GPIO pins. I'm trying to decide which way to go to complete it.

Right now, I have the MCU connected to a MAX31856 PT100 thermocouple (SPI), a PWM output, a transistor (acting as a switch), a single button and a single LED. I'm needing to add at least 2 more of the MAX31856, a display (either I2C or SPI) and a rotary encoder/button.

I've looked into GPIO expanders, but I'm doubtful that the available libraries for the additional hardware will work through the expanders. I have a Mega that will work without a doubt, but then I will have issues with WiFi & MQTT. I looked at the Mega's with onboard WiFi, but I got so confused in reading how to program it, setting the DIP switches, etc that it doesn't seem like a valid choice.

Can anyone offer guidance?

# Answer
Two main solutions comes to my mind:

1. GPIO expander (as you mentioned). It is really easy to use them as digital inputs or outputs. So you can connect button, LED, transistor and maybe even display (you did not specified type of the display, so I assume standard LCD 1602 or 2004 display). You can also connect SPI-CS signals to the expander, but this depends on used libraries...
2. Auxiliary Arduino e.g. Nano. Arduino can be used for measurement of the temperature and other stuff and NodeMCU for communication. In this case you have to implement some kind of communication between these two boards (SPI, I2C or UART).
> 1 votes

---
Tags: wifi, pins, nodemcu
---


# Question
Title: Can't Interface SIM900a With Arduino Uno
I've got the following module of SIM900a.

My connections are:

```
VCC -> External 5 Volt 1.5 Amp Supply
GND -> Common GND
TX -> Arduino RX (Pin 0)
RX -> Arduino TX (Pin 1)

```

I hear a ring when I call on the sim card that has inserted there. So it can register to a network successfully. I've uploaded a blank code in Arduino Uno to test `AT Commands`. But I'm not getting any response when I type `AT` on Serial Monitor. What am I doing wrong here?

# Answer
> 1 votes
At first, make sure that the sim has connected to the network. For this, you can call to the sim number from another phone. If not ringing that means the sim wasn't able to connect with the network. For this check power supply, antenna etc. If ringing then there something wrong in connection or code. So cross check the connection and send `AT` to the module and wait for returned data. If no data returned, then there check connection again. If the returned data is `OK`, then it is ready to use. and if returned data is `ERROR` then Arduino have connected to sim module but sim network, power supply etc problem happening.

# Answer
> 1 votes
I was facing the same issue and solved this issue when I have used softwareSerial.h library and used to connect TXD of sim900A with pin 13 and RXD of sim900A withpin 12 of ardunio MEGA.

You can also use 10 and 11 pins of mega instade of 12 and 13 i.e.

```
#include <SoftwareSerial.h>      // Configure software serial por
SoftwareSerial SIM900A(10, 11);  // (sim 900 connections RXD=>10 & TXD=>11)

```

---
Tags: arduino-uno, gsm, serial-data
---


title: Stable frequency generation

text:
# Question
Title: Stable frequency generation
I'm trying to work out the best way to generate a stable frequency with my Uno R3

I'm using interrupts to generate an approximately 40KHz frequency which drives some ICs/MOSFETs to effectively generate 40KHz AC which powers a transducer.

I need to receive the frequency at a second transducer and calculate any frequency shifts.

* The problem is that the generated frequency drifts a little bit off of 40KHz. Is there a way to lock it in at 40KHz via software? I'm receiving approximately 40KHz output (as measured using PicoScope software) with this code:

```
#define LEDPIN 13
void setup()
{
pinMode(LEDPIN, OUTPUT);
// initialize Timer1
cli();          // disable global interrupts
TCCR1A = 0;     // set entire TCCR1A register to 0
TCCR1B = 0;     // same for TCCR1B
// set compare match register to desired timer count:
OCR1A = 24;
// turn on CTC mode:
TCCR1B |= (1 << WGM12);
// Set CS11 for 8-bit prescaler:
TCCR1B |= (1 << CS11);
// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
// enable global interrupts:
sei();
}

void loop()
{
// main program
}

 ISR(TIMER1_COMPA_vect)
{
digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}

```
* If there isn't a way to lock it in, is there atleast a way for the Uno to accurately display/store the frequency of the signal it generated at a given time?

Or is this not plausible because the Uno would "think" it is generating 40KHz?

Thanks for any hints or suggestions.

**EDIT:** @RussellMcMahon pointed me in the right direction for this, so I accepted his answer. However, I wanted to share my final code and my misconceptions I encountered. Hopefully this will assist someone else in the future. I'm obviously by no means an expert, and I will try to not give any misleading information here.

My original goal was, although poorly stated, to generate as clean a 40KHz PWM with 50% duty cycle as possible.

Problems with my original code above were:

* Using an 8-bit pre-scaler
* Using an interrupt
* Using digitalWrite()

**8-Bit Pre-Scaler**
The problem here was that the counter only ticked over once every 8 clock cycles. *16MHz clock / 8 (pre-scaler) = 2MHz clock* When I asked one of my professors about this he stated something along the lines of "a cycle could be missed due to an interrupt, and would cause it to wait 7 more cycles to 'tick'". Indeed I was originally using interrupts, and when we did the calculations it seemed like it could plausibly cause up to a a 1KHz swing at 40KHz.
To rectify this I took out the pre-scaler, and ran straight at the base clock speed to increase resolution.

**Using an interrupt**
Essentially the interrupt could cause clock cycles to not be counted, further complicated by using an 8-bit pre-scaler. If one clock cycle was missed, with a 2MHz clock (after pre-scale), you add 5E-7 seconds to the counter, changing the output frequency.

**Using digitalWrite()**
The digitalWrite function is pretty slow. I'm not a guru, but I read this in multiple places and there seems to be a good comparison of methods here: Digital Pin Oscillation To get around this problem it had been suggested I toggle a single bit, which is what I set out to do in my final code. (It is worth noting, now that I've completed this project, that the previous link also makes reference to a library addition for faster digitalWrite/Read/etc....)
I went through a few variations and scrounged code from all over, and made a couple working examples but they didn't do it the way I wished. I believe part of the project I based this version off of was a melding between a previous version I had working and a class example I found online.
Without further ado, I present the code that took me an embarrassing amount of time to write from numerous sources... I really should tinker with this stuff more often:

```
#include <avr/io.h>
#include <avr/interrupt.h>
void setup()
{
//Disable interrupts
cli();
// Clear Timer1 registers
TCCR1A = 0;
TCCR1B = 0;
// Set OCR1A (TOP): 16MHz/40KHz /2 = 200 steps.
// Divide 200 by 2 = 100 because waveforms are centered around OCR1A (because toggle)
OCR1A = 100;
// Configure Timer/Counter 1
// Select P & F Correct PWM Mode, and OCR1A as TOP. Use WGM Bits 10 and 13.
// WGM Bits are in TCCR1A and TCCR1B. Any previous settings are cleared.

// Enable COM1A0 to toggle OC1A on compare match
TCCR1A = _BV(WGM10) | _BV(COM1A0);
// CS10 to enable base clock without pre-scale
TCCR1B = _BV(WGM13) | _BV(CS10);

//Set OC1A (Digital Pin 9 / Port B Pin 1) to output
DDRB |= _BV(1);
}

void loop()
{
}

```

For reference, here is the clock frequency formula. In this instance, I had to divide the result by 2 again since I am toggling.

Resultant output verified by PicoScope:

In closing, you will notice that it isn't exactly 40KHz. Research turned up that the Arduino Uno makes use of a less accurate ceramic resonator to clock the ATMEGA328P (although a 16MHz crystal oscillator is onboard to clock the USB). To further increase accuracy in a generated signal will require the Arduino to be driven with an external clock source.

# Answer
You can use a timer/counter to output a square wave signal of your choosing without processor intervention or use of interrupts.

In data sheet
**"ATmega48A/PA/88A/PA/168A/PA/328/P"Atmel-8271I-AVR- ATmega-Datasheet\_10/2014**

page 142 it says

* The double buffered Output Compare Register (OCR2A and OCR2B) are compared with the Timer/Counter value at all times. **The result of the compare can be used by the Waveform Generator to generate a** PWM or **variable frequency output on the Output Compare pins (OC2A and OC2B).** See ”Output Compare Unit” on page 143 for details. The compare match event will also set the Compare Flag (OCF2A or OCF2B) which **can** be used to generate an Output Compare interrupt request.

The interrupt CAN be generated and used but is optional.
It looks like relevant material extends as far as page 159.
> 3 votes

# Answer
I know this thread may be dead but if it happens to somebody, the aformentioned method works perfectly fine. You just need to disable timer0 (power\_timer0\_disable();) and then your 40kHz signal will not fluctuate (in frequency).

In any case, yeah try to avoid digitalWrite if you want speed.
> 1 votes

# Answer
PWM is the solution.

Russel's answer is proper. My contribution here is a simplification and to relay my observations. I made a QA about PWM recently and can affirm that "bit banging" and interrupts are not going to be stable. I observed digital writes to be roughly 1 microsecond, so toggling a pin is 2 µsec. This did not affect my project, so no further tests performed about the `digitalWrite()` function. Writing changes to the port macro as a whole is much faster than using `digitalWrite()`, however this still will not have the inherent stability setting up the PWM and its output pin will provide. *Anecdotally, analogRead() is roughly 100 µsec.*

I set up my timer with a prescaler and then applied a count to `OCRxA`. Via my prescaler and `WGM` bits, it turns out that the `OCR` registers were 1:1 for microseconds. `OCRxB` perfectly set the pulse width I was seeking.

Observing the period on an o'scope, it might have been off from the exact integer in `OCRxA` but did not drift. The error I observed was in the tens of microseconds and the values in `OCRxB` were between 6300 and 63000. Code examples are in aforementioned link to my QA. From researching my own solution, I learned this error is likely within tolerance of the crystal providing CPU freq.
> 1 votes

---
Tags: arduino-uno, atmega328, timers
---


# Question
Title: How to Work Two Linear Actuator Synchronously by Using Arduino and VNH5019 Motor Driver?
I am newbie and I want to build a project that contains two linear actuator that move synchronously. Two of them will lift up and down at same time. I use arduino mega and VNH5019 motor driver. I have thompson electrac ELD linear actuator. I have never tried to synchronize two linear actuator. Linear actuator have encoder output ( it is hall effect encoder -( not absolute. So it cannot keep last position in case of power cut )). Encoder type is hall effect type. Encoder output voltage levels low (logical zero), typical / max is 0.1/0.25 Vdc. Also it has output fully extented/retracted signal. I tested it with H-Bridge motor driver made of 4 SSR relays and push button switches to retract and extract. There is a synchronization problem.The system will stop when actuators extracted 500 mm ( actuators have 900 mm stroke length) How should I solve that synchronozation problem could you help me ? What should I do?

# Answer
It sounds like you need to watch both encoder outputs and don't let one get ahead of the other. Naturally, they won't sync exactly (i.e., pulse simultaneously) but you can set a limit on how many counts to let them differ by, before pausing the faster actuator while the slower one catches up.

If you need to save positions across a power failure, you'll need to 1) provide enough backup power to keep the system alive past the supply failure to give you time to stop both actuators and store both of their positions in EEPROM; and 2) provide a signal to the Arduino that the supplied power (not the backup) is going down, so it can begin its orderly shutdown.
> 1 votes

---
Tags: arduino-uno, motor, arduino-motor-shield
---


title: Charge lipo battery while using

text:
# Question
Title: Charge lipo battery while using
I have a system that uses Arduino and some modules. The system needs 5v dc power with 3A current at maximum(The system needs 3A current for some seconds every 5 minutes and after that the current will get back to 300-400mA) and on the other side i have a 5v dc charger with 400-500 mA current. So my problem is lack of amperage and i can't run correctly Arduino with 5v dc charger. For solving this problem i want to use a Lipo battery to connect to Arduino but the battery will ran out and i can't get energy from battery so i want to connect the battery to my charger while the Arduino uses the battery, How can i do that? Is there any module to do this work? Can i use TP4056 with protection version to do this work?(Note: I can't change charger)

# Answer
> 0 votes
You really shouldn't charge a lithium battery whilst discharging it. The charger may either never know that it has finished charging and overcharge it, or shut off early and never charge it up properly at all.

Instead you should arrange that your MCU is powered directly from the PSU so that it always has stable power, and feed that same power into a normal charger via some form of electronic switch so it can be turned on and off. The output of the battery can then be fed through another switch into your heavy load.

When it comes time for your load to be activated you switch off the power from the charger and switch on the connection from the battery to the load.

What you use to do the switching is entirely up to you - whether you choose P-channel MOSFETs or relays entirely depends on your situation.

Here's a block diagram to better illustrate it to you:

simulate this circuit – Schematic created using CircuitLab

---
Tags: arduino-uno, arduino-mega, battery, iot, lipo
---


title: Cycling through switch states

text:
# Question
Title: Cycling through switch states
I'm making a desk lamp out of 2x WS2811 strips (attached to the triple ports at top right of board below). The brightness of the strips is controlled by a potentiometer, and the colour by a switch. Each press of the switch cycles through red, blue and white:

Here's the code I've come up with:

```
#include <FastLED.h>

#define strip_pin     7
#define NUM_LEDS    15

CRGB leds[NUM_LEDS];
int distance;
int brightness;
int brightnesspin = 2;
int pin_switch = 3;

// variables to hold the new and old switch states
boolean oldSwitchState = LOW;
boolean newSwitchState1 = LOW;
boolean newSwitchState2 = LOW;
boolean newSwitchState3 = LOW;
byte state = 0;

void setup()
{
  Serial.begin(9600);
  FastLED.addLeds<WS2811, strip_pin, BRG>(leds, NUM_LEDS);
}

void loop()
{
  delay(500);
//  Colour control
//##############################################
    newSwitchState1 = digitalRead(pin_switch);
    delay(1);
    newSwitchState2 = digitalRead(pin_switch);
    delay(1);
    newSwitchState3 = digitalRead(pin_switch);
    // if all 3 values are the same we can continue
    if (  (newSwitchState1==newSwitchState2) && (newSwitchState1==newSwitchState3) )
    {

        if ( newSwitchState1 != oldSwitchState )
        {

           // has the button switch been closed?
           if ( newSwitchState1 == HIGH )
           {
                // increase the value of state
                state++;
                if (state > 3) { state = 0; }
                for (int i = 0; i < NUM_LEDS; i++)
                {
                if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}
                }
                FastLED.show();
            }
           oldSwitchState = newSwitchState1;
        }

//    Brightness control
//##############################################
  brightness = analogRead(brightnesspin);  brightness = map(brightness, 0, 1024, 0, 255);
    for (int i = 0; i<NUM_LEDS; i++)
      {
        FastLED.setBrightness(brightness);
      }
  FastLED.show();
  Serial.print("Brightness: ");
  Serial.println(brightness);
    }
}

```

The brightness control works fine, and the switch cycles through the colours *once*, but the strip stays white once it's there, even though the serial monitor shows the switch changing state. How can I get the strip to cycle back round to red?

# Answer
> 2 votes
The problem lies in your for cycle.

* If `(state == 1)` you are switching the red colour ON.
* If `(state == 2)` you are switching the blue colour is ON. So at this moment, you have red AND blue colour on, not only blue. I assume the output colour is purple-ish.
* If `(state == 3)`, you activate red (which is already ON), blue (which is also already ON) and also green (which changes state from OFF to ON) so you get white colour. At this moment you went through all three possible conditions.
* Then you go back to `(state == 1)`. All colours are already activated, so from this moment you get only white...

Solution:

```
for (int i = 0; i < NUM_LEDS; i++) {
  if (state == 1) {
    leds[i].red = 100;
    leds[i].blue = 0;
    leds[i].green = 0;
    Serial.println("Red");
  }
  if (state == 2) {
    leds[i].red = 0;
    leds[i].blue = 100;
    leds[i].green = 0;
    Serial.println("Blue");
  }
  if (state == 3) {
    leds[i].red = 100;
    leds[i].blue = 100;
    leds[i].green = 100;
    Serial.println("White");
  }
}

```

# Answer
> 2 votes
In your lines:

```
                if (state==1) { leds[i].red = 100;Serial.println("Red"); }
                if (state==2) { leds[i].blue = 100;Serial.println("Blue"); }
                if (state==3) { leds[i].red = 100; leds[i].blue = 100; leds[i].green = 100;Serial.println("White");}

```

The LEDs are set on, but are never turned off.

Sequence is:

1: Red leds turn on; strip appears red.

2: Blue leds turn on (the leds will probably actually look purple rather than blue here as the red leds are still on)

3: Green leds turn on (red and blue leds are already on); strip appears white

back to start:

1,2,3: nothing changes as all leds are already on, strip remains white.

I'd suggest adding:

```
leds[i].green = 0; leds[i].blue = 0;

```

to the `state == 1` condition and

```
leds[i].green = 0; leds[i].red = 0

```

to the `state == 2` condition.

---
Tags: switch, potentiometer, led-strip
---


# Question
Title: generate two phase-shifted PWM pulses triggered by frequency-divided external signal with Arduino uno?
I have a 4kHz pulse as trigger and I need two phase-shifted PWM output with divided frequency from arduino uno.

Now I've managed one PWM output using the following code:

```
int cnt = 0;
void setup() {
  pinMode(3, OUTPUT);
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
}

void loop() {

}

void rising_edge() {
  cnt = cnt + 1;
  if (cnt >= 4) {                           //divide by 8
    digitalWrite(3,(digitalRead(3)^1));
    cnt = 0;
  }
}

```

As suggested by Majenko♦, I tried using Timer1 lib, but the phase shift is always 15us, regardless timer1 period.

```
#include <TimerOne.h>

int cnt = 0;

void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, INPUT);
  Timer1.initialize(10000);
  Timer1.attachInterrupt(ISP_T1);
  attachInterrupt(digitalPinToInterrupt(2), ISP_INTx, RISING);
}

void loop() {

}

void ISP_INTx() {
  cnt = cnt + 1;
  if (cnt >= 4) {
    digitalWrite(3,(digitalRead(3)^1));
    cnt = 0;
    Timer1.start();
  }
}

void ISP_T1() {
  digitalWrite(4,(digitalRead(4)^1));
  Timer1.stop();
}

```

Shift should be arbitrary value between 0-1 x period (depends on divider)

Adjustable duty is preferred but not necessary.

# Answer
I think your first example is very close. What about:

```
int cnt = 0;
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
}

void loop() {

}

void rising_edge() {
  cnt = cnt + 1;
  if (cnt >= 4) {                           //divide by 8
    cnt = 0;
  }
  switch(cnt){
    case 0: digitalWrite(3,HIGH);break;
    case 1: digitalWrite(4,HIGH);break;
    case 2: digitalWrite(3,LOW);break;
    case 3: digitalWrite(4,LOW);break;
  }
}

```

Assuming a uniform input frequency, pin 3 will be 90 degrees out of phase with pin 4. You could make this adjustable if you don't mind a larger divider by expanding the switch/case to eg 6 or 8 steps.

You could get more steps by triggering on rising and falling edges (although that may not give uniform phase if the incoming PWM is not at 50% duty cycle.
> 1 votes

# Answer
> If I understand correctly, it uses timer0 for interrupt and CPU for counting.

No, it doesn't. The interrupt is an interrupt. Timer0 is a timer. At the moment you just have an *external* interrupt triggering an ISR which adds to a variable and toggles an output.

Timer0 is used to drive `millis()` and `delay()`.

What you need to do is set up a timer (*not* Timer0 since it's already reserved) which will time out with a period equal to the time difference of the phase shift. Start it in your existing ISR (when the output is toggled), and in the timer's ISR stop the timer and toggle the second output (or set it the same as the 0° output).

You may find the TimerOne library helpful for this.
> 0 votes

---
Tags: arduino-uno, interrupt, pwm, timers
---


title: Serial parsing strange data

text:
# Question
Title: Serial parsing strange data
I have a project where I use a software serial connection to read serial data from a barcode scanner.

All is good. However from time to time I have some problems with the data that I'm receiving.

> You said : 123456789��?�: @���?���?���?���?���?
>
> You said : 123456789
>
> You said : 123456789123456
>
> You said : 987654321789456123

My code is something similar to the one below

```
int count = 0;
void parseSerial() {
  char ser[20];
  while (Serial.available() > 0) {
    char c = Serial.read();
    if ( c != '\r' && count <= sizeof(ser)) {
      ser[count] = c;
      count++;
    } else {
      Serial.print("You said : ");
      Serial.println(ser);
      for(int i=0; i < sizeof(ser); i++) {
        ser[i] = '\0';
      }
      count = 0;
    }
  }
}

```

Any idea on how I can get rid of "��?�: @���?���?���?���?���?"?

Thanks.

# Answer
> 2 votes
The problem is that the buffer is not initialized to start with. When you call `parseSerial()`, it contains garbage, which is what you see on the serial monitor. In order to avoid printing out that garbage, you have to properly terminate the string, i.e. add a `\0` after the last valid character.

You did that *after* printing the string (you filled the whole buffer with `\0`, which is overkill), but that's too late. The subsequent printouts are OK though.

The recommended way to handle incoming serial data is to look for a terminating character (`\r` seems to be what you expect), and buffer all the incoming bytes until you see it. Don't forget to save 1 byte of buffer space for the terminating `\0`:

```
void parseSerial() {
    static char buffer[20];
    static int count = 0;

    while (Serial.available()) {
        int c = Serial.read();
        if (c == '\r') {           // received complete line
            buffer[count] = '\0';  // terminate the string
            Serial.print(F("You said: "));
            Serial.println(buffer);
            count = 0;
        }
        else if (count < sizeof buffer - 1) {
            buffer[count++] = c;
        }
    }
}

```

Notice that the buffer here being static, you can accumulate partial messages through successive calls to `parseSerial()`. Only when the message is complete will it print it back.

# Answer
> 0 votes
Why are you using char array when you can use String. And use Serial.readStringUntil('\r'); instead Serial.read.

Code:

```

void parseSerial(){
String read = " ";
int count = 0;
if(Serial.available()>0){
while(Serial.available()>0){

if(count != 20){
read = Serial.readStringUntil('\r');
count++;
}
}

}
Serial.println("You said: ");
Serial.print(read);
}

```

---
Tags: serial, array
---


# Question
Title: Wemos: 16x2 display doesn't show anything
I connected a 16x2 LCD display to a Arduino Uno. Then I tested a "Hello, Word" code and it works perfect. Now I want to do the same with a Wemos D1 Mini but it doesn't work.

Here the Wemos is not connected to USB:

This os the "Hello, World" code. I needed to change the name of the pins (maybe this is the problem):

```
#include <LiquidCrystal.h>

const int rs = 8, en = 7, d4 = D5, d5 = D4, d6 = D3, d7 = D2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  lcd.begin(16, 2);
  lcd.print("hello, world!");
}

void loop() {
  lcd.setCursor(0, 1);
  lcd.print(millis() / 1000);
}

```

This is the result (potentiometer works perfect):

# Answer
You are doing it on wemos d1 mini isnt it ?

Then you dint include its header files, Did you check the "LiquidCrystal.h" has definitions for wemos pinouts?

Your lcd is fine, n wemos too, its just your configuration is wrong.

Check those and update here.
> 2 votes

# Answer
Although an old question, i just ran into the excat same issue.
The problem is that the pin numeration on the wemos D1 isn't the same as on the arduino.
I've followed the liquid crystal arduino tutorial but changed the numeration of the pins to

```
const int rs = 12, en = 13, d4 = 14, d5 = 4, d6 = 5, d7 = 16;

```

Now, at least for me, the display works as it should
> 2 votes

# Answer
Three possibilities (it's impossible to be more accurate from your description):

1. The display isn't wired to the pins you specified in your sketch
2. The display doesn't accept 3.3V signals when run from 5V
3. The display doesn't function when run from 3.3V

It's certainly not being initialized, which tells me that the instructions for setting it up aren't getting through, or aren't being executed when they do get through.

You can:

1. Use an oscilloscope or logic analyzer to confirm the right pins are in use,
2. Try powering the display from 3.3V if it's currently powered by 5V
3. Try powering the display from 5V if it's currently powered by 3.3V

If it's powered by 5V you may want to consider adding some logic level translation to boost the IO signals from the Wemos to 5V.
> 0 votes

---
Tags: arduino-uno, lcd, nodemcu, display
---


# Question
Title: Upload application from Visual Studio 2019 with PlatformIO
How upload application from Visual Studio? I can’t find upload process from standard VS in documentation https://docs.platformio.org/en/latest/ide/visualstudio.html

I hate VS Code.

# Answer
I have final solution for uploading application from VS 2019.

1. Visual Studio have Tools \> External Tools... where is possible add the PlatformIO command for uploading application `pio run -v -t upload`

1. After that is possible adding custom button to Toolbar
2. Fantastic thing is, that during upload you can Stop the process
> 3 votes

# Answer
I am using Visual Studio Code, but I suppose the plugin works similar in Visual Studio. Look at the screenshot below.

In red rectangle you have "Project tasks options", where you can find "Upload" button. This will not work, if you have not set at least one environment in platformio.ini file – see the documentation. Example of the simple environment for Arduino Uno created in platformio.ini file:

```
[env:uno]
platform = atmelavr
board = uno
framework = arduino

```
> 1 votes

---
Tags: esp8266, visualstudio
---


# Question
Title: Problem with powering ublox NEO-6M GPS module
Firstly, I'd like to mention that I'm a beginner. This is the first time I've worked with a GPS module. The serial monitor is completely empty when I upload the following code to my circuit:

```
#include <SoftwareSerial.h>

// The serial connection to the GPS module
SoftwareSerial ss(4, 3);

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

void loop(){
  while (ss.available() > 0){
    // get the byte data from the GPS
    byte gpsData = ss.read();
    Serial.write(gpsData);
  }
}

```

Things I might've done wrong and some things I'd like to mention:

1. As you can see, I connected the module to 5V pin of Arduino but the datasheet says: The reason why I think this might not be the case is that there are multiple projects on the internet that have used a circuit like mine.
2. I've placed my module on the window edge so that it can get a good line of sight. I'm yet to try it outdoors.
3. After reading the datasheet, I tried a potential divider using resistors to get 3.3V and the result is still nothing. I later realized that this was probably a really silly thing to do since I created an unstable supply which is not suitable for the module.
4. For cold-start conditions, how long can it take to lock to a satellite? I've waited several times for half an hour each time only to get no result in the end. Can it take more than that? Should I wait?
5. What can I use to supply constant 3.3V to the module? Are there any special power supplies for GPS modules?
6. Is it possible to tell if my module is damaged just by seeing?

# Answer
1. The module may very well be dead now, due to giving it 5V.

But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought.

2. A window means that at least 50% of the sky is blocked by the building. The module might not be able to get a signal from enough satellites for a cold start.
3. A voltage divider only works if there is constant current. As you've noted, you just created an unstable power supply.
4. The datasheet says 27 s but that is probably with a clear view of the sky.
5. Next to the 5V pin on the Uno is a 3.3V pin. How about using that?
6. Visually, no. But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not.
> 1 votes

---
Tags: power, softwareserial, gps
---


# Question
Title: Arduino is running as a server, but want to occasionally act as a client to update time
My Arduino (actually an ESP32-based Adafruit HUZZAH32) is running as a wifi server. Its main job is to service GET requests from a user, and to periodically turn devices on and off based on the commands implicit in those GETs.

It needs to keep an accurate time/date - in order to turn devices on/off as directed. My cheap real-time clock is off a couple seconds or more per day. So I figure I'll use code such as the example at:

https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/

... in which the Arduino creates a client to get the time from an NTP server. Once a day (e.g. checking for the RTC time to be 00:00hrs in my "loop"), I'll adjust the RTC using NTP.

Looking around, it sounds like this is ok, for the Arduino to act as a client, as long as it's not actively servicing a client (the user's GET requests). Do I have that right ? Need I worry that a user might be sending a GET when that happens ?

# Answer
There is no problem with running multiple servers and use multiple clients with the WiFi library of the ESP32 core for Arduino as it is not a problem with most of the WiFi libraries for Arduino (some can't run servers (TinyGsm) or can run only one server (WiFiEsp(AT)).

But you don't need a WiFiClient for NTP time. First because NTP runs on UDP and second because the ESP32 SDK provides SNTP and the ESP32 core for Arduino wraps it in functions presented in the ESP32 examples library's SimpleTime example.
> 2 votes

---
Tags: adafruit, time
---


title: Are there any detail examples of Si4463

text:
# Question
Title: Are there any detail examples of Si4463
Recently, I bought two Si4463 chips, but I don't know how to use them. It seems complex. I'd like to know if there are any examples of an Si4463 used with an Arduino?

# Answer
This seems to be the Chip used on the RFM24. Have a look on the RadioHead Library:

http://www.airspayce.com/mikem/arduino/RadioHead/classRH\__RF24.html

I normally use the same libs for the RFM69 (Semtech SX1231) with my Whisper Node and works fine. I would expect the same for the RFM24.

Btw, getting a silicon and building the Radio can be quite complicated. You might would consider starting with a Dev Kit or an assembled module.

Also, I don't think HopeRF produces RFM24 anymore, can't find on their site (http://www.hoperf.com/rf\_transceiver/). If you just need it for a single project and does not intent to build a product of that, might be better chose a different/more popular option. Will be easier to find support for it on the Internet.
> 3 votes

# Answer
I've looked at the data sheet for this and I think it is the wrong choice of device for a beginner. Can I suggest that you start by looking at a relatively simple DPI interfaced device, such as a sensor or RTC. This will teach you the basics of sending commands via the Wire library. You might even get the hang of it just by looking at existing libraries.

I can't find a library, so you are going to need to write your own. The library will need a begin function which initialises you class and a write and read function, which write and read from an address.

```
void begin(void);
uint8_t read(const uint8_t& address);
void write (const uint8_t& address, const uint8_t& bytesOfData, const uint8_t* pData);

```

You will need to flesh those functions out, but that's it. If you want to make you library more useable read the datasheet and create wrapper functions for each of the registers that can be accessed.

```
// This instruction requires 10 buts spread over two bytes.
void writeFrequencyOffset (const uint8_t& highByte, const uint8_t& lowByte)
{
  write (0x73, lowByte);
  write (0x74, highByte);
}

```

The process of creating friendly wrappers is a tedious operations, just reading the data sheet and translating that into code.
> 4 votes

# Answer
The Si4463 IC from Silicon Labs is a great communication chip with very good sensitivity. However, its onboard MCU uses SPI as a communication interface to communicate with an external microcontroller.

In a module such as an HC-12, an STM8SF103F3 microcontroller which is programmed to act as an SPI to UART bridge. HC-12 modules lets you control all of the internal functionality of the Si4463, even using AT+ commands for things like adjusting baud rate and transmission power. Unfortunately, the code doing the SPI to UART bridging is proprietary, which leaves you at a disadvantage if you're trying to use the Si4463 chips to build a real product.

But perhaps, if you have purchased something like the RFM26W module, or you simply have a bare-bones Si4463 IC to work with, then you will need to communicate with it via the SPI pins. It must be noted that there is no standard Arduino library available for communicating with the Si4463's SPI pins.

Working with SPI pins can get a bit complicated as you're trying to sync the clockwork. If you want to get your hands dirty, then you could go ahead and have a look at the Si4463 datasheet and look at the SPI timing parameters on page 16.

Fortunately, there is a Si4463 library project on GitHub which you can look into and perhaps modify the code to fit your needs.

Here is the GitHub page for the Si4463 Arduino library made by zkemble:

https://github.com/zkemble/Si446x

Here is the blog post where he explains it in more detail:

http://blog.zakkemble.net/si4463-radio-library-avr-arduino/

Here is the documentation for the said library:

https://zkemble.github.io/Si446x/\_si446x\_8h.html
> 1 votes

---
Tags: library, spi, wireless
---


# Question
Title: How come some Arduino Nano pins (D3, D4, A3, A4, A6, A7) cannot be set high?
I made a sketch to switch on all digital and analog pins, and found out several pins did not work as expected. Note: I manually put a jumper wire from each digital and analog pin (one at a time) to a resistor, LED and GND pin.

What I noticed was that some pins did not work (D3, D4, A4, A6 and A7) and pin A3 was only lit about half intensity. I tried two different Nanos and they performed both equally (also pin A3 at half intensity).

I also tried the jumper wires directly touching the pins (without a breadboard in between, to rule out a breadboard problem). Same behavior (so the breadboard is ok).

My questions:

1. How come pins D3, D4, A4, A6 and A7 are not output VCC (3.3V) ?
2. How can I switch pins these pins on?
3. What is the reason pin A3 is blinking at half intensity?
4. How can I switch this pin fully on?
5. Bonus question: I used numbers, why are the pin names A0..A7 and D0..D12 not defined in Arduino IDE?

---

Test sketch:

```
const int NR_OF_PINS = 22;

int pins[NR_OF_PINS]   =
// 0  1  2  3  4  5  6   7   8   9  10 11   12  13  14  15  16  17  18  19  20  21
//D0 D1 D2 D3 D4 D5 D6  D7  D8  D9 D10 D11 D12 D13  A0  A1  A2  A3  A4  A5  A6  A7
 { 1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 26 };

void setup()
{
  for (int n = 0; n < NR_OF_PINS; n++)
  {
    pinMode(pins[n], OUTPUT);
    digitalWrite(pins[n], HIGH);
  }
}

void loop()
{
}

```

# Answer
> 2 votes
You don't need an array, and your "base" pin is wrong - you start at pin 1, not pin 0. Also pins A6 and A7 can only be analog inputs, not digital outputs.

It's simpler to write:

```
void setup() {
    for (uint8_t i = 0; i < NUM_DIGITAL_PINS; i++) {
        pinMode(i, OUTPUT);
        digitalWrite(i, HIGH);
    }
}

void loop() {
}

```

That will work correctly on all Arduino boards regardless of the number of pins, since the board definition defines how many pins there are, and pins are always contiguously numbered from 0.

---
Tags: arduino-nano, led, pins, port-mapping
---


# Question
Title: How to access variables by variable? (I.e. variable variables?)
Can Arduino handle variable variables?

```
function getLetterCode(char input) {
    int letter_a = 17;
    int letter_b = 42;
    int letter_c = 50;
    return letter_$$input$$; //pseudocode
}

```

This is just a stripped down code to demonstrate my question. I am aware of arrays, the switch structure and other workarounds, but for my specific need variable variables would save tons of typing.

# Answer
> 3 votes
No, you can't do that sort of thing. That sort of thing is only possible on interpreted languages where the name of the variables is seen at runtime. In compiled languages you can't see the variable names (they no longer exist) so you can't access them by name like that.

Instead you need to either store your variables in a simple array and access them by index, or create an array of "key/value" pairs (simplest to use an array of a `struct`) and iterate it looking for the right key to match with your input. Or, if there aren't too many inputs, simply use a `switch` to select different values:

```
int getval(char input) {
    switch (input) {
        case 'a': return 17;
        case 'b': return 42;
        case 'c': return 50;
        default: return 0;
    }
}

```

---
Tags: variables, functions
---


# Question
Title: How to scale a bitmap (uint8_t array) in Arduino?
So I have a project where I send text to an Arduino, which is then printed out as a QR code on a thermal printer that can take a bitmap image with a given width and height.

Is there a way I can "scale up" the "image," making it so one pixel is scaled up to 4 or 8 pixels?

Additionally, would it be possible to add a "quiet zone" of sorts on the left side of the image, as I am not able to offset/justify it to the middle.

QR Code lib: https://github.com/ricmoo/QRCode

Thermal printer lib: https://github.com/adafruit/Adafruit-Thermal-Printer-Library

# Answer
You didn't tell use the size of your QRCode, nor the type of Arduino you are using. So I am just going to guess that your problem is that you may have enough RAM to store the raw QRCode, but not enough to store a scaled bitmap version.

The Adafruit tutorial for their thermal printer library suggests printing bitmaps with the method:

```
printBitmap(width, height, tablename)

```

where `tablename` is an array holding the bitmap data. This will obviously not work if you don't have enough RAM to store the array. Fortunately, there is an overloaded method:

```
void Adafruit_Thermal::printBitmap(int w, int h, Stream *fromStream)

```

that allows you to stream the image data instead of preparing it in RAM. You can create a stream that delivers arbitrary data by writing a class that derives from `Stream`. Here is a tentative, untested implementation, that delivers a scaled-up QRCode one pixel at a time:

```
// Stream a scaled QRCode one pixel at a time.
class QRCodeStream : public Stream
{
public:
    QRCodeStream(const QRCode &code, uint8_t scale = 1)
    : qrcode(code), scale(scale) {}

    // Output: writing to this stream is a no-op.
    size_t write(uint8_t) {}
    void flush() {}

    // Input delivers the QRCode pixels.
    int available();
    int peek();
    int read();
private:
    QRCode &qrcode;
    uint8_t scale;
    bool done = false;
    uint8_t code_x = 0;  // coordinates of the QRCode module
    uint8_t code_y = 0;
    uint8_t pix_x = 0;  // pixel coordinates within the module
    uint8_t pix_y = 0;
};

int QRCodeStream::available()
{
    // For simplicity, pretend the bytes come one at a time.
    if (done) return 0;
    else return 1;
}

int QRCodeStream::peek()
{
    if (done) return -1;
    if (qrcode_getModule(&qrcode, code_x, code_y)) {
        return 0;  // black
    } else {
        return 255;  // white
    }
}

int QRCodeStream::read()
{
    if (done) return -1;
    int data = peek();

    // Move to the next pixel.
    if (++pix_x >= scale) {
        pix_x = 0;
        if (++code_x >= qrcode.size) {
            code_x = 0;
            if (++pix_y >= scale) {
                pix_y = 0;
                if (++code_y >= qrcode.size) {
                    done = true;
                }
            }
        }
    }

    return data;
}

```

This would be used as

```
printer.printBitmap(width, height, QRCodeStream(qrcode, scale));

```

Note that `QRCodeStream` delivers the image data as 8-bit gray scale, where each pixel is returned as one byte, either 0 (for black) or 255 (for white). This is likely not the format expected by the thermal printer library, which seems to expect 1-bit black and white data, with 8 pixels packed in each byte. You will have to adapt the code for the right format, which will likely be tedious, but not overly complex. I leave that “as an exercise to the reader”.
> 1 votes

---
Tags: programming, c++, library, adafruit, array
---


# Question
Title: FS100A works when Arduino connected to PC but not when connected to Raspberry Pi
I am building a simple circuit which monitors soil humidity in a flower pot. I was able to measure it and send it from one Arduino Nano to another Nano via FS100A transmitter and receiver and VirtualWire library.

As this is prototype so far I connected 1st (measuring) Nano to a powerbank and it works fine: I see the data is send and received by 2nd Arduino.

2nd Nano receives the data (it is less than 50 bytes) and send send it to PC via USB serial connection. All works fine as long as 2nd Arduino is connected to anything but Raspberry PI. Then it is not able to receive any data.

I modified source code of my program to blink built-in LED right after data is read. When 2nd Nano is powered by another powerbank it blinks (the data is read). The same happens using any other PC. But when I try to use it with RPi there is no blinking. RPi is model B+ and I tried two different devices.

I suspect that Raspberries don’t provide stable power to usb or they cause a lot of noise preventing radio from reading the data. Is there any way to overcome this?

# Answer
> 0 votes
After some attempts I finally made it work. I tried to use a level shifter. It worked somehow but I could not find any library which would work with Arduino's VirtualWire.

I just put a 220µ capacitor on power lines to the radio receiver. It filtered all the noise and Arduino is able to interpret signals correctly.

---
Tags: arduino-nano, raspberrypi, virtualwire
---


# Question
Title: Power supply affecting sensor readings ESP8266 and JSN-SR04T-2.0
I have an ESP8266 Wemos D1R2 Board with a JSN-SR04T-2.0 ultrasonic range finder and everything works perfectly when I have the device connected to my computer USB or via a 12V battery into the onboard regulator via the external power jack. However when I use a 240V AC to 12V DC transformer to power the setup my readings become quite erratic. I have checked the voltage coming out of the power supply (12.48v) and the voltage going to the sensor (3.28V, I have it coming off the 3.3V pin) and it is the same on each type of power supply so the onboard regulator is working. Can anyone advise what might cause this? The transformer provides 1A which is more than enough as I have measured the peak usage at \<100ma

# Answer
The JSN-SR04T-2.0 ultrasonic range finder is rated to 5Volts. giving it 3.3 volts may not be enough. from my limited knowledge it should work if you give it a separate power supply and not depend on the 3.3 volts of the ESP.
> 1 votes

---
Tags: esp8266, power
---


# Question
Title: Waking an ESP8266 from Light-Sleep using a signal from MQTT?
**I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?** I am planning to implement a smart switch that would receive messages from a Raspberry Pi to turn off and on, however, I don't want to have to manually hit a button to trigger an external reset (I've seen this done in many examples already). I also don't think it would be efficient for me to just set a timer and have the ESP wake up in intervals. For instance, if I want to have the smart switch turn on an appliance and the PI sends a request over MQTT when the ESP is sleeping... this will do me no good. Curious if anyone has run into this issue before and what recommendations you have.

# Answer
> I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?

No. The ESP8266 has to be awake to communicate with the MQTT server.

The best you can hope for is a periodic wakeup to connect to the server and check for any new data. But of course that relies on the data being set to QOS 2 so it keeps trying to be delivered until the ESP8266 is awake to receive it.
> 1 votes

---
Tags: esp8266, iot, mqtt
---


# Question
Title: Powering Moisture sensor via arduino pin
Can someone help me. I have this sensor

I just connected it to the 3V pin of my arduino only I read online that its better to connect it to a Arduinopin for power so you can put it off when not measuring. How do I do this? Can I just connect it to, let's say D4 and put this to HIGH and LOW or do I need something more. I googled a bit but found all kinds of different solutions. Some even talked about the need to PULLUP and PULLDOWN. whats the best way to do this.

# Answer
> 0 votes
The entire circuit board, including the LM393, power light and it's resistor, uses 2.2 mA at 3.3 VDC (4.12 mA at 5 VDC). Once the comparator is "triggered", the "D0-LED" and it's associated resistor come in to play which bumps the current up to 3.6 mA at 3.3 VDC (7.82 mA at 5 VDC).

I think it would be OK to use `digitalWrite(pin_number, HIGH)` to power the circuit board, then use `digitalWrite(pin_number, LOW)` to turn the power off.

---
Tags: sensors, arduino-nano, power
---