body:
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.

title: esp8266 deep sleep timer slightly inaccurate?

Answers: 2

body: Yes a RTC can be very inaccurate. Some RTCs will let you synchronise them.

body:
A (now 3 year old) [GitHub thread][1] 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][2].  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][3] goes into detail using a DS3231 Real Time Clock.

  [1]: https://github.com/esp8266/Arduino/issues/2635
  [2]: https://gitlab.fionabuckner.xyz/fiona/nodemcu-firmware/blob/1.5.4.1-final/docs/en/modules/rtctime.md
  [3]: https://arduino.stackexchange.com/a/91504/78174


body:
I am trying to read every sequenced-byte that is located on a txt file in the SD card. I have been reading quite a lot about the SPI and SD libraries, But I have found a lot of different information that makes me feel confused.

1. Is it really possible to read information byte per byte without buffering by default as usually happens when you use the SD or SDFat? Do you know a Library that makes it really possible?

2. Also, I found on the SDFile.cpp that is located in the src folder in the SD library, a part that mentions " // no buffering needed if n == 512 or user requests no buffering" How is it possible to request no buffering? I found the unbufferedread() function but I am afraid that this actually reads the number of bytes and not the information on the bytes (Is it possible?).

   Do you know where may I found examples of this kind of low level functions for me to find out How may I use them  for the mentioned purpose. Or a library that would make my life easier in order to get the unbufferred read.
I want a continuous data sending into a DAC, that's why I am trying no to get the unbufferred in order to make all the data's sent as continuous as possible.

Sorry for making so many questions, I just started to use Arduino a couple of months ago  so I am not that familiarized with all the terms.

Thanks for your advise.

title: Reading byte per byte from a txt file on SD Card without using the 512Bytes buffer

Answers: 0


body: 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.

title: How to connect L298N motor driver to 5v input supply?

Answers: 1

body:
Note: Since all vendors (checked Mouser, Octopart, and Sparkfun) link to the [L298 datasheet](https://www.sparkfun.com/datasheets/Robotics/L298_H_Bridge.pdf) 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](https://electronics.stackexchange.com/questions/40204/l298-h-bridge-not-working#comment1079863_195389)):

> [..] 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](https://www.sparkfun.com/products/14451), see [also](https://electronics.stackexchange.com/a/21225/52154)
 * 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](https://arduino.stackexchange.com/questions/65535/how-to-connect-l298n-motor-driver-to-5v-input-supply#comment139637_65535)). Make sure GND of the Arduino's power supply is connected to the L298's GND.


body:
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.

Answers: 2

body:
For X and Y values between -64 and 64, consider multiplying the X and Y values you are passing to the method [mouse.move()][1] 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][2].  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.

  [1]: https://www.arduino.cc/reference/en/language/functions/usb/mouse/mousemove/
  [2]: https://github.com/arduino-libraries/Mouse

body:
[The USB HID protocol for mouse][1] 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);
      }
    }

  [1]: https://wiki.osdev.org/USB_Human_Interface_Devices#Report_format_2


body:
Im trying to send temperature sensor data through NRF24L01 to Raspberry Pi and read it in Raspberry Pi using python. But the temperature sensor data comes to the Raspberry Pi as letters, which I found out is in Ascii values. Im not sure how to display the actual readings from the Arduino to the Raspberry Pi

Here is the Arduino code:
````
#include <DallasTemperature.h>
#include <OneWire.h>
#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define ONE_WIRE_BUS 2

OneWire oneWire (ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

RF24 radio(9, 10);

void setup(void) {

  Serial.begin(9600);
  sensors.begin();
  radio.begin() ;
  radio.setPALevel(RF24_PA_MAX) ;
  radio.setChannel(0x76) ;
  radio.openWritingPipe(0xF0F0F0F0E1LL) ;
  radio.enableDynamicPayloads() ;
  radio.powerUp() ;
}

void loop(void) {
  sensors.requestTemperatures();
  float temperature = sensors.getTempFByIndex(0);
  radio.write(&temperature, sizeof(float));
  delay(1000);
  Serial.print(sensors.getTempFByIndex(0));
}
````
Here is the code for Raspberry Pi in Python
```python
from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize(32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()

while True:

    while not radio.available(0):
        time.sleep(1/100)

    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    print("Received: {}".format(receivedMessage))

    print("Translating...")
    string = ""

    for n in receivedMessage:
        if (n >= 32 and n <= 126):
            string += chr(n)
    print("Our received message decodes to: {}".format(string))
````
I want to get the temperature value in numbers instead of letters. Instead of like this:

Translating ... Our received message decodes to: N

title: Arduino Sensor Values to Raspberry Pi using NRF24

Answers: 0


body:
We have two sensor one of them([MPU6050-gyro][1]) is communicating using I2C, the other is via SPI(SD card reader). Now, we need an additional component as a sensor that [the barometer][2] 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?

  [1]: https://playground.arduino.cc/Main/MPU-6050/
  [2]: https://www.seeedstudio.com/Grove-Barometer-High-Accurac-p-1865.html

title: Two sensors using I2C

Answers: 2

body: 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.

body:
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!


body:
I'm using [Adafruit 16-Channel 12-bit PWM/Servo Shield][1] 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

  [1]: https://www.adafruit.com/product/1411

title: 16-Channel 12-bit PWM/Servo Shield check if it is powered by adapter

Answers: 1

body:
I would propose a circuit like the following:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/Nbde6.png)

<!-- End schematic -->

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.


body:
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?

title: Reducing static on button reading

Answers: 1

body:
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.)


body:
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.

title: how to write Arduino code for a stepper motor to move an arm back and forth 180 degrees

Answers: 1

body:
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][1] or some kind of [Pololu drivers][2])
 - 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]: http://www.schmalzhaus.com/EasyDriver/index.html
  [2]: https://www.pololu.com/category/120/stepper-motor-drivers


body:
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.
<!-- language-all: lang-cpp -->
```
#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();
  };
}
```

title: Looking for some help with an RGB LED animation

Answers: 1

body:
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.


body:
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?
-.......................................

title: Arduino yes! and after?

Answers: 2

body:
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:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/0doIf.jpg

body:
" 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.


body:
Recently I bought this wifi adapter for my IOT projects that I connected to my arduino uno that seems to not working.
I have tried with the arduino ESP8266WiFi library with RX connected to pin 0 and TX connected to pin 1 I have also tried the softwareSerial and still the same result that is, in the serial monitor i always get "*error*" or I get nothing
Thank you in advance and sorry if I made a mistake in the post, I am new to StackExchange :)

 edit (added code to question):

    #include <SoftwareSerial.h>

    SoftwareSerial ESPSerial(10, 11); // RX, TX

    void setup() {
      // Open serial communications
      Serial.begin(115200);
      // set the data rate for the SoftwareSerial port
      // if this doesnt work you for you then try different baud rate
      ESPSerial.begin(115200);
      ESPSerial.println("Ready to take AT commands");
    }

    void loop() { // run over and over
      if (ESPSerial.available()) {
        // reads input from serial console and writes to esp8266
        Serial.write(ESPSerial.read());
      }
      if (Serial.available()) {
        // reads input from esp8266 and writes to serial console
        ESPSerial.write(Serial.read());
      }
    }

[![Esp adapter][1]][1]

[![error][2]][2]

  [1]: https://i.stack.imgur.com/Wjks9.jpg
  [2]: https://i.stack.imgur.com/iTrw9.png

title: Can't connect my ESP-12F to WiFi with my Arduino Uno

Answers: 0


body:
[![enter image description here][1]][1]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?

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

title: Why I am connecting positive wire in the circuit?

Answers: 1

body:
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.


body:
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?

title: Code for two bulb fading alternatively

Answers: 1

body:
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);
      }
    }


body:
My actual connection is like:
**Arduino -> GPRS(http)-> my server(php script)-> firebase <-android plotting app**

But it only allows to send some data once every 2 - 3 seconds (depending of ping to my server).

I need to send some data (18 bytes) but every 0.5 - 1 seconds

It is possible to send directly over tcp to firebase?
And also i thinked about this schema:

**Arduino(client) -> GPRS(tcp) -> my server(tcp socket) -> my database <- android plotter**
but I don't know how to go about it, what server software i need to redirect recieved tcp packages to mysql.

title: Send data from arduino to server using GSM, TCP

Answers: 0


body:
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.

title: RGB LED circuit problem

Answers: 1

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

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/U5Mvy.png)

<!-- End schematic -->

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.


body:
I use Arduino DUE and I noticed that many forum users use the TX-23U Wind Sensor.

https://www.amazon.com/Crosse-Technology-TX-23U-Weather-Stations/dp/B0016MYA7U

Also, many people tried to create a DIY ultrasonic anemometer like this;
https://soldernerd.com/category/arduino-ultrasonic-anemometer/

Instead of using the DIY ultrasonic anemometer, I wanted to purchase one but I couldn't find one.

Is there an ultrasonic anemometer which I can purchase and connect it with my Arduino DUE?

3.3V power, non-mechanical rotation, I2C/SPI/UART support are the requirements. Thanks.

title: Is there a digital/ultrasonic Anemometer for Arduino?

Answers: 2

body:
Frame challenge: pick a sensor that complies with your needs and specification - especially the performance characteristics you're interested in, e.g. range of wind speed to measure, required accuracy and resolution, response time and data acquisition rate, to name just a few. Don't look for something specific to Arduinos to not unnecessarily narrowing down your options. Then design or adapt an appropriate interface to make them both work together.

Common interfaces of "industrial grade" ultrasonic anemometers (e.g. [1] and [2]) are RS232/RS422/485, so technically UART, though in need of level shifters or a RS-485/RS-422 transceiver, e.g. [Maxim](https://www.maximintegrated.com/en/products/interface/transceivers/rs-485-rs-422-transceivers.html). Some also offer analogue output that might be feed into an Arduino's analogue in after matching voltage levels.

I would assume that I2C/SPI are rather uncommon as these are for short-distance, intra-board communication not for connecting a separate sensor module.

The same thought applies to the power supply, I recommend to drop the requirement of powering the sensor with 3V3 put rather select a power supply for a sensor available and affordable. The anemometers available at the linked vendors typically list a supply voltage of 5-30VDC or 6-24VDC.

 [1]: https://www.thiesclima.com/en/Products/Wind-Ultrasonic-Anemometer/
 [2]: http://gillinstruments.com/products/anemometer/anemometer.htm

body:
You can see this one: SONIC-ANEMO-MICRO
https://lcjcapteurs.com/en/girouette-anemometres-capteur-vent/sa-micro-2/


body:
I have a stepper motor, and a Uln2003a stepper driver, which is connected to an ESP8266.

The ESP8266 is powered via USB, and the stepper motor is powered via the driver, which is then powered by an external power source, providing it a bit more than 12 volt. When powered on the LED D1 and D2 lights red.

Pins D0, D1, D2, D3 are used for input signal for the drive, the stepper board.

Everything should be connected correctly, but for some reason I am not able to make my stepper motor move. It doesn't react on any of my commands - why?

I suspect that the logic level might have to be 5v instead of 3v. But I've seen stepper motors being driven by an ESP before. So why does this not work? Any suggestions?

Any ways to debug?

Code:

    esphome:
      name: steppermotor
      platform: ESP8266
      board: d1_mini

    wifi:
      ssid: "ssid"
      password: "password"

    # Enable logging
    logger:

    # ESPHome configuration
    api:
      services:
        - service: control_stepper
          variables:
            target: int
          then:
            - stepper.set_target:
                id: my_stepper
                target: !lambda 'return target;'

    # Example configuration entry
    stepper:
      - platform: uln2003
        id: my_stepper
        pin_a: D0
        pin_b: D1
        pin_c: D2
        pin_d: D3
        max_speed: 250 steps/s

        acceleration: inf
        deceleration: inf

title: Driving a stepper motor using ESP8266

Answers: 0


body:
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).

title: Error compiling for any board arduino ide 1.8.9

Answers: 1

body:
I hope this [link][1] helps you or please try a fresh install.

  [1]: https://forum.arduino.cc/index.php?topic=593072.0


body:
I have a programming circuit for the esp12(see attached) [enter image description here][1]

  [1]: https://i.stack.imgur.com/YI2mk.png

I have produced a pcb using this circuit. Upon plugging the pcb into my pc via the micro usb, the pc immediately recognizes the device.

The problem comes when I hit the upload button in the Arduino IDE. I get the following error:

    Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "NodeMCU 0.9 (ESP-12 Module), 80 MHz, Flash, Disabled, 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

    Sketch uses 265572 bytes (25%) of program storage space. Maximum is 1044464 bytes.
    Global variables use 26984 bytes (32%) of dynamic memory, leaving 54936 bytes for local variables. Maximum is 81920 bytes.
    C:\Users\XXXX\Documents\ArduinoData\packages\esp8266\tools\esptool\2.5.0-3-20ed2b9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\XXXX\AppData\Local\Temp\arduino_build_988997/WiFiScan.ino.bin
    esptool v0.4.13-1-gf80ae31 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
     setting board to nodemcu
     setting baudrate from 115200 to 115200
     setting port from COM1 to COM3
     setting address from 0x00000000 to 0x00000000
     espcomm_upload_file
     espcomm_upload_mem
     setting serial port timeouts to 1000 ms
    An error occurred while uploading the sketch
    opening bootloader
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    resetting board
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    trying to connect
     flush start
     setting serial port timeouts to 1 ms
     setting serial port timeouts to 1000 ms
     flush complete
     espcomm_send_command: sending command header
     espcomm_send_command: sending command payload
     read 0, requested 1
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Where is the error in my design that is preventing the successful upload in the Arduino IDE.

Edit: So I changed the CH340G to a CH340C and removed the 12MHz Crystal and the two 22pf caps connected the the 12MHz. It works perfectly now. I uploaded the code even at 921600 baud.

I guess the issue might have been which crystal I used or maybe the caps. Didn't think it would matter as long as the crystal is 12MHz, but maybe there is something else to account for.

Anyway...the new design will include the CH340C instead of the CH340G, but to be honest I will probably redesign it to use the CP2102.

Thank you for the quick responses. I really do appreciate it.

title: Trouble uploading code to ESP12 with CH340g

Answers: 0


body:
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.

title: Atmega328p and cp2102 with error avrdude: stk500_getsync(): not in sync: resp=0x00

Answers: 1

body:
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


body:
When using the traditional Blink example program, the light blinks as expected. Even when writing from scratch `digitalWrite`ing pin 13 to high and low repeatedly works fine. The problem is when I try to use `CircuitPlayground.redLED(false)`. That has no effect, and the Circuit Playground specific `Hello_Blink` example doesn't work at all. The LED is just constantly on no matter what I do.

I've looked through the source code for the CircuitPlayground library and it's also using pin 13, and doing essentially the same thing as the traditional blink program.

Not sure what else could be causing this.

This is the `Blink` sketch that's working:
<!-- language-all: lang-cpp -->

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

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

And this is the `Hello_Blink` sketch that is not working (LED remains on permanently):

    #include <Adafruit_CircuitPlayground.h>

    void setup() {
      CircuitPlayground.begin();
    }

    void loop() {
      CircuitPlayground.redLED(HIGH);
      delay(500);
      CircuitPlayground.redLED(LOW);
      delay(500);
    }

Changing `HIGH` and `LOW` to `true` and `false` does nothing.

I also have noticed two other strange things. The speaker does an audible click when the board resets when using the `Hello_Blink` sketch (or any other sketch that uses the CircuitPlayground library), as if pin #5 is being held high as well. Also, I added these two lines

    pinMode(6, OUTPUT);
    digitalWrite(6, HIGH);

to the `setup()` of both programs and then probed #6 with a multimeter. Pin #6 is not connected to anything. The traditional blink program allows the pin to go high as expected. The CircuitPlayground sketch, however, the pin stays low.

I am using [this library][1] with a atmega32u4.

  [1]: http://github.com/adafruit/Adafruit_CircuitPlayground

title: Red LED not turning off on Adafruit Circuit Playground Classic

Answers: 1

body:
This appears to be a bug in the Circuit Playground library. An issue was opened here.

https://github.com/adafruit/Adafruit_CircuitPlayground/issues/40

Edit: This indeed was a bug, it is now fixed in the library version 1.8.4.


body: 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 ??

title: Septic tank project

Answers: 1

body:
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.

[![enter image description here][1]][1]

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][2] 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][3]

  [1]: https://i.stack.imgur.com/m0QMU.png
  [2]: http://www.learningaboutelectronics.com/Articles/MQ-7-carbon-monoxide-sensor-circuit-with-arduino.php
  [3]: http://www.learningaboutelectronics.com/


body:
I want to read sensor values from 4x AM2302 to an Arduino UNO, and then pass those values for data logging to Raspberry Pi via Serial communication over USB cable.  The sensors are installed at 4x locations in an indoor plant growing system at difficult to access locations.  In the same script is a program that runs HVAC fans and a water pump using timers and relays.  The problem I encounter is that after working for several readings, eventually the AM2302 fails to read and continuously sends NaN value.  If I intervene and power down/repower up, and also reupload the script, then the AM2302 begin reading again, but only for a few readings then fail again.

In the sample read-out table below, the 4x AM2302 sensor read-outs are sensor 1 : (HA01 - humidity, TA01 - temp) sensor 2 : (HA02, TA02) etc..
There is another read-out CT01 which is a DS18B20, which also fails after some-time and reports a value "no more address" which is reported as -127C by the Dallas Library.

I setup a breadboard and ran the same script with 2x AM2302 and no DS18B20 attached and was unable to replicate the problem.

I have chosen to use json string as a way to pass the readings from Arduino to Raspberry Pi, and notice that sometimes the string gets corrupted - in particular the date timestamp.

I would appreciate any help / tips on diagnostics ideas to pinpoint the issue.

Code for Arduino and Raspberry Pi is available on GitHub.
https://github.com/footprintzero/plantlab

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/i6LrC.png

Updated info 2019/05/21 18:42
  I re-ran the program with a modified script and so far the sensors are continuously sending a reading (AM2302).This modified script version has the HVAC control timers with the relays commented out in HVAC.ino at line 97. So its only reading the sensors and not controlling the relays.

    // timer_mainloop();

title: NaN for reading from AM2302 from Arduino Uno

Answers: 0


body:
I installed the ESP EXCEPTION DECODER along with my Arduino IDE.  When my sketch crashes with Exception 29, I take the stack trace and input it, but I can't understand its line references (they dont seem to point to my code).

> Exception (29):
epc1=0x4020ec84 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

>ctx: sys
sp: 3ffffcd0 end: 3fffffb0 offset: 01a0

>3ffffe70:  3fffb558 00000000 3fff197c fffffffb
3ffffe80:  3fff0ea0 3fff0ea0 00000000 4020fb20
3ffffe90:  00000000 00000000 0000001f fffffffb
3ffffea0:  3fff0ea0 00000000 3fff0e9c 4020ed35
3ffffeb0:  40000f68 3ffe93b4 3fff0e9c 402120ec
3ffffec0:  00000000 00000007 3fff197c 402137fa
3ffffed0:  3ffe93b4 3ffe93b4 3fff0e9c 4021211a
3ffffee0:  ffffffff 3fff0e9c 3fff197c 4021463c
3ffffef0:  0100a8c0 3fffdcb0 3ffee960 00000030
3fffff00:  00000000 3fff0e9c 3fff197c 4021468f
3fffff10:  4020ffa8 3fff0afc 3fff0fc4 40100690
3fffff20:  40229e46 00000000 00000012 3fff0af8
3fffff30:  4020ffa8 3fff0afc 3ffe9348 4020ffb6
3fffff40:  40104d7e 948e6801 00000018 40210074
3fffff50:  3ffe9348 3ffed9fc 948e6801 00000000
3fffff60:  4022e654 3ffee928 3ffee950 60000600
3fffff70:  0fc612e0 3ffee950 3ffee928 4022e661
3fffff80:  4022e6a6 3fffdab0 00000000 3fffdcb0
3fffff90:  3ffee968 40000f65 3fffdab0 00000000
3fffffa0:  40000f49 3ffe96e8 3fffdab0 40000f49
<<<stack<<<
>Decoding stack results

>0x4020fb20: tcp_abort at core/tcp.c line 544

>0x4020ed35: netif_sta_status_callback at glue-lwip/lwip-git.c line 303

>0x402120ec: netif_set_ipaddr at core/netif.c line 545

>0x402137fa: dhcp_create_msg at core/ipv4/dhcp.c line 1825

>0x4021211a: netif_set_addr_LWIP2 at core/netif.c line 584

>0x4021463c: dhcp_release_LWIP2 at core/ipv4/dhcp.c line 1314

>0x4021468f: dhcp_coarse_tmr at core/ipv4/dhcp.c line 423

>0x4020ffa8: cyclic_timer at core/timeouts.c line 165

>0x40100690: free at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.1/cores/esp8266/umm_malloc/umm_malloc.c line 1739

>0x4020ffa8: cyclic_timer at core/timeouts.c line 165

>0x4020ffb6: cyclic_timer at core/timeouts.c line 171

>0x40210074: sys_check_timeouts at core/timeouts.c line 351

How can I find ou what happens at address `0x4020ec84` and what line it points to?

title: Arduino IDE - debugging Exception 29

Answers: 0


body:
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) ;
        }
    }

title: How to send and receive unsigned int from one arduino to another arduino

Answers: 2

body:
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;

body:
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.


body:
I am having an issue using a MAX 3421 EE based Arduino USB Host shield and an SD card shield. From my understanding, they should both function as long as they are using different CS/SS pins and only one is active at a time. I have connected the SD card CS pin to pin 4. I am trying to write a program that reads an ACM terminal and writes that data to a file on the SD card (see code below). When the SD card is not powered the USB host shield reads the ACM and prints it to serial fine. However, immediately when I connect the SD card shield power, it starts printing "ACM not ready." On a reset, it prints "OSCOKIRQ failed to assert."

Troubleshooting steps I have already tried:

 - External power source.
 - Removing SD card from the reader.
 - Commenting out all SD Card code.
 - Disconnecting USB Device (to see if initialization still works)

None of these steps have helped solve the USB initialization issue.

My code:
```c++
//Lots of Code from https://github.com/felis/USB_Host_Shield_2.0/blob/master/examples/acm/acm_terminal/acm_terminal.ino
#include <cdcacm.h>
#include <usbhub.h>

#include "pgmstrings.h"

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif

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

//https://github.com/felis/USB_Host_Shield_2.0.git
class ACMAsyncOper : public CDCAsyncOper{
public:
 uint8_t OnInit(ACM *pacm);
};

uint8_t ACMAsyncOper::OnInit(ACM *pacm){
 uint8_t rcode;
 // Set DTR = 1 RTS=1
 rcode = pacm->SetControlLineState(3);

 if (rcode)
 {
  ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
  return rcode;
 }

 LINE_CODING lc;
 lc.dwDTERate = 115200;
 lc.bCharFormat = 0;
 lc.bParityType = 0;
 lc.bDataBits = 8;

 rcode = pacm->SetLineCoding(&lc);

 if (rcode)
  ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);

 return rcode;
}

const int USBChipSelect = 10;
USB     Usb;
//USBHub     Hub(&Usb);
ACMAsyncOper  AsyncOper;
ACM           Acm(&Usb, &AsyncOper);

const int SDChipSelect = 4;
/*
const int maxLog = 10000;
volatile int logged = 0;
volatile long name = 0;
*/
void setup()
{
 Serial.begin(115200);
 Serial.println("Start");

 pinMode(USBChipSelect, OUTPUT); // Sets USB CS pin output
 pinMode(SDChipSelect, OUTPUT); //Sets SD CS pin output
 digitalWrite(SDChipSelect,HIGH);
 digitalWrite(USBChipSelect,HIGH);

 USBActive();

 if (Usb.Init() == -1){
    Serial.println("OSCOKIRQ failed to assert");
  }

 delay(500);
}

void loop(){
 String toWrite = "Error";

 toWrite = readACM();
 Serial.println(toWrite);

 if(logged>=maxLog){
  logged = 0;
  name++;
 }
 /*
 SD.begin(SDChipSelect);
 File dataFile = SD.open(String(name), FILE_WRITE);
 if(dataFile){
  dataFile.println(toWrite);
  dataFile.close();
 }*/
 delay(100);
}

//Activates USB and Deactivates SD
void USBActive(){
 digitalWrite(SDChipSelect,HIGH);
 digitalWrite(USBChipSelect,LOW);
}

//Activates SD and Deactiavates USB
void SDActive(){
 digitalWrite(USBChipSelect,true);
 digitalWrite(SDChipSelect,false);
}

String readACM(){
  Usb.Task();

  if( Acm.isReady()) {
    uint8_t rcode;

  /* reading the phone */
  /* buffer size must be greater or equal to max.packet size */
  /* it it set to 64 (largest possible max.packet size) here, can be tuned down
  for particular endpoint */
  uint8_t  buf[64];
  uint16_t rcvd = 64;
  rcode = Acm.RcvData(&rcvd, buf);
   if (rcode && rcode != hrNAK)
   ErrorMessage<uint8_t>(PSTR("Ret"), rcode);

  if( rcvd ) { //more than zero bytes received
   char rcvdData[rcvd];
   for(uint16_t i=0; i < rcvd; i++ ) {
    rcvdData[i] = (char)buf[i]; //printing on the screen
   }
   return String(rcvdData);
  }
 }
 return String("ACM Not Ready");
}

```

Thanks in Advance.

title: OSCOKIRQ failed to assert with USB HOST and SD card

Answers: 0


body:
I am trying to make a POST request with NodeMCU, but I get a HTTP status code -1.

Code:
<!-- language-all: lang-cpp -->

    #include <ESP8266HTTPClient.h>
    #include <ESP8266WiFi.h>

    #ifndef STASSID
    #define STASSID "Wifi"
    #define STAPSK  "123"
    #endif

    const char* ssid = STASSID;
    const char* password = STAPSK;
    const char* host = "https://laimonasjanutenas.000webhostapp.com/wifidata.php";

    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("WiFi connected");
      Serial.println("trying to post ");

      HTTPClient http;

      http.begin(host);
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");

      int httpCode = http.POST("temp=1337");
      Serial.println(httpCode);
      http.end();
    }

Serial monitor outputs this:

    connecting to Wifi
    ........
    WiFi connected
    trying to post
    -1

I can confirm that I can actually make a POST to the server. I tested in Postman using this:

    https://laimonasjanutenas.000webhostapp.com/wifidata.php?temp=159

I have no clue what I am doing wrong. Feel free to make POST requests to the this server if needed. Thank you.

title: Cannot POST to server. HTTP code -1. NodeMCU

Answers: 0


body:
I have a simple fan.
When I plug it to GND and Vin it spins.
I'd like to have the ability to turn it on / off with code.
Any example will do, as long as it gets it to spin.
I have a NodeMCU board, if that helps.

title: Use Arduino to turn fan on / off

Answers: 2

body:
Depending of the type of fan you are using, two solutions exist.

- First one, use a MOSFET to drive the FAN from you nodemcu
- Second one, use a relay to drive the FAN from your nodemcu

Things to consider :

- The mosfet allow you to drive the fan without mechanical part moving.
- The relay require some transistor and feedback diode to be driven by your µc.

body: So I didn't have a transistor to do a MOSFET, but I did have a motor driver which I ended up using. From there it was just finding example code to use the motor driver, connecting it up and using it.


body:
I was trying to program my Arduino (along with a connected motor controller) to switch from cycle to cycle with this program.  It doesn't seem to work however.  There's still plenty of storage space and dynamic memory, so those aren't the issue.  This is the program:

    int EnablePin1 = 8;
    int duty;
    int period;
    int cycle;

    int PWMPinA1 = 11;
    int PWMPinB1 = 3;
    int PWMPinA3 = 6;
    int PWMPinB3 = 5;

    const byte CPin1 = A0;

    int CRaw1;
    void setup() {

        Serial.begin(9600);

        pinMode(EnablePin1, OUTPUT);

        pinMode(PWMPinA1, OUTPUT);
        pinMode(PWMPinB1, OUTPUT);
        pinMode(PWMPinA3, OUTPUT);
        pinMode(PWMPinB3, OUTPUT);

    }

    void loop() {
        digitalWrite(EnablePin1, HIGH); //enable the board
        for (duty = 0; duty <= 255; duty += 15)
        {

            analogWrite(PWMPinB1, 0); //Set pinB to 0, when speed is written to pinA

            analogWrite(PWMPinA1, 255);
            delay(850);
            if (PWMPinA1 == 11)
            {
                PWMPinA1 = 3;
                PWMPinB1 = 11;
            }
            else
            {
                PWMPinA1 = 11;
                PWMPinB1 = 3;
            }
       }
       analogWrite(PWMPinA1,0);//end at max speed
       analogWrite(PWMPinB1,0);
       CRaw1 = analogRead(CPin1);

       Serial.println("Feedback");

       Serial.print(CRaw1);

       delay(2000);
       //analogWrite(PWMPinB3, 0);
       for (duty = 255; duty >= 0; duty -= 51) // ramp down speed
       {
           //analogWrite(PWMPinA1, duty);
           analogWrite(PWMPinB3, 0);
           analogWrite(PWMPinA3, 255);
           delay(period);
           //delay(cycle);
           if(PWMPinA3 == 6)
           {
               PWMPinA3 = 5;
               PWMPinB3 = 6;
               //period = 850;
           }
           else
           {
               PWMPinA3 = 6;
               PWMPinB3 = 5;
              //period = 2500;
           }
       }
       analogWrite(PWMPinA3, 0); //set to 0 speed
       analogWrite(PWMPinB3, 0);
       delay(2000);

       digitalWrite(EnablePin1, LOW);// Toggle enable to reset the power chips           if we have had an overcurrent or overtemp fault

       for (cycle = 1000; cycle < 9000; cycle += 4000)
       {
           //cycle=period;
           period=cycle;
       }

     /*for (cycle = 2000; cycle <= 3000; cycle += 1000)
       {
           //cycle=period;
           period=10000;
       }*/
       for (cycle = 9000; cycle >= 1000; cycle -= 8000)
       {
           period=0;
       }

       //delay(2000);  // Swap pins to make the motor change direction

    }//end main loop

I've also tried having the cycle loops be this:

     for (cycle = 0; cycle < 9000; cycle += 3000)
     {
         //cycle=period;
         period=cycle;
     }
     for (cycle = 9000; cycle >= 0; cycle -= 9000)
     {
         //cycle=period/3;
         period=cycle;
     }

But that didn't do anything (I can see what PWM pins are powered through LEDs, and the first attempt, the LEDs only lit up for 1 second and the 2nd, they didn't light up at all.

title: Arduino programming with multiple loops

Answers: 1

body:
## First things, try to use multiple function and call it from the loop()

You can use some code magic for dealing with multitasking on Arduino.
It's a bit tricky to understand but it's working.

Here is an example :
~~~

const int BROCHE_LED_1 = 13;
const int BROCHE_LED_2 = 12;
const int BROCHE_LED_3 = 11;

const unsigned long BLINK_INTERVAL_1 = 1000;
const unsigned long BLINK_INTERVAL_2 = 500;
const unsigned long BLINK_INTERVAL_3 = 2000;

void setup() {

  pinMode(BROCHE_LED_1, OUTPUT);
  pinMode(BROCHE_LED_2, OUTPUT);
  pinMode(BROCHE_LED_3, OUTPUT);

  digitalWrite(BROCHE_LED_1, LOW);
  digitalWrite(BROCHE_LED_2, LOW);
  digitalWrite(BROCHE_LED_3, LOW);
}

void loop() {

  task_led1();
  task_led2();
  task_led3();
}

void task_led1() {
  static unsigned long previousMillisLed1 = 0;
  static byte etatBrocheLed1 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed1 >= BLINK_INTERVAL_1) {

    previousMillisLed1 = currentMillis;

    etatBrocheLed1 = !etatBrocheLed1;
    digitalWrite(BROCHE_LED_1, etatBrocheLed1);
  }
}

void task_led2() {
  static unsigned long previousMillisLed2 = 0;
  static byte etatBrocheLed2 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed2 >= BLINK_INTERVAL_2) {

    previousMillisLed2 = currentMillis;

    etatBrocheLed2 = !etatBrocheLed2;
    digitalWrite(BROCHE_LED_2, etatBrocheLed2);
  }
}

void task_led3() {
  static unsigned long previousMillisLed3 = 0;
  static byte etatBrocheLed3 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed3 >= BLINK_INTERVAL_3) {

    previousMillisLed3 = currentMillis;

    etatBrocheLed3 = !etatBrocheLed3;
    digitalWrite(BROCHE_LED_3, etatBrocheLed3);
  }
}
~~~

## Second things, Try to use Real time operating system

You can try to use FreeRTOS, it's work with most arduino and you got lot of infos on the web.

It make multi tasking way more easy than the previous example.

Here is the [Docs i've found][1]

  [1]: https://create.arduino.cc/projecthub/feilipu/using-freertos-multi-tasking-in-arduino-ebc3cc


body:
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.

title: How to read high voltage (40-65v) from a Solar Battery bank

Answers: 2

body:
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][1] 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][2] 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.
  [1]: https://www.esp8266.com/viewtopic.php?f=160&t=13435
  [2]: https://forums.adafruit.com/viewtopic.php?f=19&t=90062

body:
**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:

[![Voltage Divider][1]][1]

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:

![Formula][2]

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:

[![Op-amp][3]][3]

  [1]: https://i.stack.imgur.com/HweJQ.png
  [2]: https://i.stack.imgur.com/RBYmH.png
  [3]: https://i.stack.imgur.com/xnlP7m.png


body:
**Project goals**

 - Send data over GSM to firebase
 - Fast sampling - need to send 16 bytes every half second to firebase
 - Send data using GET or POST to server with PHP script, that redirect data to firebase

**Problems --
Extremely low data rate!**

 - Using standard GET or POST request from client(arduino) side, is impossible to achieve second (2) project goal.
 - **To send data correctly I need to close connection with server, so next data package unfortunately waits(2-6 seconds) for establishing a new connection.**

  Is this quite nonsense? I'm using ArduinoHttpClient library.

**My actual Nonsense Connection and fully useless, but works**
<!-- language-all: lang-cpp -->

    while(1){

    http.post("/test.php","application/x-www-form-urlencoded","data=0");
    http.stop(); //closing connection with server

    //next instruction take over 5 second to establish new connection :(

    http.post("/test.php","application/x-www-form-urlencoded","data=0");
    http.stop(); //closing connection with server, whyyy?
    }
 Data are send once per 2 - 6 seconds, this is not even funny. NEED to send data every 0.5 seconds!

So I decided to create super solution, which not works :C

    while(1){
        http.post("/test.php","application/x-www-form-urlencoded","data=0");
        delay(xxx);
    //no connection closing, no wasting time for establishing new one :)
    }

Just tell my why this connection is not "Keep-Alive", also used with

> http.sendHeader("Connection: Keep-Alive"); or
> http.connectionKeepAlive();

    //First run
    http.post(blabla);// returns value: 0 & data are logged into firebase
    //Second run
    http.post(blabla);// returns value: -2 & data are not logged in firebase

**my test.php file**

    <?php
    require_once 'firebaseLib.php';
    $url = 'https://czujniki-aa5ca.firebaseio.com/';
    // --- Use your token from Firebase here
    $token = ':-CCCCCCCCCCCCCCCCCCCCCCC';

    $arduino_data_post = $_POST['data'];
    $firebasePath = '/';

    $fb = new fireBase($url, $token);
    $response = $fb->push($firebasePath, $arduino_data_post);
    sleep(2);

title: creating HTTP persistent connection, to create 'smooth' data over GSM sending

Answers: 1

body:
The ArduinoHttpCliemt library's HttpClient.stop() method does two things. It resets the state of the HttpClient object and stops the underlying Client connection (TCP connection). If HttpClient.stop() is not called, the internal state is not good to call get() or post() again.

The method resetState() is called in HttpClient.stop() to reset the internal state of the HttpClient object. But resetState() is protected. To call it we must modify the library header file.

In HttpClient.h make resetState() public (by moving 'protected:') and then in sketch call resetState() before post(). It will put the HttpClient object into initial state without disconnecting the underlying TCP connection.


body:
Is communication using tx/rx from an arduino to mkr1010 the same as any other serial communication?

I ask because I can't find any tutorials or info on connecting an arduino to mkr1010, but there are plenty on connecting one arduino to another.

title: MKR1010 serial communication

Answers: 0


body:
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.

 [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/N4Gzw.png

title: Connecting multiple RS485 together

Answers: 1

body:
It is possible you have too many resistors on the RS485 bus. From the [RS485 wikipedia page][1] 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.

  [1]: https://en.wikipedia.org/wiki/RS-485


body:
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.

Answers: 1

body:
I had attached the screenshot for this[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/66jBd.png

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.


body:
I have 4 12V(1A) [solenoids][1] running on a 12V(4.16A) power supply.
Each solenoid circuit is controlled by a 5V [relay module][2] connected to the Arduino Uno (powered by USB).

The solenoids actuate properly but eventually the Arduino resets, typically when multiple solenoids are turned on/off in fast succession. This is accompanied by random character artifacts on the LCD display (connected to the Uno) during operation but before the reset.

From what I've gathered there are back EMF surges occurring when the solenoids lose their charge. Here are some possible remedies I've found:

 1. Add a flyback diode (IN4004) to each solenoid circuit. (Redirect the surge)
 2. Add a capacitor (4700 - 10,000 uF) to the 5v supply (from the Uno) for the relays. (Filter the surge)
 3. Provide a separate 5v power source to the relay modules instead of using power from the Uno. (Isolate the surge)

Any input on which solution(s) should be applied or other possible causes for the Uno reset and LCD distortion is appreciated.

  [1]: https://www.amazon.com/gp/product/B00HR8H38A/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1
  [2]: https://www.amazon.com/Youngneer-Raspberry-Arduino-Channel-Opto-Isolated/dp/B07M88JRFY/ref=pd_ybh_a_3?_encoding=UTF8&psc=1&refRID=5NSHB73CTBAAGVPN2E96

title: Controlling multiple 12v solenoids with 5v relay modules (Arduino Reset Issue)

Answers: 2

body:
## Here is another path to explore :

- Try to use separate rail for the 5v relays
- Use a transistor or darligton array (such as ULN2003) for controling your 5v relay.
- ALWAYS put a feedback diode when you use an inductive load it can break your Arduino !!

## My analyse :

- Arduino and many other µc have limited output current on IO, be sure to not overload these value by using transistor or darligton array.
- The voltage regulator on the Arduino can provide around 200 mA of power. I you are overloading the value use an external power supply for your circuit.
- The solenoid can draw lot of current of the power supply, try to measure if a voltage drop occur on loads. It can cause the arduino to reset due to low voltage.

body:
Some of those 5V "digital" relays can be wired using a separate power supply for the relays and the Arudino. You have to move a jumper to use separate power supplies.

My guess is that you're powering both your Arudino and your relay coils from the same 5V supply, and when you energize all 4 relays at the same time you draw too much current and the Arduino doesn't get enough voltage and resets.

Read up on your relay modules, and either re-wire them using 2 different 5V supplies, or switch your 5V supply to a higher current supply. (and possibly adding a filtering capacitor to the Arduino to smooth out the power fluctuations as the relays energize and de-engergize)

I used a 4-channel relay unit in a project of mine that has optical isolation of the relay control lines, and can be wired to use separate power supplies for the Arudino and the relay power. When wired with separate power supplies, the relay's control lines just draw CMOS logic levels to control the different relay channels, and get the power for the coils independently from the microcontroller's power.


body:
I have Wemos Mega-ESP8266 board. I have uploaded a simple WebSocket server on the ESP...
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <WebSocketsServer.h>

    const char* ssid     = "SKYNET";
    const char* password = "yourdogsfavouriteauntysmaidenname";

    WebSocketsServer webSocket = WebSocketsServer(81);

    void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {

        //Serial.printf("[%u] get Message: %s\r\n", num, payload);

        switch(type) {
            case WStype_DISCONNECTED:
                break;

            case WStype_CONNECTED:
                {
                  IPAddress ip = webSocket.remoteIP(num);
                  Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload);
                }
                break;

            case WStype_TEXT:
                {
                  String _payload = String((char *) &payload[0]);
                  Serial.print(_payload);
                }
                break;

            case WStype_BIN:
                {
                  hexdump(payload, lenght);
                }
                // echo data back to browser
                webSocket.sendBIN(num, payload, lenght);
                break;

        }
    }

    void setup() {

      // Set up serial comms
      Serial.begin(115200);

      // Set up WiFi
      WiFi.begin(ssid, password);
      while(WiFi.status() != WL_CONNECTED) {
         Serial.print(".");
         delay(200);
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

      delay(500);

      // Set up web socket
      Serial.println("Start Websocket Server");
      webSocket.begin();
      webSocket.onEvent(webSocketEvent);
    }

    void loop() {
      webSocket.loop();
    }

I upload via the Arduino IDE & everything looks fine except the ESP doesnt send any information back through the serial monitor (yes I have the DIP switches correct for serial <> ESP comms).

I tried to see if was sending anything through the Mega via Serial3, the mega code (DIP switches set accordingly & ESP serial switch set to RX3). Mega code...

    // Input buffer from ESP8266
    String temp;

    void setup() {
      // Set up serial comms
      Serial.begin(115200);   // Debug to Serial Monitor
      Serial3.begin(115200);  // From ESP8266
    }

    void loop() {
      while (Serial3.available()) {
          Serial.println(".......");
          Serial.println("In from ESP8266");
          temp = Serial3.readString();
          Serial.println(temp);
          Serial.println(".......");
      }
    }

So now I get 2 one time messages to the serial monitor..

    .......
    In from ESP8266
    [WS-Server] Server Started.

    .......
    .......
    In from ESP8266
    pm open,type:2 0

    .......

I have no idea where these messages are being generated or why the ESP isnt sending the serial messages on set up eg the IP address for the ESP etc.

Any idea what's going on here?

**Edit 1:** Addition info asked for in comments (or at leat I think this is what was asked for)

[![enter image description here][1]][1]

**Edit 2:**

DIP switch settings for flashing the ESP - OFF, OFF, OFF, OFF, ON, ON, ON

DIP switch settings ESP > serial monitor - OFF, OFF, OFF, OFF, ON, ON, OFF (RX switch to TX0)

DIP switch settings for ESP > Mega > serial monitor - ON, ON, ON, ON, OFF, OFF, OFF (RX switch to TX3)

**Edit 3** I have to press the red reset button after flashing the ESP8266 & it works BUT as soon as I unplug & restart nothing again! The client connects, sends the same data but it doesnt get echoed back via the serial comms. The only way to get to work again is to reflash the ESP8266 and hit the reset button.

**Edit 4** Swapped out the board & now nothing works again. Uploads look fine but no serial comms at all from the ESP8266.

  [1]: https://i.stack.imgur.com/RNlEL.png

title: Mega <> esp8266 comms sending baffling data

Answers: 1

body:
The esptool auto-reset feature by default sets io 0 LOW over the RST line and then makes a reset over the DTR line to put the esp8266 into flashing mode. After the upload the esptool resets the board over the DTR line.

On this board Mega+WiFi, only the DTR line is wired like for AVR MCU. For flashing the io 0 pin is put LOW with the pin 7 of the DIP switch manually. So the reset after upload sets the esp8266 back to flashing mode.

The esp8266 arduino package changed from version 2.5.0 the upload tool to the python version of the esptool which makes this reset after upload. This reset can be turned off by changing the command line of the esptool in platform.txt (`--after no_reset` in `tools.esptool.upload.pattern` before `write_flash`)