# Question
Title: How do I send non-ASCII keys over the BLE HID connection using an Adafruit nRF52 Feather?
The `hid_keyboard` example sketch shows how to send ASCII characters, but how can I send non-ASCII codes like the `F1` key, or keys with shift/control modifiers?

# Answer
> 1 votes
Yo can use the `keyboardReport()` function to send key-codes with modifiers. Here is an example that will send an `!` by sending the keycode for `1` plus a shift key modifier...

```
    // The keyboardReport() function takes an array of 6 keycodes. From what I can tell, it does not
    // press the keys consecutively,. it presses them simultainiously.

    // Here we only want to send one code, so we back-fill the array with HID_KEY_NONE

    uint8_t keycodes[6] = { HID_KEY_1, HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE };
    blehid.keyboardReport( KEYBOARD_MODIFIER_LEFTSHIFT , keycodes );

    // This release seems to be required. Without it, the last pressed key just repeats forever.
    blehid.keyRelease();

```

The possible modifiers are listed here... https://github.com/adafruit/Adafruit\_nRF52\_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit\_TinyUSB\_Core/tinyusb/src/class/hid/hid.h#L188

...and the possible keyscodes are listed here.. https://github.com/adafruit/Adafruit\_nRF52\_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit\_TinyUSB\_Core/tinyusb/src/class/hid/hid.h#L212

Unfortunately the `hid_keycodes` example does not compile, but bere is a ready-to-run example sketch showing how to send keycodes directly...

https://gist.github.com/bigjosh/5d8575f26988228dcf9d40c3795d0928

---
Tags: ble, nrf52, feather
---


title: 128x64 and pushButtons

text:
# Question
Title: 128x64 and pushButtons
Could someone give me some advice related to building a menu for a 128x64 LCD using 5 pushButtons? i have 5 screens. btn1 is for display MainMenu and Selection. btn2 and btn3 is for up and down scrolling btn 4 and btn4 is for switching on/off and increase decrease values.

the problem which i encounter is related to btn2 and btn3. i don;t know how to use them for scrolling in in another screen except screen1 (MainMenu).

```

#include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(13,12,11); //Enable, RW, RS, RESET

int selectionButton = A1, selectionButtonState, selectionButtonLastState = 0, cntSelectionButtonPressed = 0, cntSelectionButtonPressed2ForMenu2 = 0;
int menuButton = A0, menuButtonState, menuButtonLastState = 0;
int scrollDownButton = A3, scrollDownButtonState, scrollDownButtonLastState = 0;
  boolean mainMenu = false;

void setup()
{
    Serial.begin(9600);
    if ( u8g.getMode() == U8G_MODE_R3G3B2 )
    u8g.setColorIndex(255);     // white
    else if ( u8g.getMode() == U8G_MODE_GRAY2BIT )
    u8g.setColorIndex(3);         // max intensity
    else if ( u8g.getMode() == U8G_MODE_BW )
    pinMode(selectionButton,INPUT);
    pinMode(menuButton,INPUT);
    pinMode(scrollDownButton,INPUT);

}

void loop()
{

 scrollDownButtonState = digitalRead(A3);
 selectionButton = digitalRead(A1);
 menuButton = digitalRead(A0);

//pin A1 = RiGHT
 if(selectionButton != selectionButtonLastState)
 {
  if(digitalRead(A1) == HIGH)
  {
    cntSelectionButtonPressed += 1;
    if(cntSelectionButtonPressed == 4)
    {
      cntSelectionButtonPressed = 0;
    }
  }
  selectionButtonLastState = selectionButton;
 }

////////////////////////
 if(menuButton != menuButtonLastState)
  {
    if(cntSelectionButtonPressed == 1 && digitalRead(A0) == HIGH)
    {
         cntSelectionButtonPressed2ForMenu2 += 1;
    }
      if(cntSelectionButtonPressed2ForMenu2 == 4)
      {
        cntSelectionButtonPressed2ForMenu2 = 0;
      }
       u8g.firstPage();
       do{
           Menu2();
         }while(u8g.nextPage());

       menuButtonLastState = menuButton;
  }
 else
 {
 u8g.firstPage();
  do{
    MainMenu();
  }while(u8g.nextPage());
 }

}

void MainMenu(){
switch(cntSelectionButtonPressed)
{

  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("> Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("> Exterior casa");
           break;
}
}

void Menu2()
{

  switch(cntSelectionButtonPressed2ForMenu2)
{
  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("> Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("> Stil3");
           break;
}
}

```

# Answer
> 1 votes
First, I'm a bit surprised you use analog pins for button checks, instead of digital pins.

About the code, without analyzing it completely, the easiest way is to make a state diagram in pseudo code first.

E.g.suppose you want to have the following screens(a screen 'title/content' is shown in\[\], a button transition with ---(key)--\>

```
InitScreen--- (right)--> MenuOption1Highlight---(right)-->MenuOption1Items
                              |       ^     \---(left)----+
                           (down)    (up)
                              v       |
                           MenuOption2Highlight---(right)-->MenuOption2Items
                                              \---(left)----+

```

To program this (roughly), create an enumeration for each menu page :

```
enum EMenuPage
{
        None,
    InitScreen,
    MenuOption1Highlight,
    MenuOption1Items,
    MenuOption2Highlight,
    MenuOption2Items
};

```

Than create a current state for it as global variable:

```
EMenuPage _eMenuPage;

```

And initialize it in Setup:

```
_eMenuPage = None;

```

Create an enum for the keys :

```
enum EKey
{
    None,
    Up,
    Down,
    Right,
    Left
};

```

It is easier to create a function that reads keys, and returns one key, maybe one key has priority over another, or you can combine keys (in that case add in EKey e.g. UpAndDown). If no key has been pressed, None is selected.

In the loop, use a state transition diagram to program out the options :

```
EKey pressedKey = GetPressedKey(); // This is for yourself to implement, it updates _pressedKey;

switch (_eMenuPage)
{
case None:
    InitScreen();
    break;

case InitScreen:
    ProcessInitScreenKeys();
    break;

case MenuOptions1HighLighted:
    ProcessMenuOptions1HighLightedKeys();
    break;

...
default:
    // Illegal key
    break;
}

```

For each page you make a function (e.g. InitScreen) which updates the state and shows the content on the display:

```
void InitScreen()
{
    _eMenuPage = InitScreen;

    // Show content on display.
}

```

Also, you create a Process...Keys function to handle the keys. Like:

```
void InitScreen()
{
    EKey pressedKey = GetPressedKey();
    switch (pressedKey)
    {
    case Right:
        MenuOptions1HighLighted();
        break;

    default:
        // Ignore other keys
        break;
    }
}

```

For another function it would look like:

```
void ProcessMenuOptions1HighLightedKeys()
{
    EKey pressedKey = GetPressedKey();
    switch (pressedKey)
    {
    case Down:
        MenuOptions1HighLighted();
        break;

    case Right:
        MenuOption1Items();
        break;

    default:
        // Ignore other keys
        break;
    }
}

```

(Btw I did not check neither compiled the code).

Probably there is a nicer more object oriented way to do this, but it costs more memory and is more advanced. This is to create an abstract Page class, which has two virtual methods (one to show and one to handle keys), and create a derived class for each page implementing the two functions from the base class.

---
Tags: programming
---


# Question
Title: Can I use a TCS34725 color sensor with a LilyPad?
I have been trying to get a TCS34725 color sensor working with a LilyPad Arduino USB - ATmega32U4 board, but with no success. I am wondering if it possible?

I have been using the following sketch to try and get a reading but nothing appears in the monitor:

```
#include <Wire.h>
#include "Adafruit_TCS34725.h"

/* Example code for the Adafruit TCS34725 breakout library */

/* Connect SCL    to analog 5
   Connect SDA    to analog 4
   Connect VDD    to 3.3V DC
   Connect GROUND to common ground */

/* Initialise with default values (int time = 2.4ms, gain = 1x) */
// Adafruit_TCS34725 tcs = Adafruit_TCS34725();

/* Initialise with specific int time and gain values */
Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);

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

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1);
  }

  // Now we're ready to get readings!
}

void loop(void) {
  uint16_t r, g, b, c, colorTemp, lux;

  tcs.getRawData(&r, &g, &b, &c);
  // colorTemp = tcs.calculateColorTemperature(r, g, b);
  colorTemp = tcs.calculateColorTemperature_dn40(r, g, b, c);
  lux = tcs.calculateLux(r, g, b);

  Serial.print("Color Temp: "); Serial.print(colorTemp, DEC); Serial.print(" K - ");
  Serial.print("Lux: "); Serial.print(lux, DEC); Serial.print(" - ");
  Serial.print("R: "); Serial.print(r, DEC); Serial.print(" ");
  Serial.print("G: "); Serial.print(g, DEC); Serial.print(" ");
  Serial.print("B: "); Serial.print(b, DEC); Serial.print(" ");
  Serial.print("C: "); Serial.print(c, DEC); Serial.print(" ");
  Serial.println(" ");
}

```

# Answer
> Can I use TCS34725 Color Sensor with Lilypad?

Yes but please note that the I2C pins are D2 (SDA) and D3 (SCL). No extra components are required when connecting to the Adafruit TCS34725 breakout board. It contains pull-up resistors, and voltage/signal level converters (if needed).

Cheers!

Ref. https://cdn.sparkfun.com/datasheets/E-Textiles/Lilypad/Lilypad\_Arduino\_USB\_v12.pdf
> 0 votes

---
Tags: sensors
---


# Question
Title: Do ultrasonic sensors sense through transparent materials?
Do ultrasonic sensors sense through transparent materials?

In my case, I have to read if there's something inside a transparent acrylic bottle.

# Answer
> 2 votes
I'm assuming you mean a "normal" sensor, like this:

Ultrasonic sensors work by sending out sound waves. Obviously, sound waves don't care whether a material is transparent or opaque, so they are blocked just as easily by acrylic as by a brick wall.

Side note: If you look on the front of an ultrasonic sensor, you will notice that it is covered by a screen, not glass or plastic. This is why.

# Answer
> 1 votes
Ultrasonic sensors detect echoes of high frequency sounds bouncing off of a boundary between air and some other substance.

As others have pointed out, the light transmission properties of an object (transparency to light) has nothing to do with its transparency to ultrasonic sound waves.

It's possible to project ultrasonic sounds through solids or liquids, but that's not what these sensors are designed to do.

Trying to send ultrasonic pulses through an acrylic bottle will no doubt mess up the signals. Try pointing one of these sensors at an acrylic bottle in a controlled environment (fixed distance, mounted firmly and the same way each time, a solid back-stop at a fairly large, fixed distance behind the bottle to avoid varying echoes from behind the bottle) and check the distance measurement with the bottle full and empty. If you detect a difference in readings, then use those 2 different distance values for full and empty. (But make sure your production environment is the same as your test environment, including the area around and behind the bottle you're measuring)

# Answer
> 1 votes
Wanting to use HC-SR04 to measure water level, but protect the SR04 from moisture I tried covering with cling film, the most minimal film I could find. No - the sensor sees it and reports 1cm distance. So these sensors have to be left exposed - probably won't last long at top of my water tank.

# Answer
> -1 votes
Well, you can visualize babies in a womb using ultrasonic sensors. So why should it be a problem to "hear" inside a bottle? Maybe not with the sensors you can afford, and maybe not with an arduino, but basically it is possible, even if the bottle is not transparent.

if the bottle is open, and the content is liquid, a simple approach could be implementing a kind of ultrasonic range finder. This can be done with comparatively cheap hardware.

---
Tags: sensors
---


# Question
Title: Stack smashing protect failure ESP32 with Modbus RTU
I'm doing a project using an ESP32 TTGO with LoRa, the Max485 and a WELLPRO ADAM 8082 for Modbus communication. I'm trying to use the ESP32 as a master to and the ADAM as a slave. I'm also using Node-RED to send the input signals (reading the digital inputs on the ADAM or sending signals to the digital outputs). Whenever I send a signal there's no problem, the ADAM receives it correctly and sends the answer. But when my ESP32 receives the answer, I get the following error:

```
Stack smashing protect failure!

abort() was called at PC 0x400dc860 on core 1

```

I tried debugging my program and the error happens when my program comes back from the function that has my reading modbus loop. I'm pretty new to Arduino, so I don't really understand what could be causing this stack overflow.

Here's my code.

My global variables:

```
unsigned char ucSt[N_MAX];
int delayTime;

HardwareSerial modbusData(2);

WiFiClientSecure espClient;
PubSubClient client(espClient);
boolean bWifiConnected = false;

const byte button = PRG_BUTTON;

```

Modbus reading with loop:

```
void vReadingModBus()
{
  int i, nCmpt = 0;
  unsigned int uiCRC;

  while (modbusData.available() > 0)
  {
    Serial.print("nCmpt: ");
    Serial.println(nCmpt);
    ucSt[nCmpt] = (unsigned char)modbusData.read();
    nCmpt++;
    delay(delayTime - 2);
  }
  if (nCmpt)
  {
    Serial.print("He llegit aquests ");
    Serial.print(nCmpt);
    Serial.println(" bytes: ");
    char szResposta[N_MAX] = "", szByte[3];
    for (i = 0; i < nCmpt; i++)
    {
      sprintf(szByte, "%02X", ucSt[i]);
      strcat(szResposta, szByte);
      Serial.print(ucSt[i], HEX);
      Serial.print(" ");
    }
    Serial.println();
    client.publish(TEMA_RESPOSTA_MODBUS, szResposta);
    uiCRC = uiModRTU_CRC(ucSt, nCmpt - 2);
    if ((byte)(uiCRC >> 8) == ucSt[nCmpt - 1] && (byte)(uiCRC & 0xFF) == ucSt[nCmpt - 2])
    {
      Serial.println("Trama amb CRC correcte");
    }
    else
    {
      Serial.println("Trama amb CRC incorrecte");
    }
  }
  nCmpt = 0;
}

```

Modbus transmission:

```
void vModbusTx(unsigned char *uc, int nLen)
{
  int i;

  Serial.print("Enviat: ");
  for (i = 0; i < nLen; i++)
  {
    Serial.print(uc[i], HEX);
    Serial.print(" ");
  }
  Serial.println();

  vModeTxRxRS485(RS485Transmit);
  delay(1);
  for (i = 0; i < nLen; i++)
  {
    modbusData.write(uc[i]);
  }
  delay(delayTime);

  vModeTxRxRS485(RS485Receive);
}

```

My setup:

```
void setup() {
  Serial.begin(115200);    // U0_RXD:GPIO3, U0_TXD:GPIO1 (UART0)
  modbusData.begin(9600); // U2_RXD:GPIO16, U2_TXD:GPIO17 (UART2)

  pinMode(PRG_BUTTON, INPUT_PULLUP);
  pinMode(GPIO_R2, INPUT); // 39
  pinMode(SSerialTxControl, OUTPUT); // hardwired to GPIO_R2
  pinMode(LED, OUTPUT);

  vModeTxRxRS485(RS485Receive); // RS485Receive is a 0, and vModeTxRxRS485 controls the DE/RE bits for the Max485

  delayTime = 0;

  //Wire.begin(I2C_SCL_OLED);

  delay(1000); // give me time to bring up serial monitor
}

```

My loop:

```
void loop() {
  boolean bButtonState = !digitalRead(button);
  static boolean bLastButtonState = bButtonState;

  // MODBUS READING LOOP
  vReadingModBus();

  if (!client.connected())
  {
    reconnect();
  }

  // BUTTON STATE CHECK
  if (bButtonState != bLastButtonState)
  {
    bLastButtonState = bButtonState;
    vDelayESP(50);
    if (!bButtonState)
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "UNPRESSED");
    else
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "PRESSED");
  }

  client.loop();
}

```

And finally here's an example of my program running and giving the error mentioned:

```
Connecting to WiFi network
Waiting for WIFI connection...
..............................................
Attempting MQTTS connection...connected
Message arrived [/clot/dam/biel/esp32/escriuModbus] 010F000000080111
Petició a ModBus:
010F000000080111
Mida: 8
ucSt[0] = 1
ucSt[1] = F
ucSt[2] = 0
ucSt[3] = 0
ucSt[4] = 0
ucSt[5] = 8
ucSt[6] = 1
ucSt[7] = 11
Enviat: 1 F 0 0 0 8 1 11 3E 99
He llegit aquests 8 bytes:
1 F 0 0 0 8 54 D
Trama amb CRC correcte

Stack smashing protect failure!

abort() was called at PC 0x400dc7d8 on core 1

Backtrace: 0x4008c800:0x3ffb1ef0 0x4008ca31:0x3ffb1f10 0x400dc7d8:0x3ffb1f30 0x400d1eed:0x3ffb1f50 0x400d23c0:0x3ffb1f90 0x400d513d:0x3ffb1fb0 0x4008879d:0x3ffb1fd0

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x17 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:928
ho 0 tail 12 room 4
load:0x40078000,len:8424
ho 0 tail 12 room 4
load:0x40080400,len:5868
entry 0x4008069c

```

# Answer
tl;dr: The message probably means your function is overwriting its array:

A stack overflow is caused by a stack that grows downward into the allocated heap space, either causing damage to data within the heap, or code using that heap space causing damage to the contents of the stack.

But "stack smashing" refers to damage caused by function code writing past the bounds of an automatic local variable and damaging the stack contents, typically including the function's return address.

\[Feel free to skip rather long explanation:\]

A function's stack-frame begins with the return address - the address following the instruction that calls the function, i.e., the address of the next instruction to be executed after the function returns. Then, building downwards, the call parameters are put on the stack and become local variables. Then any variables allocated during the function execution are allocated, still building downward.

Assume one of those allocated variables is an array. Its zero-th element is in the lowest address of the allocated space, and subsequent elements are at successively higher addresses. If I start writing into the array, and continue past its length, I'll eventually overwrite other automatic locals, my parameters, and and my return address. Then, when the function tries to return, instead of jumping to the code that called the function, the MCU uses the damaged return address and jumps to ... ????

To catch this error, the compiler can insert code that 1) allocates and writes a "canary" - a known value - just after the return address, and 2), checks the canary for damage just before the function returns. If the canary has been altered, you get the message you saw, because it's likely that the return address will have been altered also. But regardless, the canary isn't part of your code and isn't accessible to it. Thus, it detects *writing-out-of-bounds errors*.

\[End of wordy explanation\]

Check the code in your function 'void vReadingModBus()' - my money is on the loop that writes into `szResposta[]`:

```
  char szResposta[N_MAX] = "", szByte[3];
    for (i = 0; i < nCmpt; i++)
    {
      sprintf(szByte, "%02X", ucSt[i]);
      strcat(szResposta, szByte);
      Serial.print(ucSt[i], HEX);
      Serial.print(" ");
    }

```

Update:

> If I understood correctly, it means szResposta must be overwriting the function's return address? How should I avoid this?

The short answer is make your array big enough for what you're going to put in it. But that's probably not a satisfying answer though, so let's take a closer look. I'm not sure exactly what your intent is in that loop, but since you print the `strcat()` result at every iteration and you don't seem to use `szResposta` after that, perhaps you meant to call `strcpy()` (replace the contents of the array) instead of `strcat()` (extend the contents of the array). If so, `strcat()` would quite likely write past the array bounds.
> 2 votes

---
Tags: c, esp32, modbus, espressif
---


# Question
Title: esp8266 deep sleep timer slightly inaccurate?
I'm making a door open timer using a hall sensor and have a wemos d1 mini that uses a deep sleep to sleep for 1 minute after checking the hall sensor state and printing the value on the serial port. I'm using the Arduino IDE to monitor the serial output and have the Show timestamp option enabled so that I could time how long the device is running after it resets. However, I'm getting output like this:

```
08:03:26.286 -> ^H⸮ȸ$RKx⸮⸮x⸮I⸮⸮696
08:04:25.454 -> HEA⸮⸮⸮d⸮⸮⸮⸮⸮⸮⸮696
08:05:24.681 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮696
08:06:23.915 -> ⸮DP⸮V⸮l⸮X⸮X⸮H⸮⸮694
08:07:23.178 -> ⸮A⸮K`E⸮M⸮⸮xxE⸮696
08:08:22.406 -> ⸮HlX⸮K⸮I|⸮⸮xE⸮693
08:09:21.703 -> ⸮⸮NI⸮ hlE⸮0⸮⸮E⸮694
08:10:20.978 -> 8H⸮JcD⸮M⸮⸮xxE⸮695
08:11:20.306 -> ⸮⸮NI⸮AhlE⸮ Op⸮⸮696
08:12:19.573 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮539
08:13:18.897 -> ⸮⸮OI⸮AhlE⸮⸮O⸮⸮538
08:14:18.196 -> HEA⸮⸮⸮d⸮⸮⸮⸮I⸮⸮539
08:15:17.561 -> ⸮dG⸮⸮⸮hLJ⸮@h⸮⸮(⸮539

```

The garbage output isn't what I'm asking about, it's the timestamps being created by the arduino ide. Since I sleep for 60,000,000 microseconds, I would assume that the second value of the minute would be slightly more each time. But as shown above, it becomes slightly less every time, as if it takes less than a minute. So what I'm wondering is if the sleep timer on these devices is not accurate enough to count on this or something else I should be considering like an inaccuracy in the IDE? I only wanted to measure the uptime so that I could consider it for battery drain considerations, I don't really need a millisecond accurate timer for the functionality of the device.

# Answer
> 4 votes
A (now 3 year old) GitHub thread suggests using an external RTC if time tracking is of importance. It also points at a dead NodeMCU document link. That document appears to have moved. This document describes the lengths taken to provide a better account for time passage during sleep. Which, apparently, includes guessing at the sleeping chip's temperature:

> Time keeping on the ESP8266 is technically quite challenging. Despite being named RTC, the RTC is not really a Real Time Clock in the normal sense of the word. While it does keep a counter ticking while the module is sleeping, the accuracy with which it does so is highly dependent on the temperature of the chip. Said temperature changes significantly between when the chip is running and when it is sleeping, meaning that any calibration performed while the chip is active becomes useless mere moments after the chip has gone to sleep. As such, calibration values need to be deduced across sleep cycles in order to enable accurate time keeping. This is one of the things this module does.

Update:

A recent Arduino stack exchange answer goes into detail using a DS3231 Real Time Clock.

# Answer
> 1 votes
Yes a RTC can be very inaccurate. Some RTCs will let you synchronise them.

---
Tags: serial, esp8266, arduino-ide, timers
---


title: Two sensors using I2C

text:
# Question
Title: Two sensors using I2C
We have two sensor one of them(MPU6050-gyro) is communicating using I2C, the other is via SPI(SD card reader). Now, we need an additional component as a sensor that the barometer which communicates via I2C.

Can we use all three modules without any problem? I wonder if two I2C modules is used in a hassle-free manner? Otherwise, what can be done?

# Answer
> 4 votes
Yes, that's the idea behind bus protocols like i2c. You only require the sensors on i2c to have different bus adresses. A sensor's address usually can be chosen by soldering a jumper (the mpu6050 provides this feature on pin AD0). If you can't avoid an address collision you could use an i2c multiplexer or a microcontroller in between the sensor and the actual mcu (but probably that's not neccessary when using only two sensors).

Using SPI and I2C at the same time is absolutely no problem on the atmega!

# Answer
> 1 votes
I2C is a bus. There can be many devices connected to that bus, each one having it's own address. Everytime you want to communicate with one of them, you have to send the address of the device. When you are using the `Wire` library, thats done by calling `Wire.beginTransmission()` or `Wire.requestFrom()`. Most slave devices have an adress, that is partly configurable, often by wiring special pins to Vcc or ground. Make sure, that every device on the bus has a unique address, or you will run into problems with corrupted data or a stuck bus.

---
Tags: arduino-ide, sensors, i2c, esp32
---


# Question
Title: How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move?
How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move? Is it possible to modify the header file or use a different library? I used the MouseTo library, but it wasn't the move I wanted. We want to move as fast as possible to the relative coordinates, not as one pixel. I've searched almost every community, but I haven't. Give them a hand.

# Answer
The USB HID protocol for mouse is the limitation on sending more then a byte sized value for the mouse movement in one event.

You can't create a faster USB mouse. Repeat the call of the move() function. Of course you can use a function to call move() repeatedly to move to target destination.

```
void mouseMove(long x, long y) {
  long max = max(abs(x), abs(y));
  int count = (int) (max / 127);
  signed char stepX = x / (count + 1);
  signed char stepY = y / (count + 1);
  for (int i = 0; i < count; i++) {
    Mouse.move(stepX, stepY);
  }
  signed char resX = x - (stepX * count);
  signed char resY = y - (stepY * count);
  if (resX != 0 || resY != 0) {
    Mouse.move(resX, resY);
  }
}

```
> 2 votes

# Answer
For X and Y values between -64 and 64, consider multiplying the X and Y values you are passing to the method mouse.move() by 2. In the above linked page, the example call to mouse.move() looks like this:

> mouse.move(xVal, yVal, wheel)

Consider writing it like this for twice the change in either direction:

> mouse.move((2 * xVal), (2 * yVal), wheel)

For values less then -128 or greater than 128, consider calling the method multiple times instead of once for each time it is desired to move the mouse.

A more difficult approach: You may also consider re-writing or adding to the Arduino mouse driver. It appears the Arduino mouse driver is located here. As this is C++ you will need to change the definition of the "mouse" method as well as how you handle int as opposed to char sized variables. In this case you can take advantage of the C++ Method Overloading feature. That is, you can have 2 methods of the same name with different parameter types. C++ will treat them as two individual methods. So the original mouse.move method can remain untouched. While the new mouse.move method will be able to handle type singed int instead of type singed char values.
> 0 votes

---
Tags: mouse
---


title: Reducing static on button reading

text:
# Question
Title: Reducing static on button reading
I have a very simple code for a controller I'm working on for a robot.

```
void setup() {
  // put your setup code here, to run once:
  pinMode(3,INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(digitalRead(3));
}

```

The only problem is that I can't get a constant reading on switches because when I flick the switch I will get a constant stream of 1s, but when I flick the switch off I get a sporadic stream of ones and zeros. I have noticed though that if I put my finger on the USB port leading from my Arduino Nano I get a constant stream of 1s when on and zeros when off.

Does anyone have a recommendation to get around this problem or simulate touch on the USB port?

# Answer
Sounds like you need a pull-down resistor.

If a CMOS input like and Arudino digital input isn't attached to anything it will "float", bouncing between 1 and 0.

Attach a 10k resistor between the input pin and ground (before the switch). That way, if the switch is off/open, the resistor pulls the input to ground.

If the switch is on/closed, it feeds +5V into the pin, overwhelming the resistor.

(Note that you can instead use a pull-up resistor, and then have the switch connect to ground instead of +5 volts. When you do this the input is reversed {HIGH if the switch is not pressed and LOW if the switch is pressed.} There is an internal pull-up resistor on the digital input pins that you can connect by using the setting `INPUT_PULLUP` instead of `INPUT` when you configure the pin with the `pinMode()` function. That way you don't need an extra resistor.)

Also note that in addition to needed a pull-up or pull-down resistor, you may need to debounce your switch. You can do this by writing your code that detects switch presses to ignore changes for 100 ms or so. This avoids the rapid on/off/on/off jitter you often get from switches as their contacts transition from open to closed (or closed to open.)
> 2 votes

---
Tags: usb
---


# Question
Title: how to write Arduino code for a stepper motor to move an arm back and forth 180 degrees
I am currently working on a project which involves picking up plastic balls and depositing them in a box. I am trying to use a stepper motor to move an arm which is attached to a square piece of plywood which has Pringles cans on it. This is how I plan to collect the plastic balls.

The stepper motor needs to move the arm back and forth 180 degrees to collect and deposit the plastic balls. But I am unsure as to how to write the code to accomplish this as I am quite new to Arduino coding. Any form of help would be greatly appreciated. Thank you in advance.

# Answer
There is not enough information about your stepper motor, so let's assume some: let's use stepper motor with 1.8 degree per step (very popular step motor), and we will drive without any microsteps.
To accomplish the task you would need:

* Arduino,
* stepper motor,
* stepper motor driver (like EasyDriver or some kind of Pololu drivers)
* power supply. To avoid interference I would suggest powering up your Arduino with PC (through USB port) and additional, powerful PSU for the motor/motor driver only.

Now, you would need to provide at least two signals from Arduino to stepper driver (what I am saying here is **example of EasyDriver**). The signals named DIR and STEP. DIR selects the direction of the motor to spin. Depending of the stepper motor to driver PCB connections you may have clockwise spin when signal is in one state and counterclockwise when DIR is in opposite state. STEP accepts pulses to move the step motor. Driver moves the stepper motor when STEP input sees raising edge. One raising edge equals to one step = 1.8 degree (again, this apply **when you do not use microstepping**). To spin motor 180 degrees you need 100 steps.
To summarise:

* Use two ports (simplest solution here with EasyDriver): One defined as DIR, other as STEP.
* DIR low (selecting one of directions)
* STEP pulse 100 times (step motor rotates 180 degrees)
* pause (for whatever needs to be done)
* DIR high (opposite direction to rotate back)
* STEP pulse 100 times (stepper motor rotates 180 degrees to initial position)
> 1 votes

---
Tags: arduino-uno
---


title: Arduino yes! and after?

text:
# Question
Title: Arduino yes! and after?
I am new to electronics and am currently working with an Arduino UNO. I know the basics of PCB manufacturing (Besides, I'm fiddling with mine, very basic of course) Anytime I'm curious about how to get from Arduino to a finished PCB with the same result only on my Arduino prototype?

For example, my project has several components such as leds, An RFID module, a TFT LCD Shield 3.5 ", another 240x320 OLED screen ... How to put all this on a printed circuit board?

Do I need to solder the same components to my PCB? -Do I need to run my Arduino code on my PCB once it is assembled? -.......................................

# Answer
> 3 votes
A printed PCB can be used to place your components on (typically resistors, ICs, capacitors etc).

However, if you want to connect an LCD or big components, it would be a waste of space for your PCB. So in that case, I guess the best way is to create an enclosure where your displays fit in (and your RFID module if it is big too), and create some kind of connector from the PCB (e.g. using a terminal block or other way) and connect it to your displays.

On your PCB also an Arduino needs to be added, I guess the best solution is to use the Arduino chip (AtMega328P probably), and some external circuitry needed. Optionally using an IC socket in case you want to change the program later on.

On some Arduinos you can take out the AtMega328 DIP28 IC from your Arduino Uno board. Program it, than place it in the socket on your PCB board.

**Update**

Maybe you can use an Arduino Micro or Nano and place that directly onto your PCB (with headers preferably). Than you get something like below:

# Answer
> 0 votes
" Optionally using an IC socket in case you want to change the program later on." No need, put an FTDI header on for serial programming, or put an ICSP header on and use a Programmer to program via the SPI pins.

Making your own PCB is very straightforward. I use EAGLE CAD software and design boards all the time. To duplicate a Promini for example, one only needs a '328P, 16 MHz xtal, two 22pF caps, 4 0.1uF caps, and a 10K resistor. Then the 2 headers for convenient bootloading and/or programming. Bootload and program it just like it was an Uno.

---
Tags: arduino-uno, prototype
---


# Question
Title: What components I need for a small GPS tracker
I am new to Arduino and want to create a graduation project for my university. I am thinking to create a GPS tracker that can be attached to a cloth to track kids, for example. So the requirements for this project is as follows: \- The device should be small \- It should upload its location to a web server constantly. \- the device should work with battery for at least 8 hours

Now what components are needed for this project? What concern me a lot is that how can I find battery last this much time, if I need bigger battery, it may hinder the device from being attached easily.

# Answer
In addition to @Majenko's post, you will save considerable power by turning the GPS & GSM off when not needed - for example, you might decide that once per minute, or once per 5 minutes is enough (maybe send it a text to trigger "continuous mode"?). Once the Arduino has switched off the other devices, it can go into "sleep" mode for a while. Check out Nick Gammon's excellent treatise on power saving modes at http://www.gammon.com.au/power

You can save both power and size by replacing an entire Arduino with an ATTiny - prototype on an Arduino first, then once it's working, move to an AtTiny - they have fewer pins, less memory, and are cheaper & smaller.

I doubt you could get the size smaller than a small cellphone, which can be had for very little - $35ish plus shipping, from http://www.aliexpress.com/item/Cheap-original-Mobile-phone-LG-Optimus-One-P500-WIFI-GPS-JAVA-Android-OS-Unlocked-Mobile-Phone/32274282341.html?spm=2114.01020208.3.1.zgFwLV&ws\_ab\_test=searchweb201556\_1,searchweb201527\_3\_71\_72\_73\_74\_75,searchweb201560\_9
> 0 votes

# Answer
You need four things:

* A GPS receiver
* A GSM modem
* An Arduino
* A Battery

Using off the shelf products you would probably end up with something about the size of a cigarette packet at best - probably bigger.

To make it small enough to be unobtrusive would take a lot of work. You would need to design your own circuitry combining everything that is contained in the three circuits above into the smallest design you can, and since most existing solutions use pre-built modules (*cans*) that are relatively large you would first have to discover how they work and replicate them as one single tiny module.

And then there is the battery. GPS receivers are very sensitive devices. They have quite powerful preamplifiers to detect the incredibly faint signals of the satellites. Consequently they use quite a bit of power. Similarly GSM modems are quite power hungry, especially when they are far from a cell tower.

Put those together and you have quite large power requirements - so the battery will consequently be relatively large. Many times the size of the circuit you designed above.

So if you're trying to make something that James Bond might stick on the back of someone's jumper without them noticing you're very much out of luck I'm afraid.

That is why most tracking of people is done using a larger device that most people have sat in their pocket already: a mobile phone. You can already get software for most phones that will allow you to track your children.
> 1 votes

# Answer
You have two options. Option 1. Buy a ready made pet tracking device from online market e.g (https://www.aliexpress.com/item/Pets-Smart-Mini-GPS-Tracker-Anti-Lost-Waterproof-Bluetooth-Tracer-For-Pet-Dog-Cat-Keys-Wallet/32887784462.html?spm=2114.search0104.3.1.26793604pFMLma&ws\_ab\_test=searchweb0\_0,searchweb201602\_3\_10065\_10068\_319\_10059\_10884\_317\_10887\_10696\_321\_322\_10084\_453\_10083\_454\_10103\_10618\_10307\_537\_536,searchweb201603\_52,ppcSwitch\_0&algo\_expid=09c58262-a0e7-4205-8fba-cd8265c15b3e-0&algo\_pvid=09c58262-a0e7-4205-8fba-cd8265c15b3e). Then you can download the app and start tracking movement.

Option 2: The other alternative is to build one from scratch by purchasing all the necessary components. This is option is most appropriate for students. You can check this page for more https://electronicsforu.com/electronics-projects/hardware-diy/gsm-gps-based-vehicle-tracking-system. However, you may not be able to achieve the small size as you wanted but you should have something close to it if you carefully select your components.
> 1 votes

---
Tags: gsm, gps, adafruit, components
---


# Question
Title: Why I am connecting positive wire in the circuit?
I have constructed a simple fade in and fade out circuit similar to given on this website https://roboindia.com/tutorials/arduino-analog-output-led-fade Now I am connecting a wire from 5V power pins to +ve side line, but i don't know why I am doing this because when I remove this wire or connect it to 3.5V pin the led is still running fine. Also as side lines are connected horizontally there is no other further connection given to the +ve wire. Can you tell me why I am joining the wire?

# Answer
This is indeed not needed. As you can see in the diagram, the horizontal line which you connected the 5 V pin to.

The horizontal line of holes just above the red horizontal line) are connected. However, since it only connected to the 5V pin of the Arduino, the all pins on that horizontal line have 5 V, but since there is nothing connected to it (thus no closed circuit), the effect is zero.

The reason why the connection is made (the wire from Arduino to 5V), is that it is 'default' to connect both GND and 5V (or 3.3V) as a starting point. It is easy to forget later and than no current will flow when you connect something to the +5 V horizontal line of pins.

Btw, the 3.5 V pin you mention, is 3.3 V, not 3.5 V.
> 2 votes

---
Tags: arduino-uno, wires
---


# Question
Title: Reading data from airspeed v3 eagle tree
I am trying to get values from this sensor **Airspeed v3** from eagle tree but it seems my I2C is not working properly.

I bought a module in third party mode and followed these instructions from the manufacturer website.

I went to rcgroups forum and discovered the right values for the bits mentioned in the documentation about WRITE and READ.

I started the development of a code but I cannot get the values from the sensor. It is supposed to send me a 2 byte-formatted value indicating the airspeed measured. But surprisingly when I call this method `Wire.requestFrom(AIRSPEED_ADDRESS, 2)` it returns 0, so someway the communication is not working. I have used I2C before for ADXL345 sensor and it works perfectly.

The results from these lines

```
Serial.println(data[0]);
Serial.println(data[1]);

```

are just -1 indicating that no data is available to display.

Does anybody know how to get this working? Am I missing something?

This is my code right now.

```
#include <Wire.h>

#define AIRSPEED_ADDRESS  0xEA
#define WRITE_BIT         0x00
#define READ_BIT          0x01

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  Wire.begin();
  Serial.begin(9600);
  Serial.println("Program started");
}

void loop() {
  byte data[2] = {0};
  int i = 0;
  int16_t velocidade = 0;

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  if (!Wire.write(WRITE_BIT)) {
    Serial.println("error sending write_bit");
  }
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  if (!Wire.write(0x07)) {
    Serial.println("error sending 0x07");
  }
  Wire.endTransmission(false);

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  if (!Wire.write(READ_BIT)) {
    Serial.println("error sending read_bit");
  }
  else {
    //Serial.println("ok sending read_bit");
  }
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Serial.print("bytes read from slave: ");
  Serial.println(  Wire.requestFrom(AIRSPEED_ADDRESS, 2) );
  data[0] = Wire.read();
  data[1] = Wire.read();
  Wire.endTransmission();

  velocidade = data[1] | (data[0] << 8);
  Serial.println(data[0]);
  Serial.println(data[1]);
  Serial.println(" ");

}

```

# Answer
> 1 votes
That's interesting but after using a different library the code worked out.

It has to follow exactly what the datasheet says in order to get things done.

The following source code makes it and get the airspeed from the sensor:

```
#define SENSOR_ADDRESS 0xEA
#include <Wire.h>
#include <I2cMaster.h>
TwiMaster AIRSPEED_SENSOR(true);

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

long airspeed_update(void) {
  static struct {
    union { int16_t val; uint8_t raw[2];
    } airspeed16;
  } airspeedv3;

  long airsp;

  if(AIRSPEED_SENSOR.start(SENSOR_ADDRESS | I2C_WRITE)) {
    delay(10);
    AIRSPEED_SENSOR.write(0x07);
    delay(10);
    AIRSPEED_SENSOR.stop();
  }

  if(AIRSPEED_SENSOR.restart(SENSOR_ADDRESS | I2C_READ)) {
    delay(10);
    airspeedv3.airspeed16.raw[0]=AIRSPEED_SENSOR.read(false);
    delay(10);
    airspeedv3.airspeed16.raw[1]=AIRSPEED_SENSOR.read(true);
    delay(10);
    AIRSPEED_SENSOR.stop();
  }

  airsp=airspeedv3.airspeed16.val;
  return airsp;
}

void loop() {
  int airspeed = airspeed_update(); Serial.println(airspeed);
  delay(50);
}

```

Get this library from here.

# Answer
> 2 votes
I found the I2C address on my Eagletree Airspeed V3 sensor to be 0x75 NOT 0xEA.

the following code adapted from first sample above works on my Nano:

```
/*
 * note that timming is critical - see delay (5)
 * and bps set to 115200
 * works ok, but clean up 5-19-2019 jaf
 */

#include <Wire.h>

#define AIRSPEED_ADDRESS  0x75
#define WRITE_BIT         0x00
#define READ_BIT          0x01

void setup() {
  Wire.begin();
  Serial.begin(115200);
  Serial.println("Program started");
}

void loop() {
  byte data[2] = {0};
  int i = 0;

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(WRITE_BIT);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(0x07);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(READ_BIT);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.requestFrom(AIRSPEED_ADDRESS, 2);
  data[0] = Wire.read();
  Wire.endTransmission();

  Serial.println(data[0]);
  delay(5);
}

```

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


title: Code for two bulb fading alternatively

text:
# Question
Title: Code for two bulb fading alternatively
I have written this code

```
const int A = 3;
const int B = 5;
void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);

}

void loop() {
  for(int i=1;i<=255;i++)
  {
    int j =255-i;
    analogWrite(A,i);
    analogWrite(B,j);
    delay(100);
  }
  for(int i=255;i>0;i--)
  {
    int j =255-i;
    analogWrite(B,j);
    analogWrite(A,i);
    delay(100);
  }
}

```

Is this code correct? If yes then can it be modified in any way to make it better?

# Answer
> 0 votes
To keep the two loops more symmetrical, let the first loop go from 0 until 254: \[0 .. 255) and the second loop from 255 to 1: \[255 .. 0), so both iterations have 255 values each.

Also, it is quite common in programming to include the start element, and not include the end element (as in the values above: \[start\_element .. end\_element).

Also, for the simple formula (255 - i), I would leave out the formula. And to make things more clear define constants for the min/max values (0,255) and the delay.

Than you get:

```
const int A = 3;
const int B = 5;

const int MIN_INTENSITY = 0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
}

void loop()
{
  for(int i = MIN_INTENSITY; i < MAX_INTENSITY ; i++)
  {
    analogWrite(A, i);
    analogWrite(B, MAX_INTENSITY - i);
    delay(DELAY_TIME);
  }

  for(int i = MAX_INTENSITY ; i > MIN_INTENSITY; i--)
  {
    analogWrite(B, MAX_INTENSITY - i);
    analogWrite(A, i);
    delay(DELAY_TIME);
  }
}

```

By making a function and use arguments for the variable values, and create some better names for constants and variables you get this:

```
const int LED_1_PIN     =   3;
const int LED_2_PIN     =   5;

const int MIN_INTENSITY =   0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup()
{
  pinMode(LED_1_PIN, OUTPUT);
  pinMode(LED_2_PIN, OUTPUT);
}

void loop()
{
  fade(MIN_INTENSITY, MAX_INTENSITY,  1);
  fade(MAX_INTENSITY, MIN_INTENSITY, -1);
}

void fade(int startIntensity, int endIntensity, int stepValue)
{
  for(int intensity = startIntensity; intensity < endIntensity; intensity += stepValue)
  {
    analogWrite(LED_1_PIN, intensity);
    analogWrite(LED_2_PIN, MAX_INTENSITY - intensity);
    delay(DELAY_TIME);
  }
}

```

---
Tags: arduino-uno, code-review
---


# Question
Title: Looking for some help with an RGB LED animation
I'm working on a project that is running off of a Sparkfun Pro Micro 5V. I'm trying to accomplish a color rainbow cycle animation which will have a function when triggered to fade the rainbow to black and fade-in some white LED. I'm using a Adafruit RGBW Neopixel for this. I'm having trouble getting some code that does this as when I try to trigger my fade-out it's turning off faster than expected due to the way I wrote it. I'm hoping someone can point me to a piece of code or suggest an edit that will help.

Constraints for animation:

* Must execute quickly (if at all possible avoid floats or other constructs that take a lot of time; relatively)
* Be able to configure a maximum brightness set on initialization (0 - 255)
* Must not have any "delay" or "while" loops that are designed to hold the code up.
* When triggered by a button press the rainbow should fade to black (i.e. off) and previously off white LED should fade in.
* When button pressed a second time white should fade out and rainbow starts or resumes.

I don't really care how the color animation works. It can cycle to/between specified colors or use whatever. To keep it simple what I tried was to have it just cycle RGB values with each 1/3 out of phase. My cycle includes a "dead" time where the color stays off for a part of the loop to keep the colors more distinct so they don't merge into white through color mixing. I specifically didn't use any sort of HSV conversion or sin/cos/whatever to calculate position in the cycle I am because those require a lot of calculation relative to incrementing a number.

Here is the code I wrote for your review. This has some servo control and the button checking and the LED in it. The bit at the very end is to prevent the pixels from updating during the time the servo pulses are being sent which prevents servo jitter due to the neoPixels.

```
#include <Servo.h>
#include <Adafruit_NeoPixel.h>

#define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8)

class ColorCycle {
  private: int maxB;
  private: int offH;
  private: int stepD;
  private: int curD;
  private: int rVal;
  private: int gVal;
  private: int bVal;
  private: int wVal;
  private: int rHold;
  private: int gHold;
  private: int bHold;
  private: int wHold;
  private: bool rDir;
  private: bool gDir;
  private: bool bDir;
  private: bool wDir;
  private: bool showWhite;

  public: ColorCycle(int maxBrightness, int offHold, int stepDelay) {
      maxB = maxBrightness;
      offH = offHold;
      rVal = gVal = bVal = wVal = 0;
      rHold = 0;
      gHold = (maxB + offH) * .5;
      bHold = (maxB + offH);
      wHold = 0;
      rDir = gDir = bDir = true;
      wDir = false;
      stepD = stepDelay;
      curD = 0;
    }

    void moveStep() {
      moveSteps(1);
    }

    void moveSteps(int count) {
      if (count == 1) { //going to skip the delay if you are trying to move more than one step intentionally.
        if (curD > 0) {
          curD--;
          return;
        }
        curD = stepD;
      }

      for (int s = 0; s < count; s++) {
        if (showWhite) {
          whiteHold();
          wDir = true;
        } else {
          wDir = false;
        }

        //setting the direction and holds when appropriate
        if (rVal == 0)
          rDir = true;
        if (rVal == maxB) {
          rDir = false;
          rHold = offH;
        }

        if (gVal == 0)
          gDir = true;
        if (gVal == maxB) {
          gDir = false;
          gHold = offH;
        }

        if (bVal == 0)
          bDir = true;
        if (bVal == maxB) {
          bDir = false;
          bHold = offH;
        }

        //stepping the values
        if (rDir && rHold == 0)
          rVal++;
        if (!rDir && rVal > 0)
          rVal--;
        if (rVal == 0 && rHold > 0) {
          rHold--;
        }

        if (gDir && gHold == 0)
          gVal++;
        if (!gDir && gVal > 0)
          gVal--;
        if (gVal == 0 && gHold > 0) {
          gHold--;
        }

        if (bDir && bHold == 0)
          bVal++;
        if (!bDir && bVal > 0)
          bVal--;
        if (bVal == 0 && bHold > 0) {
          bHold--;
        }

        if (wDir && wVal < maxB)
          wVal++;
        if (!wDir && wVal > 0)
          wVal--;
      }
    }

    int getRedValue() {
      return rVal;
    }
    int getGreenValue() {
      return gVal;
    }
    int getBlueValue() {
      return bVal;
    }
    int getWhiteValue() {
      return 0;
    }

    void setShowWhite(bool sw) {
      showWhite = sw;
    }

    void whiteHold() {
      rHold = 5;
      gHold = (maxB + offH) * .5;
      bHold = (maxB + offH);
      rDir = gDir = bDir = false;
    }
};

#define BUTTON_LED_PIN 16
#define BUTTON_SWITCH_PIN 14

Servo lidServo;
int lidServoPosition;
Servo leftServo;
int leftServoPosition;
Servo rightServo;
int rightServoPosition;

#define LID_LED_CONTROL_PIN 3
#define LID_LED_COUNT 8
Adafruit_NeoPixel lidPixel(LID_LED_COUNT, LID_LED_CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
ColorCycle ccLid(50, 50, 10);

#define BASE_LED_CONTROL_PIN 4
#define BASE_LED_COUNT 8
Adafruit_NeoPixel basePixel(BASE_LED_COUNT, BASE_LED_CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
ColorCycle ccBase(50, 50, 10);

void setup() {
  pinMode(BUTTON_LED_PIN, OUTPUT);
  digitalWrite(BUTTON_LED_PIN, LOW);
  pinMode(BUTTON_SWITCH_PIN, INPUT);
  lidServo.attach(5);
  leftServo.attach(6);
  rightServo.attach(9);
  lidPixel.begin();
  lidPixel.show();
  basePixel.begin();
  basePixel.show();

  Serial.begin(9600); //This pipes to the serial monitor
  Serial.println("Starting");
}

void loop() {
  if (digitalRead(BUTTON_SWITCH_PIN) == true)  {
    digitalWrite(BUTTON_LED_PIN, HIGH);
    lidServoPosition = 0;
    leftServoPosition = 0;
    rightServoPosition = 0;
    ccLid.setShowWhite(true);
    ccBase.setShowWhite(true);
  } else {
    digitalWrite(BUTTON_LED_PIN, LOW);
    lidServoPosition = 180;
    leftServoPosition = 180;
    rightServoPosition = 180;
    ccLid.setShowWhite(false);
    ccBase.setShowWhite(false);
  }
  lidServo.write(lidServoPosition);
  leftServo.write(leftServoPosition);
  rightServo.write(rightServoPosition);

  ccLid.moveStep();
  ColorCycle tempCc = ccLid;
  for (int i = 0; i < lidPixel.numPixels(); i++) {
    lidPixel.setPixelColor(i, lidPixel.Color(tempCc.getGreenValue(), tempCc.getRedValue(), tempCc.getBlueValue(), tempCc.getWhiteValue()));
    tempCc.moveSteps(10);
  }

  ccBase.moveStep();
  tempCc = ccBase;
  for (int i = 0; i < lidPixel.numPixels(); i++) {
    basePixel.setPixelColor(i, basePixel.Color(tempCc.getGreenValue(), tempCc.getRedValue(), tempCc.getBlueValue(), tempCc.getWhiteValue()));
    tempCc.moveSteps(10);
  }

  if (TCNT1 > usToTicks(8192)) {
    lidPixel.show();
    basePixel.show();
  };
}

```

# Answer
> 1 votes
You are writing your code non-blocking, but you don't introduce any way of timing code. This way the calculation of the new color values happens as fast, as the code can run. You can write timed action in a non-blocking way by using the coding style from the `BlinkWithoutDelay` example, that comes with the Arduino IDE. Then the LED code will only be executed, if the correct time has come. You save a timestamp of the last calculation execution in a global variable and then check, if enough time since then has passed. Only then you again execute the calculation and update your timestamp.

```
unsigned long timestamp = 0;
unsigned int interval = 10;

void loop(){
    //--------
    // Omitted the servo code
    //--------
    if(millis() - timestamp > interval){
        timestamp += interval; // update the timestamp to the next value
        //--------
        // Omitted the calcuation and the LED update (show() method)
        //--------
    }
}

```

Note, that here I used `millis()`, which will return the number of milliseconds, that passed since the Arduinos startup. I used an interval of 10 milliseconds, so that the LEDs will be updated every 10 milliseconds. You can change this value as you need it (also during the code execution). If you need faster execution, than a few milliseconds, you can use `micros()` instead of `millis()`, so that you work with microseconds. Of course, you cannot get faster, than the rest of the code runs.

For further explanation of this principle, you can google it. It has been described numerous times on the web and on this site.

---
Tags: servo, rgb-led, neopixel
---


# Question
Title: 16-Channel 12-bit PWM/Servo Shield check if it is powered by adapter
I'm using Adafruit 16-Channel 12-bit PWM/Servo Shield with Arduino Uno controller

In `setup()` I have a number of default positions with PWM commands for motors with plug of USB to PC and turning on

I'm trying to figure out, how to avoid `setup()` commands, or any other signals during process to servos, in case if shield is not powered from power adapter, which is 6V 8Amp in my case, to not send signal to servo while it is not powered by power supply

# Answer
I would propose a circuit like the following:

simulate this circuit – Schematic created using CircuitLab

The voltage divider (consisting of the resistors) will divide the 6V to 5V for the Arduinos digital input. The values are not critical, they can be made higher, but maintain the relationship to still get the 5V. The diode will prevent current to flow from the shield into the voltage divider, when the shield is powered through other means. Now you can simply do a `digitalRead()` on the corresponding digital input pin of your Arduino, to check, if the power was applied.

---

Please notice, that the diode will reduce the voltage a little by it's forward voltage (depends on the diode). But that shouldn't be a big problem.
> 0 votes

---
Tags: pwm, servo, arduino-uno
---


title: RGB LED circuit problem

text:
# Question
Title: RGB LED circuit problem
I have written the following code for RGB LED:-

```
const int RED =11;
const int GREEN = 10;
const int BLUE= 9;
void setup() {
  pinMode(RED,OUTPUT);
  pinMode(GREEN,OUTPUT);
  pinMode(BLUE,OUTPUT);
}

void loop() {
  analogWrite(RED,0);
  analogWrite(GREEN,255);
  analogWrite(BLUE,0);
  delay(1000);
}

```

Now according to my understanding if I run the above code then only pin named `GREEN` i.e. 10th pin will give me current not 9, 11th pin. But when I upload the code and run it I see that 9 and 11 pin are giving me current not 10th pin as it is supposed to. Is there a problem in my code? I have checked my circuits are correct. To check current I took jumper wire that was connected to one of my colour and tried inserting it's other end at pins(9, 10 or 11) of Arduino board. If there is current bulb will glow. For above code the bulb was glowing when I inserted the wire at 9 and 11th pin.

# Answer
A common anode RGB LED can be sketched in a schematic like this:

simulate this circuit – Schematic created using CircuitLab

The positive voltage has to be applied to the top, for all the LEDs together. To light the LEDs up, you have to sink the current on the other end, meaning providing ground level at the bottom of that schematic at the corresponding pins. The current will then flow from your 5V pin, through the LEDs into the Arduinos pin.

That means, that `analogWrite(pin, 0)` will turn the LED on that pin ON and `analogWrite(pin, 255)` will turn the LED OFF. The logic is inverted here, because the Arduinos output pin is on the other side of the LED.

So your circuit and code work perfectly, you just didn't expect the inverted logic.

---

Note: The pins of the Arduino can only source/draw a certain amount of current (20mA continuously, 40mA at maximum) without getting damaged. A single, not too strong RGB LED should be OK, but as soon, as you want to drive more LEDs, you should consider using a driver circuit (for example simple transistors). That way the output pins don't have to provide the LEDs current, but only the current to control the transistor.
> 1 votes

---
Tags: arduino-uno, code-review, rgb-led
---


# Question
Title: Atmega328p and cp2102 with error avrdude: stk500_getsync(): not in sync: resp=0x00
I recently bought a usb/ttl cp2102 converter for testing with a standalone Atmega328p, I made the DTR connection with the pin 1 in the Atmega using a ceramic capacitor of 0.10uf (104) so that when I send my code to my Atmega standalone it save the code without having to worry about the reset. However, when trying to send it the first time it worked and the other attempts failed, it seems that whenever I restart the computer and turn it on again it sends the code to the Atmega and in the other attempts it fails. To try to solve I tested with IDE Arduino 1.8.5 and 1.8.9 in Linux Mint and Windows 10 and gave the same problem, I recorded the bootloader again and did not solve.

The error that appears in the output of the IDE is this:

```
avrdude: stk500_getsync(): not in sync: resp=0x00

```

From what I read, this error is generic and hardly helps to solve the error.

# Answer
> 0 votes
Researching a little and found the solution! In addition to capacitor 104, its necessari need to add a 10k resistor by connecting the 5 volts to pin 1.

This is the link of the GitHub project where I found the solution with the assembly scheme, I hope this helps somebody else!

https://github.com/leonvandenbeukel/Arduino-on-a-breadboard/blob/master/README.md

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


# Question
Title: Aruino RTC using rtclib not understanding functions
I am missing something fundamental using RTClib.
When I use the rtc.adjust function to change the time in the RTC, I cannot get the updated time from the RTC, just increments a fixed time. I have searched for examples for what I need, and the same few samples of code keep getting quoted.

I want my code to set the RTC at compile to the system time, which it does, then in the Loop I want to increment the hour. In reality I will use a button for this, but for now I am just trying to understand how DateTime now = rtc.now and rtc.adjust work. How to write to the RTC, how to read it back. I am missing something regarding these variables.

Two version of my code. One with output showing the clock working, and one where the output is static, just increments the hour.

**This one works:**

```
#include <RTClib.h>
#include <Wire.h>
int ArduinoHour;
int ArduinoMin;
int ArduinoSec;
RTC_DS1307 rtc;

void setup()
{
  Serial.begin(250000);
  Wire.begin();  //sets up the I2C
  rtc.begin();   //initializes the I2C to the RTC

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }
    if (rtc.isrunning()) {
    Serial.println("RTC IS running!");
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }
}
void loop()
{
  DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

  ArduinoHour = now.hour();
  ArduinoMin = now.minute();
  ArduinoSec = now.second();

  Serial.print("AT TOP");
  Serial.println();
  Serial.print("RTC Time");
  Serial.println();
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  Serial.println();
  delay(1000);

  Serial.print("Arduino Time");
  Serial.println();
  Serial.print(ArduinoHour, DEC);
  Serial.print(':');
  Serial.print(ArduinoMin, DEC);
  Serial.print(':');
  Serial.print(ArduinoSec, DEC);
  Serial.println();
  Serial.println();
  delay(1000);

  //RTC increments when these are commented out. Does not when active
  //ArduinoHour = ArduinoHour +1;
  //rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

}

```

Here is the output. Looks fine:

```
RTC IS running!
AT TOP
RTC Time
11:38:3

Arduino Time
11:38:3

AT TOP
RTC Time
11:38:5

Arduino Time
11:38:5

AT TOP
RTC Time
11:38:7

Arduino Time
11:38:7

AT TOP
RTC Time
11:38:9

Arduino Time
11:38:9

```

***This one does not Work:*** Now I try to simply increment variable ArduinoHour and then write it to the RTC using rtc.adjust. ***The only change are the two lines at the bottom are uncommented.***

```
#include <RTClib.h>    //https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code
#include <Wire.h>

int ArduinoHour;
int ArduinoMin;
int ArduinoSec;

RTC_DS1307 rtc;

void setup()
{
  Serial.begin(250000);
  Wire.begin();  //sets up the I2C
  rtc.begin();   //initializes the I2C to the RTC

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }
    if (rtc.isrunning()) {
    Serial.println("RTC IS running!");
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop()
{
  DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

  ArduinoHour = now.hour();
  ArduinoMin = now.minute();
  ArduinoSec = now.second();

  Serial.print("AT TOP");
  Serial.println();
  Serial.print("RTC Time");
  Serial.println();
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  Serial.println();
  delay(1000);

  Serial.print("Arduino Time");
  Serial.println();
  Serial.print(ArduinoHour, DEC);
  Serial.print(':');
  Serial.print(ArduinoMin, DEC);
  Serial.print(':');
  Serial.print(ArduinoSec, DEC);
  Serial.println();
  Serial.println();
  delay(1000);

  //RTC increments when these are commented out
  ArduinoHour = ArduinoHour +1;
  rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

}

```

Here is the output, RTC time is not changing. I know I am doing something basically wrong with how I am updating the variables writing/reading from the RTC. Can't figure it out.

```
RTC IS running!
AT TOP
RTC Time
11:41:54

Arduino Time
11:41:54

AT TOP
RTC Time
12:41:54

Arduino Time
12:41:54

AT TOP
RTC Time
13:41:54

Arduino Time
13:41:54

AT TOP
RTC Time
14:41:54

Arduino Time
14:41:54

```

# Answer
If by "RTC time is not changing" you mean minutes and seconds frozen at the same value, then this is entirely of your doing.

Your sketch spends 99% of the time between the initial `rtc.now()` request

```
 DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

```

and the final `rtc.adjust()` call

```
rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

```

This period is the period when your RTC is supposed to be "ticking", progressing forward.

But you actually store the original minutes and seconds values in `ArduinoMin` and `ArduinoSec` at the beginning of this period. And later, at the end of this period, you bash these values back into the clock. By doing this you forcefully *erase* whatever progress the clock made between these two lines. No wonder your minutes and second do not change.

This problem actually has no perfect solution. `RTC_DS1307` class (and, I suspect, the underlying RTC hardware) provide no means to change just the hours value without disrupting minutes and seconds. When you call `adjust()`, you have to set everything, which means that you will always somehow "disrupt" the whole clock.

In your sketch you can *minimize* the adverse effects by re-requesting the minutes and seconds values right before doing `adjust()`:

```
//RTC increments when these are commented out
ArduinoHour = ArduinoHour +1;
now = rtc.now();
rtc.adjust(DateTime(now.year(), now.month(), now.day(), ArduinoHour, now.minute(), now.second()));

```

Note, that I'm using your updated `ArduinoHour` values, but everything else comes from a just-refreshed `now` object.

This is still not perfect, since it still suffers from a race condition against a real-time clock, but it is better than what you had originally.
> 0 votes

# Answer
This is the content of `ajust` method:

```
void RTC_DS1307::adjust(const DateTime& dt) {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire._I2C_WRITE((byte)0); // start at location 0
  Wire._I2C_WRITE(bin2bcd(dt.second()));
  Wire._I2C_WRITE(bin2bcd(dt.minute()));
  Wire._I2C_WRITE(bin2bcd(dt.hour()));
  Wire._I2C_WRITE(bin2bcd(0));
  Wire._I2C_WRITE(bin2bcd(dt.day()));
  Wire._I2C_WRITE(bin2bcd(dt.month()));
  Wire._I2C_WRITE(bin2bcd(dt.year() - 2000));
  Wire.endTransmission();
}

```

You can write new `Hour` value directly to the clock without erasing other clock data:

```
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire._I2C_WRITE((byte)2); // Hour location
  Wire._I2C_WRITE(bin2bcd(ArduinoHour));
  Wire.endTransmission();

```
> 0 votes

---
Tags: rtc
---


# Question
Title: How to send and receive unsigned int from one arduino to another arduino
I'm trying to send some big numbers ranging from 0-62000 from one arduino to another via serial communication. I'm using unsigned int to hold values from 0 to 65535. And I'm using serial.print() and serial.write () to send numbers and serial.read()-'0' ; to receive numbers, but I'm unable to send and receive numbers above 9. Please help me.

Here is my code -

(For master)

```
const int Button_1 = 2;
unsigned int s =0;
void setup ()
{
   Serial.begin(115200) ;
   pinMode(Button_1,INPUT);
}
void loop()
{
  if (digitalRead(Button_1))
  {
     s = 61805;
     Serial.write(highByte(s)) ;
     Serial.write(lowByte(s));
     delay (5);
     s=0;
  }
  else
  {
     s = 60005;
     Serial.write(highByte(s)) ;
     Serial.write(lowByte(s));
     delay (5);
     s=0;
  }
}

```

(code for slave)

```
unsigned int upperByte, lowerByte, r=0,p=0;
void setup()
{
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT) ;
}
void loop ()
{
  If (Serial.available()>1)
  {
     upperByte = Serial.read();
     lowerByte = Serial.read();
  }
    r = (upperByte << 8) + lowerByte ;

   while (r==61805)
    {
        digitalWrite(LED_BUILTIN, HIGH) ;
    }
    while (r==60005)
    {
        digitalWrite(LED_BUILTIN, LOW) ;
    }
}

```

# Answer
There are 2 ways to transmit data over serial: As byte data or in ASCII codes

1. **Byte data:** Everything, that is digitally stored or processed, is a series of 0s and 1s (bits) (electrically HIGH and LOW level), which are grouped into bytes (8 bits). So all data is just numbers at low level. The different datatypes (like numbers, Strings, executable code) are only reached by different interpretation of the byte data. You can take the number value of a byte directly. A byte like `0b00000101` for example is equivalent to the decimal value `5`. So every byte can hold numbers between 0 and 255. (Google the binary system for more information). To hold bigger numbers, more bytes are put together. For example an integer consists of 2 bytes (16 bits) and can hold numbers between 0 and 65535. Note: These are the unsigned types. There are also signed types, that also can hold negative values. To understand this, google binary two's complement. To transmit such a bigger type over serial (which is byte based), you need to seperate the bytes of the type, send them consecutively and put them back together at the receiving side. You can do this with the following code:

```
unsigned int number = 54321;
Serial.write(number & 0xFF); //getting the lower byte of the number by using bitwise AND
Serial.write(number >> 8); // getting the high byte of the number by shifting the bits of the value 8 bits to the right

```

There are macros defined for Arduino, that can do this for you:

```
Serial.write(lowByte(number));
Serial.write(highByte(number));

```

In long term, you should learn, how the bitwise operators work. They are often needed. To put the data back together, you can look at CrossRoads answer.

Note: `Serial.write()` will send the byte data unchanged, while `Serial.print()` will convert the data to ASCII before sending. They are not equal.
2. **ASCII Data:** One interpretation of byte data is the ASCII standard (which is really old). Every byte value between 0 and 127 get's a corresponding ASCII value, meaning characters of the alphabet, digits, some special characters and some control characters. Numbers, that are transmitted as ASCII data, consist of multiple bytes, one for each digit. Thats, what you tried. Since the receiver has to seperate the different numbers to process them correctly, you have to mark the end of each number. This is commonly done with the newline character `\n` (optionally preceeded by the carriage return character `\r`, windows style). You add this at the end of every number. `Serial` has an extra function for that: `Serial.println()` will print the parameter as ASCII and will add a carriage return and newline character. On the receiving side you read the bytes into a buffer, until you see this delimiter sequence. After that, you process the whole buffer. If you want to know, how this Serial communication is done in code, look at the `SerialEvent` example, that comes with the Arduino IDE.

What way you use for transmitting data, is up to you and depends on your needs. If you only want to transmit number data, nothing else, you can use byte data. For complex or diverse data types, you can use the ASCII representation.

---

EDIT: I have described above, that - when using ASCII data - you can use one or more special characters to delimit one message/number. The receiver can then distinguish between the numbers in that row of digits. This is just some kind of protocol, that you impose on the data. You state, that every message is ended with this special character, much like very sentence in the english language is ended with a dot.

An important requirement is, that the special character does not occure inside of a message/number. So cannot use the character `'1'` as delimiter, since it will also occur inside of your numbers and you would chop the numbers in the wrong way.

The same principle can be imposed as protocol onto a byte stream. For example: You define, that every message/number will be ended with a special byte sequence, so that the receiver always can say: "This is the whole data of a number and not just a part of it." As above, the special byte sequence must not occur inside of the valid data. You wrote, that your numbers are always in the range of 0 to 62000. This means, that the value 65535 will never occur as valid data, thus you can use it as delimiter. In hex 65535 is written als `0xFFFF`, which means, that you send two bytes with every bit set to 1 (each byte having a decimal value of 255). In your code everytime, that you are receiving something, you can check, if you have got 2 consecutive bytes with the value 255 (or written as `0xFF`). If not, write the data into a buffer. If yes, that means, that you can process the data inside the buffer to a number.

For sending that would look like this:

```
Serial.write(lowByte(number));
Serial.write(highByte(number));
Serial.write(0xFF);
Serial.write(0xFF);

```

Note: This protocol will make sure, that sender and receiver cannot get out of sync. But still the first reading after a transmission problem (for example that a byte got send before the receiver was ready) will be garbage. That will happen very very rarely, so for most people it's not a problem. There are more principles, that you can use in your protocol to mitigate those problems, if you want to. For example you can define another special byte sequence as the start of a message/number. Or you can calculate a checksum of the number and only use messages/numbers, that fit to that checksum.
> 3 votes

# Answer
Try something like this to send and receive/recombine two bytes:

Send side:

```
Serial.write (highByte (your unsigned int));
Serial.write (lowByte (your unsigned int));

```

Receive side:

```
if (Serial.available() >1){ // two byte received
upperByte = Serial.read();
lowerByte = Serial.read();
}
newInt = (upperByte <<8) + lowerByte;

```
> 1 votes

---
Tags: arduino-uno, serial, arduino-nano
---


title: Septic tank project

text:
# Question
Title: Septic tank project
We are to make a project.We have to connect MQ7, buzzers and lights to Arduino. And one buzzer will make sound when gas reaches high level and another buzzer will beep when gas level is very low.. High gas amount will lead to red light glow and very low gas will lit green light.. HOW TO EXECUTE ??

# Answer
> 2 votes
Easy, this is one of the simple projects used as an introduction to Arduino programming. You will find many versions of free code out there. below is an example and a total newbie step-by-step.

Download Arduino IDE. Buy an MQ7, an Arduino or NodeMCU, a breadboard, a LED and some jumper wires and you are in business. Use the sketch below or google "MQ7 arduino sketch".

```
/* MQ-7 Carbon Monoxide Sensor Circuit with Arduino */

const int AOUTpin=0;//the AOUT pin of the CO sensor goes into analog pin A0 of the arduino
const int DOUTpin=8;//the DOUT pin of the CO sensor goes into digital pin D8 of the arduino
const int ledPin=13;//the anode of the LED connects to digital pin D13 of the arduino

int limit;
int value;

void setup() {
  Serial.begin(115200);//sets the baud rate
  pinMode(DOUTpin, INPUT);//sets the pin as an input to the arduino
  pinMode(ledPin, OUTPUT);//sets the pin as an output of the arduino
}

void loop() {
  value= analogRead(AOUTpin);//reads the analaog value from the CO sensor's AOUT pin
  limit= digitalRead(DOUTpin);//reads the digital value from the CO sensor's DOUT pin
  Serial.print("CO value: ");
  Serial.println(value);//prints the CO value
  Serial.print("Limit: ");
  Serial.print(limit);//prints the limit reached as either LOW or HIGH (above or underneath)
  delay(100);
  if (limit == HIGH){
    digitalWrite(ledPin, HIGH);//if limit has been reached, LED turns on as status indicator
  } else {
    digitalWrite(ledPin, LOW);//if threshold not reached, LED remains off
  }
}

```

original sketch published by Learning About Electronics

---
Tags: sensors
---


# Question
Title: Error compiling for any board arduino ide 1.8.9
my arduino ide Until yesterday it worked properly . but today All previous projects dont compiling and all of them have one error : Error compiling for board and It's no different that Which board I choose in all of board i have this error . please help me .

image link : http://uupload.ir/files/6hjr\_capture1.jpg error : * Error while detecting libraries included by C:\Users\ali\_m\AppData\Local\Temp\arduino\_build\_706504\sketch\timer.ino.cpp

* xtensa-lx106-elf-g++: error: CreateProcess: No such file or directory
* Error compiling for board NodeMCU 1.0 (ESP-12E Module).

# Answer
I hope this link helps you or please try a fresh install.
> 0 votes

---
Tags: arduino-ide, compilation-errors
---


# Question
Title: How to connect L298N motor driver to 5v input supply?
I'm trying to connect 5v supply to a L298N motor driver at it's 12V-35V input pin but it's not working. If I'm connecting to 7.2V supply it's working. Is there any way to connect 5v supply? I want a constant 5v at output pins for motors.

# Answer
Note: Since all vendors (checked Mouser, Octopart, and Sparkfun) link to the L298 datasheet when listing the L298N I will assume they are reasonably equivalent.

I will assume that the "*12V-35V input pin*" is the V\_S pin, despite that label. There are only two supply pins on the L298 with the following electrical characteristics:

* V\_S, Supply Voltage, pin 4, Operative Condition V\_IH + 2.546V (max.: 46V)
* V\_SS, Logic Supply Voltage, pin 9, typical 5V (min.: 4.5V, max.: 7V)

with

* V\_IH, Input High Voltage, ranging from 2.3V to V\_SS

Which would explain that the circuit works at 7.2V under the assumption that the logic inputs (enable A and B as well as inputs 1 through 4) are at close to 5V high levels. And here's the trick that might make it work: as noted V\_S (the supply voltage) needs to be at a level of V\_IH + 2.546V while V\_IH could be as low as 2.3V and 2.3V + 2.546V \< 5V. So driving the L298's logic inputs with a lower voltage for logic 1, i.e. closer to 2.3V high levels, could help.

Why is this? (source):

> \[..\] The actual restriction is that the motor supply be somewhat greater than the logic "1" input, but that need not match the logic supply. \[..\]

A warning though:

* this circuit is now operating at the fringes, one might call it shady at best, intolerable at worst
* saturation voltage is related to output current and other parameters, e.g. temperature, so this might work now under certain conditions and fails horribly another day

---

Therefore better bets are:

* use a higher supply voltage
* ditch the L298 and its high voltage drop Darlingtons and use a MOSFET H-bridge motor driver, such as the TB6612FNG, see also
* ditch the L298 and use single bipolar transistors, depending on the output current

---

Other things to check:

Make sure V\_SS is connected to the logic supply voltage (see AnT's comment). Make sure GND of the Arduino's power supply is connected to the L298's GND.
> 3 votes

---
Tags: motor, voltage
---


title: Connecting multiple RS485 together

text:
# Question
Title: Connecting multiple RS485 together
I am trying to build communication across multiple Arduino using RS485. When i am trying to connect 3 Arudino nano together using breadboard my code doesn't reach slave where as if i just if i do direct connection between 2 RS485 without breadboard it works but i use breadboard for 2 it doesn't work. Am i missing any setup here?

Breadboard connection - A & B are connected to + & - of both RS485.

Working connection - A & B of first RS485 connected to A & B of 2nd RS485.

# Answer
> 3 votes
It is possible you have too many resistors on the RS485 bus. From the RS485 wikipedia page there is this quote:

> Ideally, the two ends of the cable will have a termination resistor connected across the two wires.

This may explain why you can use 2 of your RS485 interfaces but not 3. Consider removing the resistors from the RS485 board in the middle if possible.

---
Tags: arduino-nano, rs485
---


# Question
Title: How to control 2 servos at same time in sync?
For overcoming torque issues, I have attached 2 *identical* servos on a certain part of my robot arm and because I saw someone do the same.

Now, while writing code I realize:

```
#include <Servo.h>
...
...
shoulder1.write(map(analogRead(p1), 0, 1023, 0, 179));
shoulder2.write(map(analogRead(p1), 0, 1023, 0, 179));
...

```

will turn `shoulder1` by 20\* and then `shoulder2` by another 20\*, ie. an overall turn of 40\*; that too with too much load on servos, as the other servo would be inactive at the time first is active.

I want to achieve 20\* fully-sync.ed turn on both servos, how do I accomplish this? Any arduino libraries or walkthrough?

---

Can I possibly move them both at the same time \- something like multithreading on arduino? Here's what I tried:

```
void rotateTwoServoInSync(int angle) {
    for(int i = 0; i<angle; i++) {
        shoulder1.attach(9);
        shoulder1.write(i);
        shoulder1.detach();
        shoulder2.attach(10);
        shoulder2.write(i);
        shoulder2.detach();
    }
}

```

Will it work? Is this approach recommendable?

# Answer
If you have two RC servos that are always required to move together you can simply connect both control inputs to a single output.
> 5 votes

# Answer
Spehro's answer is the most obvious. But note that there is no such thing as identical servos. You may stress them if you connect them through a stiff connection.

If you want to have two mechanical parts make the same movement the proper solution is to connect them mechanically, rather than have two servos doing the same action.
> 3 votes

# Answer
`analogRead()` and `map()` are slow; only perform them once.

```
unsigned char rot = map(analogRead(p1), 0, 1023, 0, 179);
shoulder1.write(rot);
shoulder2.write(rot);

```
> 0 votes

# Answer
To operate two or more servos at the same time you need to interpolate their movements, first moving one servo a little, then moving the next one, back and forth until all servos arrive at their destination point. I haven't seen a library yet that accomplishes this for you so you probably need to write your own routine. Here is a project where I interpolated three servos and includes the code: https://www.instructables.com/id/MonkeyBot-3-Servo-Climbing-Robot/
> 0 votes

---
Tags: programming, servo
---


# Question
Title: How to read high voltage (40-65v) from a Solar Battery bank
I would like to monitor the battery voltage of a 48v solar battery system. The **expected voltage range is 40-65v**.

I have tried creating a voltage divider with 2 resistors but with all values I have tried one resistor almost melts as soon as you connect to battery.

Also, using a voltage divider creates a (small) drain which I would like to avoid.

Can anyone suggest a way of reading high DC voltage (40-65v) with and Arduino (really I'm using an ESP8266)?

**If Voltage Divider**

please suggest resistor types (e.g. 1/4watt or 1-2% etc, I'm new here but know there are many types) and values that I could read with A0 (analog pin, max 5v)

Can I use a MOSFET to connect the voltage divider just before reading the voltage? How?

**or another way**

like a circuit (from AliExpress) or using some other component that would be greatly appreciated.

So far this article has been helpful, it talks about a voltage divider with a opamp to get more accuracy, but I need a bit more advice from someone that knows more than myself.

https://openenergymonitor.org/forum-archive/node/11011.html

Thanks in advance for any help.

# Answer
> 5 votes
**You need a voltage divider with resistors that have large values.**

> ...but with all values I have tried one resistor almost melts as soon as you connect to battery.

This suggests that you have been using values that are too low.

So lets go through the calculations to select good resistor values.

1/4 Watt resistors are common and easily available so I will base my calculations on that. These calculations will also be suitable for 1/2 Watt and 1 Watt resistors.

I am also going to add some margin above the 65V max that the solar panel can output (plus it makes the math easier)

Max Voltage = 100V

---

The voltage Divider:

Let's simplify. Almost all of the current will be going from your source, through the resistors (R1 & R2) to ground. Let's simplify by initially calculating the resistance required if R1 & R2 were combined into a single resistor:

From V = I x R
And P= V x I

Minimum resistor = V^2 / P

R = 75^2 / 0.25

R = 22500 Ω minimum

I would go further and say double that because I never like operating a resistor right on its maximum power rating. ie the minimum that R1 + R2 should equal is 50kΩ.

Lets play it safe and say that R1 + R2 is 100kΩ. The ESP8266 ADC pin input voltage range is 0 to 1V. Input is 0-100 V (which covers the required 40-65V range). Now all we have to do is calculate for R1.

**Note:** Most ESP8266 development boards come with an internal voltage divider. For these boards the input range is 0 to 3.3V.

**Edit:** The OP tells me that they get a max analog reading at 3.0V not 3.3V. Adjust the below calculations for an input voltage of 3.0V not 1V.

The formula to calculate the output voltage is:

Vout / Vin = R2 / (R1 + R2)

1 / 100 = R2 / 100kΩ

0.01 = R2 / 100k

Therefore R2 = 1k Ω

R1 = 100k - R2 = 99kΩ

I would up R1 to 100kOmega; as it will only result in a 1% error.

So R1 = 100kΩ and R2 = 1kΩ

---

Values of R1 = 49.5kΩ and R2 = 500Ω would also work.

In this case R1 could be made up of 2-3 resistors in series:
47KΩ
2.2KΩ
300Ω or 330Ω (optional)

---

The raw ADC input on the ESP8266 chip is 0-1V with a high input impedance (~20M). This means an op-amp buffer is not needed.

However, if you are interested, a op-amp circuit can be built from a 741 IC (among others) and is configured like this:

# Answer
> 3 votes
It sounds as if you have tried using far too small a value resistors. For example, if you used resistors totaling , say, 1,000 ohms across a 50V supply then they would dissipate V^2/R watts = 2.5W. Standard 1/4 watt resistors are going to melt when overloaded 10 times.
So it boils down to picking a pair of resistors that
1) Are working within their wattage rating.
2) Give a convenient scaling factor.
3) Draw an insignificant amount of current relative to the ratings of the solar panels.
The design of any voltage divider also depends on the input impedance or load imposed by the ESP8266. Referring to the ESP8266 Community Forum the analog input imposes a 50nA load, but they also state that the maximum input voltage is only 1V (equivalent to 20 M ohm impedance). The Adafruit forum also suggests that 1V is the maximum. Maybe the board you have has different built in scaling.
For the sake of argument, let us assume the following
Voltage range to be measured = 40 - 65V
Maximum input voltage of pin A0 = 1V
Pin A0 can draw 50nA and this should not effect the measurement by more than 1 in 2048 (half the least significant bit of the ADC).
The current through the voltage divider should therefore be at least 2000 * 50nA = 0.1 mA. This almost certainly meets the requirement of not significantly loading the battery. So based on the low end of the voltage range the divider chain should total in the region of 45V / 0.1mA = 450K ohms. The two resistors need to be in the ratio 64:1 in order to drop a 65V input to 1V. Referring to standard resistor values, 360K and 5K6 in series will be very close to 64:1 (64.28:1). They will draw a maximum of 65V/(360K + 5K6) = 0.18mA and the 360K resistor will dissipate about 10mW.
So standard quarter watt E24 series 1% resistors should be suitable.

---
Tags: esp8266, battery, voltage-divider
---


# Question
Title: How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino?
How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino?

I am a beginner and I need help on how to control two 12 V motors using the Pololu dual MAX 14870 Motor Drive Shield for Arduino Uno.

# Answer
I had attached the screenshot for this

This picture tells you about the Arduino Connection with the with the SHIELD.

1. `EN (Enable Pin)` is used to enable and disable the motor drivers. As it is inverted `SET this PIN HIGH` will Disable the Motors and vice versa.
2. `DIR pinS` is used direction of rotation. It highly depends upon your connection, setting this `PIN HIGH LOW` will make the motor rotation from `CLOCKWISE & ANTI CLOCKWISE` or vice versa depends upon your hardware connection.
3. `PWM pins` are used to control the rotation speed of the MOTOR. `Driving PWM signal` on this pin will adjust your rotational speed. `MAX PWM frequency suggested is 50Hz`.
4. `Fault` is the `INPUT PIN to Arduino` with `ACTIVE LOW` signal indicating some kind of fault is there.
> 1 votes

---
Tags: arduino-uno
---


title: Arduino Program Memory Ran Out

text:
# Question
Title: Arduino Program Memory Ran Out
I have a Arduino sketch I made and I have run out of dynamic memory on my Arduino Nano. How could I possibly reduce the amount of memory the program takes? (I'm not that good at this stuff)

P.S: The code is here:

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

const int chipSelect = 4;

#define OLED_RESET 5
Adafruit_SSD1306 display(OLED_RESET);

#if (SSD1306_LCDHEIGHT != 64)
#error("Fix Height");
#endif

/********************************************/

#define CHARWIDTH           5
#define CHARHEIGHT          8
#define AXISWIDTH           (2 + 1)
#define VISIBLEVALUEPIXELS  (128 - AXISWIDTH)
#define NUMVALUES           (2 * VISIBLEVALUEPIXELS)

#define TRIGGER_ENABLE_PIN       2
#define SCREEN_UPDATE_ENABLE_PIN 3

byte values[NUMVALUES];
int pos = 0;
int count = 0;
unsigned long readStartTime = 0;
int sampleRate = 1;

void displayln(const char* format, ...)
{
  char buffer[32];

  va_list args;
  va_start(args, format);
  vsprintf(buffer, format, args);
  va_end(args);

  int len = strlen(buffer);
  for (uint8_t i = 0; i < len; i++) {
    display.write(buffer[i]);
  }
}

// Draws the graph ticks for the vertical axis
void drawAxis()
{
  // graph ticks
  for (int x = 0; x < 2; x++) {
    display.drawPixel(x,  0, WHITE);
    display.drawPixel(x, 13, WHITE);
    display.drawPixel(x, 26, WHITE);
    display.drawPixel(x, 38, WHITE);
    display.drawPixel(x, 50, WHITE);
    display.drawPixel(x, 63, WHITE);
  }
}

// Draws the sampled values
void drawValues()
{
  int start = 0;

  if ( digitalRead(TRIGGER_ENABLE_PIN) ) {
    // Find the first occurence of zero
    for (int i = 0; i < NUMVALUES; i++) {
      if ( values[i] == 0 ) {
        // Now find the next value that is not zero
        for (; i < NUMVALUES; i++) {
          if ( values[i] != 0 ) {
            start = i;
            break;
          }
        }
        break;
      }
    }
    // If the trigger point is not within half of our values, we will
    // not have enough sample points to show the wave correctly
    if ( start >= VISIBLEVALUEPIXELS )
      return;
  }

  for (int i = 0; i < VISIBLEVALUEPIXELS; i++) {
    display.drawPixel(i + AXISWIDTH, 63 - (values[i + start]), WHITE);
  }
}

// Shows the time taken to sample the values shown on screen
void drawFrameTime(unsigned long us)
{
  display.setCursor(9 * CHARWIDTH, 7 * CHARHEIGHT - 2); // almost at bottom, approximately centered
  displayln("%ld us", us);
}

/********************************************/

void setup() {

  // Set up the display
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Initialize with the I2C addr 0x3D (for the 128x64)
  display.setTextColor(WHITE);

  pinMode(TRIGGER_ENABLE_PIN, INPUT);
  pinMode(SCREEN_UPDATE_ENABLE_PIN, INPUT);
    // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("init start");

  if (!SD.begin(chipSelect)) {
    Serial.println("fail");
    // don't do anything more:
    while (1);
  }
  Serial.println("init ok");
}

/********************************************/

void loop() {

  // If a sampling run is about to start, record the start time
  if ( pos == 0 )
    readStartTime = micros();

  // If this iteration is one we want a sample for, take the sample
  if ( (++count) % sampleRate == 0 )
    values[pos++] = analogRead(0) >> 4; // shifting right by 4 efficiently maps 0-1023 range to 0-63

  // If we have filled the sample buffer, display the results on screen
  if ( pos >= NUMVALUES ) {
    // Measure how long the run took
    unsigned long totalSampleTime = (micros() - readStartTime) / 2;     // Divide by 2 because we are taking twice as many samples as are shown on the screen

    if ( !digitalRead(SCREEN_UPDATE_ENABLE_PIN) ) {
      // Display the data on screen
      display.clearDisplay();
      drawAxis();
      drawValues();
      drawFrameTime(totalSampleTime);
      display.display();
    }

    // Reset values for the next sampling run
    pos = 0;
    count = 0;
  }
  String dataString = "";

  // read three sensors and append to the string:
  for (int analogPin = 0; analogPin < 3; analogPin++) {
    int sensor = analogRead(analogPin);
    dataString += String(sensor);
      dataString += ",";
  }

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
}

```

# Answer
> 1 votes
## Few things to consider :

* Each variable in your program take memory, try to use the smallest datatype ( don't use a float if you need an int for example).
* Eliminate strings
* Reduce the usage of array
* Reduce your code size by using function for redudant task
* Avoid using digital and analog red/write. Use port manipulation instead (link here)
* Modify library to remove unused code inside
* Use ICSP programmer instead of serial bootloader
* Simplify your code for reducing its size.

## Or simply ...

Use another board such as STM32 ou bigger ATmega chip with more RAM and bigger ROM size ...

---
Tags: atmega328, memory, progmem
---