# Question
Title: I can't use buffer without printing in my Nodemcu esp8266
```
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "password"

void setup() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  ////////////////////////////////////////////

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/photos");
  http.addHeader("Accept", "*/*");

  int httpCode = http.GET();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);

  //reading response with buffer
  static char buff[128] = { 0 };
  while (http.connected() ) {
    size_t size = client->available();
    if (size) {
      int c = client->readBytes(buff, ((size > sizeof(buff) ) ? sizeof(buff) : size));
      //if i uncomment this next line, everything is fine.
      //Serial.write(buff, c); Serial.println();

      //but if i dont use serial.write program never gets here
      if (char * pch = strstr (buff, "quis fuga")) {
        char str[20] = { 0 }; int g =   0 ;
        while (pch[g] != '\"') {
          str[g] = pch[ g];
          g++;
        }
        Serial.print("FOUND IT: "); Serial.println(str);
      }

    }
    else if (!size) {
      Serial.println( "reading done");
      break;
    }
    delay(1);
  }

}

void loop() {

  delay(222222);

}

```

**EDIT** here i created a compilable runnable code. basically i am trying to find a word in a http response. my real example`s response isnt json and it is as long as this example`s response. one other problem is i cant read all of the repsponse. it unexpectedly finishes reading sometimes after a few lines sometimes after a few hundred. in this particular request my nodemcu cant read after id 258. or id 8. object in the json response: https://jsonplaceholder.typicode.com/photos

if i dont use serial.write print buffer content, it finishes reading immideatly and thats exactly where i have the problem.

# Answer
The Serial printing creates a delay. That delay enables to collect more characters in the buffer. If you read the input in small pieces (3 to 10 bytes) then the buffer doesn't contain the searched substring because it splits into two subsequent buffers. Even if you could read full buffers, it still can happen that the search string will be split.

To search for a string in a stream of data you can use function `find(string)`. The networking Client class inherits this function from Arduino Stream class. `find` will read the stream until it finds the searched string. Then the next read from the stream will read the data right after the searched string.
> 0 votes

---
Tags: esp8266, http, buffer
---


# Question
Title: Is it possible to get values only during vibration/movement from an Accelerometer(ADXL335/MPU6050)?
I'm trying to make a wearable motion sensor using ESP32 board and ADXL335 Accelerometer.

Presently when I'm serial printing the output I'm getting the tilt value as well, which have different values at different orientation (I'm printing average of the X,Y & Z). So when I try to light up an led by setting a threshold the average value is different in different orientation.

Is there way to get values only during vibration and be zero when there is no vibration/body movement.

Thanks in advance guys for the help.

# Answer
Acceleration is a vector quantity. Therefore, instead of looking at the average values of X,Y, and Z, you should probably look at the magnitude of the acceleration vector, that is (X^2+Y^2+Z^2)^0.5. Then, you can set an acceleration threshold below which you would send no data.

The benefit of using the magnitude of the acceleration vector is that it is independent of the orientation of the device. For example, if you placed the device on a table along the X-axis, the accelerometer would read something like X = -g, Y=0, Z=0, where g is the gravitational acceleration. Similarly, if you placed the device on a table at 45 degrees between X and Y axes, the accelerometer would read something like X = -g sqrt(2)/2, Y=-g sqrt(2)/2, Z=0. In both cases, the magnitude of the acceleration vector is just g. On the other hand, the average values would be -g/3 and -g sqrt(2)/3, respectively, as you observed in "...the average value is different in different orientation."
> 1 votes

# Answer
Yes.

**Linear Acceleration at given axis = Actual Acceleration - Gravitational Acceleration**

Gravitational Acceleration across any Axis = Magnitude of Gravity Vector x Cosine of axis angle with the Gravity Vector
> 0 votes

---
Tags: programming, arduino-ide, esp32, accelerometer, mpu6050
---


# Question
Title: Is the shiftOut code depending on the (low) speed of an Arduino?
In the (official) file `wiring_shift.c` I found the following code for shiftOut:

```
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

```

However, the last two `digitalWrite` commands occur directly after each other. I wouldn't hope that `digitalWrite` depends on some time or delay, so how can it be assumed that the slave device sees the clockPin is HIGH if the Arduino immediately sets the clockPin to LOW again?

(My plan is to convert the shiftIn/shiftOut code to STM32 using HAL/CubeIDE).

# Answer
> 3 votes
Some time ago, I timed digitalWrite() and direct port write commands by looping over 10,000 executions of each and timing them with millis(). I made both tests on a 16MHz Atmega 328p at 16MHz.

For `digitalWrite(13, LOW)`, I got 2.7usec / call.
For `PORTB &= 0x20;`, I got 0.15usec / statement. (The direct port access was executed 10 times within the loop to further pad it out for the `millis()` result to have any significance.)

\[In my notes I wrote that I timed `PORTB &= 0x20;`, but the correct equivalent to the `digitalWrite()` version is `PORTB &= ~0x20;`. That is probably what I actually did, but note that the bit-mask would be generated at compile time, so either way should have produced the same result.\]

> how can it be assumed that the slave device sees the clockPin is HIGH

It would depend on the specifics of the slave, but it is quite likely triggered by a pulse, rather than polling its input until it finds a high-level.

Update: To confirm my timing data, I redid my 2.5-years-ago experiment. I put 10 statements in each of 2 loops of 10,000 iterations, either:

```
digitalWrite(13, LOW);

```

or

```
PORTB &= ~0x20;

```

And got these total times in msec for the 100,000 executions:

digitalWrite(): 305 // digitalWrite(13, LOW); PORTB (correct): 15 // PORTB &= ~0x20;

These translate to single execution times in 10s of nanoseconds:
3050 nsec == 3.05 usec for the function call,
150 nsec for direct port I/O, making port I/O about 20x faster.

---
Tags: shift-register, timing, digitalwrite
---


# Question
Title: If-statement matches but doesn't give a result
I just started two weeks ago with Arduino and I'm hooked!

I got off to a good start and went through some online tutorials quite easily. Then came the RGB LED, which I couldn't get to work all of a sudden (it required putting in a color through the serial monitor, which would then be given by the RGB).

And the strange thing is, I can't get anything to work anymore that requires input through the serial monitor, where I used to get it working immediately...

I presume it's something with the if-statement, because if I remove it and just say digitalwrite HIGH to a certain pin, it works fine....

Checks I did:

* Full re-install of Arduino (didn't solve it).
* Check the LEDs by hooking them up to 5V directly (they all work).
* Reconnecting the Arduino (didn't solve it).
* Use a multimeter to measure current (there isn't, although the if-statement matches...

Here's my code. Does anybody see it? Because I don't...

Regards,

nannev (using Mac and Arduino Uno)

```
int yellowPin=8;
int redPin=9;
int greenPin=10;
String myLED;

void setup() {
  Serial.begin(9600);
  pinMode(yellowPin,OUTPUT);
  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
}

void loop() {
  Serial.println("Your color?");
  while (Serial.available()==0) {
  }

  myLED=Serial.readString();
  Serial.print(myLED); //check if the input came through correctly, which it did
  delay(1000);
  if(myLED == "yellow"){ .    //nothing happens at yellow....
    digitalWrite(yellowPin, HIGH);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "red"){             //nothing happens at red....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, HIGH);
    digitalWrite(greenPin, LOW);
  }

  if(myLED == "green"){       //nothing happens at green....
    digitalWrite(yellowPin, LOW);
    digitalWrite(redPin, LOW);
    digitalWrite(greenPin, HIGH);
  }
}

```

# Answer
The Arduino IDE uses the C and C++ programming languages.

***Some string comparison basics using C:***

In the C programming language, a string can be thought of as an array of 8 bit values. One way to compare two strings is to compare each 8 bit value and consider the strings different (not equal) upon finding the first not-matching 8 bit value. Here is an example from programmingsimplified.com:

```
int compare_strings(char a[], char b[])
{
   int c = 0;

   while (a[c] == b[c]) {
      if (a[c] == '\0' || b[c] == '\0')
         break;
      c++;
   }

   if (a[c] == '\0' && b[c] == '\0')
      return 0;
   else
      return -1;
}

```

There is a common function called strcmp() which can be used instead. Here is another example from the same web page which uses strcmp():

```
#include <stdio.h>
#include <string.h>

int main()
{
   char a[100], b[100];

   printf("Enter a string\n");
   gets(a);

   printf("Enter a string\n");
   gets(b);

   if (strcmp(a,b) == 0)
      printf("The strings are equal.\n");
   else
      printf("The strings are not equal.\n");

   return 0;
}

```

Note that in both cases the array of strings is assumed to end with a NULL or zero value byte. If you do not wish to follow this format you can use an alternate version of the function called strncmp() where the number of characters to be compared is passed along with pointers to the 2 strings.

***Some string comparison options using C++:***

There are C++ ways to compare 2 strings which make coding Arduino Sketches easier. But C++ string manipulation usually requires more RAM. And RAM is usually in short supply on inexpensive embedded processors.

As the code in the question is written using type String we can explore that approach. And, as there is some concern the strings may have unexpected trailing characters, we will continue to check only the necessary number of characters. In this slightly modified code example from geeksforgeeks.org string s1 is compared with string s2. But only the first 6 characters are compared:

```
void compareOperation(string s1, string s2)
{
    // Compares 5 characters from index number 3 of s2 with s1
    if((s2.compare(0, 6, s1)) == 0)
        cout << "Here, "<< s1 << " are " << s2;

    else
        cout << "Strings didn't match ";
}

```

The number 6 was chosen because "yellow" contains 6 printable characters. In this way, we can avoid the uncertainty of what character(s) follow the characters that make up "yellow" as received from the serial port.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to set a time out like Serial.setTimeout() for Serial.read()?
I read a comment form here:

"Serial.setTimeout() sets the maximum milliseconds to wait for serial data when using Serial.readBytesUntil(), Serial.readBytes(), Serial.parseInt() or Serial.parseFloat(). It defaults to 1000 milliseconds."

According to the latest webpage,

"Serial functions that use the timeout value set via Serial.setTimeout():

```
Serial.find()

Serial.findUntil()

Serial.parseInt()

Serial.parseFloat()

Serial.readBytes()

Serial.readBytesUntil()

Serial.readString()

Serial.readStringUntil()

```

"

So apparently, there's no direct indication to set a timeout option for Serial.read().

How to set a time out like Serial.setTimeout() for Serial.read()?

# Answer
> 1 votes
You can't set timeout for read(), but you can use readBytes() to read one byte.

```
byte b;
int count = Serial.readBytes(&b, 1); // read one byte with timeout
if (count) { // 0 or 1
  Serial.write(b); //echo
}

```

---
Tags: serial, time, uart
---


# Question
Title: ATTiny85 Digispark clones failing USB handshake - how to program them?
I've recently bought a batch of ATTiny85 modules (Digispark clones) from China, and tried to write a first test program into them now. I noticed that they do seem to have some bootloader already installed since the P1 LED is flashing, but they do not seem to make any reasonable USB handshake. (I have ordered other seemingly identical modules from a different seller on Ali before and was able to use them just fine.. so I generally know how to work with these.)

Linux dmesg shows me that a device was plugged in, but does not get any vendor or model ID. Windows tells me that 'the device last plugged in has failed enumeration'. This looks to me like the bootloader is incomplete or somehow broken.

So, as a next step, I tried to rewrite the AVR with an USBASP adapter over ISP, only to find out that the /reset pin apparently has been disabled via fuse bit.

I'm in some kind of a loop now... If the bootloader doesn't speak USB correctly, I can't use the Arduino IDE or avrdude or anything to write to it, and if the /reset is remapped I can't replace the bootloader via ISP to get USB working.

Can anyone provide a hint on how I can get these modules to work? Or should I just assume I bought a bad batch, throw them away and order fresh ones?

# Answer
> 3 votes
I had problems too - SHORT: all about USB-hub or PC's root-hub and extension cables +Luck.

My ebay items were going under the name "Digispark Kickstarter ATTINY85 Arduino Micro USB Development Board" and naturally it came with no Digispark-(c)-right infringing markings from China. I kept my fingers crossed that my items would at least be AVRisp-programable..

So in high hopes I plugged in my China import into my trusty USB HUB2.0(which I always use at least as a current limiter) – after testing it first on a powerbank (\>5secs blinky-blink) .. checked for enumeration (which it did-but no driver yet) .. installed the DPinst\[64\].exe drivers.. and then kept getting messages like \>\>device failed to enumerate\<\<, etc. - the list of my failures:

* determined directly plugged into a PC's USB root-hub rigged/minimalistic usb devices do not enumerate at all (all 0s)
* with a certain USBAmale-to-USBAfemale extension cable with plastic-encasing(female side) the USBA device’s was not allowed to go "in" probably just for some millimeters to short.. the Data-lamella do not connect correct – just power's okay (blinky-blink) .. but no Windows device-recognition .. No-No!
* AND reminding the FTDI black-listing dilemma I used PCs without out the drivers still – using the good old “USBview.exe” program to check on the enumeration (on all my available device the same .. previously plugged into my driver-enable PC or just into an “out of the fab”-one

```
idVendor:           0x16D0
idProduct:          0x0753
bcdDevice:          0x010B

```

so no mis-configuration of the bootloader through a \>possibly mallign\< Digispark clone dis-configurator (as I was thinking the FTDI schemes .. of course FTDI only did it to protect their name X-) – to stop getting accused for faulty devices coming from cheap chinese fake or clone-producers) * EVEN tried to deinstall the Drivers with DPinst\[64\].exe /D .. which gave me .. Yes .. yet again “Drivers all installed properly!”..

.. and IN THE END .. I just went back to my old, initial “USB HUB-behind root-hub” configuration .. and *Abra-ca-Zang* .. the device just enumerated and registered as “Digispark Bootloader” (windows device manager under libusb-win32 Usb Devices)

and all went okay - reprogramming with the Arduino IDE - NO FUZZ! .. The !very same! config I was using on my “first testings” (minus some fair time and headaches of debugging)

So my advice .. always do a Basic-Test on a USB Powerbank, USE an USB-Hub, check your cables - use ones you trusted before! – try as many options as you (may) have .. and use the tools at your hand .. down to PC-progs or an logic-analyzer or an Beagle USB / protocol analyer to check where the problem may be.. trace back your tracks and even retry..

There may be a suprise for you at the end of the rainbow!

# Answer
> 1 votes
Using Arduino IDE 1.8, I had a *Windows did not recognize USB Device* message.

I successfully installed the DigiSpark drivers but still the PC was not recognizing the Tiny85 development board. In the Arduino IDE I had *initially* selected the **DigiSpark (16.5 MHz default)** as instructed in a YouTube video. I did some more research, someone suggested trying a different board. I selected the **DigiSpark (No USB 16 MHz)** uploaded the `Blink` example.

The LED started to flash and windows stopped complaining about the unrecognized device. I removed the flashed board and plugged in another, Windows started complaining, I uploaded the sketch successfully windows stopped complaining. I removed the second board and installed the first one and there were no further issues with Windows.

# Answer
> 0 votes
Bootloader is poorly programmers it hand overs the overall hardware to user code,many people encounter error when uploading sketch second time. Well i have solution though it may sound wears but it works for sure "1.Disconnect board from USB , 2.Hit upload button., 3.Timout timer starts for 60 seconds. 4. Go ahead plug board to USB 5. CONGRATULATIONS" thank me it will work...

---
Tags: atmel, bootloader, avrdude, attiny85
---


# Question
Title: How to power Nodemcu using 12 volt AC to DC adapter?
I am trying to make a small project using Nodemcu. My project is WiFi controlled LED, 2 LED's will blink at the same time. I have successfully uploaded the code and it works fine using USB connection. But I want to power the Nodemcu using 12 volts 1.5 amps AC to DC adapter. I have checked it in web search but I have not found an understanding circuit. please help me out guys.

# Answer
> 1 votes
You connect the + side of the adapter to VIN pin and the - side to GND.

You have to check the maximum voltage when using the VIN pin. Probably it means you 'waste' some power (but it's from a wall wart, so it should be ok). See the remark of Flyingfenix below for heating consequences.

See this link: Power Related ESP-12E Development Board Pins, fragment 'Using a Wall Wart':

Examples: Wall-Mount-AC-Adapters

The current (1.5A) should be more than enough; the adapter's current should be higher than what is needed by the NodeMCU + circuit. So this is ok.

---
Tags: nodemcu
---


title: Unconsistent time in arduino loop

text:
# Question
Title: Unconsistent time in arduino loop
I have this code:

---

The output looks like this:

Why are there non-periodically some extremely large values?

Thanks

# Answer
> 2 votes
As explained by theSealion in his answer, this may be due to the different background tasks performed by the microcontroller. However, I personally find that 1 ms looks excessive. My guess is that the main culprit is the USB stack pushing all those bytes down the wire.

In order to check this, I wrote the following program. It measures a histogram of the loop execution times and then prints it through the serial port. Since the data is only printed *after* the measurements are done, the serial port does not do any work while the timings are being measured.

```
const int HISTOGRAM_LENGTH = 512;

uint16_t histogram[HISTOGRAM_LENGTH];

void print_histogram() {
    Serial.println(F("t (us)  count"));
    Serial.println(F("-------------"));
    for (int i = 0; i < HISTOGRAM_LENGTH; i++) {
        if (histogram[i] == 0) continue;  // skip zeros
        Serial.print(i * 4);
        Serial.print('\t');
        Serial.println(histogram[i]);
    }
    Serial.println(F("-------------"));
    Serial.flush();
}

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

void loop() {
    static uint32_t last_time;
    uint32_t now = micros();
    uint32_t dt = now - last_time;
    uint32_t bin = dt / 4;  // resolution of micros() is 4 us
    if (bin >= HISTOGRAM_LENGTH)
        bin = HISTOGRAM_LENGTH - 1;
    if (++histogram[bin] == UINT16_MAX) {
        print_histogram();
        exit(0);
    }
    last_time = now;
}

```

These are the results when run on an Arduino Uno:

```
t (us)  count
-------------
8       21888
12      65535
16      632
20      323
56      1
-------------

```

This shows that most loop iterations take 8–12 µs. Those iterations that were interrupted took 16–20 µs. The outlier at 56 µs is most likely the time between the program starting and the very first iteration of `loop()`.

Here, the only interrupt source that affects the measurements is the timer interrupt. It fired exactly 955 times during the measurement period, which is consistent with the number of samples recorded at 16–20 µs. We can see from this data that the timer interrupt takes roughly 8 µs to run, which is quite reasonable. Again, I would not consider a 1 ms delay as reasonable.

# Answer
> 1 votes
There are be several "tasks" and interrupts that run in the background and they influence how often the loop() function is called.

For example timer, usart ...

They all need some attention from time to time. If the need some really fixed execution time you must use something like a hardware timer.

and by the way: a maximum of ~1.1ms is not bad for such a small controller. :-)

And as a addition to your question in your comments: I don't think there is a way to make the loop faster. As long as you need the other tasks, you have do give them some time.

# Answer
> 0 votes
> In addition, the original problem for this question was that I am driving a stepper motor and I need to communicate with Raspberry Pi using UART. The problem is that when I send some data about the motor to RPi and the motor is already spinning very fast, I often loose a step

Your stepper code has to run very consistently to maintain 3000 steps/sec without jitter or dropping steps. It must not have to wait for communication or any other task but be able to issue the next step command on-time. Some possible techniques to accomplish this:

* Don't post an entire message to the Pi but send only a few characters at a time, between steps.
* Talk to the Pi in shorter, tightly coded messages, and let the Pi expand them if it needs to.
* Use the highest baud rate the Uno & Pi can reliably use.
* Issue step commands in a timer-driven interrupt routine, with any stepper housekeeping done in the background, between step-commands.
* Use a faster processor.

---
Tags: serial, arduino-micro
---


# Question
Title: esp8266 cant make more than one request at time
i am trying to make a get request, read that request and make another request with that read value. i havent shown it in this code but i want to make a request inside in a request. is it possible to make a request without ending one, if its, how do i do that?

here is the code :

```
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "pw"

void conn();
void getreq();
void anothergetreq();

void setup() {
  conn();
  getreq();
}

void loop() {
}

void getreq() {
  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/users/1");

  int httpCode = http.GET();
  String payaload = http.getString();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  //here i presume got the value from payload, and making another request with it
  anothergetreq("posts/1");
  http.end();

}
void anothergetreq(String p) {

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/"+p);

  int httpCode = http.GET();
  String payaload = http.getString();

  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  http.end();
}

void conn() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

```

here is the output:

```
Connected with IP: 192.168.1.100

HTTP CODE: 200
PAYLOAD: {
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}
HTTP CODE: -1
PAYLOAD:

```

# Answer
> 1 votes
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#bearssl-client-secure-and-server-secure

> Secure clients and servers require siginificant amounts of additional memory and processing to enable their cryptographic algorithms. In general, only a single secure client or server connection at a time can be processed given the little RAM present on the ESP8266

you have two BearSSL::WiFiClientSecure instances at time. it is simple to change your code to first free the first SSL client object.

---
Tags: esp8266, http
---


# Question
Title: What are these stray resistors on the Arduino Mega schematic?
I am using the Arduino Mega schematic found here and it's mostly clear, but there are a few resistors floating in the middle and I'm not quite sure what they're for or where they go:

Does anyone know what these are and where they go?

# Answer
Those are unused resistors in resistor arrays. The arrays have 4 resistors side by side in a single package. Not all of the elements are always needed, but they have to be in the schematic anyway since they exist in real life.

* Elements A and D of Resistor Network 1 (RN1)
* Elements B and C of Resistor Network 2 (RN2)
* Element C of Resistor Network 3 (RN3)
> 12 votes

---
Tags: arduino-mega
---


# Question
Title: Cannot call function in call back for onRequest()
I am a NOOB! Trying to use the ZS-042 RTC module to retrieve the current time and send it back to the RPi over I2C. I can call the function and spool it to Serial but when I try to call the function to update the global variables from within the call back function for onRequest() the Ardiuno (Micro) crashes.

```
#include <Wire.h>

// LED on pin 13
const int TEMP_PIN1 = A0;
const int RELAY_PIN1 = 4;
const int SAMPLE_TIME = 100;
const byte RPI_I2C_ADDRESS = 0x08;
const int DS3231_I2C_ADDRESS = 0x68;

byte number = 0;
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

/*
 * RTC Setup
 */
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return( (val/16*10) + (val%16) );
}
void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
      dayOfMonth, byte month, byte year)
{
  // sets time and date data to DS3231
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set next input to start at the seconds register
  Wire.write(decToBcd(second)); // set seconds
  Wire.write(decToBcd(minute)); // set minutes
  Wire.write(decToBcd(hour)); // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (0=Sunday, 6=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month)); // set month
  Wire.write(decToBcd(year)); // set year (0 to 99)
  Wire.endTransmission();
}

/*
void readDS3231time(byte *second,
    byte *minute,
    byte *hour,
    byte *dayOfWeek,
    byte *dayOfMonth,
    byte *month,
    byte *year)
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}
*/

void readDS3231time()
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  second = bcdToDec(Wire.read() & 0x7f);
  minute = bcdToDec(Wire.read());
  hour = bcdToDec(Wire.read() & 0x3f);
  dayOfWeek = bcdToDec(Wire.read());
  dayOfMonth = bcdToDec(Wire.read());
  month = bcdToDec(Wire.read());
  year = bcdToDec(Wire.read());
}

void displayTime()
{
  //byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
  // retrieve data from DS3231
  //readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  readDS3231time();
  // send it to the serial monitor
  Serial.print(hour, DEC);
  // convert the byte variable to a decimal number when displayed
  Serial.print(":");
  if (minute<10)
  {
    Serial.print("0");
  }
  Serial.print(minute, DEC);
  Serial.print(":");
  if (second<10)
  {
    Serial.print("0");
  }
  Serial.print(second, DEC);
  Serial.print(" ");
  Serial.print(dayOfMonth, DEC);
  Serial.print("/");
  Serial.print(month, DEC);
  Serial.print("/");
  Serial.print(year, DEC);
  Serial.print(" Day of week: ");
  switch(dayOfWeek){
  case 0:
    Serial.println("Sunday");
    break;
  case 1:
    Serial.println("Monday");
    break;
  case 2:
    Serial.println("Tuesday");
    break;
  case 3:
    Serial.println("Wednesday");
    break;
  case 4:
    Serial.println("Thursday");
    break;
  case 5:
    Serial.println("Friday");
    break;
  case 6:
    Serial.println("Saturday");
    break;
  }
}

void flash_data(int loops)
{
   for (int i = 0; i < loops; i++)
   {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println("LED Pin HIGH: "+String(digitalRead(LED_BUILTIN)));
      delay(50);
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("LED Pin LOW: "+String(digitalRead(LED_BUILTIN)));
      delay(50);
   }
}

// callback for received data
void receiveData(int byteCount)
{
  Serial.println("Receiving Data... ");
  if ( Wire.available() ) {
    number = Wire.read();
  }
  Serial.println("Data Received: "+String(number));
}

void sendData() {
  Serial.println("Sending Data on Request");
  //byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
  // retrieve data from DS3231
  //readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  readDS3231time();
  //char buf1[20];
  //sprintf(buf1, "%02d:%02d:%02d %02d/%02d/%02d",  hour, minute, second, dayOfMonth, month, year);
  //Serial.print(buf1);
  Wire.write("Hello");
}

void setup() {
  Serial.begin(57600);
  do {
    delay(500);
  } while (!Serial);

  delay(500);
  Serial.println("Initializing Wire I2C on "+RPI_I2C_ADDRESS);
  // Join I@c bus as slave with RPI_I2C_ADDRESS 8
  Wire.begin(RPI_I2C_ADDRESS);

  Serial.println("Setting call back for Wire.onReceive");
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);

  //Setup pin 13 as output and turn LED off
  Serial.println("Setting LED Pin up for Output");
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(RELAY_PIN1, OUTPUT);
  pinMode(TEMP_PIN1, INPUT);
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);
}

float getVoltage(int pin)
{
  // This function has one input parameter, the analog pin number
  // to read. You might notice that this function does not have
  // "void" in front of it; this is because it returns a floating-
  // point value, which is the true voltage on that pin (0 to 5V).
  return (analogRead(pin) * 0.004882814);
  // This equation converts the 0 to 1023 value that analogRead()
  // returns, into a 0.0 to 5.0 value that is the true voltage
  // being read at that pin.
}

/*
 * MAIN LOOP
 */
void loop() {

  if ( number > 0 ) {
    //Serial.println("Flash Data: "+String(number));
    flash_data(number);
    float voltage, avgVoltage, degreesC, degreesF;
    if (number == 1) {
      digitalWrite(RELAY_PIN1, HIGH);
    } else if (number == 2) {
      digitalWrite(RELAY_PIN1, LOW);
    } else if ( number == 3 ) {
      voltage = getVoltage(TEMP_PIN1);
      //gets and prints the raw data from the lm35
      Serial.print("Voltage: ");
      Serial.print (voltage);
      Serial.println(" ");
      // Now we'll convert the voltage to degrees Celsius.
      // This formula comes from the temperature sensor datasheet:
      degreesC = (voltage - 0.48) * 100.0;
      Serial.print("CELSIUS: ");
      Serial.print(degreesC);
      Serial.println("*C ");
      //converts celsius into fahrenheit
      degreesF = degreesC * (9.0/5.0) + 32.0;
      Serial.print("FAHRENHEIT: ");
      Serial.print(degreesF);
      Serial.println("*F");
    } else if ( number == 4 ) {
       displayTime();
    }
    number = 0;
  } else {
    byte pinValue = bitRead(LED_BUILTIN, 3);
    if ( digitalRead(LED_BUILTIN) == HIGH ) {
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
  delay(SAMPLE_TIME);
}

```

Any guidance would be appreciated! THanks

# Answer
The onRequest and onReceive callback functions are called from inside an ISR. Thus you cannot use any code in there, that relies on interrupts to work. Serial writes or prints for example will only work, as longs as the buffer is not full (since the actual communication is handled by interrupts). If the buffer is full, the serial code will either block or loose data (depending on the version of the Arduino core. Not blocking in an ISR is a relatively new change). Such things also hapoen with other interrupt driven functions.

Let's take your codes logic particular in the onRequest callcack function. As written above, this is called from an ISR. The Wire library was contacted by the master to send data to it. With this callback the library uis asking you, what to answer the master. During that time, the current transmission (master read, slave send) is already active, but the slave is stalling the transaction, until the data is ready, meaning until you exit the onRequest callback. Now inside the callback you try to initiate another transaxtion on the same I2C bus, now as a master. The same I2C bus, where there is already a transaction going on. That cannot work. The former slave cannot take the control over the bus, since the first master haven't released it yet (as you tried this in the middle of it's transaction. So you are not only using interrupt driven functions in an ISR, you are also trying to reconfigure hardware, that you just got an interrupt from (which is a bad idea, unless you really know, what you are doing). The library has configured the hardware as slave and in the middle of the transaction you try to configure it as master.

I don't know, why you even try to do this. Since you already have the RTC on the same bus as the Pi, why not making the Pi the only master and let it directly poll the RTC? Why do you need the Arduino between them?

If you really really need the multi master setup for whatever reason (though I cannot think of one), you have to do the transactions independent of one another. The Arduino could poll the RTC regularly, when the bus is free, and buffer the results. Then it could send these results to the Pi, when it requests the Arduino to do that.

---

Note: I'm currently not up to date, how good the multi master support in the Wire library is these days. It incorporated the possibility for multi master since a long time, but when I checked last time, the bus arbitration was not implemented (meaning that if 2 masters try to send at the same time, the bus gets stalled). If it is still this way, you shouldn't use multi master with the Wire library.
> 1 votes

---
Tags: i2c, arduino-micro
---


# Question
Title: How to determine minimum and maximum angle for cheap servos?
I have some cheap KY66 (seems to be SG90 clone) servos.

When I turn them to 0°, the servo tries moving and moving, without actually getting to 0°. I read that they are reaching the endpoint but the built-in potentiometer does give a reading of 0.

By changing the code and fiddling with the angle, I find that the minimum for one particular servo is 25°.

I'm now trying to figure out how the Arduino could determine this value automatically. I have tried

```
servo.write(0);
delay(3000);
int direction = servo.read();

```

and expected to get back a value near 25, but it was 0 instead. So the result of `read()` does not seem to be an actual reading, but more the "last known" setpoint.

I've also tried to relax the servo before reading:

```
servo.write(0);
delay(3000);
int direction = servo.read();

```

with no better result.

I like to figure out the minimum and maximum angle of the servo

* because I don't like the servo to make much noise (it really doesn't sound healthy)
* without having the user to figure out by himself and the need of re-programming the Arduino.

I know that these cheap servos only have 3 pins. 2 pins are for power supply only, so there's only 1 pin left.

My questions:

* Is the data pin uni-directional (PWM output from Arduino to servo)?
* Will it ever be possible to implement what I want without additional hardware?
* How do people solve this issue? Do more expensive servos either have better calibration to actually go from 0° to 180° or do they provide a way to read the potentiometer with another pin?

# Answer
> 1 votes
> Is the data pin uni-directional (PWM output from Arduino to servo)?

As you found out, standard servos have only three pins. And yes, two of them provide ground and power, and the third is a unidirectional signal.

This signal is commonly a pulse of 1 ms to 2 ms, repeated every 20 ms.

`servo.read()` can therefore only return the last value set by `servo.write()`.

> Will it ever be possible to implement what I want without additional hardware?

I don't think so.

You could insert a shunt into the power line and measure the current. If it stays high for extended periods, it means that the servo is still powering its motor. But this could be true also for other reasons than being at its own mechanical limit.

> How do people solve this issue? Do more expensive servos either have better calibration to actually go from 0° to 180° or do they provide a way to read the potentiometer with another pin?

Since servos are used as a closed (sub-)system, I don't think that they are opened to read their potentiometer. And even if you do this, you might affect the internal working of the servo.

Eventhough I built several model aircrafts since the late 70s and used different servos, I have no feeling about the calibration of cheap or expensive servos. IIRC some data sheet documented ranges of only +/- 45°.

So the values `0` to `180` for `servo.write()` is just a mapping for 1 ms to 2 ms.

To make a long story short, I have no idea how people solve this.

You might like to limit your range to some "healthy" values, or ask the user to help in calibration. The calibration results can be stored in EEPROM, there is no need to reprogram the Arduino.

If you need the robot's head to turn from 0° to 180°, consider using some gear so that the servo just needs to move between, let's say, 30° to 150°. This is the way modellers go.

# Answer
> 1 votes
I think you have 2 choices: either measure and store for each one individually, or find the worst case for all of them and code around that.

Do you really need the full travel? If you're using the servo to push/pull, the servo-travel endpoints are pretty weak anyway.

> I wanted a robot look left and look right, which is 0° or 180°.

Maybe you can make up the limited angular travel of the servo in the linkage between the it and the camera platform.

---
Tags: servo
---


title: First Start Arduino Uno

text:
# Question
Title: First Start Arduino Uno
When I started connecting my Arduino Uno for first project: LED to pin 13, resistor, breadboard, USB connected to Windows Laptop, the orange on-board LED flashes every second and the LED on the breadboard did the same. What program is driving this? I had NOT uploaded any program. Please explain.

# Answer
It is a preloaded sketch and will be overwritten when you upload your first sketch into the Arduino.

Typically it's the Arduino Blink sketch which can be found here:

https://www.arduino.cc/en/Tutorial/Blink

Which has the following (functional) content:

```
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```
> 0 votes

---
Tags: led
---


title: Arduino Uno First Program

text:
# Question
Title: Arduino Uno First Program
Please help with this error. Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"

Sketch uses 882 bytes (2%) of program storage space. Maximum is 32256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes. avrdude: ser\_open(): can't open device "\\.\COM4": Access is denied.

Windows 10 Pro Arduino UNO ATmeg 328P-PU Have never been able to Upload a sketch. Pin 13 and Orange LED blink at 1 second

# Answer
> 1 votes
Welcome to the Stack Exchange and on the Arduino World.

Just a note: Since yesterday there is a new version of Arduino IDE (the last version is now 1.8.11).

When you buy an Arduino, a default sketch is already present. This will blink your LED (pin13) with a 1 second interval. This just mean that your Arduino is working and has a bootloader.

To program it, you need to know which COM port is created for your Arduino module:

* Press WIN-'R' (execute application)
* Write `devmgmt.msc`

Check the COM port to see wich COM port was used for your Arduino.

This is the only cause, the message could appear if you use a standard USB-cable connected to your standard Arduino UNO board.

---
Tags: compilation-errors, upload
---


# Question
Title: Missing buffers with serial communication
I am currently facing a problem with Serial communication with my arduino MEGA 2560.

My project is to collect data from an encoder. There are 2 signals : ACP and ARP. For 1 rotation, there are 16 384 ACPs (counter) and 1 ARP (reference). I have to store the high level and length of EACH ACP and if there is an ARP. To receive these signals I created a little PCB with a dual line receiver (because At the output of the encoder I revceive differential signals).

To store these data, I use a buffer of bytes. I need 3 bytes to store both ACP length and high and 1 ARP (I store the data in an ISR, see code below) :

```
buff1[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
i++;
buff1[i] = char(acpHigh);
i++;
buff1[i] = char(acpPeriod);
i++;

```

I use 2 circular buffers (when 1 is filled, I start wrinting into the other). As there are different speed rotation, the fastest one is 15 RPM (rotation per minute) so 1 ACP signal (1 period) last for 244 us and 4 s are needed for 1 rotation.

To collect the data, I directly use :

`Serial.write(buff1, sizeof(buff1));`

Here is the code I am using :

```
#include <eRCaGuy_Timer2_Counter.h> //To use timer in ISRs

//Constants
#define NO_DEFAULT_LED_PIN            40
#define DEFAULT_LED_PIN               42
#define WRITE_LED_PIN                 44
#define REC_IN_PROGRESS_LED_PIN       50
#define ACP_LED                       46
#define ARP_LED                       48
#define ACP_PIN                       20
#define ARP_PIN                       21
#define STOP_REC_BUTTON_PIN           28

#define SIZE                          800
#define BAUDSPEED                     230400

//Variables
boolean recordingEnded = false;
volatile boolean writing = false;
volatile unsigned short arpNbr = 0;
volatile unsigned short acpHigh = 0;
volatile unsigned short acpPeriod = 0;
volatile int i = 0;
volatile bool change_buffer = 0;

char buff1[3 * SIZE];
char buff2[3 * SIZE];

//Variables for interruption routines
volatile unsigned long acpHighUs = 0UL; volatile unsigned long acpPeriodUs0 = 0UL; volatile unsigned long acpPeriodUs1 = 0UL;

/**************************************************************************************/
/* Initialization                                                                     */
/**************************************************************************************/
void setup()
{
  Serial.begin(BAUDSPEED);

  //Setup LED pins
  pinMode(DEFAULT_LED_PIN, OUTPUT);
  pinMode(NO_DEFAULT_LED_PIN, OUTPUT);
  pinMode(SD_WRITE_LED_PIN, OUTPUT);
  pinMode(REC_IN_PROGRESS_LED_PIN, OUTPUT);
  pinMode(ACP_LED, OUTPUT);
  pinMode(ARP_LED, OUTPUT);

  //Setup ACP and ARP inputs
  pinMode(ACP_PIN, INPUT_PULLUP);
  pinMode(ARP_PIN, INPUT_PULLUP);

  //Setup the button
  pinMode(STOP_REC_BUTTON_PIN, INPUT_PULLUP);

  //Light ALL LEDs during initialisation
  digitalWrite(DEFAULT_LED_PIN, HIGH);
  digitalWrite(NO_DEFAULT_LED_PIN, HIGH);
  digitalWrite(SD_WRITE_LED_PIN, HIGH);
  digitalWrite(REC_IN_PROGRESS_LED_PIN, HIGH);
  digitalWrite(ACP_LED, HIGH);
  digitalWrite(ARP_LED, HIGH);
  delay(500);

  //Setup the timer
  timer2.setup();

  //Setup is done
  digitalWrite(NO_DEFAULT_LED_PIN, LOW);
  digitalWrite(SD_WRITE_LED_PIN, LOW);
  digitalWrite(ACP_LED, LOW);
  digitalWrite(ARP_LED, LOW);

  //Attach interruption at the end of the initialisation (recording starts...)
  attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpRising, RISING);
  attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpRising, RISING);
}

/**************************************************************************************/
/* Main loop                                                                          */
/**************************************************************************************/
void loop()
{
  //Check if the user stops the recording
  if (digitalRead(STOP_REC_BUTTON_PIN) == LOW && !recordingEnded )
  {
    noInterrupts();
    delay(500);

    //Switch off the recording LED
    digitalWrite(SD_WRITE_LED_PIN, LOW);
    digitalWrite(REC_IN_PROGRESS_LED_PIN, LOW);
    digitalWrite(ACP_LED, LOW);
    digitalWrite(ARP_LED, LOW);

    return;
  }

  //Check if the writing should be done
  if (writing && !recordingEnded)
  {
    digitalWrite(WRITE_LED_PIN, HIGH);

    if (change_buffer) {
       Serial.write(buff1, sizeof(buff1));
    }
    else {
       Serial.write(buff2, sizeof(buff2));
    }

    digitalWrite(WRITE_LED_PIN, LOW);
    writing = false;
  }
}

/**************************************************************************************/
/* This method is called at the beginning of each ACP.                                */
/**************************************************************************************/
void acpRising()
{
  digitalWrite(ACP_LED, HIGH);
  acpHighUs = timer2.get_count();
  acpPeriodUs1 = timer2.get_count() / 2 - acpPeriodUs0;
  acpPeriodUs0 = timer2.get_count() / 2;

  acpPeriod = acpPeriodUs1;

  attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpFalling, FALLING);
}

/**************************************************************************************/
/* This method is called at the end of each ACP.                                      */
/**************************************************************************************/
void acpFalling()
{
  digitalWrite(ACP_LED, LOW);
  acpHighUs = (timer2.get_count() - acpHighUs) / 2;
  acpHigh = (unsigned short)acpHighUs;

  if (change_buffer) {
    buff1[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
    i++;
    buff1[i] = char(acpHigh & 0xFF);
    i++;
    buff1[i] = char(acpPeriod & 0xFF);
    i++;

  }
  else  {
    buff2[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
    i++;
    buff2[i] = char(acpHigh & 0xFF);
    i++;
    buff2[i] = char(acpPeriod & 0xFF);
    i++;
  }

  arpNbr = 0;

  if (i == 3 * SIZE) {
    i = 0;
    change_buffer = !change_buffer;
    writing = true;
  }

  attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpRising, RISING);
}

/**************************************************************************************/
/* This method is called at the beginning of each ARP.                                */
/**************************************************************************************/
void arpRising()
{
  digitalWrite(ARP_LED, HIGH);
  arpNbr = 1;

  attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpFalling, FALLING);
}

/**************************************************************************************/
/* This method is called at the end of each ARP.                                */
/**************************************************************************************/
void arpFalling() {
  digitalWrite(ARP_LED, LOW);
  attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpRising, RISING);
}

```

# Problem :

I use CoolTerm software to collect my data into a .txt file and analyse it with Hexed.it.

It seems like after a certain period, like 6-10 minutes, I loose a part of 1 buffer. I checked this beacause as I wrote above, I need 3 bytes for information and in Hexed.it, I saw that I had only 2 bytes at once, and after, data was correct.

After analysing in depth, I saw that there was a part of a buffer and a few more (1-2) which were missing. I managed to see this because there was not 16384x3 bytes between 2 ARP (reference signal of the encoder).

I checked all timings to see if I sent the buffer before it was filled but everything is fine...

I also tried other methods like :

* Writing on a SD card;
* Changing buffer size;
* Changing baudrate;
* Using polling method instead of ISRs.

But nothing concluant ...

# EDIT:

It seems like my problem came from CoolTerm software after correcting my code. I now use RealTerm and I made a 1 night recording duration and every seems to be perfect. I don't have any data lost.

# Answer
> 1 votes
Not a direct answer to your questions, but after reading your code I would like to give some comments:

1. You are not using “circular buffers”, you are double-buffering. If you used a circular buffer, you would not need two of them.
2. `recordingEnded` is always `false` and thus serves no purpose.
3. When `writing` and `change_buffer` are both true, you should transmit `buff2`, not `buff1`, as the ISR is now filling `buff1`.
4. There are too many globals. Variables that are used in a single function should be local to the function. If you need the value to be preserved between calls, qualify the variable as `static`.
5. The code that fills the buffers would be clearer, IMO, if you avoided the repetition. E.g.

```
char *buff = change_buffer ? buff1 : buff2;
buff[i++] = (arpNbr << 7) | (acpPeriod >> 8);
buff[i++] = acpHigh & 0xFF;
buff[i++] = acpPeriod & 0xFF;

```

Note that `buf[i++]` is idiomatic C/C++.

Now, regarding your specific question, you mentioned in a comment that “*there were not 3x16384 bytes between 2 ARP*”. This may well be a consequence of issue 3: you are not sending the bytes in the correct order, as at times (when `Serial.write()` runs ahead of the ISR) you may be sending old data.

---

**Edit**: to answer the comment

> `char *buff = change_buffer ? buff1 : buff2;` won't take useless time?

Not really. Testing `change_buffer` is something you have to do either way. Assigning the buffer address to a local pointer is also done, under the hood, by the compiler. In the *best case*, it optimizes your code to something like:

```
register char *Z;
if (change_buffer)
  Z = buff1 + i;
else
  Z = buff2 + i;
Z[0] = (arpNbr << 7) | (acpPeriod >> 8);
Z[1] = acpHigh & 0xFF;
Z[2] = acpPeriod & 0xFF;
i += 3;

```

Using an explicit `buff` pointer gives a similar result, as the compiler will allocate this to the CPU's Z register. Actually, you may get shorter code, as the compiler may not entirely factor out the repetition.

---
Tags: serial, arduino-mega, interrupt
---


# Question
Title: Arduino UNO not showing up in USB devices on Ubuntu 18.04
I have an Arduino UNO (clone, not original) that was working fine until a couple of days ago. Now, it does not show up when I connect it to my laptop.

Things that I've troubleshouted:

1. USB cable is fine (tried with another Arduino).
2. USB ports are fine (tried with another Arduino).
3. Followed all the fixes and checks listed here and everything is successful.
4. I can upload sketches trough ICSP using a working Arduino.
5. I've tailed `syslog` while connecting and disconnecting the failing Arduino and nothing shows up (it does when using the "good one").
6. I've tried on a Windows 10 machine and it doesn't show up.

What else can I try?

# Answer
> 1 votes
I can't comment yet but have you updated your board manger for UNO on unbunto?

tools \> Board \> Board Manger \> Search UNO

Kind of dumb to have to do that but it happen to me before and this was the solution I did.

---
Tags: serial, usb, icsp
---


# Question
Title: Piezo buzzer not sounding well with ATmega328
I am using an ATmega328 to drive a 16x2 LCD, a LED, and a piezo buzzer. Piezo buzzer needs to buzz after every 5 seconds. But it doesn't make a nice sound it just gives out a faint buzz. Suspecting the buzzer to be faulty, I tested it separately from a 5V supply and it worked well. Then I put it back in the circuit and checked for the amount of current the whole circuit used. It was about 26mA when buzzer and LED were turned off, and 36mA with buzzer and LED ON. So no problem there. Additionally, the buzzer sometimes start sounding well too occasionally. This occurs after about half a minute the circuit is turned ON. This looks like that the buzzer is somewhat warming up before it can work properly. But this occurs occasionally.

I am using A0 Analog pin (or Pin no. 23 on ATmega328) for driving the Buzzer and giving 100Hz square wave to it.

What could possibly be the reason for this problem?

# Answer
> 1 votes
If it works well with direct 5v supply and not from an Arduino pin, you probably need a transistor to drive the buzzer.

Here is an example how to drive a buzzer using a transistor: https://www.maxphi.com/piezo-buzzer-interfacing-arduino-tutorial

# Answer
> 0 votes
Some buzzers are active buzzers and will self oscillate when powered. Other buzzers requires an oscillating signal on their pins in order to make a sound. If the buzzer works on 5v then its an active buzzer and you only need to feed it a HIGH signal to make it work. Don't try to feed it a 100hz square wave.

---
Tags: piezo
---


title: USB Power switch

text:
# Question
Title: USB Power switch
Can an Arduino power a USB device like a tablet from one of it's pins or do I need a relay? I want to essentially have the Arduino turn on and off a USB charger. Thanks

# Answer
> 2 votes
If you already have a 5V source then you can use a MOSFET as a switch to turn on/off the power to the tablet like this:

But if you want to turn on/off a USB charger that goes to an AC outlet, then you will need to control a relay to turn on/off the AC supply to the USB charger. You can use a relay module like this: https://www.amazon.com/Tolako-Arduino-Indicator-Channel-Official/dp/B00VRUAHLE

---
Tags: arduino-nano, usb, arduino-leonardo
---


title: Send structure through Serial

text:
# Question
Title: Send structure through Serial
Suppose that one defined a data structure and wanted to send it through serial.

```
 struct Gyro_data_structure {
    char command_name[5];
    float gyro_X;
    float gyro_Y;
    float gyro_Z;
};

Gyro_data_structure Gyro_data;

int size_gyro=sizeof(struct Gyro_data_structure);

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  Gyro_data.command_name[0]='H';
  Gyro_data.gyro_X++;
  Serial.println(size_gyro);
  delay(500);
  Serial.write(Gyro_data,size_gyro);
}

```

However, it returned an error saying "no matching function for call to 'HardwareSerial:write(Gyro\_data\_structure&,int&)'". I googled and found Michaël Roy's answer here. However, it's not working: "can not convert ..."

How to send a structure through UART?

# Answer
> 5 votes
I tried the code from the link you posted and it worked:

```
struct Gyro_data_structure
{
    char command_name[6];
    int gyro_X;
    int gyro_Y;
    int gyro_Z;
};

struct Gyro_data_structure Gyro_data = {"Hello", 48, 49 , 50};

int size_gyro = sizeof(struct Gyro_data_structure);

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop()
{
  send(&Gyro_data);
  Serial.println();
  delay(1000);
}

void send (const Gyro_data_structure* table)
{
  Serial.write((const char*)table, size_gyro);  // 2 bytes.
}

bool receive(Gyro_data_structure* table)
{
  return (Serial.readBytes((char*)table, sizeof(Gyro_data_structure)) == sizeof(Gyro_data_structure));
}

```

I changed the **float** type to **int** for easy representation. When you run the code the serial window will show: **Hello012**

Because Arduino IDE serial window shows ASCII characters. 0's ASCII value is 48 and so on.

---

# Update

It depends on what you want from the read function. Let's break down what Michaël Roy's implementation is doing. First, he reads **sizeof(Gyro\_data\_structure)** number of serial bytes and put it in the variable that table points to:

```
Serial.readBytes((char*)table, sizeof(Gyro_data_structure))

```

The 2nd argument of readBytes() takes how many bytes you want to read. Also readBytes() return how many bytes it read. Let's say we stored that number in **return\_bytes**. In the next part he did:

```
return (return_bytes == sizeof(Gyro_data_structure))

```

He is checking if the number of bytes readBytes() read is the same as the size of **Gyro\_data\_structure**. If it is not, then return **false**.

This just tells you if you read more or less than what you are supposed to read. Regardless of true or false, the actual bytes that were read will be in the variable that you passed to the receive() function.

If you don't want the function to not return anything this is how it should be:

```
void receive(Gyro_data_structure* table)
{
  Serial.readBytes((char*)table, sizeof(Gyro_data_structure));
}

```

# Answer
> 2 votes
First of all, you have to decide whether you want to send the data as raw bytes (“binary data”) or as an ASCII text representation. Binary tends to be more efficient: you can send a `float` with *full precision* in only four bytes, whereas you would typically need 8 to 9 significant digits to recover the full precision from an ASCII representation. Binary is, however, harder to handle: some types have different binary representations on your Arduino and your PC, and you may need to define a protocol of sorts in order to get the framing right. ASCII is easier, and you can usually use end-of-lines as a simple framing device. I generally recommend using ASCII unless you *really* need the extra efficiency of a binary protocol.

## Sending as binary

You can easily send arbitrary binary data using the method `write(const uint8_t *buffer, size_t size)` from the `Serial` object:

```
Gyro_data_structure Gyro_data = {"Gyro", 0.0, 4.0, 5.0};

void loop() {
    Gyro_data.gyro_X++;
    Serial.write((uint8_t *) &Gyro_data, sizeof Gyro_data);
    delay(200);
}

```

Here is an hex dump of the output:

```
0000  47 79 72 6f 00 00 00 80  3f 00 00 80 40 00 00 a0  |Gyro....?...@...|
0010  40 47 79 72 6f 00 00 00  00 40 00 00 80 40 00 00  |@Gyro....@...@..|
[...]

```

which can be parsed as follows:

```
47 79 72 6f 00 = {'G', 'y', 'r', 'o', '\0'}
00 00 80 3f    = 0x3f800000 = 1.0f
00 00 80 40    = 0x40800000 = 4.0f
00 00 a0 40    = 0x40a00000 = 5.0f

```

Note that the floats are sent in little-endian order: lest significant byte first. The 32-bit hex numbers above are the binary representations of the floats.

## Sending as text

`Serial.print()` is intended to print a text representation of the data you give it. But since it does not know how to represent a `Gyro_data_structure`, you have to `Serial.print()` each data member in turn, and then add some formatting around all that:

```
void print_gyro(const Gyro_data_structure &gyro) {
    Serial.print(F("Gyro{command = \""));
    Serial.print(gyro.command_name);
    Serial.print(F("\", X = "));
    Serial.print(gyro.gyro_X);
    Serial.print(F(", Y = "));
    Serial.print(gyro.gyro_Y);
    Serial.print(F(", Z = "));
    Serial.print(gyro.gyro_Z);
    Serial.print(F("}"));
}

void loop() {
    Gyro_data.gyro_X++;
    print_gyro(Gyro_data);
    Serial.println();
    delay(200);
}

```

The output is

```
Gyro{command = "Gyro", X = 1.00, Y = 4.00, Z = 5.00}
Gyro{command = "Gyro", X = 2.00, Y = 4.00, Z = 5.00}
[...]

```

## Making your data printable

This is a variation on the previous technique. You can `Serial.print()` your object directly, if you tell the Arduino core how to print this type of objects. This is done by letting your class inherit from `Printable` and implementing the virtual method `printTo()`. But then the class is not an “aggregate” anymore, and thus needs an explicit constructor:

```
struct Gyro_data_structure : Printable
{
    char command_name[5];
    float gyro_X;
    float gyro_Y;
    float gyro_Z;
    Gyro_data_structure(const char *name, float x, float y, float z)
    : gyro_X(x), gyro_Y(y), gyro_Z(z) {
        strncpy(command_name, name, 4);
        command_name[4] = '\0';
    }
    size_t printTo(Print& p) const {
        size_t count = 0;
        count += p.print(F("Gyro{command = \""));
        count += p.print(command_name);
        count += p.print(F("\", X = "));
        count += p.print(gyro_X);
        count += p.print(F(", Y = "));
        count += p.print(gyro_Y);
        count += p.print(F(", Z = "));
        count += p.print(gyro_Z);
        count += p.print(F("}"));
        return count;
    }
};

Gyro_data_structure Gyro_data("Gyro", 0.0, 5.0, 5.0);

void loop() {
    Gyro_data.gyro_X++;
    Serial.println(Gyro_data);
    delay(200);
}

```

The output is identical as before. The definition of the class gets a little bit clumsier, but then you can very easily print to any serial port (be it an UART or a software implementation), to an LCD... or whatever understands `print()`.

---
Tags: serial, uart, struct
---


title: Problem with Input from Serial Monitor

text:
# Question
Title: Problem with Input from Serial Monitor
I have a piece of code as shown, and I wish to print the value I send using serial monitor along with a message: "Writing data to slave...".

But everytime I enter a character/number in the serial monitor(like 'a' as shown), the loop runs two times instead of just once. It seems like an extra character(somewhat invisible or null) is being sent along with the typed character.

If I use the condition (Serial.available()\>1) then the loop runs just once on sending one character.

Why is this so?

# Answer
I suspect an end of line character is send (probably \n or \r, see comment of Edgar Bonet), or an end of string (0 character).

You can easily find it out by printing the integer value of the character:

```
char c = serial.read();
Serial.print((int) c);

```
> 0 votes

---
Tags: serial
---


title: Servo Program Questions

text:
# Question
Title: Servo Program Questions
Hi programming in arduino, I am trying to get a nested for loop inside a for loop with industrial servo which used PUL +- DIR+- (bought motor off amazon).

My goal is to get the puls delay to increase. I have a sensor attached that I want the servo to turn on when triggered.

So the sensor will get triggered and the the servo will start off fast and get slower up to 255 micros second delay.

example:

```
int sensor = 26;
int PUL = 23; //define Pulse pin
int DIR = 25; //define Direction pin

void setup() {
  pinMode(sensor, INPUT);
  Serial.begin(115200);
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
}

void loop() {
  int sen = digitalRead(sensor);
  if (sen == HIGH) {
    Serial.println("HIGH");
    delay(1000);
     for (int i=0; i<500; i++)
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}
  } else if (sen == LOW) {
    Serial.println("LOW");
    delay(1000);
    } else {
    Serial.println("ERROR");
  }
}

```

**EDIT**

I am trying to nest a FOR loop inside a FOR loop What I want to do is get x to increase with i until x is 255 then I will continue unit i reaches 500. Right now x goes 0-255 and then i increase by 1. I need the value of x to increase along side with i until 255

```
for (int i=0; i<500; i++) {
  for( int x=0; x<255; x++){
  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }
}

```

# Answer
> 1 votes
Do you want i and x to increment at the same rate 0-255 then x to remain 255 while i increases to 500?

this should do what you want. i and x increase together until x reaches 255 then it wont increment.

```
int x=0;
for (int i=0; i<500; i++) {

  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }

   if(x<=255){
        x++;
   }

}

```

---
Tags: motor, servo, arduino-due, loop
---


title: Nested For Loop Controlling speed

text:
# Question
Title: Nested For Loop Controlling speed
I have a servo motor That I am trying to determine the delay speed in between pulses with a nested for loop. This issue is instead of running together like 0,0 1,1 2,2 its actually going up like 0,0 0,1 0,2. SO the first for loop i will only go up once all of the x for loop goes to its max 255.

What I want it to do is go up together until x reaches 255 and then it will stabilize there as I will countering to climb.

If any know anything about nested for loop I would appreciated (please only add valuable comment or help to this. I don't need pointless or dumb comments (talking about jsotola and all he did was criticized my question)

```
 for (int i=0; i<500; i++)
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}

```

# Answer
> 0 votes
These are nested loops:

```
for (int i = 0; i < 500; i++) {
    for (int x = 0; x < 255; x++) {
        do_something_with(i, x);
    }
}

```

“Nested loops” means you have a loop within a loop: within each iteration of the outer loop you get a full run of the inner loop. The sequence of (i, x) pairs is:

```
(0, 0), (0, 1), (0, 2), ... (0, 254)
(1, 0), (1, 1), (1, 2), ... (1, 254)
...
(499, 0), (499, 1), ...     (499, 254)

```

> What I want it to do is go up together until x reaches 255 and then it will stabilize there as I will countering to climb.

This sentence is not very clear. I assume you mean that you want the following sequence of (i, x) pairs:

```
(0, 0), (1, 1), (2, 2), ... (255, 255),
(256, 255), (257, 255), ... (499, 255)

```

If this is what you want, you can more easily achieve it with a single loop:

```
for (int i = 0; i < 500; i++) {
    int x = min(i, 255);
    do_something_with(i, x);
}

```

---
Tags: arduino-mega
---


# Question
Title: Customize FTDI driver for custom PID and VID
I have changed PID and VID of my FTDI board for arduino program because i wanted to rename the com port name. The ic is FT232R a USB to serial UART interface IC. I have store new vid and pid to EEPROM. Now It is showing in unknown devices. I am not able to update driver of it. I have followed this article http://forum.arduino.cc/index.php?topic=6929.0.

Can anyone tell how to make cutmoize driver for it. Any suggestions will be very helpful.

# Answer
> 1 votes
**On Windows**

You can refer to FTDI's documentation here for details on how to create your own custom device driver. The FTDI website has a lot of resources for this, however they seem to be a little outdated. Microsoft details how drivers work in it's Hardware Dev Center.

**On Linux**

On Linux it may be as easy as registering the device with `modprobe`. For example, for a device with a VID of 0102 and a PID of 1234, execute the following from the shell:

```
modprobe ftdi_sio
echo "0102 1234" | sudo tee /sys/module/ftdi_sio/drivers/usb-serial\:ftdi_sio/new_id > /dev/null

```

# Answer
> 1 votes
You can do it, but you cannot change the PID and VID without a new certificate.

Did you changed the name with the FT-Prog Tool (MProg is outdated)? You can download the last version from here: https://www.ftdichip.com/Support/Utilities.htm#FT\_PROG

You can set everything on your FTDI chip, even change the PID and VID. But at this point, you will not be able to use the standard FTDI driver anymore as you need to sign it with a new certificate (it is about 400$/year).

What you can do is leave the PID and VID and just give another name. So you will be able to use the default driver and you will see your custom name in the device manager.

Of course, in the list you just see "USB Serial Port (COM X)". But in the description of the device (Serial port), you will find this string:
`FTDIBUS\VID_0403+PID_6011+YOURCUSTOMNAME&1\0000`

If you create an application, you can just check for this, to see if it is your module. If you want more, you have to develop and release your own driver. But you can't do it anymore without a certificate, or without start Windows in unprotected mode.

---
Tags: serial, ftdi
---


# Question
Title: Does the Arduino deteriorate after shorting the voltage regulator?
I mistakenly connected a 7.4V battery backwards to an Arduino Nano via the Vin pin. The Arduino still works (I can upload code) connecting it to the PC using the USB cable. Here's my question: will the Arduino deteriorate using this method or can I continue using it (I'm soon going to buy a new voltage regulator)?

# Answer
> 0 votes
Of course, if you can upload the code, you can continue to use it ;)

Even if the Arduino is cheap, it is really reliable. There are always some short circuit protections.

The Voltage Regulator (I think it is a simple LM1117) has a overcurrent protection too (see: http://www.ti.com/lit/ds/symlink/lm1117.pdf)

So, don't worry. You can continue, continue and continue to use it...

Edit: just a note: never drain more than 50mA on an output. This will destroy the pin on your Arduino.

---
Tags: arduino-nano
---


# Question
Title: Serial monitor read value depending on delay
I am working on a small piece of code as shown:

When I enter character 'a' in the Serial Monitor and use a delay in between successive reads then the monitor gives out acceptable results(i.e 97 for character 'a' and 10 for new line) as shown:

Whereas if I do not include the delay, it seems like the microcontroller is not able to read the next value(i.e 10 for new line) immediately and just gives out a -1. And it is only after the loop is run again that we get to see the value 10 for new line(again with -1).

Is my observation correct? If yes, what causes this to occur?

EDIT: I am sorry for the improper format of displaying the code. I am adding the code as below:

```
#include <Wire.h>

void setup() {

  // Initialize I2C communications as Master
  Wire.begin();
  // Setup serial monitor
  Serial.begin(9600);
  Serial.println("I2C Master Demonstration");
}

void loop() {

  if(Serial.available()>0)
  {
    char c = Serial.read();
    Serial.print((int)c);
    delay(10);
    char d=Serial.read();
    Serial.print((int)d);
    Serial.println("Writing data to slave...");
}
}

```

# Answer
Yes, UART is much slower then the CPU and you run it on extremely slow baud rate. The CPU runs many loops before Serial.available() is again more then 0.

From reference of read() function:

> Returns the first byte of incoming serial data available (or -1 if no data is available).
> 1 votes

---
Tags: serial
---


# Question
Title: Send Arduino data to Database using ESP8266
My project is to receive data from Bluetooth (HC-05) sensor and storing it in the database. I have successfully received data from Bluetooth sensor and stored it in a String variable. Now i have to store this data to the database. I want to use the sensors as standalone (not connecting to the PC - operated on battery). Can I store the data to the database using ESP8266.

# Answer
Since you mention you operate on a battery (standalone), what exactly do you mean by "the database"? Do you have online connectivity? Do you have any peripherals like an sdcard or other storage?

In case you don't have a permanent online connection, you would need to use some writable memory (like EEPROM) to store your data in some organized form. Since the ESP8266 doesn't seem to have any EEPROM built in, you would need to use its flash memory, like described in those answers.

A database could be as simple as a `fixed length string list` (essentially how string arrays look in memory). For example if the string data you want to save always has 32 bytes, you could just divide your available storage (e.g. 4096 bytes) to have a "database" wich can store 128 entries (4096/32). Your "database entries" will then be addressable in multiples of 32, you would find the 1st entry at byte 0, the 2nd at byte 32 and so on.

Once you are online, you could send the data out for further processing. Getting the data into a database can be as simple as a https request.
> 1 votes

---
Tags: arduino-uno, esp8266, wifi
---


# Question
Title: Powering NodeMCU with battery and LDO; what if battery is empty?
I want to battery-power my NodeMCU. It will be mostly deep sleeping and waking up every 1-2 minutes.

I've seen the best way to power it with the least wasting of power is through a lithium battery.

So I've bought a 18650 rechargable battery and a MCP1700 LDO which will give me a constant 3.3 V, that will connect straight to the 3.3 V pin and bypass the NodeMCU's regulators, as I understand from here.

My question is: if all of the previous is correct, what will happen when the 18650 battery power fall below the 3.5 V (3.3 V + 0.2 V from MCP1700 dropout)? Will it stop automatically giving power at all? Will it provide less than 3.3 V and will it harm the NodeMCU?

# Answer
> 0 votes
As with any electronics, once you get outside of normal operating parameters, behaviour becomes undefined. It's up to you to avoid that.

The smartest thing to do is to employ a battery protection circuit or some means to shut down the system (or prevent it from waking up from deep sleep) before the voltage drops too low. This will also prevent your battery from damage by overdischarging it.

The ESP's minimum operating voltage according to its datasheet is 3.0V. Below that, behaviour is undefined but you can expect unreliable operation, crashes or even permanent damage. If you're writing to Flash memory when below the minimum voltage, the Flash might become corrupted (including the program the ESP is running).

---
Tags: nodemcu, battery
---


# Question
Title: stepper motor doesn't work but get no error message
So I work for a department that uses arduino to move a stepper motor for a wave machine and I am encountering a issue. They gave me the code that they used to use but it doesn't move the motor and just makes this intermittent beeping noise.

My code is as follows:

```
int pulse_delay = 20;
int wave_period = 1000;

void setup() {
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
}

void loop() {
digitalWrite(9,HIGH);
delay(10000);
for (int i=0;i<wave_period;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(pulse_delay);
  digitalWrite(8,LOW);
  delayMicroseconds(pulse_delay);
}
digitalWrite(9,LOW);
for (int i=0;i<wave_period;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(pulse_delay);
  digitalWrite(8,LOW);
  delayMicroseconds(pulse_delay);
  }
}

```

I do not receive any error messages and the IDE just says upload complete. We use a Arduino Mega board. I am pretty new to Arduino.

Edit: Someone asked for pictures about how it was connected. Sorry for the late response, had a family emergency.

The cable coming in from the bottom of first picture is from the stepper motor, as is the cable I'm holding but that is what I was told isn't necessary.

# Answer
> 0 votes
What are 8 and 9 plugged into on your stepper? also define your baud rate based on the motor requirements.

```

void setup() {
pinMode(8,OUTPUT); < should be PUL
pinMode(9,OUTPUT); < should be ENA(maybe dir)
digitalWrite(8,LOW);
digitalWrite(9,LOW);
Serial.begin(115200);
}

void loop() {
digitalWrite(9,HIGH);
delay(10000);
for (int i=0;i<1000;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(20);
  digitalWrite(8,LOW);
  delayMicroseconds(20);
}
digitalWrite(9,LOW);
for (int i=0;i<1000;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(20);
  digitalWrite(8,LOW);
  delayMicroseconds(20);
  }
}

```

# Answer
> 0 votes
Here you can find the manual of your stepper driver.

Look at page in the section "CN3 (I/O signals)". Beside the pulse and directions, that you already set in your code, there are 2 more input signals defined: AWO will turn off the motor completely, if you provide a signal, CS changes the source of the step angle setting. As you don't configure any pins, other than pulse and direction, the other pins on the Arduino are set as input/high impedance. The state of these pins can float wildly depending on what noise is comming by. I don't know, if this really matters for this driver, but you should try to provide a valid state on all the input pins of the driver. For example a floating AWO pin might randomly disable and enable your motor very fast (which would at least fit with the described behavior). Set the corresponding pin on the Arduino as output (via `pinMode()`) and give them the state, that you want via `digitalWrite()` (I suggest LOW for AWO to enable the motors and HIGH for CS to get the basic step angle).

I cannot see on your images, if everything is connected to the driver, as it should (here a wiring diagram or a schematic would help). For now I assume, that the signal pins on the Arduino side are connected correctly.

The input signals of the driver are meant to be provided by a pair of twisted wires. This is done to minimize noise on the line. Thus all input signals have 2 pins: "+" and "-". Connect all "-" pins to ground and the "+" pins to the appropriate digital output pin on the Arduino.

If a have a oscilloscope or a logic analyzer, you can also monitor the ALM and TIM outputs of the driver. Maybe they are showing, what is going wrong.

Let us know, if this helps.

---
Tags: arduino-mega, stepper-motor
---


title: Hardware Interrupt Triggered Randomly

text:
# Question
Title: Hardware Interrupt Triggered Randomly
So there is this pretty generic part of my project that involves triggering an ISR that will flip a boolean value. I have set up the software side like so:

```
void setup() {
  attachInterrupt(digitalPinToInterrupt(2), displayConvergence, FALLING);
}

void loop() {
  if(flashConvergence) {
    //Do stuff that takes several seconds
    delay(3000);
    flashConvergence = false;
  }
}

void displayConvergence() {
  if (!flashConvergence) {
    flashConvergence = true;
  }
}

```

The schematic is as follows:

simulate this circuit – Schematic created using CircuitLab

But the behavior of my circuit surprised me as the pin interrupt would get triggered randomly at a frequency at (guessing here) 3 times a second.

Weird, I thought. I fiddled around and found that when the boost converter's 180V is not connected to any load, the interrupt service triggers as expected, as in it starts working correctly. So I thought perhaps the issue was some noise introduced by the boost converter.

I modified the circuit by adding a capacitor across the switch:

simulate this circuit

I tried 1 uF at first, but that didn't help and neither did 10 uF. However, when I tried 100 uF (I thought decoupling capacitors are usually 0.1uF to 1 uF, is the value I am using too big?), things seem to be working as expected with the exception that when I hold the switch in the closed position for a long time, then let it go back in the open position, the interrupt service can be triggered randomly for a short period right after I let go of the switch.

Is my initial assumption that the ISR is triggering randomly due to EMI from the boost converter correct? Perhaps there are other causes I am not looking at? Is there a way to make this work 100% (as in solve the issue right after the switch is put in the open position)?

Thanks for the help!

# Answer
> 1 votes
It has come to my attention I never posted a followup to this but I was actually able to solve this problem by shielding the wire going from the switch to the arduino. The switch's wire was about 2 to 3 inches long and I wrapped aluminum foil around it, which shielded the signal from what I suspected was EMI induced by the switching converters.

# Answer
> 0 votes
If you don't have any bulk capacitance (100uF or so) on your logic supply you will have noise problems. You should also use some smaller (1uF and 0.1uF) to provide bypass for higher frequency noise in the power supply system.

Glenn

# Answer
> -1 votes
An alternative approach is to detach the interrupt handler and use the internal pullup instead of external resistor (and capacitor).

```
const int BUTTON = 2;
volatile bool flashConverage = false;

void setup()
{
  setmode(BUTTON, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(BUTTON), displayConvergence, FALLING);
}

void loop()
{
  if (!flashConvergence) return;

  // Do stuff that takes several seconds
  delay(3000);
  flashConvergence = false;
  attachInterrupt(digitalPinToInterrupt(BUTTON), displayConvergence, FALLING);
}

void displayConvergence()
{
  detachInterrupt(digitalPinToInterrupt(BUTTON));
  flashConvergence = true;
}

```

The processing ("stuff that takes several seconds") will debounce the button (or at least ignore it :).

Cheers!

---
Tags: interrupt, isr, timing
---


# Question
Title: Seeking help - Using CJMCU 8*8 LED matrix with arduino
The CJMCU 8\*8 LED board is a grid of 64 W2812 (addressable) LEDs. The board is configured as if it was one long LED strand (just a single DIN, 5v and GND). For some flipping hair pulling reason, my code works fine on 2812 LED strands, but I get nothing on the board. Just random flickering when I jostle the 5V wire. Any ideas? Am I completely missing something here? Pretty sure the board is fine, just can't seem to take any input...

(Here's a link to the board: http://www.aliexpress.com/store/product/CJMCU-64Bit-WS2812-5050-RGB-LED-Development-Board-Built-in-RGB-Driver-White-SKU-11481/933826\_32249197598.html)

# Answer
> 1 votes
I just received 2 of these from 2 different suppliers on EBAY. None work using the pins called \[GND +5V DIN\]. As it turns out the DIN is actually NOT DIN. The other connector area \[GND +5V DOUT\] is the DIN. Ugh!

These boards are marked CJMCU-8\*8 on the back side and on the front they say "WS2812B-64 RGB LEDS". Which is another issue. They are using the 6 pin WS2812, not the 4 pin WS2812B.

So if this is what your board looks like then perhaps try the pin marked DOUT for your DIN. Or try to psych out the traces to make sure first.

# Answer
> 1 votes
Unbelievably, as I've just discovered, this has been a known issue with these boards for at least a year and a half, yet they are still shipping them. The silk screening process of labeling the board is the problem. Just poor quality control. The front (LED) side of these low quality CMJCU-8\*8 boards are incorrectly marked "SM2812B RGB LEDS". (The actual LEDs are 6 pin SM2812's, not 4 pin SM2812B's), but the real problem is with the back side of the board. The manufacturer printed the boards upside down, so that the input and output labels are reversed (DIN is really DOUT and vise versa).

I just purchased one of these defectively printed boards on line and received it a few days ago. Took me awhile to figure out why I couldn't get it to work, but I finally did. When hooked up backwards, the CMJCU-8\*8 will do nothing at all (no LEDs will come on), because of the built in reverse polarity protection, but if you run your thumb hard (it's just +5V) over the other pins (the ones that include the erroneously marked DOUT) while the board is powered up, one or more of the SM2812 LEDs will magically come on. This is because your thumb makes an intermittent connection between the real DIN and the +5v rail, providing a forward bias to a few random LEDs. Once lit, these LED's will actually stay on until you cut power to the board, so if you keep ding it, you can get quite a few of the SM2812s to come on.

# Answer
> 0 votes
Literally spent hours painstakingly chasing same problem. Complained bitterly to supplier that board refused to respond or operate when received. They responded by trying to tell me I had no clue about how to connect, but eventually agreed to send replacement after I proved had connected correctly, while waiting for replacement came across this post, went and found original board and reconnected, 5V to DIN side, and DIN to DOUT (Instant operation) because the reverse polarity protection does not prevent being energized this way. if supplier comes good, will have another board to compensate my trouble.

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


# Question
Title: PIR Sensor Gives False High in 55 Minutes (Can't find a way to solve)
I have built a system to identify motions and fire alerts. System can send a SMS in case if it's identify such alerts.

System consist of two parts,

Part 1: Armed and Disarmed using a PIN (Using Arduino Uno)

This Module Consists with 4\*4 PIN PAD, I2C Module, 2 LEDs and Arduino UNO This part works fine

Part 2: Sensor Systems and SMS System

This module consists of Arduino NANO, MQ135 Gas Sensor, PIR Sensor, SIM 800L Module, Tamper Switches This part also works, but in every 55 minutes it generates a false motion alert and I could not troubleshoot the issue.

Schematics is attached.

Codes as Below,

Part 1: Test6-LCD\_Intigrated\_Working\_Temper.ino

```
#include <Keypad.h>
#include<EEPROM.h>
#include <Wire.h> // Library for I2C communication
#include <LiquidCrystal_I2C.h> // Library for LCD
char password[4];
char pass[4],pass1[4];
int i=0;
int k=0;
char customKey=0;
byte col = 0;
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {

{'1','2','3','A'},

{'4','5','6','B'},

{'7','8','9','C'},

{'*','0','#','D'}

};

byte rowPins[ROWS] = {9, 8, 7, 6}; //connect to the row pinouts of the keypad

byte colPins[COLS] = {13, 12, 11, 10}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad

Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2);
void setup()
{
  lcd.begin();

  Serial.begin(9600);
  pinMode(4, INPUT);      // Tamper Signal
  pinMode(3, OUTPUT); //Armed
  pinMode(2, OUTPUT); //Disarmed

  lcd.setCursor(0, 0);
  lcd.print ("--SECURE ROOM!--");
  Serial.print("Server Room");
  lcd.setCursor(0, 1);
  lcd.print ("PLEASE ENTER PIN");
  Serial.print("\n*********Keypad Lock********* ");
  delay(2000);
  Serial.println("\n*********Enter Ur Passkey:*********");

  for(int j=0;j<4;j++)
    EEPROM.write(j, j+49);
  for(int j=0;j<4;j++)
    pass[j]=EEPROM.read(j);
}

void Armed(){

  digitalWrite(3, HIGH);
  digitalWrite(2, LOW);
  Serial.println("\n***System is Armed***");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("--SYSTEM ARMED--");
  lcd.setCursor(0, 1);
  lcd.print("-SENSORS ACTIVE-");
  delay (2000);
  lcd.noBacklight();
  i=0;
  customKey=0;

  }

void change()
{
  int j=0;
 lcd.backlight();
  Serial.println("\n*********UR Current Passk*********");
  lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("   CURRENT PIN   ");

  while(j<4)
  {
    char key=customKeypad.getKey();
    if(key)
    {
      pass1[j++]=key;

      Serial.print(key);
      lcd.setCursor(j+6, 1);
      lcd.print(key);

    }
    key=0;
  }
  delay(500);

  if((strncmp(pass1, pass, 4)))
  {

    Serial.println("\n*********Wrong Passkey*********");
    lcd.clear();
    lcd.setCursor(0, 0);
      lcd.print("  UNAUTHORIZED  ");

    Serial.println("\n*********UNAuthorized Access*********");
      lcd.setCursor(0, 1);
      lcd.print(" ACCESS  DENIED ");
    delay(10000);
  }
  else
  {
    j=0;

    Serial.println("\n*********Enter New Passk: *********");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(" ENTER NEW PIN! ");

    while(j<4)
    {
      char key=customKeypad.getKey();
      if(key)
      {
        pass[j]=key;

        Serial.print("*");
        EEPROM.write(j,key);
        lcd.setCursor(j+6, 1);
        lcd.print(key);
        j++;

      }
    }

    Serial.println("*********Done*********");
    lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("----UPDATED!----");
    delay(1000);
  }

  Serial.println("\n*********Enter Ur Passk: *********");
  lcd.clear();

      lcd.setCursor(2, 0);
      lcd.print ("SECURE ROOM!");
      lcd.setCursor(0, 1);
      lcd.print ("PLEASE ENTER PIN");
      lcd.noBacklight();
  customKey=0;
}

void tamper(){
  Serial.println("\n***System is Tampered***");
  lcd.clear();
  lcd.setCursor(2, 0);
  lcd.print("--TAMPERED--");
  lcd.setCursor(0, 1);
  lcd.print("WARN COMPROMISED");
  delay (2000);
  lcd.backlight();
  i=0;
  customKey=0;

  }

void loop()
{
  Serial.println(digitalRead(4));
  customKey = customKeypad.getKey();
  if(customKey=='A')
    Armed();

    if(customKey=='C')
    change();
   /*
    if(digitalRead(4)==LOW)
    tamper();
 */
  if (customKey)
  {
    lcd.backlight();
    password[i++]=customKey;

    Serial.print("*");
    lcd.setCursor(0, 0);
    lcd.print("    PIN INPUT    ");
    lcd.setCursor(0,1);
    lcd.print("       ----     ") ;
    lcd.setCursor(i+6, 1);
    lcd.print("*");

      }

  if(i==4)
  {
    delay(200);
    for(int j=0;j<4;j++)
      pass[j]=EEPROM.read(j);
    if(!(strncmp(password, pass,4)))
    {

      Serial.println("\n*********Passkey Accepted*********");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("---AUTHORIZED---");
    lcd.setCursor(0, 1);
    lcd.print("SYSTEM  DISARMED");

      delay(1000);
      digitalWrite(2, HIGH);
      digitalWrite(3, LOW);
      i=0;

    }
    else
    {

      Serial.println("\n*********Access Denied*********");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  UNAUTHORIZED  ");
      lcd.setCursor(0, 1);
      lcd.print(" ACCESS  DENIED ");

      delay (5000);

      Serial.println("\n*********Enter Passkey: *********");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print ("--SECURE ROOM!--");
      lcd.setCursor(0, 1);
      lcd.print ("PLEASE ENTER PIN");
      lcd.noBacklight();

      i=0;

    }
  }
}

```

Part 2: Test7\_Tested\_Tamper\_Smoke\_PIR\_GSM.ino.ino

```
/*
    Arduino with PIR motion sensor and MQ 135 Smoke Detector with SMS Alert
    Developed By Vinod Amarathunga 18.09.2019
    DMS Electronics (Pvt) Ltd
*/

#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 5); //SIM800L Rx Tx
char msg;
String textMessage;

int smokeA0 = A0;            // MQ135 Analog Input
int led = 13;                // the pin that the LED is atteched to
int priState = LOW;             // by default, no motion detected
int TampSignal = 11;       // Tamper 5V Signal
int sensorThres = 150; //Smoke Air Quality Threshold
int pretamper = LOW;
bool premotion = false;
bool prefire = false;

void setup() {
  pinMode(led, OUTPUT);      // initalize LED as an output
  pinMode(3, INPUT);    // initialize sensor as an input
  pinMode(TampSignal, OUTPUT); // Tamper Drive Signal as Output
  pinMode(10, INPUT);    // Tamper Alert
  Serial.begin(9600);        // initialize serial
  mySerial.begin(9600);
}

void SmokeSMS()
{
  Serial.println("Warning!! Secure Room Fire Detected");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+xx\"\r");
  delay(1000);
  mySerial.println("Warning!! Secure Room Fire Detected");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  delay(5000);

  Serial.println("Warning!! Secure Room Fire Detected");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+xx2\"\r");
  delay(1000);
  mySerial.println("Warning!! Secure Room Fire Detected");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void MotionSMS()
{
  Serial.println("Warning!! Secure Room Motion Detected");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"xx\"\r");
  delay(1000);
  mySerial.println("PIN 3 HIGH");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  delay(5000);
/*
  Serial.println("Warning!! Secure Room Motion Detected");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"xx2\"\r");
  delay(1000);
  mySerial.println("Warning!! Secure Room Motion Detected");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");
*/

}

void TamperSMS()
{

  Serial.println("Warning!! System Tamper Detected");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"xx2\"\r");
  delay(1000);
  mySerial.println("Warning!! System Tamper Detected");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  delay(5000);

  Serial.println("Warning!! System Tamper Detected");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"xx\"\r");
  delay(1000);
  mySerial.println("Warning!! System Tamper Detected");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void loop() {
  int analogSensor = analogRead(smokeA0);
  digitalWrite(TampSignal, HIGH); // Drive Signal Always High
  //val = digitalRead(3);   // read sensor value
  //  ReceiveMessage(); //System Recive Messages
  //Serial.print("Smoke Level:");
  //Serial.println(analogSensor);
  Serial.println(digitalRead(3));
  if (analogSensor > sensorThres  ) {           // check if the sensor is HIGH and Armed Status
    digitalWrite(led, HIGH);   // turn LED ON
    Serial.print("\nSmoke Alert....!!!");
    SmokeSMS(); // Smoke SMS Alert
    delay(100);                // delay 100 milliseconds

  }

  else if ( priState == LOW && digitalRead(3) == HIGH && digitalRead(7) == HIGH ) {

    digitalWrite(led, HIGH);   // turn LED ON
    Serial.println("Motion detected!");
    MotionSMS(); //Motion SMS
    priState = HIGH; // Previous Motion Status set to High

    delay(15000);

  }

  else if ( digitalRead(7) == HIGH && digitalRead(10) == LOW )
  {

    digitalWrite(led, HIGH);   // turn LED ON and Temper Alarm On
    Serial.println("One of the TIP Switches being Trigered");
    if ( pretamper == LOW ) {
      TamperSMS(); // Tamper SMS
      pretamper  = HIGH;
      delay(15000);
    }

  }

  else {
    digitalWrite(led, LOW); // turn LED OFF
    digitalWrite(11, HIGH); // Tamper Signal
    delay(200);             // delay 200 milliseconds
    pretamper = LOW;
    //Serial.print("\n.....Normal.....");

    if (priState == HIGH) {
      Serial.println("Motion stopped!");
      priState = LOW;       // update variable state to LOW

    }
  }

}

```

I am loosing my mind because I could not find the problem of getting false alert in every 55 minutes.

I am very grateful any one can help.

# Answer
> 0 votes
After tons of research found a way to solve this issue.

This is common for ordinary PIR sensors when we use the 5V out from Arduino. Therefore we have to separate the power for PIR and the Arduino using a Opto Coupler and some transistors to smooth the signal. Now the solution works fine.

I am posting here to help someone stuck with same issue.

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


title: Power Source for Arduino

text:
# Question
Title: Power Source for Arduino
So I have SIM900 Shield and Arduino Uno and they have both power jack, is it possible to power one of them using one power jack and connect it's power with another? If it is possible, I sincerely need the explanation.

I've research about the VIN pin of Arduino but I didnt quite get it and can't take the risk that I might fry the board since Im new here.

# Answer
> 0 votes
It depends on what voltage the devices run at and what their current draw is from the power supply versus what voltage & current your power supply provides.

If everything runs at 3.3V or 5V and minimal amps then you're good to go.

Read the datasheet for each device and for your power supply.

---
Tags: arduino-uno, power
---