# Question
Title: Count specific range of output as 1 single output
The LDR sensor gives a range of values to show whether a LED is OFF/ON, let's say above LDR range 400, the led is ON. When a LED is ON, after reading the sensor values it shows above LDR range 800, because the LDR sensor measuring in ms, a single LED blink shows six LDR 800+ values. Is there any way to count all the six LDR 800+ values to increase counter by 1?

Here's my output in serial monitor. 314 to 322 is led OFF state and 816 to 851 is led ON state.

```
LED : 314
LED : 314
LED : 314
LED : 321
LED : 322
LED : 322
LED : 816
LED : 817
LED : 818
LED : 817
LED : 817
LED : 815
LED : 351
LED : 329
LED : 323
LED : 327
LED : 326
LED : 339

```

# Answer
There are two distinct problems here.

The first problem is to convert the analog reading into a binary value. You measure a value between 314 and 856, and you want to know whether the LED is ON or OFF. The simplest solution is to compare the reading to a threshold that is roughly in the middle of the range you measure. You could say, for example, that the LED of OFF if the reading is below 580, and is ON otherwise:

```
bool led_is_on = analogRead(ldr_pin) >= 580;

```

If the readings are noisy while they cross the threshold (does not seem to be the case in the short span of data you show), you may want to use some noise cancelling techniques. You could, as suggested by Michel Keijzers, require multiple consecutive “ON” reading before deciding the LED is actually ON. Or you may research the technique of using *hysteresis*, which would be my favorite solution, as it is extremely simple. However, if your readings are always as clean as what you are showing us (never fluctuating mid-range), you can stick with the simple threshold solution shown above.

The second problem is called *edge detection*. You want to count the blinks. For this, you need to count how many times the LED *turns* ON, which is not the same as how many times the LED *is* ON. You know that the LED turned ON if you just detected it is ON and, *on the previous iteration* it was OFF. So you have to remember whether the LED was ON last time you looked at it. This means you have to store this information (whether the LED was ON) in a `static` (or, if you prefer, global) variable. Which leads to the following program:

```
int blink_count;

void loop() {
    static bool led_was_on = false;
    bool led_is_on = analogRead(ldr_pin) >= 580;
    if (!led_was_on && led_is_on) {
        blink_count++;
    }
    led_was_on = led_is_on;
}

```

Note the condition: `!led_was_on && led_is_on` means “The LED was *not* ON and now it is ON”.
> 2 votes

# Answer
I'm not sure what the value 400 is used for exactly, but the code below is for increasing the counter when at least 6 consecutive values above 800 are occurred.

The key is to use a state machine. I don't have a compiler at hand so forgive possible syntax errors. First we define a state. In your case, there are only two possibilities, so a boolean (`bool`) is used, normally an `enum` is used.

```
bool _counting = FALSE;

```

We also need a constant (or define) and a counter to see how many ON values are needed before incrementing the counter, which counts downwards to 0 (and can go negative when more ON values occur).

```
const int MIN_FLASH_LENGTH = 6;
int _onBeforeIncrementing = MIN_FLASH_LENGTH;

```

However, we can use the last variable to see if counting is occurring, so we do not have to use the boolean above.

Then we need a counter for the amount of flashes itself:

```
int _amountOfFlashes = 0;

```

Both of these are global variables.

Furthermore, in the loop, we need to check for the LED value.

Thus the entire code will be:

```
const int MIN_FLASH_LENGTH = 6;

int _onBeforeIncrementing = MIN_FLASH_LENGTH;
int _amountOfFlashes = 0;

void loop()
{
    int ledValue = getLedValue(); // Use your code here
    if (ledValue >= 800)
    {
        _onBeforeIncrementing --;
        if (_onBeforeIncrementing == 0)  // Flash of enough length occurred
        {
            _amountOfFlashes++;
        }
    }
    else // Restart counting
    {
        _onBeforeIncrementing = MIN_FLASH_LENGTH;
    }
}

```

The code fragment

```
if (_onBeforeIncrementing == 0)
{
    _amountOfFlashes++;
}

```

can be reduced to:

```
 _amountOfFlashes += (_onBeforeIncrementing == 0) : 1 : 0;

```

Also note if you have more code to add, to use the name LED or LDR into the global variables for clearity.
> 1 votes

# Answer
By my understanding you want to count the values where your LED is on (800+ values in your case).

For this you can simply create an if condition where in you say if the value is greater than 800 increase counter by 1

```
int count = 0;

if(value>=800):
    count++

```

Here the variable value is the data you are printing on your serial monitor and count is your counter.

Also add the if condition inside the loop function and the declare the variable count = 0 outside the loop function
> 0 votes

---
Tags: arduino-uno, programming, led, photoresistor
---


# Question
Title: formatting strings in Arduino for output
I wander what is the best option for formatting strings in Arduino for output. I mean what's a preferable way in the point of view of performance, memory usage – things like that. I see, people usually use direct Serial.print/println, like this:

```
  int x = 5;
  // 1st option
  Serial.print("x = ");
  Serial.println(x);

```

Or like this:

```
  // 2nd option
  Serial.println("x = " + String(x));

```

But what is wrong with, I believe, more traditional way of doing this:

```
  // 3rd optoin
  char strBuf[50];
  sprintf(strBuf, "x = %d", x);
  Serial.println(strBuf);

  // better one?

```

# Answer
> 7 votes
If you need the result in a single string then your 3rd option is the preferred way.

If you don't, then the first option of printing each part separately is the most efficient in terms of memory.

The second version, String concatenation, is the worst option in all respects and should be avoided at all costs.

I often use `sprintf` to a buffer if I need a specific format (for instance leading zeroes on a number).

If you want to avoid the extra code bloat of `sprintf` you can use various combinations of `strcpy`, `strcat` and `itoa` etc to build up a string into a memory buffer (if you really need to put it in a buffer).

Note that on an 8-bit Arduino `sprintf` has no float support - so you would still need to use `dtostrf` to format a float into a char buffer first, or print it directly.

# Answer
> 3 votes
I agree with Majenko's answer.

I created a simple CStringBuilder class to combine the first and third approach mentioned in your question. It enables to build the c-string with printf and with Print functions, which can print float or IPAddress. It is available in StreamLib in library manager.

```
#include <CStringBuilder.h>
#include <IPAddress.h>

const char* s = "Lorem ipsum";
char c = 'X';
int i = 42;
float f = PI;
IPAddress ipAddress(192, 168, 0, 1);

void setup()
{
  Serial.begin(115200);
  while (!Serial);

  char buff[150];
  CStringBuilder sb(buff, sizeof(buff));

  sb.print(F("Some text: "));
  sb.println(s);
  sb.print(F("Some char: "));
  sb.println(c);
  sb.print(F("HEX of char: "));
  sb.println(c, HEX);
  sb.print(F("Some integer: "));
  sb.println(i);
  sb.print(F("Some float: "));
  sb.println(f, 3);
  sb.print(F("IP address: "));
  sb.println(ipAddress);

  int l = sb.length();
  sb.print("this text doesn't fit in the remaining space in the buffer");
  if (sb.getWriteError()) {
    sb.setLength(l);
  }
  sb.println("test test");

  Serial.print("size to print: ");
  Serial.println(sb.length());
  Serial.println();
  Serial.println(buff);

  sb.reset();
  sb.printf(F("Formatted: %s;%c;%05d\r\n"), s, c, i);
  Serial.println(buff);
}

void loop()
{

}

```

Other classes in the library are BufferedPrint and ChunkedPrint. Both support sprintf.

# Answer
> 2 votes
The printf() family of functions is far preferable to *me* as the programmer, but in a resource-constrained environment such as the smaller AVR (and other) processors, the extra code space may not be justified or available, or the performance hit of interpreting the format string may be limiting. And `sprintf(buf, ...); Serial.print(buf);` also takes a stack hit for the temporary buffer (compared to just `printf(...);` ) It's a trade-off between code size and speed vs. you having more flexibility to write the code to the create the output you want.

# Answer
> 2 votes
The wrong thig with option 3 is the buffer length, you should use **snprintf** instead.

The other problem is that first you build the string, then you print the output, the program traverses the string twice. Option 2 creates object from string, then applies `+` operator to create a new string, then prints it - it is comfortable with short strings, but least efficient (depends on the compiler optimalizations).

Option 1 is most effective, since it directly prints arguments to the output char by char (see Arduino Print class) and traverses the arguments only once.

You can use stdarg.h to create one-liner with Serial.prints:

```
#include <stdarg.h>

void Serialprintln(const char* input...) {
  va_list args;
  va_start(args, input);
  for(const char* i=input; *i!=0; ++i) {
    if(*i!='%') { Serial.print(*i); continue; }
    switch(*(++i)) {
      case '%': Serial.print('%'); break;
      case 's': Serial.print(va_arg(args, char*)); break;
      case 'd': Serial.print(va_arg(args, int), DEC); break;
      case 'b': Serial.print(va_arg(args, int), BIN); break;
      case 'o': Serial.print(va_arg(args, int), OCT); break;
      case 'x': Serial.print(va_arg(args, int), HEX); break;
      case 'f': Serial.print(va_arg(args, double), 2); break;
    }
  }
  Serial.println();
  va_end(args);
}

```

Then you can use it like sprintf (but efficiently):

```
void setup() {
  int n = 42;
  float f = 42.42;
  const char* s = "answer";
  Serial.begin(9600);
  // The answer is 42 (101010 BIN, 2A HEX), in float 42.42
  Serialprintln("The %s is %d (%b BIN, %x HEX), in float %f", s, n, n, n, f);
}

void loop() {
}

```

# Answer
> 0 votes
The third option, sprintf, is unsafe and may give buffer overruns if buffer is not sized correctly. You can use snprintf instead. However I would recommend my SafeString library and tutorial for general string processing and output.

---
Tags: serial, string, c-string
---


# Question
Title: What is the cheapest way to add wifi to Arduino?
I am trying to find some sort of wifi adapter for Arduino, it needs to be as small as possible (not a shield) and as cheap as possible.

So far I can only seem to find shields that cost about £10+ but I figured that if you can get a replacement wifi adapter for a laptop for next to nothing that I should be able to get a wifi adapter for Arduino much cheaper than this.

It's possible I just don't know what to search for.

# Answer
Some months have passed since my previous answer and now the ESP8266 based WiFi modules are available.

They get connected to your project serially (3.3V) and are controlled in a modem like way using AT commands.

With a pricing of round about $5 they fit the question better than my previous OpenWrt based answer.

For more information about ESP8266 ask your favorite finding machine or list news with tag ESP8266 at Hackaday.

---

*(Old answer from the pre-ESP8266-days:)*

I vote for a small router reflashed with OpenWrt like "TP-Link TL-WR703N".

It is like building an own Yùn with an Arduino of your choice...

The WR703N:

It has Ethernet, 150MBit WiFi, USB and if you want to solder, a serial console and 2 GPIO-Pins which can be turned into I2C.

This sure is not a chip- or stamp-sized solution but often cheaper than the alternatives, more powerfull and extendable.

Search the net with your favourite find'o'bot for "arduino wr703n" and you'll find lots of examples...
> 8 votes

# Answer
The Roving Networks RN-XV WiFly module (found sold at €30) might be a solution. I've never tried it. It supports 802.11b/g.
> 1 votes

# Answer
https://www.forward.com.au/pfod/CheapWifiShield/index.html provides a very inexpensive wifi addon for Arduino

The WiFi Shield needs just two parts, 4 bits of wire and some soldering equipment. Parts List:-

Adafruit HUZZAH ESP8266 Breakout US$9.95 + shipping
Uno Protoshield US$1.88 + shipping
Total US$11.83 (as of June 2015)
For an even cheaper version ~US7 see https://www.forward.com.au/pfod/CheapWifiShield/ESP2866\_01\_WiFi\_Shield/index.html
Both of these need a US10 USB to TTL cable to program them

After you have installed the pfodESP8266BufferedClient library, open the Arduino IDE and copy this sketch, ESP8266\_WifiShield.ino, into the IDE. That provides this setup webpage.
> 1 votes

# Answer
Texas Instruments CC3000 module 10USD/1000pcs, it does only support connecting to AP, i.e. no AdHoc/AP which is useless for direct using with iPad.
> 0 votes

---
Tags: arduino-mega, wifi
---


title: Flash Arduino Due via UART

text:
# Question
Title: Flash Arduino Due via UART
I would like to write code in Arduino language, compile it in the Arduino IDE, grab the resulting binary code, and flash it to the Due via the TX/RX UART pins, bypassing both the USB Programming Port and Atmel16U2 chip. Before the UART flash, I am manually toggling the Erase and Reset pins on the Due to initiate a hard reset of the SAM3X chip, and SAM-BA now waits for the code. I would like to know: can I directly grab the binary code compiled by the Arduino IDE and give it to SAM3X via UART or is there extra code baked into that binary by the Arduino compiler that would cause this method to fail?

# Answer
> 1 votes
# It depends

This may not have been the answer the question was originally asked, but now it appears to be: it depends on which revision of the Due you have.

The V03 schematics on the website show a 74LVC1G125DCK part designated IC10 that is being used to translate the 5V TXD signal from the ATMega16u2 (being used as a serial transceiver) to the 3.3V logic needed for the ATSAM3X8. As drawn the TXD line is connected to the buffer/level converter input but it is also connected to its active-low output-enable line. In effect, they're not just using it to convert logic levels, they are also converting the signal to a kind of open collector signal. Looking at the ATSAM3X8 datasheet shows that, yes, there is an internal pullup in the pin receiving the signal.

**If your Due is of this design,** then yes, you can program the chip by attaching a USB-\>logic-level-serial adapter to D0 and D1 (USART) pins and program using the SAM-BA protocol. You need to make sure you are not sending over the on-board serial transceiver while this is happening so as to not have it wired-ORing its data with your adapter. The ATMega16U2 has code in it that controls the ATSAM3X8's erase pin, as well as reset pin, by request of the PC via serial-over-USB's DTR and RTS. Since the erase signal is not routed to outside of the Due (on its headers), you would need to use the erase button, barring some modification to the board.

**However, not all Due are of this design.** Some DUE boards have the output-enable of 74LVC1G125DCK hard-wired active rather than connected to the transceiver TXD; so on these designs it does **not** behave as open-collector, and the ATMega16u2 serial transceiver is actively driving the line when idle. This destroys the ability to program the board over UART via pins D0 and D1. It does however make cleaner rising edges. Without modifying the board, no, you can't do it with this design.

## Identification

So far as I can tell, whether or not your ATMega16U2-\>ATSAM3X8 connection is open collector/UART-programming-friendly follows the location of the buffer part. The chip is an SC70 package, a small 5-pin thing that looks a bit like SOT23-5. If it is located off the ATMega16U2 itself it seems you have a open-collector configuration, again so far as I've been able to tell. If it is located next to D0, between D0 and the "COMMUNICATION" header, then you have one that drives-high.

If you have a scope, you can put it on D0 and watch the edges generated when you send traffic from the PC over the ATMega16U2 at higher baud rates. You will either see characteristic open-collector rising edges or you won't and that will answer the question.

---
Tags: arduino-due, flash, bossa
---


# Question
Title: Is it possible to have long wire connections from an NodeMCU to a servo motor or button?
For my proyect, I need to conect my NodeMCU to a servo motor as well as a push button, the thing is, the distance from the NodeMCU and both components has to have a distance of around 6.10 meters (or 20.0131 feet), I dont know if it is possible to do this connection, I worry if the pwm signal or the voltage would drop by the time it reached either component. I havent been able to try this because I dont have long enough cables to do the connections. In the case that it would be possible, what type of cable should I use and should I add something extra to the circuit to make it work better? Thanks.

# Answer
I would suggest a pull up resistor forcing at least 1 mA or more of current through the switch contact. This helps keep the switch contact clean if it is not rated for dry switching. Then from the junction of the pull up resistor put a 20 - 100K resistor in series with your input pin. You can also add a 100nF cap between the input and ground to kill noise. This forms a low pass filter and denounces some of the switch noise. The other wire to the switch will be ground. I did this a lot with 12/24VDC control systems. If you do several inputs check your currents and be sure you do not over power the Arduino. This will forward bias the top input protection diode pushing current into the Arduino VCC. The inputs are typically rated at 20mA but check to be sure yours is rated properly.
> 1 votes

# Answer
A push button won't be a problem. That is a very simple change in resistance from open circuit to a few ohms. You just need a low enough resistance to force the voltage coming through weak internal pullup resistor down to ground. It looks like 22 gauge wire has about 52.7 ohms / 1000 meters.

I don't think 6 meters of 22 gauge wire will be a problem for a 5V PWM signal either. If it's a very electrically noisy environment you might want to use shielded or twisted pair cable, but it seems unlikely that would be needed.
> 0 votes

---
Tags: nodemcu, pwm, voltage, connector
---


title: How to compare a string

text:
# Question
Title: How to compare a string
How to compare a string coming from serial monitor with some predefined text stored as a local variable? If I say:

```
int led = 2;
String a = " abcds";

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

void loop() {
  String b = Serial.read();
  Serial.println(b);

  if (b != a) {
    digitalWrite(2,LOW);
  }
  else
  {
    digitalWrite(2,HIGH);
  }
}

```

just as an example, this code will not compile because on the serial I receive bytes and I want to compare with a string. So my question is... how should be done?

# Answer
> 6 votes
version using String (not recommended, but it makes simpler to understand the following C-string version)

```
#define LED 2
const char* a = "abcd";

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    String s = Serial.readStringUntil('\n');
    s.trim();
    if (s == a) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
}

```

the version with C-string:

```
#define LED 2
const char* a = "abcd";
char buffer[32];

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    size_t l = Serial.readBytesUntil('\n', buffer, sizeof(buffer - 1));
    if (buffer[l - 1] == '\r') {
      l--;
    }
    buffer[l] = 0; // the terminating zero
    Serial.println(buffer);
    if (strcmp(buffer, a) == 0) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
}

```

# Answer
> 1 votes
If you do a Google search on "Arduino String" you should find a class reference on the String class. https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/

It has a function `compareTo()` that should do what you need.

# Answer
> 1 votes
C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.

# Answer
> 0 votes
Here is the loop() code from the SafeString\_ReadCmdsTimed.ino example in the SafeString library available from the Arduino library manager. It is non-blocking, i.e. no delays.

There is an extensive tutorial and examples available for SafeStrings. SafeStrings has built-in error checking and debugging. SafeStrings provides the functionality of Strings without the memory fragmentation problems of dynamic memory allocation.

If you are reading from telnet there is also a processbackspaces() method in SafeStrings to handle terminal typing corrections. The delimiters are whatever you would like. The example handles Windows, Unix and Mac end-of-lines.

```
char delimiters[] = " .,\r\n"; // space dot comma CR NL are cmd delimiters

void loop() {
  if (input.read(Serial)) {  // read from Serial, returns true if at least one character was added to SafeString input
    input.debug("after read => ");
    timeout.start(TIMEOUT_MS); // restart a 0.1sec timer every time something is read
  }

  if (input.nextToken(token, delimiters)) { // process at most one token per loop does not return tokens longer than input.capacity()
    token.debug("after nextToken => ");

    if (token == startCmdStr) {
      running = true;  Serial.print(F("start at ")); Serial.println(loopCounter);

    } else if (token == stopCmdStr) {
      running = false; Serial.print(F("stop at ")); Serial.println(loopCounter);

    } else if (token == resetCmdStr) {
      loopCounter = 0; Serial.print(F("reset Counter:")); Serial.println(loopCounter);

    }// else  // not a valid cmd ignore
  }
  if (timeout.justFinished()) { // nothing received for 0.1secs, terminated last chars so token will be processed.
    input += delimiters[0]; // any delimiter will do
    SafeString::Output.print(F("Input timed out"));
  }
  // rest of code here is executed while the user typing in commands
  if (running) {
    loopCounter++;
    if ((loopCounter % 100000) == 0) {
      Serial.print(F("Counter:")); Serial.println(loopCounter);
    }
  }
}

```

---
Tags: c, string
---


title: ESP32 feedback from NTP

text:
# Question
Title: ESP32 feedback from NTP
The basic example for ESP32 NTP is very rough:

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

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

```

But it tells nothing about the success of the operation.

I need to know if it was able to update the time from the NTP server. Is there a method to know that?

I can't rely on the time struct because I must init it manually at startup, say to 1st Jan 2020 00:00.

# Answer
Did you follow that manual?

https://lastminuteengineers.com/esp32-ntp-server-date-time-tutorial/

The `printLocalTime();` function does all you ask for.

```
void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

```

`getLocalTime`returns false on failure. Let the `printLocalTime` do the same.

```
boolean printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return false;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
  return true;
}

```

Now the print function tells you if it failed (returns false) or not (returns true).
> 2 votes

# Answer
I'm not entirely sure there is a good solution for that with the normal ESP32 library, as it only checks to see if a valid year has been set, and the user has already set a valid year.

You could try using the NTPClient library or a similar one to get the time; its functions do a different check and actually return TRUE or FALSE.

On success, you can then use the newly retrieved time value to update the ESP32's RTC.
> 0 votes

---
Tags: esp32, time, rtc
---


# Question
Title: Standalone ATmega clock continuous lifetime
Here I have made a standalone ATmega328p clock without any RTC module using the breadboard ATmega328p , LCD I2C , and some buttons which I would like to turn on for atleast an year (supposed to be without any reset or power-interrupts).

I am powering my ATmega using an old mobile charger (5v , 500mA) of a old broken Android.

However I am not using any millis() or something alike these in the clock code,

So how long will my clock run if is it supposed to be online 24/7

Should I reset it sometimes? If yes , when, after how many days should I reset it?

And do I need a coolant system for it? (I guess not)

Thanks for your precious time .

# Answer
> 3 votes
> So how long will my clock run if is it supposed to be online 24/7

Until you turn it off or a stray neutrino corrupts the flash memory, or the flash memory degrades (20-100 years or so depending on temperature).

> Should I reset it sometimes? If yes , when, after how many days should I reset it?

No.

> And do I need a coolant system for it? (I guess not)

No. Not unless it's in a sealed container with no ventilation and a hot environment.

**However**

Your RTC-less "clock" will probably not be particularly accurate, unless you have some external source of time (NTP, GPS, etc) as the Arduino's internal timing is not very accurate, and built on a breadboard it's even less so due to excess stray capacitance.

---
Tags: lcd, atmega328
---


title: Why sensor acts erratically?

text:
# Question
Title: Why sensor acts erratically?
I am trying to connect an ADXL355 digital sensor to an Arduino. The wiring and the code I think are OK because the system returns the correct values sometimes and partly correct answers mostly. The code checks the device register, and the correct data is printed to serial most of the time. The code also checks for temperature but only returns the correct value occasionally. The values are polled every few seconds. The values are correct all of the time if they are correct the first time after restart but never if they are incorrect on restart. I thought it might help to unplug the sensor when uploading the program or powering up the Arduino through USB to the computer but there is no clear pattern.

It is not a defective sensor because I have 2 that behave the same way. What could be the problem? Is this a problem with the Arduino?

I only wire VDD, VDDIO, ground,chip select, sclk, MOSI and MISO.

code:

```
#include <SPI.h>

    const int ID = 0x00;
    const int FIFO = 0x11;
    const int TEMP = 0x06;
    const int TEMP1 = 0x07;
    const byte FIFO_WATERMARK = 0x29;
    const int chipSelectPin = 7;

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

        SPI.begin();

        pinMode(dataReadyPin, INPUT);
        pinMode(chipSelectPin, OUTPUT);

        // writing 0 to to enable sensor
        writeRegister(0x2D, 0x00);

        delay(100);

        Serial.println(readRegister(ID));
        Serial.println(readRegister(FIFO_WATERMARK));
    }

    void loop() {
        int temp = (readRegister(TEMP)); // << 8) | (readRegister(TEMP1))) ;
        temp = (temp<<8)|(readRegister(TEMP1));
        Serial.println(((1852 - temp)/9.05) + 19.21);
        Serial.println(readRegister(ID));

        delay(1000);
    }

    byte readRegister (byte thisRegister){
        byte inByte = 0 ;
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer((thisRegister << 1) | 1);
        inByte = SPI.transfer(0x00);
        digitalWrite(chipSelectPin, HIGH);
        return inByte;
    }
    void writeRegister (byte thisRegister, byte value){
        SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE0)); // 500khz clock
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(thisRegister << 1);
        SPI.transfer(value);
        digitalWrite(chipSelectPin, HIGH);
    }

```

Some one suggested it might be signal bounce on the SPI and the clock rate was set to 500kHz but it didn't work.

Update:
Not long ago, the correct device ID would be read consistently (173 for 0xAD); now that returns 0. The temperature would either return 0 from the register or changing values between -1 and -5 that may have been wrongly calibrated temperature. But sometimes the correct temperature would return. Now it also only returns 0 from the registers.

# Answer
This is a poor product, look at this: that describes exactly the problems you (and me) are experiencing. Correct me if you've found any solutions so far.

## edit

Try looking at description of regster 0x2f in datasheet and to this question.
I think that the first problem you describe can be solved this way, the second behaviour sounds like you fried the device.
> 2 votes

# Answer
Per your post looks like you have not wired any grounds. Consider wiring Analog and Digital grounds.

Here are excerpts from the datasheet
> 1 votes

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


title: ADXL355 accelerometer code

text:
# Question
Title: ADXL355 accelerometer code
I am doing a project which monitors vibrations using an ADXL355 sensor and an Arduino. I have used the MPU-9250 sensor before.

I am not able to find a library or tutorials for calibrating, filtering, and reading accurate data from the sensor. Can anyone who has worked previously with the sensor help me? I am mechanical engineer new to the field of electronics.

If library files are not available, how can I use the datasheet to write the entire code myself? Is there any tutorial available for this?

Sorry if the post seems confusing..

# Answer
> 2 votes
I had a similar learning path as yours and I also tried to use ADXL345 and ADXL355. The latter was a pain for the issues described in many posts like this.

I couldn't find any good tutorial on this topic and had to learn all by myself.

I also use a different approach because I program ESP32-wrover devices with MicroPython. Nevertheless the logic is the same for translating DataSheets -\> code.

1. You have to decide which serial interface to use

* I2C if you are constrained to limited wires
    * SPI for high frequency measures
2. in both cases you write/read to/from registers of the device which are identified by an address, indicated in the datasheet (look for the registers map section). In each address you read/write a byte, that is 8 bits (0 or 1), that are packed into an hexadecimal format (e.g. you can set power mode to 'measure' writing 0x01 in register with address 0x2d)
3. with both you normally have a library that implement 3 main methods:

1. init() for initializing the interface with the parameters you find in the datasheet:
        * SPI: polarity, phase, max\_clock\_frequency, first bit MSB or LSB
        * I2C: max\_clock\_frequency
    2. read(register\_address, nbytes) -\> bytearray
    3. write(register\_address, bytearray)
4. before reading accelerations you must set range (e.g. ±2g), output data rate (e.g. 1000Hz), power mode (e.g. measure mode)
5. then you read acceleration data from corresponding registers. Consider that you can read multiple registers in one transaction reading multiple bytes starting from an address (e.g. you can read x,y,z measure in one transaction by starting from the first byte of x data and then reading 9 bytes = 3 axes * 3 bytes)
6. Then you have to convert from bytes to g units: in this accelerometer the value of one axis consist of 20 bits that are split in 3 bytes. You have to join the 3 bytes, shift away the trailing 4 bits, then apply two's components (that is for allowing negative numbers, look at this guide), then multiply by the scale factor indicated in the datasheet.

---
Tags: accelerometer
---


# Question
Title: Joy-IT RS232 Shield and RS232 voltage levels
First of all, sorry if this is a dumb question, but I'm pretty new to the whole Serial RS232 concepts.

I do have an Arduino Board that, from what I read about, is not able to communicate via RS232 because of different levels.

My question now is: If the Joy-IT RS232 Shield will make up for that. So is this shield handling the RS232 level shift? I don't really know what to look for so I am asking here.

Thanks!

# Answer
> 2 votes
Yes, that shield will handle the level shifting for you. If you look closely at the images of the shield, you see the MAX232 chip, which is a commonly used chip for getting UART (which is the Serial interface of the Arduino) to speak over RS232.

And yes, RS232 uses different voltage levels. The UART on a microcontroller usually uses the voltages 0V and 5V (or 3.3V depending on it's supply voltage), which is also called TTL levels (Transistor-Transistor Logic), while RS232 mostly works with +-10V (though different voltages are also inside the standard). You see, that this is a symmetrical voltage around ground (0V).

---
Tags: arduino-uno, serial, shields, voltage-level, rs232
---


# Question
Title: Recommendation for a projector module or approach?
I am looking to create a projector effect similar to one seen in projector alarm clocks like

https://www.amazon.com/Mooas-White-Projection-Alarm-Projector/dp/B07Q6W53LK/ref=asc\_df\_B07Q6W53LK/?tag=hyprod-20&linkCode=df0&hvadid=343191208006&hvpos=&hvnetw=g&hvrand=4354131467724049360&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9019795&hvtargid=pla-758051396522&psc=1&tag=&ref=&adgrpid=68752454603&hvpone=&hvptwo=&hvadid=343191208006&hvpos=&hvnetw=g&hvrand=4354131467724049360&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9019795&hvtargid=pla-758051396522

and I am looking for some module that would accomplish it

https://www.mouser.com/ProductDetail/Texas-Instruments/DLPDLCR2000EVM?qs=BZBei1rCqCAQetmBz0G1xQ%3D%3D&gclid=Cj0KCQiA-rj9BRCAARIsANB\_4ABW01iyq1W96Kd3piCLku3MSKib7xc\_TspaZIa364hTXtJ\_kYPSg0AaAvSAEALw\_wcB

This is the closest thing I can find to what I am looking for but it's very pricey I would think given how popular these sorts of alarm clocks are there would be something much cheaper and easy to get your hands on out there.

# Answer
As written in the comments, the linked projector is a DLP projector with 640x320 pixels. Of course, that is expensive. It is a complete pixel display, which can display anything (with the max resolution of 640x320). That is way more, than the projector watches.

The watches often use one of two possibilities:

* A bright 7 segment LED display, which is projected to the wall via a lens. The seven segment display needs to be bright enough, depending on the intended brightness of the projection and how big the projected image should be.
* An LCD display, which is illuminated from behind by a bright LED. That is then also projected to the wall with a lens. I would guess, that this is, what the linked watch is doing.

**How to build that yourself?** You can always salvage one of these watches. But when building it yourself, you should also follow one of the above possibilities. Which one depends on your requirements.

Using a standard 7 segment display will be the easiest. Though that might be not bright enough. You could look for especially bright 7 segment displays and test, if that is enough for you.

The second possibility would be more hacky. Most LCD displays, that you can buy, have a LED lit plane in the back as a backlight. You would need to remove that plane, so that the display gets transparent. Also you most likely would need to rotate the polarizing filter on the top of the LCD, because as standard a driven segment of the LCD gets more opaque, while you want it to get transparent. A new filter (up to a few cm) can be salvaged from the passive 3D glasses from a movie theater.

In both cases you install the display inside a tube together with a fitting lens. Look, what you can get from your location and then experiment with it.

> can you link to parts

No, we are not really doing that here, because that is really dependent on your location, on your price- and other requirements. Also such part suggestions are usually very fast outdated. But you can look at the electronics shops, that you have at your location and search there for the general description of the parts (for example "7 segment display").
> 0 votes

---
Tags: led, lcd, hardware
---


# Question
Title: Can't change pins in AM2320 code, types mismatch
I took a simple A2320 temperature sensor and connected it not to A4/A5, but to A1/A0 pins. SDA =\> A1, SCL =\> A0. (In C code they are number 15 and 14). But I can't call the library to take these pins.

The basic example from the library uses the default values, probably from some tutorial.

I read the `.h` and `.cpp` files and see these definitions:

```
Adafruit_AM2320::Adafruit_AM2320(TwoWire *theI2C, int32_t tempSensorId,
                                 int32_t humiditySensorId)
    : _temp(this, tempSensorId), _humidity(this, humiditySensorId),
      _i2c(theI2C) {}

bool Adafruit_AM2320::begin() {
  _i2caddr = 0x5C; // fixed addr
  _i2c->begin();
  return true;
}

```

I just tried to make types match. Not even port number.

I declared a `TwoWire` instance and passed it to AM2320 constructor, but without success:

```
#include "Wire.h"
...
TwoWire mywire();
Adafruit_AM2320 am2320 = Adafruit_AM2320(mywire, -1, -1); // as the default values

```

Outputs in error log:

```
error: no matching function for call to 'Adafruit_AM2320::Adafruit_AM2320(TwoWire (*)(), int, int)'
    Adafruit_AM2320 am2320 = Adafruit_AM2320(&mywire, -1, -1);
In file included from testproj.ino:2:0:
...Adafruit_AM2320.h:52:3: note: candidate: Adafruit_AM2320::Adafruit_AM2320(TwoWire*, int32_t, int32_t)
   Adafruit_AM2320(TwoWire *theI2C = &Wire, int32_t tempSensorId = -1,
   ^~~~~~~~~~~~~~~
...Adafruit_AM2320.h:52:3: note:   no known conversion for argument 1 from 'TwoWire (*)()' to 'TwoWire*'

```

What am I doing wrong?

# Answer
Two problems:

1. When you create an object instance with no parameters you must not have parentheses. You should construct thus:

```
TwoWire mywire;

```
2. The constructor expects a *pointer* to an object, not an object. Just take the address of the object with `&` and pass that:

```
Adafruit_AM2320 am2320 = Adafruit_AM2320(&mywire, -1, -1); // as the default values

```

**However**

Most Arduino boards have the I2C pins hard-wired internal to the chip and can't be changed. You would need to use some form of software implementation that is also a polymorphic child of the `TwoWire` class. If such a thing exists.
> 1 votes

---
Tags: adafruit, cpp
---


# Question
Title: I'm looking for a way to emulate addressable LED strip using LED diodes in a custom arrangement
What I want to achieve is, I want to use my own LED pin diodes, customly place them into my sculpture and animate them. This is as I understand quite straightforward. The problem is the amount of wiring . I would want them to connect one another in series with addresses, rather then each led needing a direct data from the controller on a separate cable.

I know that addressable LEDs use a single data line through the all lights, eliminating the need to connect each led physically to the controller to get data. Is there any way to build a similar system with a bus-like structure, I believe it is possible. And if so, how? What would I need? I guess I need individual small chips for each LED, but I don't know if that's the case or even if it is how so.

I consider myself quite a newbie in electronics-arduino or LEDs, however I'm actively looking into it and researching.

# Answer
> 2 votes
You can buy individually addressable LEDs like the ones in LED strips. If you are fairly new to electronics I would not try to build your own serial LED controller.

---
Tags: led
---


# Question
Title: Building RS485 serial to USB adapter with digispark
Is it possible to build an serial-adapter with digispark board? Like: Embedded System with 2-wire RS-485 Port connect to my digispark board. Digispark Board is connected via USB to my Computer (running Linux tty or Windows COM Putty Interface)

I also own a Raspberry Pi. I'm very new at this thing, so maybe there is a way to convert the RS485 signals to monitoring my devices with my computer?

# Answer
There are some good books available to help. There is the Raspberry Pi cookbook and the Arduino cookbook. These will take you from the very beginning to the point where you can make your own designs and they will work.
> 1 votes

# Answer
I would steer you away from using something that has a chip with neither a USART nor USB hardware for the purposes of making something like that. The ATTiny85 that's on the Digispark has USI (Universal Serial Interface), which is really more of a USART construction kit. The USB support it has is bitbanged and somewhat unreliable.

If you do go in this direction and want a small Arduino type board like Digispark, the "Beetle" ATMega32u4 based boards are a better choice. It has a native USB interface, and a proper USART to hook to an RS-485 driver.

The chip also has a bootloader section; it is difficult to corrupt your own sketch. It also has more memory, not that you necessarily need it.
> 0 votes

---
Tags: serial, usb, raspberrypi, rs485, digispark
---


# Question
Title: Writing a 1Mb bitmap to an SDcard with only 96kB RAM
My goal is to have an Arduino Due (96 KB RAM) write a +-1MB bitmap to an SD card.

I have an array of a several coordinates on my Arduino Due and I would like to generate the bitmap where all the coordinates have a certain color and all the other pixels/background have another color.

I do have code to write a bitmap to an SD card (see below) but the problem is that the bitmap is dynamically generated and allocated in ram and then written to the SD card. So as soon as the bitmap I do want to write to the SDcard becomes bigger than the RAM available I get an error: "xx.elf section '.bss' is not within region 'ram'.

Could anyone advice me on how to put parts of the bitmap in ram and write them to the sdcard one after another. Or would there maybe be another better approach?

```
#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

char name[] = "9px_0000.bmp";       // filename convention (will auto-increment)
const int w = 800;                   // image width in pixels
const int h = 400;                    // " height
const boolean debugPrint = true;    // print details of process over serial?

const uint32_t imgSize = w*h;
int px[w*h];                        // actual pixel data (grayscale - added programatically below)

File file;

const int amount_CT_samples = 20;
int Yarr[amount_CT_samples];
int Xarr[amount_CT_samples];

void setup() {

  // SD setup
    SerialUSB.begin(9600);
  while (!SerialUSB) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  SerialUSB.print("Initializing SD card...");

  if (!SD.begin(chipSelect)) {
    SerialUSB.println("initialization failed!");
    return;
  }
  SerialUSB.println("initialization done.");

  // if name exists, create new filename
  for (int i=0; i<10000; i++) {
    name[4] = (i/1000)%10 + '0';    // thousands place
    name[5] = (i/100)%10 + '0';     // hundreds
    name[6] = (i/10)%10 + '0';      // tens
    name[7] = i%10 + '0';           // ones
    file = SD.open(name, O_CREAT | O_EXCL | O_WRITE);
    if (file) {
      break;
    }
  }

  // set fileSize (used in bmp header)
  int rowSize = 4 * ((3*w + 3)/4);      // how many bytes in the row (used to create padding)
  int fileSize = 54 + h*rowSize;        // headers (54 bytes) + pixel data

  // create image data; heavily modified version via:
  // http://stackoverflow.com/a/2654860
  unsigned char *img = NULL;            // image data
  if (img) {                            // if there's already data in the array, clear it
    free(img);
  }
  img = (unsigned char *)malloc(3*imgSize);

  for (int y=0; y<h; y++) {
    for (int x=0; x<w; x++) {
      int colorVal = px[y*w + x];                        // classic formula for px listed in line
      img[(y*w + x)*3+0] = (unsigned char)(colorVal);    // R
      img[(y*w + x)*3+1] = (unsigned char)(colorVal);    // G
      img[(y*w + x)*3+2] = (unsigned char)(colorVal);    // B
      // padding (the 4th byte) will be added later as needed...
    }
  }

  // create padding (based on the number of pixels in a row
  unsigned char bmpPad[rowSize - 3*w];
  for (int i=0; i<sizeof(bmpPad); i++) {         // fill with 0s
    bmpPad[i] = 0;
  }

  // create file headers (also taken from StackOverflow example)
  unsigned char bmpFileHeader[14] = {            // file header (always starts with BM!)
    'B','M', 0,0,0,0, 0,0, 0,0, 54,0,0,0   };
  unsigned char bmpInfoHeader[40] = {            // info about the file (size, etc)
    40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0, 24,0   };

  bmpFileHeader[ 2] = (unsigned char)(fileSize      );
  bmpFileHeader[ 3] = (unsigned char)(fileSize >>  8);
  bmpFileHeader[ 4] = (unsigned char)(fileSize >> 16);
  bmpFileHeader[ 5] = (unsigned char)(fileSize >> 24);

  bmpInfoHeader[ 4] = (unsigned char)(       w      );
  bmpInfoHeader[ 5] = (unsigned char)(       w >>  8);
  bmpInfoHeader[ 6] = (unsigned char)(       w >> 16);
  bmpInfoHeader[ 7] = (unsigned char)(       w >> 24);
  bmpInfoHeader[ 8] = (unsigned char)(       h      );
  bmpInfoHeader[ 9] = (unsigned char)(       h >>  8);
  bmpInfoHeader[10] = (unsigned char)(       h >> 16);
  bmpInfoHeader[11] = (unsigned char)(       h >> 24);

  // write the file (thanks forum!)
  file.write(bmpFileHeader, sizeof(bmpFileHeader));    // write file header

}

void loop() { }

```

**UPDATE**

With the following code my problem was solved. Credits to those who answered my question below!

```
#include <SPI.h>
#include <SD.h>
const int chipSelect = 10;

struct Pixel {
    uint8_t r, g, b;
};

char name[] = "CT_0000.bmp";       // filename convention (will auto-increment)
const int w = 800;                   // image width in pixels
const int h = 400;                    // " height
const boolean debugPrint = true;    // print details of process over serial?

const uint32_t imgSize = w*h;
int px[w*h];                        // actual pixel data (grayscale - added programatically below)

File file;

const int amount_CT_samples = 50;
int Xarr[amount_CT_samples];
int Yarr[amount_CT_samples];

Pixel getPixel(int x, int y) {
    const Pixel black = {0, 0, 0},
                green = {0, 255, 0};

    for(int i=0; i < amount_CT_samples; i++){
      if(Xarr[i] == x && Yarr[i] == (h - y))return green;
    }
    return black;
}

void writeBitmap(File &file, int w, int h) {
    size_t rowSize = 4 * ((3*w + 3)/4);  // padded to multiple of 4
    size_t fileSize = 54 + h*rowSize;    // includes header

    // Write image header.
    uint8_t header[54] = {
        // File header.
        'B','M',
        (uint8_t)(fileSize >>  0),
        (uint8_t)(fileSize >>  8),
        (uint8_t)(fileSize >> 16),
        (uint8_t)(fileSize >> 24),
        0,0, 0,0, 54,0,0,0,

        // Image info header.
        40,0,0,0,
        (uint8_t)(w >>  0),
        (uint8_t)(w >>  8),
        (uint8_t)(w >> 16),
        (uint8_t)(w >> 24),
        (uint8_t)(h >>  0),
        (uint8_t)(h >>  8),
        (uint8_t)(h >> 16),
        (uint8_t)(h >> 24),
        1,0, 24,0
    };
    file.write(header, sizeof header);

    // Write image data.
    uint8_t row[rowSize];
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            Pixel pix = getPixel(x, y);
            row[3*x + 0] = pix.b;
            row[3*x + 1] = pix.g;
            row[3*x + 2] = pix.r;
        }
        file.write(row, sizeof row);
    }

    file.close();
}

void setup() {
    Serial.begin(9600);
    Serial.print("Initializing SD card...");

    //create dummy X and Y points
    for(int i = 0; i < amount_CT_samples; i++){
        Xarr[i] = i;
        Yarr[i] = i;
    }

    if (!SD.begin(chipSelect)) {
      Serial.println("initialization failed!");
      return;
    }
    Serial.println("initialization done.");

  // if name exists, create new filename
  for (int i=0; i<10000; i++) {
    name[3] = (i/1000)%10 + '0';    // thousands place
    name[4] = (i/100)%10 + '0';     // hundreds
    name[5] = (i/10)%10 + '0';      // tens
    name[6] = i%10 + '0';           // ones
    file = SD.open(name, O_CREAT | O_EXCL | O_WRITE);
    if (file) {
      break;
    }
  }

  Serial.println("start writing bitmap.");
  writeBitmap(file, w, h);
  Serial.println("done writing bitmap.");

}

void loop() { }

```

# Answer
> 3 votes
You can write the file in chunks. As suggested by ocrdu in a comment, writing line by line is a good strategy. In order to keep the complexity of the code manageable, I would put the logic of deciding the color of a pixel in its own function, and use another function for managing writing the bitmap. For example:

```
struct Pixel {
    uint8_t r, g, b;
};

// Dummy example. Replace with your own logic.
Pixel getPixel(int x, int y) {
    const Pixel black = {0, 0, 0},
                green = {0, 255, 0};
    if (((x - y) & 0x0f) == 0) return green;
    return black;
}

void writeBitmap(File &file, int w, int h) {
    size_t rowSize = 4 * ((3*w + 3)/4);  // padded to multiple of 4
    size_t fileSize = 54 + h*rowSize;    // includes header

    // Write image header.
    uint8_t header[54] = {
        // File header.
        'B','M',
        (uint8_t)(fileSize >>  0),
        (uint8_t)(fileSize >>  8),
        (uint8_t)(fileSize >> 16),
        (uint8_t)(fileSize >> 24),
        0,0, 0,0, 54,0,0,0,

        // Image info header.
        40,0,0,0,
        (uint8_t)(w >>  0),
        (uint8_t)(w >>  8),
        (uint8_t)(w >> 16),
        (uint8_t)(w >> 24),
        (uint8_t)(h >>  0),
        (uint8_t)(h >>  8),
        (uint8_t)(h >> 16),
        (uint8_t)(h >> 24),
        1,0, 24,0
    };
    file.write(header, sizeof header);

    // Write image data.
    uint8_t row[rowSize] = {0};
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            Pixel pix = getPixel(x, y);
            row[3*x + 0] = pix.b;
            row[3*x + 1] = pix.g;
            row[3*x + 2] = pix.r;
        }
        file.write(row, sizeof row);
    }
}

```

Then after opening the file, you just have to:

```
writeBitmap(file, 800, 400);

```

Note that the `getPixel()` function above is just a dummy example that draws green diagonal lines across the image. See timemage's answer for ideas on how to implement your own pixel-generating function.

# Answer
> 1 votes
Normally I'd write this a differently, but I've kept in relatively simple just to illustrate the basic idea:

```
struct point {
  int x;
  int y;
};

const point points_of_interest[] = {
  { 7, 11},
  {23, 17},
  {13, 19},
  { 3,  5},
  {17,  3},
};

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

void loop() {
  delay(4000);
  Serial.println("\n\n\n");

  for (int i = 0; i < 24; ++i) {
    for (int j = 0; j < 24; ++j) {
      bool coordinate_of_interest = false;

      for (const auto poi: points_of_interest) {
        coordinate_of_interest = j == poi.x && i == poi.y;
        if (coordinate_of_interest) {
          break;
        }
      }

      if (coordinate_of_interest) {
        Serial.print("XX");
      } else {
        Serial.print("..");
      }
    }

    Serial.println();
  }
}

```

It's printing a 24x24 or 576 "pixel" grid. But only five coordinates are stored. It would matter if it were a 2400x2400 grid, but it would not print nicely on a maximized Serial Monitor for example purposes.

With your bitmap, you could get more sophisticated. E.g. checking that distance (or more efficiently distance squared; no sqrt() operation) from the pixel under consideration (i, j) to any point in the list is less than or equal to some amount, and coloring based on that. This would result in solid circles centered on your points in your bitmap. Or color gradient around the point if you base the color on the distance.

If you have a lot of points you will need to do something like sort them by their vertical coordinates and advance an index that represents the points on or below your horizontal sweep line, etc. That is, if you have a lot of points you don't want to have to be taking the distance to all of them for every pixel under consideration.

---
Tags: arduino-due, sd-card, sram
---


# Question
Title: Cant make the second 74HC595 to start counting
I'm doing my first project with Arduino, however I got in a block and cannot figure out what I am doing wrong.

This project is 'simple'. It's that Stranger Thing's Wall.

However, I want to use the 74HC595 to leave pins free on the arduino for maybe expand and do something else with that too, so, I tried doing the arduino tutorial (https://www.arduino.cc/en/Tutorial/Foundations/ShiftOut)

So my current schematic is this one below

My code, however, is kind of a frankenstein. I used the shiftOut from the tutorials, however I must confess I do not know how it works (And I think its where the error may lie). I do know VBA and Python, but I know nothing of C (Or whichever this language is)

```
    //Pin connected to ST_CP of 74HC595
#define latchPin 5
//Pin connected to SH_CP of 74HC595
#define clockPin 7
////Pin connected to DS of 74HC595
#define dataPin 6
String text;                                                    //Variável do tipo string que receberá o texto
void setup() {
  Serial.begin(9600);                                           //Velocidade de comunicação
  for (int i = 2; i < 7; i++) {
    pinMode(i, OUTPUT);                                   //Declarando o pino como saída
  }
  Serial.println("Iniciando");
  inicializationEffect();                                       //Chamada da Função responsável pelo efeito inicial
  //basicTest();
}
void loop() {

  receiveText();                                               //Chamada da função responsável por receber o texto digitado
}
//Função que recebe o texto diitado
void receiveText() {
  while (Serial.available() > 0) {                              //Verifica se existe alguma informação na Serial
    char c = Serial.read();                                     //atribui cada caractere a variável c que é do tipo char
    if (c != '\n') text.concat(c) ;                              //verifica se a variável do tipo char recebeu uma quebra de linha que indica o fim da palavra ou frase e concatena todos os caracteres na String text
    delay(10);                                                  //aguarda 10 milissegundos
  }
  if (text.length() > 0) {                                      //verifica se a string text tem tamanho maior que 0
    text.toUpperCase();                                       //transforma tudo que estiver na string text para maiúsculo
    if (text[0] == '#'){
      waveEffect();
    }else {
      executeEffect(text);                                        //chama a função executeEffect passando a string text como parâmetro
    }
  }
  text = "";                                                    //limpa a string text
}
//Função responsável por ativar linha que recebe como parâmetro o número da linha
void lineActivation(int line, int keepalive) {
  if (keepalive == 0) {
    for (int i = 2; i <= 4; i++) {
      digitalWrite(i, LOW);
    }
  }
    digitalWrite(line+1, HIGH);                               //coloca a linha 1 em estado lógico alto
}

void activateLetter(char letter, int on, int off) {
  int lt;
  lt = (((int)letter - 64) % 9);
  if (((int)letter - 64) > 8) {
    lt = lt + 1;
  }
  if (on) {
    callCol(1<<lt-1);
    delay(on);                                                //mantém o pino em nível lógico alto durante o tempo que foi determinado no parâmetro da função
  }
  if (off) {
    callCol(0);
    delay(off);                                               //mantém o pino em nível lógico baixo durante o tempo que foi determinado no parâmetro da função
  }

}

void callCol(int col){
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, 0);
  shiftOut(dataPin, clockPin, col);
  digitalWrite(latchPin, HIGH);

}
void executeEffect(String text) {
  for (int i = 0; i < text.length(); i++) {
    if (text[i] == ' ') {
      delay(1000);
    } else if ((int)text[i] < 65 or (int)text[i] > 90) {
    } else {
      lineActivation(int(((int)text[i] - 64) / 9) + 1, 0);
      activateLetter(text[i], 1000, 200);
    }
  }
}

void inicializationEffect() {
  for (int i = 1; i < 27; i++) {
    lineActivation(int(i / 9) + 1, 0);                          //ativa a linha
    activateLetter(char(64 + i), 1000, 10);                   //ativa a letra
  }
}
void waveEffect() {
  for (int i = 1; i < 4; i++) {
    lineActivation(i, 1);                          //ativa a linha
  }
  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 100, 0);
  }

  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 0, 100);
  }
  for (int i = 1; i < 4; i++) {
    lineActivation(i, 1);                          //ativa a linha
  }
}

void basicTest() {
  lineActivation(2,1);
    for (int i = 0; 1 < 500; i++) {
    callCol(255-i);
    delay(100);
    }

}

void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low
//internal function setup
int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);
//clear everything out just in case to
//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);
//for each bit in the byte myDataOut�
//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--)  {
digitalWrite(myClockPin, 0);
//if the value passed to myDataOut and a bitmask result
// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}
//Sets the pin to HIGH or LOW depending on pinState
digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}
//stop shifting
digitalWrite(myClockPin, 0);
}

```

If I understood right (Which I may not) theoretically, when I send a value over 255, it should "overflow" to the next 74HC595, which would be used to light the ninth column.

# Answer
> 3 votes
Solved using https://arduino.stackexchange.com/a/17093/37827

By removing the custom shiftOut function and changing my

```
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, col);

```

with

```
shiftOut(dataPin, clockPin, MSBFIRST, highByte(col));
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(col));

```

Works like a charm

PS: Feel free to suggest something else, but this way it fixed my problem

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


# Question
Title: 'Servo_Pointer' was not declared in this scope
I can't seem to find the error I made; can anyone help me?

The error message: `'Servo_Pointer' was not declared in this scope`

I get the error at the end of the code with the line: `Servo_Pointer.write(servo_pos)`

The code:

```
const int photo_left = A0;    // select the input pins for the photoresistor
const int photo_right = A1;
const int ledPin_1 = 2; // These leds will be used for the testing of the pointing of the servo motor
const int ledPin_2 = 4;
const int ledPin_3 = 7;
const int ledPin_4 = 8;
const int ledPin_5 = 12;
const int photoValue = 0;  // variable to store the value coming from the photoresistor
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin_1, OUTPUT);
  pinMode(ledPin_2, OUTPUT);
  pinMode(ledPin_3, OUTPUT);
  pinMode(ledPin_4, OUTPUT);
  pinMode(ledPin_5, OUTPUT);
  Serial.begin(9600);
  #include <Servo.h>
  Servo Servo_Pointer;
  Servo_Pointer.attach(9);
  int servo_pos = 0;
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading  ) {
    readings[thisReading] = 0;
  }
}

void loop() {
  Servo_Pointer.write(servo_pos); // tell servomotor to go to position in variable 'servo_pos'
  delay(15);          // waits 15ms for the servo to reach the position
  // turn the ledPin on
  delay(15);
}

```

# Answer
> 3 votes
You should make `Servo Servo_Pointer;` global, i.e. place it outside the `setup`function, e.g. after the line `int average = 0;`.

In your code, it is a local variable within the `setup` function. When this function ends, the local variables within this function (such as `Servo_Pointer` ) do not exist anymore.

By making the variable global, you can use it anywhere. However, it's not a good coding practice to use global variables when not needed.

A benefit of making the variable global is that you can see the memory consumption of the instance of `Servo_Pointer` when compiling.

Also see the comment of timemage below: Don't put `#include` statements in the middle of your code, put them in the beginning of your code.

# Answer
> 0 votes
You need to place the decleration outside of your `setup()` function. In other words, you need to move the following 3 lines and place then above your `setup()` function:

```
#include <Servo.h>
Servo Servo_Pointer;
int servo_pos = 0;

```

Your code should look like this:

```
#include <Servo.h>

const int photo_left = A0;    // select the input pins for the photoresistor
const int photo_right = A1;
const int ledPin_1 = 2; // These leds will be used for the testing of the pointing of the servo motor
const int ledPin_2 = 4;
const int ledPin_3 = 7;
const int ledPin_4 = 8;
const int ledPin_5 = 12;
const int photoValue = 0;  // variable to store the value coming from the photoresistor
const int numReadings = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
int servo_pos = 0;

Servo Servo_Pointer;

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(ledPin_1, OUTPUT);
  pinMode(ledPin_2, OUTPUT);
  pinMode(ledPin_3, OUTPUT);
  pinMode(ledPin_4, OUTPUT);
  pinMode(ledPin_5, OUTPUT);
  Serial.begin(9600);
  Servo_Pointer.attach(9);
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading  ) {
    readings[thisReading] = 0;
  }
}

void loop() {
  Servo_Pointer.write(servo_pos); // tell servomotor to go to position in variable 'servo_pos'
  delay(15);          // waits 15ms for the servo to reach the position
  // turn the ledPin on
  delay(15);
}

```

---
Tags: arduino-uno, serial, programming, arduino-ide
---


title: Separate control unit from LEDs

text:
# Question
Title: Separate control unit from LEDs
I am using an adapter (12 VDC, 2A) and I want to be able to power an LED strip with it plus the control circuit.

The problem is that the Atmega328 reboots, but when I only power up the LED strip with that adapter and power the control circuit with an independent 5 V adapter everything seems to be alright.

I can't do that in real world; I need to ude the same adapter.

I attached a picture of what I am doing right now. Please help me fix this.

**I am using a 7805 regulator to reduce the 12 V to 5 V.**

# Answer
Why not use the barrel input connector and input 12VDC there, the filtering etc on the board will help. Also as dandavis stated you need a bigger power supply or remove about 1/2 of your LEDs.
> -1 votes

---
Tags: led, adapter
---


# Question
Title: L298N regulated output is greated than 5V
A few months ago I used a L298N module (actually the Velleman VMA409) and I managed to make my motors working fine.

However now that I want to reuse it for another project something seems off: **The regulated 5V output is always equal to the 16V VMS input.**

To give more details:

* I'm powering the board with 4x 3.7V 18650 batteries in series for an input of about 16V. This should be OK since according to the specs the range for VMS is 5V-35V
* I'm reading the output value on the two pins I marked with an arrow in the following picture (using both of the GND pins) and in all cases I get about the same value as what I have on VMS.
* This is when I have the 5V\_EN jumper in place, if I remove it I get no output at all (Which I think is normal, since that disable the internal regulator)
* For now I haven't connected my arduino because I want to understand what's going on before, so the Inx and EnX pins are connected to nothing.

So my questions are:

* Is it indicating that I somehow fried my driver board?
* Can I get back this 5V regulated output?

# Answer
> 0 votes
You are making an incorrect assumption, the L298N is an "H" bridge driver for small motors, not a 5V power supply. The 5 volt output is provided by a separate 78L05 regulator on the module. This regulator cannot supply much power. Take a look at the schematic link given to you by ocrdu. Be sure all the grounds are connected.

---
Tags: l298n
---


title: Detect if MCU is ESP8266 or ESP32

text:
# Question
Title: Detect if MCU is ESP8266 or ESP32
I'm coding a library which handles sleep procedures.

Since I'm using both ESP826 and ESP32, which uses different sleep commands ( and WiFi ), I'm looking for a way to detect the MCU, while NOT using a boolean flag that indicates so.

Guy

# Answer
> 6 votes
I take this to mean that you do not want to have to ask *the user* of the code to configure a boolean flag.

The ESP8266 Arduino package provides `-DARDUINO_ARCH_ESP8266 -DESP8266` command-line options these while calling g++. These effectively `#define` feature test macros as though they were at the beginning of the source code.

For ESP32 it does likewise with `-DARDUINO_ARCH_ESP32 -DESP32`

You could perform tests in your code such as:

```
#if defined (ARDUINO_ARCH_ESP8266)
// do one thing
#elif defined(ESP32)
// do another
#else
#error Architecture unrecognized by this code.
#endif

```

There are likely also macros like these that are predefined by the xtensa g++ compiler.

---
Tags: esp8266, esp32
---


# Question
Title: (very new to C) I'm trying to use irsend with what I think is char* but it won't take it. How can I convert it to what it needs?
I'm attempting to use a raspberry pi to send ir codes directly to my arduino to have as simple as a C program as possible. Here's my code I've been tinkering with that leads to errors or not working if I don't specifically hardcode the hex ir signal.

```
#include <IRremote.h>

char buf[80];

String code = "empty";

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0; // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

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

IRsend irsend;

void loop() {
  if (readline(Serial.read(), buf, 80) > 0) {
    Serial.print("You entered: >");
    //Serial.print(buf);
    //Serial.println("<");
    //irsend.sendNEC((uint32_t) buf, 32);
    String str(buf);
    //irsend.sendNEC((uint32_t) code, 32);
    //irsend.sendNEC(0x210704FB, 32);
    code = buf;
    delay(600);
    //Serial.print((uint32_t) buf, 32);
    Serial.print(code);
    irsend.sendNEC(buf, 32);

  }

```

I've left my mess on the bottom to illustrate how little I know and what I've tried. I've been trying to figure out what I'm sending it but it doesn't help that serial.print doesn't work like irsend. I'm intending to send hex codes directly and have the arduino blindly plug them into irsend.sendNEC(0x210704FB, 32); which works but when I try to put my own variable in it won't.

Very much appreciate any help! I know it'd be easy for anybody who knows a little C.

irsend.sendNEC(buf, 32); returns: initializing argument 1 of 'void IRsend::sendNEC(uint32\_t, uint8\_t, bool)' void sendNEC(uint32\_t data, uint8\_t nbits, bool repeat = false);

and irsend.sendNEC((uint32\_t) buf, 32); doesn't throw any errors but also does not seem to do anything

# Answer
> 2 votes
If you are sending HEX values like `0x1234abcd` from the Pi to the Arduino to send those as an IR code you first have to interpret that string data as a hexadecimal number.

That's not as simple as just casting the string since, as @timemage says, all you're doing there is casting the *address* of the character array.

Instead you should use `strtoul()` to parse the string and give you the equivalent number to what it contains.

`strtoul()` can convert numbers in a number of different bases, and can even work automatically. From the Linux man page:

> **SYNOPSIS**
>
> `unsigned long int strtoul(const char *nptr, char **endptr, int base);`

And later on:

> If base is zero or 16, the string may then include a "0x" prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it is taken as 8 (octal).

That means it can automatically parse `0x1234abcd` as a hexadecimal number, `12345678` as a decimal number, and `052714` as an octal number (it's important to remember that one so you don't accidentally add a leading zero to a decimal number and have it parsed wrong).

So knowing all that you can now:

```
uint32_t code = strtoul(buffer, NULL, 0);

```

and `code` will contain the contents of `buffer` represented as an actual numeric variable (assuming the content can be parsed as a number).

# Answer
> 1 votes
The library you're using and the protocols it implements are not for sending large chunks of data.

The sendNEC function you're using is simply limited to 32 bits per transmission. You're not going to be able to send an arbitrary length string with it, except by constructing some protocol around it that breaks the string into multiple transmissions of as much as 32 bits at a time.

Without splitting hairs about the language standard and qualifying everything to be perfectly accurate: what you're doing with your `(uint32_t)` cast is sending the memory address of your string over IR, which is no doubt not what you wanted nor likely particularly useful on the receiving end.

What you appear to want is something closer to IrDA. That said, you probably *could* do what you want by calling `sendNEC()` on each character of your data in the simple case. Better would be to send 32-bits of the string at a time since there is overhead to each transmission. But again, these functions and protocols are designed for sending short, infrequent messages. They were designed to be dirt simple so that they could on be implemented hardware a fraction of the power of a typical Arduino, so that they could be cheap decades ago when when they were inverted. In an effort to be both simple and at least *somewhat* reliable, they sacrifice a lot of speed.

---
Tags: programming, c++, ir, remote-control
---


title: AnalogRead always 1023 on Arduino Due?

text:
# Question
Title: AnalogRead always 1023 on Arduino Due?
Just using the Basic Example `AnalogReadSerial`.

```
// the setup routine runs once when you press reset:
  void setup()
{
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop()
{
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

```

I have a basic voltage divider set up between two 10K resistors from 5V to GND. I have verified with a DMM that the DC voltage at pin A0 is 2.5V. Grounding the A0 pin has no effect.

It also seems that enabling either ADC channel 7 (Arduino pin AD0) or enabling every channel, putting the ADC in free-running mode, and deliberately setting it to *not* sleep has no effect:

```
ADC->ADC_CHDR = 0;
ADC->ADC_CHER |= 0xFF;
ADC->ADC_MR |= 0b10000000;
ADC->ADC_MR &= 0b11011111;

```

Also, by running the sketch `DigitalInputPullup`, I can get the LED on pin 13 to toggle and serial communication to work as I tie the pin to ground, demonstrating that the board is being programmed properly.

I guess I'm just stumped. Should be the simplest thing in the world and it's just not working.

EDIT: This is my attempt at manually controlling the ADC:

```
volatile unsigned long value;

void setup()
{
  //ADC setup
  ADC->ADC_WPMR &= 0xFFFE; //disable write protect
  ADC->ADC_CHER = 0b100; //Enable AD2     |
  ADC->ADC_MR &= 0b11111111000000001111111100000000;
  ADC->ADC_MR |= 0b00000000000100100000000000000000; //software trigger, hi res, no sleep, not free running
  ADC->ADC_IER = 0b100; //enable interrupt
  ADC->ADC_IMR = 0b100; //enable interrupt in mask

  ADC->ADC_CR |= 0b10; //start first conversion
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop()
{
  ADC->ADC_CR |= 0b10; //start conversion
  while (!(ADC->ADC_ISR & 0b100)); //wait for conversion to end

  for (int i = 0; i <= 15; i++)
 {
    value = ADC->ADC_CDR[i]; //read conversion data for all channels
    Serial.println(value);
 }

 Serial.println();
 Serial.println();
 Serial.println();

 delay(3000);
}

```

Just doesn't seem to be doing anything. `ADC_CHSR` (the ADC channel status register) shows channel 2 and only channel 2 enabled and conversions are starting and completing, yet now the conversion data is always 2048. Here's the serial output of all 15 channels, now in 12 bit mode:

```
0
0
4095
0
0
0
0
0
0
0
0
0
0
0
0
0

0
0
4095
0
0
0
0
0
0
0
0
0
0
0
0
0

```

# Answer
I've abandoned all hope and decided that the ADC is just bad.
> 0 votes

# Answer
You need to add this to your setup():

```
pinMode(A0, INPUT);

```

...to set the pin for reading.

Since you're reading an input that's already pulled up (in the middle of a voltage divider), that should be all. However, you can turn on the internal pull-up with:

```
digitalWrite(A0, HIGH);

```

...while the pin is in input mode.

More details here:

http://arduino.cc/en/Reference/PinMode

http://arduino.cc/en/Tutorial/AnalogInputPins
> 2 votes

# Answer
Answer to a 6 years old thread. Hope this will help others :)

Looks like you have been using an external power source and only connected the positive core to the pin. If you had an external power source, did you connect the external power source GND to Arduino GND?
> 2 votes

# Answer
If you have AREF pin pulled out onto the shield board not connected to anything, and you don't declare analogReference in your code (thus keeping it as the default internal 5V), it could still cause you to have the 1023 symptom you are describing. My suggestion: cut the AREF connecting pin, or put a constant 5v onto the AREF line.
> 1 votes

# Answer
Try to force sensorValue at the beginning of the void loop to zero, put short delay before reading the analogue pin. I tried this and works for me. Unless your prgram will misbehave at zero sensor value at every loop start. The will No need of initializing A0 as input because they are input by default.
> 1 votes

# Answer
Try adding this line in your void setup(), also disconnect AREF pin from any kind of bias,

```
analogReference(INTERNAL1V1);

```
> 1 votes

---
Tags: arduino-due, analogread
---


# Question
Title: Stepper motor driver not working properly
I have a problem. I am following this guide about controlling a NEMA 17 stepper motor: https://www.makerguides.com/a4988-stepper-motor-driver-arduino-tutorial/

I uploaded the code to my arduino uno and powered on everything, but the stepper motor doesn't rotate, except when I put my finger on the metal screw of the a4988 driver. The arduino is powered by a 5v 1A adapter and the a4988 driver is powered with a 12v 2amp adapter.

What is causing this?

# Answer
The "metal screw" is a "trim potentiometer" that is used to set the current used to drive the motor. It sounds like you may be altering the current when you push against it. Try turning it to different angles to see what effect that has on the motor.

Alternatively if it only ever works when you push on it then it could be that you have a faulty potentiometer on your board.
> 2 votes

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


# Question
Title: How to assign ESP8266 access point a hostname that can be resolved by the stations?
I want to assign a *hostname* to a ESP8266 **access point**, so that the clients can reach a webserver on this access point without caring about the IP address of the AP. How can that be done?

I tried using `WiFi.hostname("something");` but that does not work with AP mode. Can this somehow be done?

### UPDATE

Using *mDNS* seems to work in this AP mode too. However, I am still curious to know if this is possible to access the webserver on the AP using the *hostname* and not *mDNS*.

# Answer
> 1 votes
I'm unclear on the distinction being drawn here:

> the hostname and not mDNS

mDNS, like DNS, and hostname lists are all things a "resolver" would use to map a "hostname" to an IP address.

If you mean "how do I use DNS instead of mDNS?", you'd need to have your ESP8266 running a DNS server. And for clients to be aware of it you'd probably have to be running a DHCP server as well.

By the way, the examples list for the ESP8266 Arduino package contains a DNSServer/DNSServer example that appears to do exactly this. I have just tested it.

This is the exact code I ran out of the ESP8266 Arduino github repo at the tag for the version of the ESP8266 Arduino core I tested it on, 2.7.4.

---
Tags: esp8266, esp32, espressif, esp
---


# Question
Title: Device Signature Error uploading to ATMEGA168PA
I keep getting a device signature error and can't program my Atmega168pa chip.

I'm using the board from: https://mcudude.github.io/MiniCore/package\_MCUdude\_MiniCore\_index.json

I've pasted the error below from an attempt to upload a new sketch:

```
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

```

```
Arduino: 1.8.13 (Linux), Board: "ATmega168, No bootloader, EEPROM retained, 168P / 168PA, BOD disabled, LTO Disabled, Internal 8 MHz"

Sketch uses 412 bytes (2%) of program storage space. Maximum is 16384 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 1015 bytes for local variables. Maximum is 1024 bytes.
/home/rick/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/home/rick/.arduino15/packages/MiniCore/hardware/avr/2.0.7/avrdude.conf -v -patmega168p -cstk500v1 -P/dev/ttyUSB0 -b19200 -Uflash:w:/tmp/arduino_build_51999/sketch_nov15a.ino.with_bootloader.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/rick/.arduino15/packages/MiniCore/hardware/avr/2.0.7/avrdude.conf"
         User configuration file is "/home/rick/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega168P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

An error occurred while uploading the sketch
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

Pictures of my wiring:

I have:

* D13 -\> (PCINT0/CLKO/ICP1) PB0 \[Pin 14\]
* D12 -\> PB4 (MISO/PCINT4) \[Pin 18\]
* D11 -\> PB3 (MOSI/OC2A/PCINT3) \[Pin 17\]
* D10 -\> (PCINT14/RESET) PC6 \[ Pin 1\]

I have a 100n capacitor between vcc & gnd and between avcc & gnd. I have a 10 uF capacitor between “Reset” and “Ground” pins on the Arduino. Power is fed via the 5v pin from Arduinio.

I know this nano works (I programmed an ATTiny84 with it before and after my attempts on the Atmega). I've checked pwr & gnd. I'm not 100% sure of the wiring. These chips are new from China so I'm not sure if they are configured for internal or external clock, although I believe they are set to internal by default.

# Answer
> 1 votes
The ISP pins are usually all next to each other. The connection D13 to PB0 is unlikely to be correct. It should be connected to PB5.

You can check your connections here: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoToBreadboard (there is UNO, but pin numbering/wiring is exactly the same as for Nano)

Another possible mistake is burning wrong fuses (with bootloader) for external xtal setting (also mentioned in the article)

---
Tags: arduino-nano, avrdude, atmel
---


# Question
Title: ESP32 AsyncWebServer SPIFFS problem loading page
I can load spiff docs, but I get a 404. Wireless works, IP addressing works and I can load other examples successfully. This simple image load ino is giving me fits!

```
#include <WiFi.h>
#include <AsyncTCP.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
const char *ssid = "x";
const char *password =  "123456789";
IPAddress staticIP(10,0,0,1); //ESP static ip
IPAddress gateway(0,0,0,0);   //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0);  //Subnet mask

AsyncWebServer server(80);

void setup() {
  Serial.begin(115200);
  WiFi.softAP(ssid, password);

server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{request->send(SPIFFS, "/index.htm", "text/html");});

server.on("/image.png", HTTP_GET, [](AsyncWebServerRequest *request)
{request->send(SPIFFS, "/image.png", "image/png");});

server.begin();

}//END setup

void loop()
{
}

```

```
<!DOCTYPE HTML>
<html>
<head>
     <meta charset='UTF-8'>
</head>
<body>
     <img src="image.png" alt=" image goes here">
</body>
</html>

```

# Answer
I don't have an ESP32 to test with. Though, I tried to make your code run on an ESP8266, but it's a bit of an effort to validate what is ultimately a wild guess on my part.

And that is: *perhaps* you have some uppercase letters in your filename such that `"/image.png"` does not match perfectly and furthermore *maybe* SPIFFS is case sensitive. That is, your file could be named Image.png or IMAGE.png and that might matter.

UPDATE:

In my exploring this on the ESP8266, I'd forgotten to execute `SPIFFS.begin()`. And I see no counterpart to it in your code. At least one example of ESPAsyncWebServer I've seen does call `SPIFFS.begin()`

I found that the filenames **are** case sensitive, again at least on the ESP8266; so that can be a source of problems.

Also checked that if the SPIFFS size is changed through menu selections, I did indeed need to reupload the SPIFFS image.

I know these are different systems; in fact the code I'm using to test doesn't compile for ESP32, but I suspect a lot of the code is shared, and so maybe the problems are as well.
> 0 votes

---
Tags: esp32, spiffs
---


# Question
Title: Dimming this ~30V led with PWM, what do I need?
I have a street lamp with a led and simple driver in it, I don't know the exact led voltage but the driver (image attached) says `27-36V DC output`, `MODEL: 50W`.

Is there a part I could place between this driver and the led, so I can control dimming by Arduino via PWM ?

**The led driver specs** (large image below) says: `INPUT; AC 85-285V` and `OUTPUT: DC 27-36V 1500mA`, `MODEL: 50W`

I thought it would work to put this "*PWM power module*" between the driver output and the led, but (I tested months ago) I remember it started to blink, I think only when decreasing power but not on full power (controlled by PWM with arduino).

* Should it work with this module or I am trying something very wrong ?
* Are there any other parts that should work for sure in this situation ?

**The specs on the PWM module** are these:

```
Voltage: 5 V - 36 V DC;
Power: 400 W;
Current: 30 A;
PWM Voltage: 3.3-20V;
PWM frequency: 0-20kHz ;

```

# Answer
It will not be possible for you to PWM dim your LED with that LED driver (power supply).

That is a *constant current* driver with under/over-voltage protection. It delivers a specific amount of current (1.5A) and varies the voltage to allow that to happen.

If the voltage rises too high or falls too low then there must be a fault, so it shuts the power off. This is usually because there is either a short (LEDs tend to "fail short") or an open circuit. The former causes the voltage to drop too low and the latter for it to be too high.

When you insert PWM control you alternate between driving the LEDs and an open circuit. If that open circuit persists too long (low duty cycles) the driver will shut off.

You will need to replace the LED driver (the power supply) with one which includes PWM control internally to it.
> 5 votes

# Answer
If you buy a 30V current-limiting power supply set to limit the current to 1.5A, you should be able to use it to power your LED light through a high power logic level MOSFET. You could control the MOSFET with a PWM signal from an Arduino and use that to vary the brightness of your light. With a little googling I found an adjustable power supply with an output ranging from 0-30V and a power rating of 0 - 1.5A https://www.canakit.com/r182-0-30v-0-1.5a-adjustable-regulated-power-supply.html

It does not look to be weather-proofed like the one you show however, and you'd need to make sure the heat-sink was able to dump enough heat to prevent it from overheating.
> 2 votes

---
Tags: power, led, pwm, current, voltage
---


# Question
Title: Trying to connect to WiFi on ESP32 using credentials from SD card
I am trying to connect to WiFi on an ESP32 using credentials I stored on an SD card. I am able to read and parse the credential and printing them to the serial monitor shows that the SSID and password are correct, but it is not connecting to WiFi. When I hardcode the WiFi credentials it works. What could I be doing wrong?

# Answer
I use the NVS partition to store NON VOLATILE information.

I use this library: NVS library

You can save like string and restore after reset/off.

Example:

```
#include <Arduino.h>
#include "ArduinoNvs.h"

void setup() {
    NVS.begin();
    Serial.begin(115200);
    // write to flash
    String set_SSID = "WIFI_name";
    NVS.setString("nvs_wifi_name", set_SSID ); //upload 1 time. after comment this line and upload again **
    // read from flash
    String get_SSID = NVS.getString("nvs_wifi_name");
    Serial.printf("Wifi name stored %s\n", get_SSID);
}

void loop() {}

```
> 0 votes

---
Tags: esp32
---


# Question
Title: Looking for information and/or how to connect the RF433Mhz module (WL101-341/WL102-341)
I'm trying to find information about this 433MHz RF module: QIACHIP

Apparently it can be connected to an Arduino with the RadioHead library, but I don't have diagrams of how to connect them togheter in order to send/recieve data, becasue the module have 4 pins (Vcc, Gnd, Dat and En). I guess Dat pin should be connected to any Arduino pin, but as I only have one module I dont wanna risk it. I have no previous experience with RF modules :-(

I have found some Youtbe video, but the language of the video is in russian, and I don't know that langauge (I even ask the owner of the chanel for subtitles).

Please, if anyone have worker whit this module before, share:

* How to connect the module with an arduino?
* A simple example of how to send a simple word (let's say: "Hello") from the transmitter to the reciever

# Answer
You're right not to just go ahead and wire things up. There's a couple of nuances that you need to take into account.

**Transmitter**

* Ignore the EN pin - that does nothing on that module
* The transmitter is 1 3.3V device. You need to power it from the 3.3V pin and use logic level (5V -\> 3.3V) translation on the Data pin

simulate this circuit – Schematic created using CircuitLab

**Receiver**

The receiver is much simpler as it is a 5V device:

simulate this circuit

On the Arduino it shouldn't matter what IO pin you use, the Radiohead library should work fine with any of them. These modules are pretty dumb - you raise DAT high on the TX and DO on the RX goes HIGH. Very simple.
> 2 votes

---
Tags: rf
---


# Question
Title: Compensate weight due to acceleration (load cells)
I'm trying to make a weighing scale that works in a lift. I'm using load cells to measure the weight, let's say it's F. Then I use that weight F and g which I know is 9,81 m/s2 to calculate the mass of the object like this:

F = m·g \<=\> m = F/g

This works when the lift is in rest (or when moving at a constant speed), but when it accelerates the weight F increases and because of that the mass also increases. Is there a way to compensate this weight(/extra force) due to acceleration?

# Answer
> 1 votes
The force due to acceleration is: F = m\*a

So to calculate the weight while accelerating the formula is:

F = m*g + m*a or F = m(g + a)

Note, of course, that a can be positive or negative depending on whether the elevator is accelerating or decelerating.

The trick here is to know what "a" is. The best approach is probably to get an accelerometer and use its reading in your calculations.

By the way, the mass is always a constant here. It does not change, in Newtonian Physics at least, due to acceleration.

# Answer
> 1 votes
You could measure the total acceleration (g + lift acceleration) with an accelerometer, and use that value in your calculation instead of 9.81m/s2. If the measured value is 0, sound an alarm.

Or, assuming the elevator only accelerates/decelerates for short periodes only (say, less than 2s) during a "trip", you could make a series of measurements in a loop at, say, every 0.5s.

When you get, say, 5 measurements that are the same, or very close to each other, you know acceleration = 0 and you can average those 5 measurements to get the desired result.

Values may vary depending on the lift, and the measurements will be slow in coming.

---
Tags: sensors
---


# Question
Title: Arduino "Maximum Power point tracker" (MPPT) Problem
I need an IV curve for a solar panel. As far I know, solar-panel and Diode IV curve pretty much the same. Here, I am using diodes(6A10-1) as a solar-panel. Where each Diode voltage drops 0.6volt. I provide 4.8v across the diodes from a power supply and limited the current at 1amp of the power supply for acting like a solar panel. The number of diodes is 8 for a 4.8V drop. A 1-ohm resistor for measuring the current. I am using Arduino to measure the value of current and voltage by varies the MOSFET(IRF540) gate voltage. A low pass filter is connected between D2 and Mosfet Gate. A0 for measuring the solar voltage and Current, Id=A0-A1. But Arduino gives incorrect values of A1 and current, Id, and sometimes negative values with respect to a multimeter.

\[

```
const int V1 = A0;
const int V2 = A1;
float SolarVolt = 0.0;
float V1_VOLT = 0.0;
float V2_VOLT = 0.0;
float Id  = 0.0;
int V1_value = 0;
int V2_value = 0;
double gateVoltage=150; //For Gate volt
double mstep=5.1;
int GatePin=2;

void setup() {
  pinMode(GatePin,OUTPUT);
  Serial.begin(9600);
  pinMode(V1,INPUT);
  pinMode(V2,INPUT);
}

void loop() {
  analogWrite(GatePin,gateVoltage);
  gateVoltage=gateVoltage+mstep;
  Serial.print("GateVolt = ");
  Serial.print(gateVoltage);
  Serial.print("    ");
  if (gateVoltage <= 0) {
    mstep = 1;
  } else if (gateVoltage>=255){
    gateVoltage = 255;
    mstep = -1;
    delay(50);
  }

  V1_value = analogRead(V1);
  V1_VOLT = (V1_value * 5.0) / 1024.0;

  Serial.print("V1_VOLT= ");
  Serial.print(V1_VOLT);
  Serial.print("    ");

  V2_value = analogRead(V2); // for Id1
  V2_VOLT= (V2_value * 5.0) / 1024.0;

  Serial.print("V2_VOLT= ");
  Serial.print(V2_VOLT);
  Serial.print("    ");

  Id=V1_VOLT-V2_VOLT;

  Serial.print("ID= ");
  Serial.print(Id);
  Serial.println();

  delay(1000);
}

```

# Answer
> 2 votes
Your current signal will also show PWM, so you will need to filter that before measuring. It would be much simpler if you could rearrange your circuit to put the sense resistor on the ground side of the MOSFET, since then you can use a simple RC filter and a single A0 measurement. Also, you wouldn't have to worry about the no-load voltage from the solar panel (when the MOSFET is off) going above the 5V limit of the A0 pin.

---
Tags: arduino-uno, arduino-mega, arduino-nano, electronics
---


# Question
Title: How to increase the frequency of data transmission of SIM900A GSM Module connected to Arduino Uno?
I have a SIM900A GSM Module hooked onto an Arduino Uno board. The Arduino is connected to a MPU6050 Accelerometer which is constantly monitoring data at 1 second interval. I am trying to transmit the gathered data to ThingSpeak server. I have successfully established the connection with the server and the transmission is occurring. However, the interval between two transmitted readings are very large, varying between 1 to 3 minutes. That interval is too large to use the data. Is there any way I can enhance the transmission frequency so that the data points are close enough? At least to a few seconds distance?

# Answer
There does not appear to be a complete description of how ThingSpeak throttling works. However there is this text on the Thing Speak License FAQ web page:

> As a reference, one unit provides the ability for a device sending data to ThingSpeak at once per second to send data to ThingSpeak for one year.

Assuming your code is working as expected and the ThingSpeak throttling is to suspend your service for 15 minutes, it may be that you are sending data faster than ThingSpeak will allow.

To test this, try to send messages slower than once per second.
> 0 votes

---
Tags: arduino-uno, gsm, iot, thingspeak
---