body:
I am trying to connect `arduino` and `esp8266` as like this

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

I know `arduino` runs at 5V and RX of ESP8266 should not have voltage more than 3.5V. If you see my diagram there voltage is large than need on RX of ESP8266. I know resistor can help me for this and ohm law.

    V = R.I => R = V/I

So I want to understand how should I select what ohm resistor for this cuicuit ? Can anyone explain with some calculation using ohm law ?

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

title: How to select which resistor is required for my curcuit to reduce voltage

Answers: 2

body:
A voltage divider made with a 4.7KOhm between your +5V and input and a 10Kohm between your input and ground will result in a 10/14.7 ratio, giving you 3.4V on your input.

If you use a 5.6KOhm to +5V instead, your voltage will be 3.2V which may be a bit easier on the ESP8266.

The trick here is not the specific value of any resistor, but the relationship between two resistors.  You need to find a divider that will change 5 into 3.3 volts, a ratio of 0.66.  Thus, any resistor values where the value of the bottom one in the diagram below divided by the value of both resistors is close to 0.66 will work.  My suggestion would work equally well if you chose 1K Ohm and 470 Ohm.
[![enter image description here][1]][1]
Note that a voltage divider should only be used for signals and not for powering the ESP.

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

body:
A resistor can only drop a certain voltage when there is a certain current - as you know from Ohm's Law.  If you have resistance *R* and current *I* the voltage dropped is *R×I*.

So if the current changes the voltage changes - and if the voltage changes the current changes.

So what do we do? Well, we have *one* known fixed value, and that is the 5V from the GPIO pin. And since that is fixed (at least when HIGH) we could add a fixed resistance to it to give a fixed current, right?

So let's do that. Pick a random value. Experience teaches you that certain values are better than others, but the actual value doesn't matter too much, as long as:

1. It's not so small that too much current flows out of the GPIO pin, thus damaging it, and
2. It doesn't create too high an *output impedance*, which we will come on to later.

10kΩ is a good figure to start with. Not only does it keep the current low enough, but it's pretty much guaranteed that you'll have one in your bits box somewhere. And we connect it to the GPIO like this (we completely ignore the ESP8266 for the moment):

<!-- 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/DgQ9H.png)

<!-- End schematic -->

When TX is HIGH it's at 5V. It's connected directly across a 10kΩ resistor, so therefore we can use Ohm's Law to calculate the current - I=V÷R = 5 ÷ 10,000 = 0.0005, or 0.5mA. (Another useful thing with 10kΩ resistors is it makes calculations nice and easy).

Now, what if we were to split that resistor in half, so it was two 5kΩ resistors in series? The circuit would look 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/O5cyY.png)

<!-- End schematic -->

Resistors in series add together, so those two 5kΩ resistors are the same as one 10kΩ resistor. We know that 0.5mA flows through 10kΩ at 5V, so the same must run through 5+5kΩ at 5V. But now we have two fixed value resistors. Because of that we can now apply Ohm's Law to *each* one to find the voltage drop across it.

So with 0.5mA flowing through a 5kΩ resistor we get V=I×R = 0.0005 × 5000 = 2.5V.  That's 2.5V across R1 and 2.5V across R2, since they are both the same. That's exactly 50% of the 5V across each one. At the point in the middle, point "A" on the schematic, you can see that the voltage has been cut in half. Once the current has gone through one resistor the voltage has halved (dropped by 2.5V), and when it goes through the other resistor it drops the rest to 0V, which is the other 2.5V.

If we were then to connect something to point A it would see a logic signal of 0V (LOW) and 2.5V (HIGH) from our 0V (LOW) and 5V (HIGH) signal.

But 2.5V is too low for the ESP8266 to read. Well, the answer is simple. We see that if we use two resistors we divide the voltage into two. The same applies for dividing it into three. For instance:

<!-- 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/USXek.png)

<!-- End schematic -->

The sum is 10kΩ (well, 9.9kΩ but we'll call it 10kΩ for simplicity - a third each resistor, 3333.33Ω). 0.5mA through 3.3kΩ would be 0.0005 × 3333 = 1.66V. Funnily enough, 5 ÷ 3 = 1.66, so we have proved that it splits it into a third. That means at point A 1.66V of our 5V has been dropped (across R1), so 5V is now (5-1.66) 3.33V. Perfect for the ESP8266. Incidentally, point B would be 1.66V (3.33 - 1.66).

So now we have three resistors and the result we desire. However it's a little messy still. Remember that resistors in series add together? So why not add R2 and R3 together into a single resistor? That would be 6.6kΩ. Now I don't know of a 6.6kΩ resistor that's easily available, but 6.8kΩ ones are, though chances are you may not have one. If you did then a 3.3kΩ and a 6.8kΩ would net us near enough 3.3V to be usable.

But as I say you may not have one. So you pick resistor values that you *do* have. For instance you could use a 2.2kΩ and a 4.7kΩ, or a 10kΩ and a 22kΩ - anything that gives a *roughly* 1:2 ratio of value (the "upper" R1 resistor about half the value of the lower "R2" resistor).

Now - we get onto that mysterious phrase I mentioned earlier: *Output Impedance*. You recall we calculated the current that flows through the resistors - 0.5mA. The higher the value of resistors we use the lower the current. Well, that current not only flows through the resistors - a small amount also heads off into the ESP8266. The more that the ESP8266 wants for its RX pin the less there will be available for the R2 resistor. The result? Less current through the resistor = less voltage dropped across it.

*The current drawn by the pin attached to point A on our circuit affects the voltage dropped across the resistors*.

Too much current drawn and the voltage at point A will droop. Less will be dropped across the (current starved) R2, which means more must be dropped across R1. So point A is now a lower voltage. If that gets too low (too much current is drawn) then the RX pin can't read it properly.

Increasing the resistances decreases the current, but also decreasing the resistances increases the current. If the current is increased then the fraction of the current needed by the RX pin becomes reduced compared to what is available, so the output voltage drops less.

This *output impedance*, in case you're interested, is measured in Ohms, and is the same as the value of the two resistors in parallel - so (R1×R2)÷(R1+R2).

For instance, I tried connecting an ESP8266 the other day using 3 10kΩ resistors - R1 = 10K, R2 = 20K. It didn't work. You'd expect it to, given the ratios involved, however the output impedance (6.66kΩ) was too high for the ESP8266 I was using. Replacing them for 1kΩ resistors, so it was 666Ω output impedance, made it work straight away.

You can understand it easier if you think of the ESP8266 as just another resistor (it's actually more complex than that - it's also like a capacitor, so it forms a *low pass filter* which limits the frequency of, and deforms the shape of, the incoming digital waveform). For example:

<!-- 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/dof2Q.png)

<!-- End schematic -->

I have deliberately shown the ESP8266 as a lower resistance that it would really be (you can expect MΩ) so as to illustrate the problem clearer.

Your R2 now has R(esp) in parallel with it. So the nice clean 20kΩ is now actually (20,000 × 100,000) ÷ (20,000 + 100,000) = 16.66kΩ. That gives us a total of 26.66kΩ, and at 5V that means a current of 0.188mA. Through the 10kΩ resistor we end up with (10,000 * 0.000188) 1.875V dropped. Take that from 5V and you can see that the ESP8266 would only be getting 3.125V.

By reducing the resistors in our network the difference that R(esp) makes to R2 reduces. For instance, reducing it to 1kΩ + 2kΩ gives us an R2 total of (2,000 * 100,000) ÷ (2,000 + 100,000) = 1.96kΩ - hardly any different from the 2kΩ we started with, so the voltage difference will be minimal (3.31 as opposed to the ideal 3.33).

The simple formula for calculating the output voltage from an input voltage and pair of resistors, so you don't have to go long-hand through Ohm's Law every time (though it is useful for understanding exactly what is happening) is:

*Vout = R2 ÷ (R1 + R2) × Vin*

I can never remember it, though, and usually use an [online voltage divider calculator](http://www.ohmslawcalculator.com/voltage-divider-calculator).


body: What are the differences between the Arduino Micro and Pro Micro?

title: Arduino Micro vs. Pro Micro

Answers: 2

body:
I actually think you are meaning what is the difference between the [Arduino Mini][1] and the [Arduino Pro Mini][2], since there is no such board as the *Arduino Pro Micro*. However there is a board called the [Arduino Micro][3] and also the [Sparkfun Pro Micro][4], so this answer will look at all four.

[Arduino Mini][1]
[![Arduino Mini][5]][5]

[Arduino Pro Mini][2]
[![Arduino Pro Mini][6]][6]

[Arduino Micro][3]
[![Arduino Micro][7]][7]

[(Sparkfun) Pro Micro][4]
[![Pro Micro][8]][8]

**Microcontroller**
Arduino Mini: ATmega328
Arduino Pro Mini: ATmega328 (ATmega168 on older boards)
Arduino Micro: ATmega32U4
Pro Micro: ATmega32U4

**Memory**
All four have 32KB of Flash and 1KB of EEPROM
Both Minis have 2KB of SRAM where as both Micro boards have 2.5KB

**Digital I/O**
Both Minis have 14 (of which 6 provide PWM output)
The Arduino Micro has 14 also (of which 7 provide PWM output)
Some of the analog pins can also be used as digital I/O
The Pro Micro has 12 (5 PWM pins)

**Analog Inputs**
Arduino Mini/Pro Mini: 8 (some boards only break out 6 analog inputs)
Arduino Micro: 12 ([6 dedicated and 6 from digital I/O pins][9])
Pro Micro: 9 channels of 10-bit ADC

**USB**
Arduino Mini/Pro Mini: Requires FTDI cable or Sparkfun breakout board to provide USB power and communication to the board.
Arduino Micro / Pro Micro: Native USB

**Clock**
All 16 MHz
(Some 3V3 variants run at 8MHz)

**Power**
Arduino Mini: 7-9 V
Arduino Pro Mini: There are two version of the Pro Mini. One runs at 3.3V and 8 MHz, the other at 5V and 16 MHz. VRAW  can accept voltage up to 12VDC.
Arduino Micro: USB or external supply of 6 to 20 volts (recommended range is 7 to 12 volts)
Pro Micro: can accept voltage up to 12VDC

**Interrupts**
Arduino Pro Mini: The Atmega328 has 2 hardware interrupts available
Arduino Micro / Pro Micro: The ATMega32u4 has 5 hardware interrupts available
credit: [Enric Blanco][10]

  [1]: https://store.arduino.cc/arduino-mini-05
  [2]: https://store.arduino.cc/usa/arduino-pro-mini
  [3]: https://store.arduino.cc/usa/arduino-micro
  [4]: https://www.sparkfun.com/products/12640
  [5]: https://i.stack.imgur.com/PLY8h.jpg
  [6]: https://i.stack.imgur.com/LKcvq.jpg
  [7]: https://i.stack.imgur.com/l4hOF.jpg
  [8]: https://i.stack.imgur.com/pzZiL.jpg
  [9]: https://www.arduino.cc/en/uploads/Main/ArduinoMicro_Pinout3.png
  [10]: https://arduino.stackexchange.com/a/34577/19409

body:
sa_leinad gave a detailed answer.

a simplified version would be on the chips used: 328 vs. 32u4.

the 32u4 is a superb chip if you are into mixed signal mcu. the ability to put a programmable gain and differential analog input into the adc module at such a low price point is simply superb.

unfortunately, not many boards route out AIN0/AIN1 pins.


body: its possible to read serial ouput from ICSP or Tx Rx pin instead from USB port? If it's possible how? thanks for reply

title: Alternative ways for read Serial Output

Answers: 1

body:
The TX and RX pins are connected directly to the USB to UART adaptor embedded in the board (an ATMega16U2 on the Uno R3, or a CH340G on a cheap Chinese clone). Anything that goes through the USB also goes through those pins.

You can also, if you must, use SoftwareSerial to get serial on any other pair of pins of your choice.


body:
I want to use both IMU at the same time using the [Sparkfun Library][1] on a SAMD21 mini breakout board. Can anyone help?

The begin function is :

    inv_error_t MPU9250_DMP::begin(void) {
      inv_error_t result;
      struct int_param_s int_param;
      Wire.begin();
      result = mpu_init(&int_param);
      if (result)
        return result;
      mpu_set_bypass(1); // Place all slaves (including compass) on primary bus
      setSensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS);
      _gSense = getGyroSens();
      _aSense = getAccelSens();
      return result;
    }

  [1]: https://github.com/sparkfun/SparkFun_MPU-9250-DMP_Arduino_Library

title: Accessing two MPU-9250 DMP

Answers: 1

body:
Sorry, but I'm not 100% sure of what you are trying to do, I don't understand 'both imu the' in your question.  I think you are trying to use two identical boards at the same time.  (If not tell me so I can edit my answer)

You will need to modify the library so the `begin` function takes a parameter.
That parameter for `MPU9250_DMP::begin` then identifies the address of the device, this will need passing to `Wire.begin()` I think (you'll need to check the Wire.begin() function, I can't).

That should let you create two different instances of the class.

    MPU9250_DMP apple;
    MPU9250_DMP banana;
    apple.begin(0x68);
    banana.begin(0x69);


body:
        #include <Servo.h>
    Servo tilt, pan;

    // Arduino pin numbers
    const int SW_pin = 2; // digital pin connected to switch output
    const int X_pin = 0; // analog pin connected to X output
    const int Y_pin = 1; // analog pin connected to Y output
    int x, y;

    // Second joystick pin numbers

    const int SW_pinn = 4;
    const int X_pinn = 3;
    const int Y_pinn = 5;

    void setup() {
      pinMode(SW_pin, INPUT);
      digitalWrite(SW_pin, HIGH);
      Serial.begin(115200); // setting serial baud rate tp 115200
      tilt.attach(7);
    }

    void loop() {
      x = X_pin; // defining the variable
      y = Y_pin;
      Serial.print("X-axis: ");
      Serial.print(analogRead(X_pin));
      Serial.print("\n");
      Serial.print("Y-axis: ");
      Serial.println(analogRead(Y_pin));
      Serial.print("\n\n");
      x = map(analogRead(X_pin), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec
      y = map(analogRead(Y_pin), 0, 1023, 900, 2100);
      tilt.write(x); // sets the servo position according to the scaled value
      pan.write(y);
      delay(5);

    }

      x = X_pinn; // defining the variable
      y = Y_pinn;
      Serial.print("X-axis: ");
      Serial.print(analogRead(X_pinn));
      Serial.print("\n");
      Serial.print("Y-axis: ");
      Serial.println(analogRead(Y_pinn));
      Serial.print("\n\n");
      x = map(analogRead(X_pinn), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec
      y = map(analogRead(Y_pinn), 0, 1023, 900, 2100);
      tilt.write(x); // sets the servo position according to the scaled value
      pan.write(y);
      delay(5);
    }

When I compile this code in the Arduino IDE it gives me the error

       arduino-builder/arduino-builder -compile -core-api-version 10611 -build-path /tmp/166416428 -hardware arduino-builder/hardware -hardware arduino-builder/packages/cores -tools arduino-builder/tools -tools arduino-builder/packages/tools -built-in-libraries arduino-builder/latest -libraries /tmp/358566849/pinned -libraries /tmp/358566849/custom -fqbn arduino:avr:uno -build-cache /tmp -verbose=false /tmp/358566849/sketch_may12a

    Multiple libraries were found for "Servo.h"

    Used: /home/admin/builder/arduino-builder/latest/Servo-1.1.2

    Not used: /home/admin/builder/arduino-builder/latest/Printoo_Library-1.0.2

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:40:3: error: 'x' does not name a type

    x = X_pinn; // defining the variable

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:41:3: error: 'y' does not name a type

    y = Y_pinn;

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:42:3: error: 'Serial' does not name a type

    Serial.print("X-axis: ");

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:43:3: error: 'Serial' does not name a type

    Serial.print(analogRead(X_pinn));

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:44:3: error: 'Serial' does not name a type

    Serial.print("\n");

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:45:3: error: 'Serial' does not name a type

    Serial.print("Y-axis: ");

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:46:3: error: 'Serial' does not name a type

    Serial.println(analogRead(Y_pinn));

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:47:3: error: 'Serial' does not name a type

    Serial.print("\n\n");

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:48:3: error: 'x' does not name a type

    x = map(analogRead(X_pinn), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:49:3: error: 'y' does not name a type

    y = map(analogRead(Y_pinn), 0, 1023, 900, 2100);

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:50:3: error: 'tilt' does not name a type

    tilt.write(x); // sets the servo position according to the scaled value

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:51:3: error: 'pan' does not name a type

    pan.write(y);

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:52:8: error: expected constructor, destructor, or type conversion before '(' token

    delay(5);

    ^

    /tmp/358566849/sketch_may12a/sketch_may12a.ino:53:1: error: expected declaration before '}' token

    }

    ^

    exit status 1

In short, it saying that x does not name a type in this part of the code

    x = X_pinn; // defining the variable
      y = Y_pinn;
      Serial.print("X-axis: ");
      Serial.print(analogRead(X_pinn));

Even though I defined it as a variable at the beginning... Any ideas?

title: '[Class name]' does not name a type in C++ Error

Answers: 1

body:
If that is really your code then the errors are caused by one error.
As Majenko says lines 58 through to 71 should not be there.  It could be a cut and paste error when you wrote the post, but if it isn't that will cause a problem.

Some tips regarding your style that might help spot these faults in future.

 1. Don't give variables a larger scope than they need.  See x and y, these don't need to be global variables.  You only use them within the `loop()` and you don't store the value between loops.  In fact lines (42 and 43) aren't needed which means you could define them as `const int` values on line 50 and 51.
 2. Braces {} - I know people like to write braces in the java style now, because it saves a line of text and all those 2 bytes will eventually add up, but If you had always put braces on line on there own you would have seen the error because line 57 doesn't have an opening brace.
 3. Encapsulate related data - I appreciate its only a little scrap program, but I would have placed the pin information in a class.  This would have let you have better variable names.

`const PinInfo joystick1 (2, 0, 1);`

`const PinInfo joystick2 (4, 3, 5);`


body:
Okay so I did this project from [Fritzing](http://fritzing.org/projects/arduino-lcd-alarm-clock) first in my [circuits.io project](https://circuits.io/circuits/4891438-alarm-clock/) then on the arduino itself, it all works fine just how I wanted it.

But here is what I wanted to add, as you can see when you plug the arduino in it will set the time to 00:00 and you can adjust it yourself to the time right now, let's say 12:57. Then you put in the alarm so let's say you want to sleep an hour u put the alarm on 13:57.

Is there a way to automatically get the time from the computer? So you don't have to adjust it yourself everytime and start from 00:00.

Thanks for all the help!

title: How can I automatically get the time from the computer into an alarm clock (starts at 00:00 when plugged in)?

Answers: 1

body:
There are several ways, and they are covered in the comments above.

 1. The answer to your question. Via Arduino USB to serial interface. and a simple batch file on a windows computer example:

    @echo off

    set datetimef=%time:~0,2%.%time:~3,2%:%time:~6,2%

    echo �tetimef% > COM5

COM5 is used as a example, your serial port can be another number.

The format in the example is hour.minute:second


body:
I,m trying to find the right mosfet or transistor to switch on-off a neopixel strip to safe battery power on a Lipo 3.7v using a pro mini 3.3v.

My Animation-Setup and Power Comsumption with 35 Neopixels is :

 - Sparkel      : 20mA
 - Knight Rider : 80mA
 - Pulse        : 600mA

So the maximum  current for the ledstrip is 600mA @ 3.7v
My first thought was to use the 2N 2222 - Transistor NPN TO-18 60V 0,8A 0,5W.

But then i realize the worst case:
What happens if the all 35 Neopixels turn full white caused by a software glitch or a bug in the code. Full white means every neopixles consumes 60mA.

Total power comsumption: 35 X 60mA = 2.1A

Would be destroyed the 2N2222? Because it could handle only 800mA drain current?

How can I avoid this situation. So I read about Mosfet like this one [FQP30N06L][1] :

    N channel power MOSFET
    TO-220 Package
    Vds = 30V max
    Max current = 62A
    Vgs = 2.35V max
    Rds_on = as low as 8.7 milliohm - depending on Vgs

What do you think will it work to switch on/off the led if:

 - the drain current is between 20mA - 600mA - 2.1A
 - ledstrip Vcc is 3.7v
 - pro mini out 3.3V at max 40mA

Or is there an other suitable Mosfet for this problem than the FQP30N06L with 62 Ampere for these hardware setup with only 2.1 Ampere Peak @ 3.7v ?

  [1]: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Components/General/FQP30N06L.pdf

title: Choosing the right mosfet to switch on-off a neopixel strip

Answers: 1

body:
You refer to a 2N2222 handling 800 mA.  However, the 2N2222 datasheet shows 600 mA as its maximum rating for Collector Current – Continuous.  Moreover, from the On Characteristics table, Collector – Emitter Saturation Voltage at 500 mA current could be as high as 1 V.  In typical circuits with high base drive it usually is less, eg about 0.2 V typical with 50 mA base drive, which is more current than a typical AVR output is rated for.  Anyhow, the Neopixels won't operate if your switch drops any significant voltage from the supply.  Using a 2N2222 might work ok, or briefly, or intermittently, or not at all  – depending on the quality of the  2N2222 and the amount of base drive.

You refer to a FQP30N06L handling 62 Amperes.  However, the FQP30N06L datasheet shows 32 A as its rating for Drain Current - Continuous (vs 128 A for Drain Current - Pulsed, which is irrelevant here).

Using a FQP30N06L at its maximum 32 A continuous drain current would require careful heatsinking and perhaps 10 V of VGS drive to achieve low RDS(on), like 27 mΩ. With low VGS of say 3.3 V, RDS(on) might be twice as much.  For example, if it were 45 mΩ, going above 4 or 5 A current would be problematic without careful heatsinking:  4 A → P = 4²·0.045 = 0.72 W, enough to heat up a not-heatsinked unit's junction by about 45℃ or 80℉.

But the FQP30N06L should work ok for your 600 mA typical-case scenario, and also should be ok with the 2 A worst-case as well.


body:
I am trying to send `AT` commands to `ESP8266`. I re-flashed `ESP8266` https://i.stack.imgur.com/z0hoc.jpg I followed this tutorial http://remotexy.com/en/help/esp8266-firmware-update/ and I hope it re-flashed successfully as there was no error.

When I uploaded this program http://www.pastebin.com/frhZY7tD I am trying to run AT command at 9600 baud rate on serial monitor then no response..

Below is how my circuit looks like

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

    #include "SoftwareSerial.h"

    SoftwareSerial esp8266(2, 3); // RX, TX

    void setup()
    {
      Serial.begin(9600); // serial port used for debugging
      esp8266.begin(9600);  // your ESP's baud rate might be different
    }

    void loop()
    {
      if(esp8266.available())  // check if the ESP is sending a message
      {
        while(esp8266.available())
        {
          char c = esp8266.read();  // read the next character.

          Serial.write(c);  // writes data to the serial monitor
        }
      }

      if(Serial.available())
      {
        delay(10);  // wait to let all the input command in the serial buffer
        // read the input command in a string
        String cmd = "";
        while(Serial.available())
        {
          cmd += (char)Serial.read();
        }
        // send to the esp8266
        esp8266.println(cmd);
      }
    }

Trying to execute `AT` command -

[![enter image description here][2]][2]

On clicking on send button then it shows empty response like below -

[![enter image description here][3]][3]

When I unplug power wire and plug it back then it prints some garbled message on serial monitor. I checked voltage on RX also, it was around 3.5V that seems also OK.

[![enter image description here][4]][4]

I am facing this issue after I flashed WiFi firmware to `ESP8266` then back AT firmware. It seems that AT firmware was not flashed successfully so I tried to erase everything using below command.

> esptool.py --port /dev/ttyUSB0 erase_flash

 C:\Users\williams>esptool.py --port COM4 -b 9600 erase_flash
 esptool.py v1.3
 Connecting...................

 A fatal error occurred: Failed to connect to ESP8266: Timed out waiting for pack
 et header

Before execute above command, I made changes in my circuit like below :-

[![enter image description here][5]][5]

Update
======

I have re-flashed ESP8266 on 115200 baud rate, and uploaded empty program then it started to respond `AT` commands. I connected as like above only change is TX to TX and RX to RX respectively. Alright!

    AT

    OK
    AT

    OK
    AT+GMR

    AT version:0.50.0.0(Sep 18 2015 20:55:38)
    SDK version:1.4.0
    compile time:Sep 18 2015 21:46:52
    OK

Well, I want to send `AT` commands from the Arduino serial monitor window to `ESP8266` and print `ESP8266` response to the command. When I upload above program then it stops to respond, same result as like empty screen this is weird. Isn't ?

  [1]: https://i.stack.imgur.com/hgqEl.png
  [2]: https://i.stack.imgur.com/NyVIA.png
  [3]: https://i.stack.imgur.com/c5CX5.png
  [4]: https://i.stack.imgur.com/bsgWD.png
  [5]: https://i.stack.imgur.com/judwG.png

title: AT command is not responding on serial monitor

Answers: 5

body:
The ESP's AT firmware is probably configured for a higher baud rate, 115200 is typical. SoftwareSerial only works reliably up to 9600 baud. It can transmit "reliably enough" at 115200 for you to blindly send change-baud commands, though the ESP's response will probably be garbled. So you need to either: Reduce the ESP's baud rate or use the Uno's hardware serial port for the ESP, which means giving up the Uno's terminal output and makes it a pain to reconnect your PC each time you need to update the Uno's code. I've described the process of changing the ESP's baud-rate in more detail in
[this answer][1].

Update: I'm not familiar with various AT comand-interpreter revs; my ESPs are all running with the firmware rev came on them; "AT+GMR" (show version info) replies:

    AT version:0.40.0.0(Aug  8 2015 14:45:58)
    SDK version:1.3.0
    Ai-Thinker Technology Co.,Ltd.
    Build:1.3.0.2 Sep 11 2015 11:48:04

<br>There is no AT+CIOBAUD command listed in my ESP8266 AT Instruction Set document rev 1.5.3). The only one listed that affects baud rate - and the one I  use - is:

    AT+UART_DEF=<baud>,<databits>,<stopbits>,<parity>,<flowcontrol>

, or:

    AT+UART_DEF=9600,8,1,0,0

for 9600 baud, 8 bits, 1 stop-bit, no parity, no flow control. You probably know, but just in case, note that you will lose communication immediately after you change the ESP's baud rate, until you then change the local baud rate to match.

Update2:

> This is program pastebin.com/dquCNYJj I am not sure what wrong I am
> doing

That code sets SoftwareSerial to 115200 baud; it can not run fast enough to receive data at that speed.

Update 3:

Since you've updated the ESP's firmware unsuccessfully, it's hard or impossible to know what's going on. The output in your screenshot looks rather like the result of a baud mismatch between the ESP and your terminal. You need to get a clean firmware update to the ESP before you can expect it to respond correctly and rely on its output to diagnose any other problems.

Update 4:

I'm not sure if we're talking about the same thing so please forgive me if you already know this; we might be talking about (at least) three different baud-rates:

 1. The rate in use during flashing of new firmware to the ESP;
 2. The default rate that new firmware will start listening at, whenever it is booted;
 3. The actual rate used at any given time between the ESP with its new firmware and the Arduino or some other device external to the ESP.

My own experience is with using the factory-installed AT Interpreter firmware. I have never needed to update it so I don't have personal experience with (1).

(2) and (3) are programmable by the Arduino. When I first use a new ESP (or after you've just re-flashed its AT Interpreter), it will listen at a factory-default baud rate (mine have all defaulted to 115200). There are commands to change the current rate (not saved across a reboot) and/or the default baud (saved for all future sessions).

I almost always change its default rate to 9600 to use it with an Arduino software serial port. This is my initialization for a new device, using an Arduino to talk to the ESP. (Don't transmit my '#...' comments):

    # Start talking at the ESP's default rate (115200 on my factory-fresh ones).
    AT+RST                         # Reset
    AT+UART_DEF=9600,8,1,0,0       # Default baud to 9600,N,8,1,no flow ctl
    # Here, change the Arduino's port to match: 9600 in this case.
    AT+CWMODE=1                    # Station mode (client)
    ATE0                           # Command echo off

From now on, the ESP will wake up listening at 9600 baud, in Station Mode as a client, with no command echo.

  [1]: https://arduino.stackexchange.com/questions/36447/wifiesp-not-working-on-software-serial-working-fine-on-hardware-serial/36453#36453

body:
Is it possible that this is a hardware connection issue? According to the datasheet of the ESP8266, it states that the maximum voltage input is 3.6V, but by connecting directly to the Arduino, the signal output by Arduino would be more than 3.6V. (Around 5V output)

[![Table][1]][1]

Instead of connecting directly, you might want to perform Level shifting first? (5V to 3.3V, vice versa)

(Here's the link to the ESP8266 datasheet: https://nurdspace.nl/images/e/e0/ESP8266_Specifications_English.pdf)

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

body:
First of all, Please check if you are giving proper voltage and current both to ESP8266. I've seen it not working if it doesn't get proper voltage and current.

Secondly, Connect your Rx,Tx of ESP8266 to Rx,Tx of Arduino respectively. Then, try doing one thing, just upload empty sketch having empty setup() and loop() function only.

Then, open serial monitor select your baud rate (mostly either 9600 or 115200) and you are all done! Sending "AT" via serial monitor input field will show you "OK" in serial monitor response window.

body:
On your last picture, you should connect the Rx of your Arduino to the Tx of your ESP8266 and vice versa.

If you did that and it doesn't work, try to upload an example sketch in order to determine if it's the code or the connexions that are problematic.
**I recommend that you use the WiFiScan example**, since that example doesn't require to change the code or to include other libraries othet than the ones from ESP8266Community.

body:
Try this:

    /*
      Software serial multple serial test

     Receives from the hardware serial, sends to software serial.
     Receives from software serial, sends to hardware serial.

     The circuit:
     * RX is digital pin 2 (connect to TX of other device)
     * TX is digital pin 3 (connect to RX of other device)

     Note:
     Not all pins on the Mega and Mega 2560 support change interrupts,
     so only the following can be used for RX:
     10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

     Not all pins on the Leonardo and Micro support change interrupts,
     so only the following can be used for RX:
     8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

     created back in the mists of time
     modified 25 May 2012
     by Tom Igoe
     based on Mikal Hart's example

     This example code is in the public domain.

     */
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // Serial.println("Goodnight moon!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(115200);
      // mySerial.println("Hello, world?");
    }

    void loop() { // run over and over
      if (mySerial.available()) {
        Serial.write(mySerial.read());
      }
      if (Serial.available()) {
        mySerial.write(Serial.read());
      }
    }


body:
Actually I am facing a big problem while programming my atmega328p using an arduino uno as ISP.
I followed a video on youtube  "Arduino as ISP" by Notes and Volts. Which look doing the same steps that the majority followed. For the blinking LED sketch the µC worked very well and it did not show any troubles.
So I  decided to carry on , and at this point I needed to upload a new program but this i wanted to upload my program using "avrdude" command line because my code was written with MikroC pro for avr, and here is the command line :

`"avrdude -p atmega328p -b 19200 -C arduino -P COM7 -U lfuse:w:0xf7:m -U
 hfuse:w:0xc9:m -U efuse:w:0xff:m -U flash:w:LED.hex:i " `

But unfortunately it did not work well and I have got the following error :

`avrdude : invalid byte value <ff> specified for immediate mode
 avrdude : write to file 'ff' failed
 avrdude : safemode : Fuses OK `

Seeing that error paniced me , that's why I decided to retry the programmation with an arduino sketch and then happened the big issue when the arduino generate an error message about finding a bad microcontroller [error about the device signature] [![PIC][2]][2].
My last try to find out if I ruined my µC is with switching the µCs; the arduino original and the one that I had to program and unfortunately It was not a good result :
"avrdude : stk500_recv() : programmer is not responding
 avrdude : stk500_getsync() attempt 1 of 10 : not in sync : resp=0x85"  [![PIC][3]][3]
Looking for more than day on the internet and I could not find a valid solution , except the possibility that I really BURNT my µC and I have to buy another one. And this is specifically why I am asking for your help; I need  to know if SO could figure this trouble out.Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .
Thank you
Regards

  [1]: https://i.stack.imgur.com/AykEY.png
  [2]: https://i.stack.imgur.com/0LFor.png
  [3]: https://i.stack.imgur.com/bdXCI.png

title: What if I have burnt my atmega328p?

Answers: 3

body:
> What if I have burnt my atmega328p?

get a new one.

> Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .

based on the information you have provided, no one can tell definitively. you could have changed the fuse settings, or your 2nd chip didn't have the bootloader, or bad connection, ....

a better approach is to get a separate programmer - usbasp for low prices, or dragon (older debugger with hv programming capability) and go from there.

body:
Trying your fuse settings on an
[AVR fuse calculator](http://www.engbedded.com/fusecalc/) shows that you
have selected an “external full-swing crystal” as the clock source.
Now your ATmega won't work unless you connect it to an external crystal.
Or you could try just sending a square wave into the XTAL1 pin. _Then_
you can try to reprogram it.

body:
after two days of searching on internet, I decided to just reburn the bootloader again on my target µC to discover if it's really burned or not.
SO, I guess it was not damaged because I was able to burn the bootloader and upload the blink led  sketch successfully.


body:
I've got a Uno (Elegoo UNO R3) running with
- Ethernet shield (Kuman K15),
- 4 relay board (Elegoo 4 Channel DC 5V Relay Module with Optocoupler )
- Matrix Orbital 2041 LCD connected via I2C (11mA typical, 90mA with backlight)
- A series of buttons connected

The Uno is currently running plugged in via USB to my macbook pro.

All of these devices are powered by the 5V pin on the Arduino.

The LCD goes wonky from time to time, and other times will work fine, it starts flashing the backlight, and just behaves oddly, sometimes even rebooting, when buttons are pushed (which activate the relays).

I'm wondering if this a power issue, perhaps the Uno isn't able to supply enough current to run everything.

My reading indicates that the USB port should be able to provide ~400mA, and when on an external supply I should able to draw 900 mA when using an external power adapter.  However even with on an external supply (12v, 2A) I still have these issues.

Any thoughts would be much appreciated.
Thanks

title: Uno with LCD acting strangely - power issue?

Answers: 1

body:
System resets can be caused by power droop and by noise at the Reset pin, among other reasons.  The problems mentioned could be due to power issues, or to electrical noise, or to wiring issues.

The total current draw apparently could approach or exceed the 400 mA mark mentioned in the question.  With all four relays on, and coils drawing 50 mA each, that's 200 mA.  LCD backlight and Arduino current make another 100, after which the ethernet shield could bring the total above 400 mA.

However, having the problems persist even with an external supply in use would suggest the root of the problems isn't power – if, of course, the external supply actually is supplying power directly to some of the peripherals, rather than via the regulator on the Uno.

When relays switch, they typically produce an electrical noise pulse.  If this is the problem, it could be mitigated using ferrite beads, chokes, noise filters, etc.  Using a separate power supply for +5 V to the board also should help.

Wiring issues include ground bounce and ground loops.  If you are using a breadboard, there may be poor ground or power connections.  Check that the grounds of peripheral devices and external supplies are solidly connected by decent wire and/or connected at a common point.


body:
I want to control flow level on 12V water pump with PWM pin, I'm using IRF520N MOSFET for that (and dedicated 12V power supply).

I'm assuming, that setting PWM to full byte should give me about 100% or 12V. But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%? Is it some logharitmic equation?

title: PWM water pump flow control - in percent

Answers: 3

body:
> But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%?

1. look at the pump's datasheet; and

2. experiment.

body:
Expanding on dannyf's answer, if the pump datasheet does not feature a graph, then you will have to experiment. If a flowmeter is not readily available, an excellent approximation can be calculated by pumping water into a large, known receptacle (e.g. 10 litre bucket) and timing how long it takes. Do this for 20%, 40%, 60%, 80% and 100% Pulse Width Modulation modes, and you will have a plot of flow rate vs PWM that will help you interpolate the PWM required for a desired flow rate (e.g. 50% flow rate).

Below is an example of Rotations Per Minute of a 12V computer CPU cooler water pump for a given PWM input. It is assumed that this would be under load (of pumping water), but not stated explicitly.

Note that it may not be physically possible for the motor to operate with 10% or less PWM duty cycle. At this point I imagine that the internal friction of the motor and forces required to push the water along are greater than the force provided by a "10%" duty cycle.

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

Source: [ekwb][2]

  [1]: https://i.stack.imgur.com/9z6nn.jpg
  [2]: https://www.ekwb.com/shop/ek-d5-pwm-motor-12v-dc-pwm-pump-motor

body:
You'll need to tun the pump at some number of intermediate PWM values and measure its output at each one. The more intermediate values you measure, the more precise your control can be. Then you build a table of flow-rates vs. PWM level in flow-rate order, something like:

    struct {
      float flow;  // measured flow rate
      float pwm;   // pwm value that gave that rate
    } FlowTable[FLOWTESTS] = {
     // flow  PWM
      {   0.,    0. },
      { 218.,  256. },
      { 480.,  512. },
      { 732.,  768. },
      { 885., 1023. }
    }

For a particular flow-rate, step through the table until you find a flow in the table that is >= to the flow you want (if it's ==, just use that PWM and you're done.)

We'll interpolate between the two table values that span the desired flow-rate. The idea is, if your desired flow is say, 17% (0.17) of the way between those two flows, you want a PWM value that's about 17% of the way between the two PWM values.

Let's say you want a flow of 600 (in whatever units your measurements are in - cc/minute, for example. Index 3 in the table (remember, our arrays are 0-based) has the first measured flow greater than 600, the desired flow, so we know the required PWM will be between 512 and 768. To find it, find the desired flow as a fraction of the interval [480, 732]:

` frac = (600-480)/(732-480) = 120 / 252 = 0.476`,

or letting 'i' be the index of the first table entry whose flow exceeds the desired flow:

` frac = (flow_des-FlowTable[i-1].flow) / (FlowTable[i].flow-FlowTable[i-1].flow);`

. We need the PWM that is 47.6% of the interval [512, 768]:

` pwm_req = 512 + ((768-512) * 0.476)) = 634`
or

' pwm_req = FlowTable[i-1].pwm + ((FlowTable[i].pwm-FlowTable[i-1].pwm) * frac);`


body:
I've reached the limit on available SRAM memory. I need to "cut down" some variables, but I actually don't know how far I need to go with it.

Is there a way on measuring current available memory on program execution?

title: Current available SRAM?

Answers: 1

body:
If you set "Show verbose output during compilation" in your IDE preferences, you'll see a message like the following in the IDE window's lower pane. The part I bolded is the amount of SRAM assigned:

> Sketch uses 2,148 bytes (6%) of program storage space. Maximum is 32,256 bytes.<br>
**Global variables use 204 bytes (9%) of dynamic memory**, leaving 1,844 bytes for local variables. Maximum is 2,048 bytes.

You can also include this function and print its result to get the same information on the terminal during run-time:

    int freeRAM () {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }


body:
I'm writing code that I discussed in [a previous post][1]. I now have a setup where I send my Arduino an ASCII-encoded Hex String that represents the bytes I want to write to my serial device. I think I've got most the code figured out other than the way to best convert the hex string for sending

This Code is working

    void SendCTRL (String &input)
    {
      const char *hin = input.c_str();    // Get character array
      int clen = input.length()/2;
      unsigned char cmd[clen+1]; // Leave a byte for null terminator
      for (int i=0; i < 2*clen; i+=2)
      {
        cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
      }
      cmd[clen] = 0;                     // Null-byte terminator
      digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
      for (int i=0; i< clen; i++)
      {
      RS485Serial.write(cmd[i]);   // Send string someplace
      }
      delay(clen/4);
      digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
      Serial.println();

    }

    byte dehex(char c)
    {
      // Get nibble value 0...15 from character c
      // Treat digit if c<'A', else letter
      return c<'A'? c & 0xF : 9 + (c & 0xF);
    }
From what I understand something along the lines of `char ISS = SubS.GetBytes()`, but guidance would be appreciated

  [1]: https://arduino.stackexchange.com/questions/37965/make-sure-n-is-the-last-character-in-serial-string/ "a previous post"

title: Hex String -> Byte Array -> Serial Write

Answers: 1

body:
What your code is aiming at isn't particularly clear to me, but I will assume that for some obscure reason you want to accept an input String containing a series of ASCII-encoded hex digits, and create an array of half that many bytes with reconstituted byte values.

First, here are several criticisms of the code shown.

It's likely `length(input)` won't compile but that [`input.length()`](https://www.arduino.cc/en/Reference/StringLength) will.

The expression `input.substring((2*i),(2*i)+1))` is a String of one character.  If you want two characters, use [`input.substring((2*i),(2*i)+2))`](https://www.arduino.cc/en/Reference/StringSubstring).  And use `i += 2` instead of `i++` in the `for` loop.

I don't understand `String CMD = CMD+ISS`.  I won't say it's invalid, as I don't know without more research.  But it looks like it's declaring variable `CMD` and using `CMD` in the initialization of `CMD`.  [In the example code I give below, I assume `CMD` should begin as an empty string and be filled up with reconstituted bytes.]

`RS485Serial.write(input); // Send byte to Remote Arduino` looks mis-commented; presumably it will write out all of the input, not just a byte.

Using a timed delay for holding RS485 Transmit open, as in
`delay(10);
 digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit`
may cause problems.  On the one hand, it may usually waste five to ten milliseconds of time; on the other, it might occasionally disable RS485 transmit before transmission finishes.  Instead, look for a flag to test for transmission complete, or look for a buffer-fill count, or compute how long to wait, etc.

The next paragraph describes some reasons that Strings may perform badly in this sketch.  For additional discussion of Arduino String objects, see arduino.cc's [*String*](https://www.arduino.cc/en/Reference/StringObject) page, and see Majenko's [*The Evils of Arduino Strings*](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/) page.

Each of the String-object operations in the code creates a new String.  New String objects `SubS` and `CMD` are created and destroyed in each pass of the `for` loop.  The object headers (with type data and member variables, such as a buffer pointer and buffer size) can be stack-allocated, which is harmless (does not leak or fragment memory) but takes some time.  Each String object's character-buffer is heap-allocated: see code in cores/arduino/ file `WString.cpp`.  Heap fragmentation can and will occur.  ... In brief:  In this application where using String objects is clunky and in the way, you might as well use ordinary C strings instead of String objects.

---

Ok, with criticisms out of the way, here's some example code that converts ASCII-encoded hex digits into a command string.  Note, as I don't know the specs for `RS485Serial.write()` or how it determines how much to send, for demonstration purposes I've supposed it can handle a C string.

    // Function declaration for dehex()
    byte dehex(char c); // Get nibble value 0...15 from character c

    void SendCTRL (String input) {
      const char *hin = input.c_str(); // Get character array
      int clen = input.length/2;
      // Next line invalid in C++, ok in C99.  Probably need to
      // instead declare a fixed-length array, cmd[MAXCMDLEN], etc
      char cmd[clen+1]; // Leave a byte for null terminator
      for (int i=0; i < 2*clen; i+=2) {
        cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
      }
      cmd[clen] = 0;      // Null-byte terminator
      digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
      RS485Serial.write(cmd); // Send string someplace
      delay(clen/4);  // Wait for write to complete? What rate?
      digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
    }

    byte dehex(char c) { // Get nibble value 0...15 from character c
      // Treat digit if c<'A', else letter
      return c<'A'? c & 0xF : 9 + (c & 0xF);
      // Above assumes that c is a 'hex digit' in 0...9, A or a ... F or f.
      // It would make more sense to just use 16 consecutive characters,
      // like eg 0123456789:;<=>? or @ABCDEFGHIJKLMNO so the above
      // could just say `return c & 0xF;`
    }

*Edit 2:*

1. The first statement, `byte dehex(char c);` is a function declaration for the `dehex()` function.  It tells the C/C++ compiler the datatypes that the function accepts and returns.  Note, instead of a function declaration at that point, one could instead put the function definition itself (which in the above follows `SendCTRL()`, a `dehex()` caller that needs to know `dehex()`'s datatypes).  Some versions of the Arduino IDE appear to work ok without function declarations ahead of use, but almost all other C/C++ environments will not.

2. In this edit I added `const` before `char *hin = input.c_str();` because ATE-ENGE reports  “`char *hin =input.c_str()` is giving me an invalid conversion error from const char* to char*”.  That error indicates the left-hand-side variable has a datatype different from that of the right-hand-side expression and an automatic conversion isn't available.  Note, unfortunately the arduino.cc [`c_str()`](https://www.arduino.cc/en/Reference/CStr) webpage doesn't specify the return type of `c_str()`.

*Edit 3:*  Changed `for (int i=0; i < clen; i+=2)` to `for (int i=0; i < 2*clen; i+=2)` per notes in [another question's answer](https://arduino.stackexchange.com/a/38384/3917).

*Edit 4:*  Changed `cmd[i/2] = dehex(hin[i])<<4 + dehex(hin[i+1])` to  `cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1])` to avoid an [operator precedence](http://en.cppreference.com/w/c/language/operator_precedence) problem.  The precedence of `+`, addition, is higher than that of `<<`, bitwise shift, which in turn is higher than that of `|`, bitwise OR.  The unparenthesized expression with `+` adds 4 to `dehex(hin[i+1])` and uses the total as a shift count; not at all as desired.  Note, one can of course use parentheses to control the problem, as in the expression `(dehex(hin[i])<<4) + dehex(hin[i+1])`


body:
I recreated this project from [Fritzing](http://fritzing.org/projects/arduino-lcd-alarm-clock) in my [circuits.io project](https://circuits.io/circuits/4891438-alarm-clock/) then on the arduino itself, it all works fine just how I wanted it.

The concept behind it is:

1. You plug it in and the time is set to 00:00

2. You can adjust the time to the time now let's say 22:46

3. You can put in an alarm to wake up let's say an hour later at 23:46

4. The piezo beeps in stops, so not continious.

So now my question is, **how can I add a led that flickers on the same rhythm as the piezo** (when the alarm goes off)? Can someone help me in my [circuits.io project](https://circuits.io/circuits/4891438-alarm-clock/)?

An update/edit would be great! I'm relatively new to all of this.

Thanks a lot!

title: How can I add a LED to this build?

Answers: 1

body:
 - You need to add an LED and series resistor between a currently unused Arduino pin and ground.

 - In your setup() function, set that pin's i/o mode to OUTPUT.

 - Where the code turns the tone on, it should also make the LED pin HIGH.

 - Where the code turns the tone off, it should also make the LED pin LOW.


body:
I have an LSM9DS1 breakout board by Sparkfun, and am communicating with it using a Mega 2560 over I2C. The board is given 3.3 V power as defined in the data sheet, though there seems to be confusion whether the SDA and SCL pins need level shifting for communicating with the 5 V Mega. In theory it shouldn't need to.

I am able to connect with the device and get its accelerometer and magnetometer data, however the gyro is just returning noise and no signal. I have dug in to all the registers I know of regarding high pass filters, logging rates, enabling and powering the sensor, but the only hints are that when the gyro is disabled and then polled, it returns a constant nonzero value on all three axes, as though a bit somewhere is stuck. With any other setting the results are unchanged: finite noise on a constant DC signal. Is this even possible? How can I dig deeper to understand and solve this problem?

title: How can I identify, debug or fix a faulty IMU?

Answers: 1

body:
In theory you **must** use a level shifter for SDA and SCL. The Arduino Mega 2560 board has internal pullup resistors of about 50k for SDA and SCL and extra 10k pullup resistors of 10k to 5V and according to the datasheet the ATmega2560 requires 3.5V to detect a high level for the I2C bus.

Those pullup resistors might damage the LSM9DS1.
5V-3.3V / 50k//10k times two (both SDA and SCL) = 400nA that might be pushed into the sensor (I assume there are protection diodes, and the maximum voltage is 3.6V, therefor the 400nA is just an indication).
I assume the 10k pullup resistors to 3.3V on the sensor module are enabled. They will take away some over-voltage.

The current by the pullup resistors (to 5V) is a very small current, and I don't know if the sensor is in sleep mode during startup.

To be sure you need to buy another LSM9DS1 and a level shifter. Or even better: buy a 3.3V Arduino board, like the Due or the Zero, M0, and so on.

Have to compared the raw sensor data with others ? Those sensors are very noisy. That is why there is so much to do about filter algoritms to get data that can actually be used. The LSM9DS1 does not do processing or smart filtering with the raw data. All you get is the raw data. Did you assume that the values would be zero ? They never will be, because such sensors are far too noisy and too sensitive for that.


body:
In my recent project, I'm working with Arduino and JSON. Now, I get data from JSON and I can able to receive in Arduino side.

Below one is my Arduino code:

    #include<LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    String response = "";
    bool begin = false;

    void setup()
    {
      Serial.begin(9600);
      lcd.begin(16, 2);
    }

    void loop()
    {

      while(Serial.available() || !begin)
      {
        char in = Serial.read();

        if (in == '{')
        {
          begin = true;
        }

        if(begin) response += (in);

        if(in == '}')
        {
            break;
        }
        delay(1);
      }

      lcd.setCursor(0, 0);
      lcd.print(response);
    }

Output :

    {"TPS":"0.40","MAP":"1.05","LOAD":"14"}

Now, I want to split data means store `0.40` in one variable, `1.05` in another variable and `14` in another variable. I don't know how to split this.

title: How can I split data coming from JSON?

Answers: 1

body:
Finally, I got it. I have fixed length of data. So, I use a counter to calculate the how many characters are there in my data. Now using the index of this characters, I find out proper data and then store in a different variable.

Below is my code:

    #include<LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    String responseOne = "";
    String responseTwo = "";
    String responseThree = "";
    bool begin = false;

    int counter = 0;

    void setup()
    {
      Serial.begin(9600);
      lcd.begin(16, 2);
    }

    void loop()
    {

      while(Serial.available() || !begin)
      {
        char in = Serial.read();

        if (in == '{')
        {
          begin = true;
        }

        if(begin)
        {
          counter++;

          if(counter >= 9 && counter <= 12)   // This gives 0.40
          {
            responseOne += (in);              // 0.40 store in responseOne variable
          }

          if(counter >= 22 && counter <= 25)  // This gives 1.05
          {
            responseTwo += (in);              // 1.05 store in responseTwo
          }

          if(counter >= 36 && counter <= 37)  // This gives 14
          {
            responseThree += (in);            // 14 store in responseThree
          }
        }

        if(in == '}')
        {
            break;
        }
        delay(1);
      }

      float newResponseOne = responseOne.toFloat();  // Convert string into Float
      float newResponseTwo = responseTwo.toFloat();  // Convert string into Float
      int newResponseThree = responseThree.toInt();  // Convert string into Integer

      lcd.setCursor(0, 0);
      lcd.print(newResponseOne);

      lcd.setCursor(8, 0);
      lcd.print(newResponseTwo);

      lcd.setCursor(0, 1);
      lcd.print(newResponseThree);
    }


body:
I've been doing fine with my LCD1602 I2C configuration but I discovered that command and data functions are the same even though I change the RS command/data bit, but the result is the same.

This is really strange, I really can't do anything about it??!

    #define E   2   // E  bit
    #define RW  1   // RW bit
    #define RS  0   // RS bit

    #define LCDadd_WR  0x4E
    #define LCDadd_RD  0x4F

    uint8_t bitmask = 0x08;
    uint8_t i, arr[]={0x48,0x65,0x6c,0x6c,0x6f ,0x10 ,0x3a,0x29 ,0x10 ,0x48,0x6f,0x77,0x10
    ,0x61,0x72,0x65,0x10,0x79,0x6f,0x75,0x65,0x76,0x65,0x72,0x79,0x10,0x6f,0x6e,0x65};

    // LCD prototypes
    void LCD_Init(void);
    void sendCMD(uint8_t CMD);
    void sendData(uint8_t data);
    void LCD_string(uint8_t arr1[]);
    void move_cursor (uint8_t row, uint8_t col);

    // I2C prototypes
    void I2C_init(void);
    void I2C_start(uint8_t address);
    void I2C_stop(void);
    void I2C_tx(uint8_t data);
    void I2C_TWSR_Check(void);

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

    void loop() {
    //sendData(0x0E); /* I commented this line because it has the same effect as sendCMD(0x0F); in sendCMD function */
    }

    ///////////////////////////////////////////////////
    ///////////////////////////////////////////////////
    void LCD_Init(void)
    {
      sendCMD(0x33);
      sendCMD(0x32);
      sendCMD(0x28);
      sendCMD(0x0F);
      sendCMD(0x01);
    }

    void sendCMD(uint8_t CMD)
    {
      bitmask = 0x08;
      I2C_start(LCDadd_WR);
      I2C_tx(bitmask &= ~(1<<RS));
      Serial.println("CMD");
      Serial.println(bitmask, HEX);
      I2C_tx(bitmask &= ~(1<<RW));
      I2C_tx(bitmask = CMD & 0xF0 | 0x08);
      _delay_ms(5);
      I2C_tx(bitmask |= (1<<E));
      _delay_ms(1);
      I2C_tx(bitmask &= ~(1<<E));
      _delay_ms(1);
      I2C_tx(bitmask = (CMD<<4) & 0xF0 | 0x08);
      I2C_tx(bitmask |= (1<<E));
      _delay_ms(1);
      I2C_tx(bitmask &= ~(1<<E));
      I2C_stop();
    }

    void sendData(uint8_t data)
    {
      bitmask = 0x08;
      I2C_start(LCDadd_WR);
      I2C_tx(bitmask |= (1<<RS));
      Serial.println("data");
      Serial.println(bitmask, HEX);
      I2C_tx(bitmask &= ~(1<<RW));
      I2C_tx(bitmask = data & 0xF0 | 0x08);
      _delay_ms(5);
      I2C_tx(bitmask |= (1<<E));
      _delay_ms(1);
      I2C_tx(bitmask &= ~(1<<E));
      _delay_ms(1);
      I2C_tx(bitmask = (data<<4) & 0xF0 | 0x08);
      I2C_tx(bitmask |= (1<<E));
      _delay_ms(1);
      I2C_tx(bitmask &= ~(1<<E));
      I2C_stop();
    }

    uint8_t BF(void)
    {
      I2C_start(LCDadd_WR);
      I2C_tx(bitmask &= ~(1<<RS));
      I2C_tx(bitmask |= (1<<RW));
      I2C_stop();
      I2C_start(LCDadd_RD);
      I2C_rx();
      while (!(TWDR == (bitmask & (bitmask<<3))));
      I2C_stop();
      I2C_start(LCDadd_WR);
      I2C_tx(bitmask |= (1<<RS));
      _delay_ms(500);
      I2C_tx(bitmask &= ~(1<<RS));
      _delay_ms(500);
      I2C_stop();
    }

    void move_cursor (uint8_t row, uint8_t col)
    {
      if (row==1)
      sendCMD(0x80+col);
      if (row==2)
      sendCMD(0xC0+col);
    }

    void LCD_string(uint8_t arr1[])
    {
    uint8_t cnt=0;
      for (i=0;i<29;i++)
      {
        sendData(arr1[i]);
        _delay_ms(500);
        cnt++;
        if (cnt==16)
        sendCMD(0xC0);
      }
      sendData(0x10);
    }

    ///////////////////////////////////////////////////
    ///////////////////////////////////////////////////

    void I2C_init(void)
    {
      //set SCL to 100kHz
      TWSR = 0x00;
      TWBR = 0x48;
      //enable TWI
      TWCR = (1<<TWEN);
    }

    void I2C_start(uint8_t address)
    {
      TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
      while (!(TWCR & (1<<TWINT)));
      TWDR = address;
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
    }

    void I2C_stop(void)
    {
      TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
    }

    void I2C_tx(uint8_t data)
    {
      TWDR = data;
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
    }

    uint8_t I2C_rx(void)
    {
      TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
      while (!(TWCR & (1<<TWINT)));
      return TWDR;
    }

title: Can't send Data to LCD1602 with I2C

Answers: 1

body:
    I2C_tx(bitmask |= (1<<RS));
    I2C_tx(bitmask &= ~(1<<RW));
    I2C_tx(bitmask = data & 0xF0 | 0x08);

RS is overridden in the third line, so the solution is:

    I2C_tx(bitmask = data & 0xF0 | 0x08 | (1<<RS));

And delete the first two lines :)


body:
I am sending a short 12-char control string over serial with Python and Debian Jessie.

It works, but sometimes chars are added or skipped randomly. Here it is an extract of the Arduino code:

    void setup() {
      matrix.begin();
      matrix.setTextWrap(true);
      matrix.setFont(&TomThumb);
      matrix.fillScreen(matrix.Color333(0, 1, 1));
      matrix.swapBuffers(false);
      Serial.begin(115200);
    }

    void loop() {
      char c = 0; // serial char buffer
      byte i = 0; // string counter (reused multiple times)
      // read the equalizer control string
      delay(1);
      if (Serial.available() > 0) {
        turnmatrixoff();
        String control_str = Serial.readStringUntil('\n');
        Serial.println((control_str));
        draw_equalizer(control_str.c_str());
      }

Here is the log of the strings echoed back from the Arduino:

    10563942332
    00863931110
    00773940100
    0000974940100
    00763940100
    10693931211
    00593950100
    00544840100
    00464950100
    1050000
    004549310744940100
    00664961211
    00694941111
    10784951100
    0
    00593931100
    00373931100
    00483920100
    00583720110
    10473510000
    000332710000
    00252710000
    00142510000
    00122620000
    002510000
    003310100
    00334520110
    00343520100
    00244720100
    00355820110
    00343611110
    10144621210
    00424921210
    10343921210
    00233811310

As you can see, some strings are truncated or padded (**they all should be of the same size**).

I've tried coding a char-by-char read function but the results were even worse:

    char c = 0; // serial char buffer
    byte i = 0;

    while (Serial.available() > 0) {
      delay(1);  //small delay to allow input buffer to fill
      c = Serial.read();
      if (c == '\n' || i >= EQUALIZER_STR_SIZE - 1) {
        // finished reading the string
        equalizer_str[i] = 0; // terminate the string
        Serial.println(equalizer_str); // debug echo
        draw_equalizer(equalizer_str);
        break;
      } else {
        // append to the string
        equalizer_str[i] = c;
        i += 1;
      }
    }

EDIT: [here it is the full python script][1].

Decreasing the baud rate to 9600 seems to fix the issue, but the matrix updates too slowly this way.

Maybe I could use some other serial port initialization trick to prevent buffer overflows?

UPDATE:

I've found another way to reduce the serial traffic by increasing the audio capture chunk. For some reason this way the errors are gone completely.
[Here it is a video of the code finally running fine][2].

  [1]: http://eadmaster.altervista.org/pub/prj/electr/audioleds.py
  [2]: https://www.youtube.com/watch?v=Z2HXyI6pbI4

title: Errors reading fixed-length control strings over serial

Answers: 0


body:
I developed an Arduino library that have a method called "process". This method is a Void function and must be called inside the loop and most of the time the library handles everything by it self:

    #include <HookNinja.h>

    HookNinja hookninja;

    void setup()
    {}

    void loop()
    {
      hookninja.process();
    }

The idea is to keep the user program a simple as possible. Sometimes "process" have some data to give back to the user so he can use it as he likes. A simple approach is not to make process void and make the user check for the return value of process:

    void loop()
    {
      someVariableType foo;
      foo = hookninja.process();
      if(foo) {
        //user defined things
      }
    }

But the data returned by process could be anything, from an int to an array of Strings, only the user knows the return type, also this method seems not very elegant. Im not an expert of C++, for me the ideal solution will be an object oriented approach were the user pass a function to process that can be called from the library, but I have no idea how to do this in C++, something like:

    void userFunction(type param) {
      //do something with param
    }

    void loop() {
      hookNinja.process(some how pass userFunction here)
    }

title: Passing user defined callback functions to a library method

Answers: 1

body:
A common solution would be to have the user provide a callback which
takes no arguments and returns nothing. This is how `attachInterrupt()`
works, so it may be the least surprising approach for your users. The
user function can then get data from the rest of the program using
globals.

If you really prefer passing an argument to the user function, the
problem is you do not know the data type. The usual approach in plain C
is to give it a “generic” pointer, and let the user cast it into a
pointer specific for his data type. This is how functions like `qsort()`
work:

<!-- langage: lang-c++ -->

    HookNinja hookninja;

    void userFunction(void *param) {
        someVariableType foo = * (someVariableType *) param;
        //do something with foo
    }

    void setup()
    {
        hookninja.attachCallback(userFunction);
    }

    void loop() {
        someVariableType foo = something;
        hookNinja.process((void *) &foo);
    }

A cleaner C++ approach could be to make you class a template that is
specialized for the type of the user data:

    HookNinja<someVariableType> hookninja;

    void userFunction(someVariableType param) {
        //do something with param
    }

    void setup()
    {
        hookninja.attachCallback(userFunction);
    }

    void loop() {
        someVariableType foo = something;
        hookNinja.process(foo);
    }

But keep in mind that many Arduino users may not be familiar with
templates.


body: I want to light up all the LEDs of a 7x5 matrix with arduino uno. How can i do so?

title: How to light up all LEDs of a 7x5 LED matrix?

Answers: 1

body:
You don't need an Arduino for that, and one will give you no benefit.

Connect all anodes to power, and all cathodes to the appropriate resistors, then ground.


body:
I'm looking for a way to read a 24 bpp bmp file from a SD cart, and than convert it to text and write it to the serial monitor.

So the output should look something like this:
R255,B255,G255

And that for each pixel

title: serial write pixels of a bmp image

Answers: 2

body: There is no "command" to read BMP files. They're files like any other. If you know how to read files on an SD card with an Arduino, then you know how to read BMP files. *Interpreting* the bytes of the file you just read is another matter. If the details of the BMP (width, height, depth, array offset, etc.) are known already, you may *seek* to the pixel array directly and begin parsing it (in your case, 3 bytes at a time in BGR order), remembering that BMPs are typically arranged bottom-to-top unless the height field in the header is negative.

body:
To read the pixels, start with this:

    int32_t readNbytesInt(File *p_file, int position, byte nBytes)
    {
        if (nBytes > 4)
            return 0;

        p_file->seek(position);

        int32_t weight = 1;
        int32_t result = 0;
        for (; nBytes; nBytes--)
        {
            result += weight * p_file->read();
            weight <<= 8;
        }
        return result
    }

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

        Serial.print("Initializing SD card...");
        if (!SD.begin(53)) {
            Serial.println("initialization failed!");
            while (1); // <- this is how you should block execution, not with returns
        }
        Serial.println("initialization done.");

        // Open
        bmpImage = SD.open("Circle.bmp", FILE_READ);
        textFile = SD.open("test.txt", FILE_WRITE);

        int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

        // Change their types to int32_t (4byte)
        int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
        int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
        Serial.println(width);
        Serial.println(height);

        int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

        if (pixelsize != 24)
        {
            Serial.println("Image is not 24 bpp");
            while (1);
        }

        bmpImage.seek(dataStartingOffset);//skip bitmap header

        // 24bpp means you have three bytes per pixel, usually B G R

        byte R, G, B;

        for(int32_t i = 0; i < height; i ++) {
            for (int32_t j = 0; j < width; j ++) {
                B = bmpImage.read();
                G = bmpImage.read();
                R = bmpImage.read();
                textFile.print("R");
                textFile.print(R);
                textFile.print("G");
                textFile.print(G);
                textFile.print("B");
                textFile.print(B);
                textFile.print(" ");
            }
            textFile.print("\n");
        }

        bmpImage.close();
        textFile.close();

        Serial.println("done write");
    }`
Source: [Arduino StackExchange Question: How to read bitmap image on arduino](https://arduino.stackexchange.com/questions/19795/how-to-read-bitmap-image-on-arduino)

The text output of this should be a file with an array of strings like `R10G100B25`, where R is the red component of the pixel, G is the green component and B the blue one. Work out how to print these to the serial output.

Note this is only compatible with the 24bpp format.


body:
I'm trying to make something that has one led and a gsm module which is SIM800L, I'm using seeeduino GPRS library.
What I'm trying to do is that when I call the GSM module and hung up after ringing once (about 2 seconds of ringtone) the led turns on, and when I call again and hang up after the second ringing sound (about 5 seconds of ringtone) the led turns off;
Note that the SIM800 module when starts receiving a call it prints on the serial every ringing period (about 2.5sec):

> RING
>
> {number 0664xxxxx}

then it shows up again telling, 2 times for one rington, 3 times for two ringtons, and when I stop calling the GSM the module prints:

> NO CARRIER

Here's my code as start:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    String inData;
    char incomingByte;
    //SIM800 TX is connected to Arduino D8
    #define SIM800_TX_PIN 8

    //SIM800 RX is connected to Arduino D7
    #define SIM800_RX_PIN 7

    //Create software serial object to communicate with SIM800
    SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

    void setup() {
      //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
      Serial.begin(9600);
      while(!Serial);

      //Being serial communication witj Arduino and SIM800
      serialSIM800.begin(9600);
      delay(1000);

      Serial.println("Setup Complete!");
    }

    void loop() {
      //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
      if(serialSIM800.available()){
        Serial.write(serialSIM800.read());
        incomingByte = serialSIM800.read();
        inData += incomingByte;
      }

    if(inData != "")
       {
         if (inData.indexOf("RING") >= 0) {
          delay(4000);
          serialSIM800.println("ath"); // Hang up at command
          inData = "";
         }
      }

      //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
      if(Serial.available()){
        serialSIM800.write(Serial.read());
      }
    }

I did this code so it hangs up 4 seconds after calling printing the message "RING", but it didn't work, can you please help guys, thanks!

title: Turn led on after ringing once, off after two rings when hung up SIM800

Answers: 0


body:
I want to make a very simple webserver who sends welcome message to anyone who joins it using WiFi.

I have a ESP8266MOD module, I want to program it using arduino ide and arduino uno board.
How I can use arduino uno to program this WiFi module without using urat USB serial board?

SoftwareSerial.h is not working with esp.write() command, I believe it is because of low power, can anyone suggest me on power supply too?

Thanks in advance,

Mohan

title: ESP8266MOD programing using Arduino uno?

Answers: 1

body: When you use the Uno for its UART only, i.e. grounding RST pin, its Rx pin 0 becomes Tx, and Tx pin 1 becomes Rx -- because that's what pins on the UART you are connecting to. AppMonk didn't say what specific breakout/ chip mount he's using, there are many, or say how he's managing level-shifting from the Uno to the ESP if needed. The Tx pin on Uno (0, labeled Rx) is putting out 5v and the ESP would prefer 3.3, so level shifting w/ simple voltage divider is recommended. You don't need to level shift the Tx signal from ESP to Arduino's Rx (pin 1).


body:
I am using the Adafruit datalogger shield (Rev B) and a pair of cheap 20x4 LCD I2C displays. The displays have a small I2C I/O expansion module board on the back. The LCDs I am using are these;

<https://www.amazon.ca/gp/product/B01GPUMP9C/ref=oh_aui_detailpage_o09_s00?ie=UTF8&psc=1>

I'm using the NewLiquidCrystal 1.3.4 I2C library. My UNO clone is the iteaduino-BT <https://www.itead.cc/iteaduino-bt.html>, which is a board I really like.

I am getting interference between the LCD displays and the SD card function. Sometimes I can write to the SD card, and sometimes I can't. I have tried several SD cards. After a lot of experimenting, I think I have identified the problem. The LCDs are interfering somehow with the SD card functions. The LCD objects are created with the following statements;
<!-- language-all: lang-cpp -->
    // set the lcd1 address to 0x26
    // Set the pins on the I2C chip used for lcd1 connections:
    // addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd1(0x26, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    // set the lcd2 address to 0x27
    LiquidCrystal_I2C lcd2(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

If I comment out the LCD lines, the SD problem goes away. My thinking is that the four data lines used by the LCDs (4,5,6,7) may be overlapping with the datalogger card, but after looking at the datalogger schematic, I can't see the problem. I found a couple of websites suggesting mapping the LCDs to use different data lines, but I'm not sure if that is the problem.

I also ran a program to scan the I2C bus and it showed that the LCDs were at 26 and 27 and the Adafruit datalogger at 68. No interference with addresses at least.

I really need this working yesterday. Creating datalogging projects is nothing new and I can't believe that there is no solution for including I2C LCD displays. Should I experiment with different LCD libraries or try mapping the pins differently during the creation of the LCD objects? I also am wondering if I can simply shut off the LCDs when writing to the SD card and then turn them back on after. I plan on taking measurements and writing the results every 5 minutes for several days, so high speed anything is not a requirement.

The code sample below is part of my program. I use the while(1) line as a hard break for debugging purposes.

    #include <OneWire.h>              // library for DS18B20 thermocouple
    #include <DallasTemperature.h>    // library for DS18B20 thermocouple
    #include <Wire.h>                 // used for rtc
    #include <SD.h>                   // library for SD card
    #include <SPI.h>                  // library used for SD card
    #include <RTClib.h>               // library for real time clock
    #include <LiquidCrystal_I2C.h>    // library for lcd displays
    #define ONE_WIRE_BUS 8            // Data wire for thermocouple is plugged into pin 8 on the Arduino
    #define SYNC_INTERVAL 1000        // mills between calls to flush() - to write data to the card

    RTC_PCF8523 rtc;                  // define the Real Time Clock object

    String datetimestamp;
    uint8_t MM;
    uint8_t DD;
    uint8_t mm;
    uint8_t hh;
    File logfile;                     // create file object to save results on SD card
    const int chipSelect = 10;        // for the data logging shield, we use digital pin 10 for the SD cs line
    OneWire oneWire(ONE_WIRE_BUS);        // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    DallasTemperature sensors(&oneWire);  // Pass our oneWire reference to Dallas Temperature.

    // set the lcd1 address to 0x26
    // Set the pins on the I2C chip used for lcd1 connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd1(0x26, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    // set the lcd2 address to 0x27
    LiquidCrystal_I2C lcd2(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    String inputString = "";         // a string to hold incoming data
    String ackString = "ack";        // acknowledgement string from terminal
    String temperature;              // temperature
    boolean stringComplete = false;  // whether the incoming string from serial port is complete with /n
    int interval = 60000;            // interval between measurements
    long previousMillis;
    int cycle = 1;                   // cycle number
    int heartbeat = 30000;           // ping teminal to prevent bluetooth from shutting down
    String dim_length;
    String dim_width;
    String dim_height;
    String measurements;              // string containing measurements for inclusion in SD file
    int firstcomma;
    int secondcomma;
    int thirdcomma;
    String logEntry;
    char filename[] = "logdata.txt";

    void setup(void) {
      Serial.begin(9600);
      inputString.reserve(20);               // reserve space for the inputString
      pinMode(10, OUTPUT);
      pinMode(ONE_WIRE_BUS, INPUT);          // used for thermocouple

      WaitFor(2000);

      lcd1.begin(20, 4);        // initialize the first lcd for 20 chars 4 lines
      lcd1.backlight();         // turn on backlight
      lcd1.clear();             // clear lcd11

      lcd2.begin(20, 4);        // initialize the second lcd for 20 chars 4 lines
      lcd2.backlight();         // turn on backlight
      lcd2.clear();             // clear lcd11

      //These routines update rows on the LCDs
      Row1("DATE: ");
      Row2("TEST CYCLE: ");
      Row3(" ");
      Row4(" ");

      // check for working real time clock
      if (! rtc.begin()) {
        Row4("RTC failed");
        WaitFor(500);
        while (1);
      }
      else {
        Row4("RTC found");
        WaitFor(500);
      }

      if (! rtc.initialized()) {
        Row4("RTC failed");
        WaitFor(500);
        while (1);
      } else {
        Row4("RTC initialized");
        WaitFor(500);
      }

      UpdateRow1(GetTimestamp());      // display current date and time
      UpdateRow2(cycle);               // display current test cycle

      // initialize SD card
      if (!SD.begin(10)) {
        Row4("SD init failed");
        WaitFor(500);
        while (1);
      } else {
        Row4("SD card initialized");
        WaitFor(500);
      }

      //log file setup
      if (SD.exists(filename)) {
        Row4("log file exists");
        WaitFor(500);
      } else {
        Row4("log doesn't exist");
        WaitFor(500);
      }

      // sample write to SD card
      Row4("opening log file");
      logfile = SD.open(filename, FILE_WRITE);
      Row4("writing log file");
      WaitFor(500);
      logfile.println("DateTime,Temperature");
      WaitFor(500);
      for (int x = 1; x < 6; x++) {
        logfile.print("Test # ");
        logfile.println(x);
        delay(1000);
      }
      logfile.flush();
      WaitFor(500);
      Row4("flushed log file");
      WaitFor(1000);

      while (1);  //temporary stop for debugging

title: LCDs interfere with Adafruit datalogger SD card function

Answers: 1

body:
I think your problem is with the way you create the LCD instants.

I've always used `LiquidCrystal_I2C lcd(0x27, 20, 4);` `LiquidCrystal_I2C lcd(address, row, col);` when I'm using the I2C modules.


body:
I've been rehashing some existing libraries I found on some obscure forums to measure a frequency on digital pin 5, using the ATmega328P/ATmega2560 Timer/Counter modules and an interrupt based approach in order to be able to measure frequencies up to 4MHz(-ish). However, using the code described below, the results are off by a factor of exactly 100. I used a frequency generator to accomplish these readouts. Here is an example of what I've been getting back when generating a 5000Hz square wave (50% duty cycle):

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

Can someone please point out what might be wrong. I've read the ATmega328P datasheet multiple times by now and it should just work! This is very strange.

>**Edit:**
As it turns out the AWG I use has a blantant software bug which causes it to generate a wave with a period that's 100 times too long (see picture below). Nevertheless as Edgar pointed out I made some pretty big mistakes by not taking into account race conditions. Therefore the code below has been updated. Also, the test program has been updated to generate a 50% duty cycle square wave @5000Hz for testing purposes as suggested by Edgar.

[![AWG software bug][2]][2]

This is the header file:

    #ifndef FreqCounter_h
    #define FreqCounter_h

    #include <avr/interrupt.h>
    #if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
    #else
    #include "WProgram.h"
    #endif
    namespace FreqCounter
    {
     extern volatile unsigned long f_freq;
     extern volatile unsigned char f_ready;
     extern volatile unsigned char f_mlt;
     extern volatile unsigned int f_tics;
     extern volatile unsigned int f_period;

     void start(int ms);
    }
    #endif

This is the source file:

    #include <FreqCounter.h>

    volatile unsigned long FreqCounter::f_freq;
    volatile unsigned char FreqCounter::f_ready;
    volatile unsigned char FreqCounter::f_mlt;
    volatile unsigned int FreqCounter::f_tics;
    volatile unsigned int FreqCounter::f_period;

    void FreqCounter::start(int ms) {
        f_period = ms;
     GTCCR = (1<<TSM) | (1<<PSRASY) | (1<<PSRSYNC); //halt all timers

        //set TC1 to normal mode => TOV1 flag set at TOP = 0xFFFF
     TCCR1A &= 0x00; //reset TC1 control register A
        TCCR1B &= 0x00; //reset TC1 control register B

        //set TC1 to use external clock source, clocked on rising edge
     TCCR1B |= (1<<CS10);
        TCCR1B |= (1<<CS11);
        TCCR1B |= (1<<CS12);

     //reset TC2
        TCCR2A &= 0x00; //reset TC2 control register A
        TCCR2B &= 0x00; //reset TC2 control register B

     //set TC2 to CTC Mode with TOP = OCR2A => counter cleared on reaching TOP
     TCCR2A |= (1<<WGM21);

     //TC2 is in CTC mode => set value of OCR2A = TOP
     OCR2A = 124; //TOP is reached every 125 counts (starting from 0)

        //set TC2 to use a prescaler of 1 => 16MHz / 128 = 125kHz
        TCCR2B |= (1<<CS20);
        TCCR2B |= (1<<CS22);

        f_ready = 0; //reset ready flag
        f_tics = 0; //reset TC2 interrupt counter

     //synchronize the value of both timers
        TCNT2 = 0;
        TCNT1 = 0;

        //clear interrupt flags
     TIFR2 |= (1<<OCF2A);
     TIFR1 |= (1<<TOV1);

        TIMSK2 |= (1<<OCIE2A); //enable TC2 Output Compare A interrupt => triggered on reaching TOP = OCR2A
     TIMSK1 |= (1<<TOIE1); //enable TC1 overflow interrupt => triggered on reaching TOP = MAX = 0xFFFF

     GTCCR &= 0x00; //restart all timers => start counting
    }

    /*
     * This ISR is triggered by TC2 every 1ms because
     * TC2 increments with a frequency of 16MHz / 128 = 125KHz
     * and reaches TOP every 125 counts
     * => trigger frequency = 1kHz
     * => trigger period = 1ms
     *
     * This ISR handles the Gate Time generation
     */
    ISR(TIMER2_COMPA_vect)
    {
        //increment number of TC2 interrupts (triggers when reaching TOP = OCR2A)
     FreqCounter::f_tics++;

     /*
      * If branch evaluates as true if given gate time (f_period) equals
      * amount of milliseconds TC2 has counted (= f_tics)
      */
     if (FreqCounter::f_tics >= FreqCounter::f_period)
     {
      //end of gate time => measurement ready
      TCCR1B &= ~0x07; //set TC1 to no clk source => TC1 stops counting
      TIMSK2 &= ~(1<<OCIE2A); //disable TC2 Output Compare A interrupt
      TIMSK1 &= ~(1<<TOIE1); //disable TC1 overflow interrupt
      FreqCounter::f_ready = 1; //set software flag for end of gating period

            //increment on overflow of TCNT1
      if (bit_is_set(TIFR1, TOV1))
       FreqCounter::f_mlt++;

            //calculate frequency
      FreqCounter::f_freq = 65536 * FreqCounter::f_mlt;
      FreqCounter::f_freq += TCNT1; //add value of TC1
      FreqCounter::f_freq = (long)(FreqCounter::f_freq * 1000.0 / (double)FreqCounter::f_tics);
      FreqCounter::f_mlt = 0;
        }
    }

    ISR(TIMER1_OVF_vect)
    {
     FreqCounter::f_mlt++;
    }

This is the test program:

    #include <FreqCounter.h>

    long frq;

    void setup()
    {
        //generate a 5 kHz square wave on OC0B = digital pin 5 = T1
     DDRD |= _BV(PD5); //PD5 = OC0B as output
     TCCR0B = 0; //stop timer
     TIMSK0 = 0; //disable overflow interrupt
     OCR0A = 50 - 1; //period = 50 * 64 cycles
     OCR0B = 50 / 2 - 1; //50% duty cycle
     TCCR0A = _BV(COM0B1) //non-inverting PWM on OC0B
      | _BV(WGM00) //fast PWM, TOP = OCR0A
      | _BV(WGM01); //...ditto
     TCCR0B = _BV(WGM02) //...ditto
      | _BV(CS00) //clock at F_CPU / 64
      | _BV(CS01); //...ditto
     Serial.begin(57600);
     Serial.println("Frequency Counter");
    }

    void loop()
    {
     FreqCounter::start(1000);
     while (FreqCounter::f_ready == 0);
     frq = FreqCounter::f_freq;
     Serial.println(frq);
    }

PS: This is my first ever post on this forum. Feel free to comment on the contents of my question. Tips as to how I might improve future questions are always welcome. Have a great day!

  [1]: https://i.stack.imgur.com/HQPLB.png
  [2]: https://i.stack.imgur.com/5rsZC.png

title: ATmega AVR frequency measurement with timer/counter

Answers: 1

body:
I am posting this as an answer, just because it doesn't fit as a
comment. But more than an answer it is intended to be a debugging help.

First, I would like to point out that you can use the same Arduino to
both generate the test signal and read it. This can be done by
configuring Timer 0 (the last one you have left...) to output the 5 kHz
square wave on OC0B (digital pin 5), and wire this signal to pin T1
which is... also digital 5. No wiring needed then! You can do this by
adding the following to your test program's `setup()`:

    // Generate a 5 kHz square wave on OC0B = digital pin 5.
    DDRD  |= _BV(PD5);    // PD5 = OC0B as output
    TCCR0B = 0;           // stop timer
    TIMSK0 = 0;           // disable overflow interrupt
    OCR0A  = 50 - 1;      // period = 50 * 64 cycles
    OCR0B  = 50/2 - 1;    // 50% duty cycle
    TCCR0A = _BV(COM0B1)  // non-inverting PWM on OC0B
           | _BV(WGM00)   // fast PWM, TOP = OCR0A
           | _BV(WGM01);  // ...ditto
    TCCR0B = _BV(WGM02)   // ...ditto
           | _BV(CS00)    // clock at F_CPU / 64
           | _BV(CS01);   // ...ditto

Then I would like to point out a couple of bugs in the library you are
using. First, there is an off-by-one error: the program is counting one
millisecond too much. This can be fixed by moving the lines

    //increment number of TC2 interrupts (triggers when reaching TOP = OCR2A)
    FreqCounter::f_tics++;

from the bottom to the top if `ISR(TIMER2_COMPA_vect)`.

Next, there is a race condition between the ISRs. Race conditions are
nasty bugs because they are hard to reproduce and most of the time you
don't see them. And then the program just fails at a random time after
many tests showed it works fine.

Here it works as follows: let's say that after the required time has
elapsed, `TIMER2_COMPA` fires and _right after that_ `TIMER1_OVF` fires
also. This second interrupt is put on hold (it's a _pending interrupt_)
while `TIMER2_COMPA_vect` runs through its prologue. Then you compute
the frequency based on `FreqCounter::f_mlt` (which has not been updated
to account for the overflow) and `TCNT1` (which has already overflown to
zero). Thus you get an incorrect result. Not only that, the overflow
flag remains set, so the ISR will run _right away_ as soon as the
interrupt is enabled again by your next call to `FreqCounter::start()`.
And again you get an incorrect result.

The fix is two fold: first you have to detect the pending interrupt
condition in `ISR(TIMER2_COMPA_vect)`: after stopping the timers and
before computing `FreqCounter::f_freq`, you need this:

    // Did we miss an overflow?
    if (bit_is_set(TIFR1, TOV1))
        FreqCounter::f_mlt++;

Next, you have to clear the interrupt flag. This is customarily done
right before enabling the interrupt, and just to be safe you do it for
every interrupt you enable. Thus, in `FreqCounter::start()`, right
before touching `TIMSK2` and `TIMSK1`, you would:

    // Clear interrupt flags.
    TIFR2 = _BV(OCF2A);
    TIFR1 = _BV(TOV1);

There are a couple of other minor issues, like the statement
`TCCR2A &= ~(1<<WGM22);` which makes no sense (the bit belongs to
another register). But given that this, like a few other statements, has
no effect whatsoever, it should not affect the working of the program.
It does reveal sloppy programming though.


body:
I am having small project where I want to read couple of analog inputs from Arduino UNO, send it via software serial to ESP8266-01 and from that to python server using TCP.

Data is sent to ESP using this code on Arduino UNO

    #include <SoftwareSerial.h>

        SoftwareSerial mySerial(10, 11); // RX, TX
        int pin = 5;

        void setup() {
          mySerial.begin(9600);
          delay(20000);
        }
        void loop() {
          delay(1000);
          int data = analogRead(pin);
          mySerial.println(data);
        }

Code on ESP is bellow

    void loop() {
        while(Serial.available()>0){
        char data = Serial.read();
        client.print(data);
        }
    }

When data is sent to Python server, it prints it out but data is sent in two seperate parts, so it always looks like this

    9
    59

, but number sent from arduino is just 959!

Python server code snipet:

    while True:

            #Receiving from client
            data = conn.recv(1024)

            print data

            #send data to database
            post.create(
                current = str(data)
            )

             if not data:
                break

So the question is, why data sent to server is separated in two parts? Maybe it have to do something with how data is reading from serial on esp?

title: ESP8266 problem with recieved data trasmission via TCP

Answers: 1

body:
You assume all 5 bytes of `959\r\n` are received by the server at the same time. The data is sent byte after byte, based on the `client.print(data)` in the ESP code and assuming the underlying library doesn't buffer bytes before transmitting, so there's no way they'll arrive at the server simultaneously. Most likely, your first pass with `conn.recv(1024)` grabs the first byte `9` and times out. And then on the second pass, the others (at least 2) arrive and are read. The newline between the packets is typical Python 2 `print` behaviour.

What you need to do is parse the data at the server. Basically read data till you get CRLF i.e. `\r\n`, which is a good enough delimiter and you're sending it already anyways, and then use that to know when to write to your database.