body:
I'm using piezzos too, for making art installations, and I used max-msp too, but I don't like it too much.
It's a whole new world change from the computer to the Arduino. Because it's not only the code, you must deal with electronic components I'm quite a novice too and I don't know how much you know about music and electronic components so maybe I say things wrong or that you already know, but I will say:

 - AC Adapter

I will use an AC Adapter better than batteries, because the batteries will run out in a couple of hours and in a night club almost for sure you will have access to some power extension. Arduino usually works with 9v 1A, but it'll go for 2A.

 - Music Shield

And you need a music shield, you can buy a cheap one, but I recommend the Adafruit ones, because they come with a lot of more information, and more people are working with them, but they're usually more expensive. With the music shield you need a SD card. Arduino don't have enough memory so you need a music shield with a SD card to storage the sounds.

 - Speakers and amps

and finally the speakers, it depends in what kind of speakers are you using, if you're using a big ones like some Yamaha MSP you will need and amplifier,  but if you're using little ones like 8ohm 0.25W with the music shield will be enough

 - some kind of box

you will need to put the Arduino in some kind of box, and I will secure it in the wall and not in the ground


sender: user

message:
Variable was not declared in this scope

When I compile this code I get a  error: 'currentState' was not declared in this scope.

The code:

    enum state: int
     {
      NOTREADY,
      WAITSTARTUP,
      WAITSECRET,
      REVEALSECRET
     }

    state currentState; <---- Error

    const int BUTTONPIN = 4;
    const int ROTARYPIN = A0;

    void setup()
    {
      //Open Serial Monitor for debugging purposes
      Serial.begin(9600);

      //Configure the pins
      pinMode(BUTTONPIN, INPUT);
      pinMode(ROTARYPIN, INPUT);

      //Initialise the LCD
      lcd.begin(16, 2);

      //Assume that the current state is wait for start up signal

      currentState=WAITSTARTUP;
    }

sender: assistant

body:
You have missing semicolon after the enum:

    enum state: int
     {
      NOTREADY,
      WAITSTARTUP,
      WAITSECRET,
      REVEALSECRET
     };  // <-- here


body:
//go the Tools > Boards and check that you have selected the right option of your hardware? your remaining code is almost ok. But remember to add semicolon ";" sign at end every coding line.

      enum state: int{NOTREADY,WAITSTARTUP,WAITSECRET,REVEALSECRET};
      state currentState; //<---- Error

      const int BUTTONPIN = 4;
      const int ROTARYPIN = A0;

      void setup()
      {
        //Open Serial Monitor for debugging purposes
        Serial.begin(9600);

        //Configure the pins
        pinMode(BUTTONPIN, INPUT);
        pinMode(ROTARYPIN, INPUT);

        //Initialise the LCD
        lcd.begin(16, 2);

        //Assume that the current state is wait for start up signal

        currentState=WAITSTARTUP;
      }


message:
unexpected primary-expression before ';' token

I'm new to the Arduino world and am working on a sketch to run a servo up and down with a spdt switch.
 My code is :

    include #include<Servo.h>
    int pos = 0;

    Servo myservo;
    void setup() {
      pinMode(2, INPUT);
      pinMode(3, INPUT);
      myservo.attach(9);
    }
    void loop() {
      if (digitalRead(2) == HIGH && pos < 180) {
        pos++;
        servo.write(pos);
        delay(15);
      }
      if (digitalRead(3) == HIGH && pos > 0) {
        pos--;
        servo.write(pos);
        delay(15);
      }
    }

 When I compile I get the "unexpected primary-expression before ';' token" error with exit status 1.

What am I doing wrong???

body:
**1)** You should be using:

    myservo.write(pos);

instead of

    servo.write(pos);

for all of your  methods.

**2)** Change:

    include #include<Servo.h>

to

    #include <Servo.h>

**This code only verifies when it is run on certain boards*, so make sure you are using one of those boards.Good luck and welcome to the Arduino world!:)**

*Verify that your board will work, I know Mega, Uno and Nano will function properly.

P.s. Here is the whole code in correct format:

    #include <Servo.h>

    int pos = 0;

    Servo myservo;
    void setup() {
     pinMode(2, INPUT);
     pinMode(3, INPUT);
     myservo.attach(9);
    }
    void loop()
    {
      if ( (digitalRead(2) == HIGH) && (pos < 180)) {
        pos++;
        myservo.write(pos);
        delay(15);
      }
      if ( (digitalRead(3) == HIGH) && (pos > 0)) {
        pos--;
        myservo.write(pos);
        delay(15);
      }
    }


message:
Uno - measure the voltage, NOT connecting GND

I'm trying to use an Arduino Uno, to measure the Voltage over a Resistor in a circuit. I guess the usual way would be to connect GND to one side of the Resistor and the AD0 Pin to the other end, and scale the (0..1023) to (0..5V).

The problem is however, that connecting the GND to one side of the Resistor affects the circuit. Since the GND of Arduino is also connected to a Servo Driver (and other stuff), Some of the power that was supposed to be consumed by my Resistor, is now consumed by the parallel circuits.

Is there any way to measure the Voltage over the resistor without using GND?

body: If I understand the description correctly, neither side of the resistor is at ground potential.  There's a wide gamut of methods of dealing with this, for example using a differential ADC unit, or using an instrumentation amplifier ahead of a single-ended ADC.  But perhaps the simplest method is to use two ADC channels, one attached to each end of the resistor, with ADC ground connected to some common reference point.  Measure both voltages and take their difference .


message:
ST7735 display with esp32

I have edited the adafruit ST7735 library so that it supports esp-32.I made some edits in Adafruit_ST7735.h file. which are as follows.

[![the definitions for esp32 should be added as in the picture bellow][1]][1]

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

The code works fine but I had expected the screen to work faster with esp-32(due to higher processing power) but it does not do that.

I checked the time for fill screen operation for esp-32 and arduin mega. They come out to be almost the same. (around 0.12 seconds). Can anyone explain why this is happening and can I increase the speed?

body:
The ST7735 uses SPI to communicate. It will always be slow compared to parallel connected screens.

The fact that you appear to be using bitbanged SPI (manually toggling IO pins) makes it even slower.

The fastest you will be able to get with that screen will be to use hardware SPI instead (which most likely limits which pins you can use - I am not familiar with the ESP32 though) but that will still be somewhat slow.

If you want really high speed screen updates then you will need a parallel interface screen, ideally a 16-bit parallel interface screen. However, for that you need around 20 IO pins to drive it.


message:
Conversion of Arrays into Matrix?

I'm going through problem in Arduino code. I have three Arrays and want to convert them into a matrix. I have tried hard but couldn't solve issue.

    float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
    float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
    float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
    float Loadbase,Loadshift;

    void setup() {
        for (int i=0;i<24;i++){
            Loadbase={lb1[i],lb2[i],lb3[i]};
        }
    }

    void main() {
    }

body:
Two dimensional arrays in C++ (directly):

    float matrix[3][24] = {
        {1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730},
        {1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450},
        {500,500,600,600, 380.3005 ,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250}
    };

Two dimensional array indirectly (array of pointers):

    float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
    float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
    float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
    float * matrix[3] = {lb1, lb2, lb3};

If you want two dimensional array with copies of lb1/lb2/lb3:

    float matrix[3][24];
    for (int i = 0; i < 24; ++i) {
        matrix[0][i] = lb1[i];
        matrix[1][i] = lb2[i];
        matrix[2][i] = lb3[i];
    }

Btw: you were saying something about "mistakes" if I split definition on more lines, but guess what:
`float lb3[24]={500,500,600,600,  380.3005  ,3155`. This is a valid float number, but you have only 23 items then.

If you use at least space as a number separator, it can't be even compiled:

    float lb3[24] = { 500, 500, 600, 600, 380. 3005, 3155, 530, 400,  400, 600, 350, 250, 250, 500, 500, 250, 1655, 1655, 3155, 2130, 250, 150, 250};


body:
Check this code with slight amendments:

    float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
    float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
    float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};

    void setup() {
    int loadbase[3][24] = {{lb1}, {lb2}, {lb3}};
    void main()
    {}


message:
How to Read Voltage Level?

I want to read voltage level by my Arduino board please help in this regard. I am using this syntax.

    volts = analogRead(A3);    // read the input pin
    Serial.println(volts)

body:
//use this syntax and add ; sign at end of each line and try to read voltage level via voltage divider circuit.

    volts = analogRead(A3);    // read the input pin
    Serial.println(volts);             // debug value


body:
First off you need to convert your signal's units from analog -> voltage. Do this by using the following equation. I've modified your code so you can copy and paste it into your IDE.

    float volts = analogRead(A3) * ( 5.0 / 1024.0) ;

Hope this helps! Good luck!


message:
Communicating between two arduino terminal using Xbee

I have 2 Arduinos, mounted with Xbee Shield and Xbee S1 module on each.
One arduino is mounted on car chassis while another is connected with PC. Our AIM is to send signal from the arduino connected on PC and the motor will be controlled by the Arduino connected on car chassis.
Here is the code of the arduino connected with PC:

    char msg= "";
    void setup(){
     Serial.begin(9600);}

    void loop(){
     msg=Serial.read();
     serial.println(msg);
    }

Here is the code of the Arduino on car chassis:

    char msg = ' ';
    int motorA1 = 2;
    int motorA2 = 3;
    int motorB1 = 4;
    int motorB2 =5;

    void setup() {
      pinMode(motorA1, OUTPUT);
      pinMode(motorA2, OUTPUT);
      pinMode(motorB1, OUTPUT);
      pinMode(motorB2, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      while(Serial.available()>0){
      msg=Serial.read();
      switch(msg){
       case 'f':Serial.println("Forward");break;
       case 'b':Serial.println("Backward");break;
       case 'r':Serial.println("Right");break;
       case 'l':Serial.println("Left");break;
       case 's':Serial.println("Stop");break;
     }
    if(msg=='f'){
      digitalWrite(motorA1,HIGH);
      digitalWrite(motorA2, LOW);
      digitalWrite(motorB1,HIGH);
      digitalWrite(motorB2,LOW);
      Serial.println("Running Forward");
      }
    if(msg=='b'){
      digitalWrite(motorA1,LOW);
      digitalWrite(motorA2,HIGH);
      digitalWrite(motorB1,LOW);
      digitalWrite(motorB2,HIGH);
      }
    if(msg=='s'){
      digitalWrite(motorA1,LOW);
      digitalWrite(motorA2,LOW);
      digitalWrite(motorB1,LOW);
      digitalWrite(motorB2,LOW);
      }
    if(msg=='r'){
      digitalWrite(motorA1,HIGH);
      digitalWrite(motorA2, LOW);
      digitalWrite(motorB1,LOW);
      digitalWrite(motorB2,LOW);
      }
    if(msg=='l'){
      digitalWrite(motorA1,LOW);
      digitalWrite(motorA2,LOW);
      digitalWrite(motorB1,HIGH);
      digitalWrite(motorB2,LOW);
      }
    }
    }
Now our next AIM is to send back a feedback from car to the Arduino terminal of PC, e.g. if we are giving 'f' as a input and we get a reply 'Running Forward' on the next line. What line of code should we incorporate for that?

body:
//your code looks almost ok. The thing that i am feeling wrong is that arduino at the PC end. It should communicate with PC and 2nd arduino at the same time. So use arduino mega or "#include <SoftwareSerial.h>" library to avail extra Serial at this end if you are using arduin uno. Your code will be like this..

    char msg= "";

    void setup(){
    Serial.begin(9600);
    Serial1.begin(9600)//<----error
    }

    void loop(){
     msg=Serial.read();
     serial1.println(msg);//<- - -error
    }


message:
If Else Alternative

I've written a function that heavily relies on the If / Else statement but I feel it's a very beginner way to achieve functionality. Are there any better ways to achieve the same functionality?

Code:

    void jumpThree() // Update from left then right
    {
      if (effectCounter[0] < tiles) // Right, first tile
      {
        Serial << flag[6] << "\t";
        Serial << newRed[0] << " " << newGreen[0] << " " << newBlue[0] << "\t";

        if (flag[6] == 1)
        {
          oldRed[0]   = (tileBuffer[effectCounter[0]] & 0xff0000) >> 16;
          oldGreen[0] = (tileBuffer[effectCounter[0]] & 0x00ff00) >> 8;
          oldBlue[0]  = (tileBuffer[effectCounter[0]] & 0x0000ff);

          Serial << effectCounter[0] << "\t";
        }

        else if (flag[6] == 0)
        {
          oldRed[0]   = (tileBuffer[6 - effectCounter[0]] & 0xff0000) >> 16;
          oldGreen[0] = (tileBuffer[6 - effectCounter[0]] & 0x00ff00) >> 8;
          oldBlue[0]  = (tileBuffer[6 - effectCounter[0]] & 0x0000ff);

          Serial << (6 - effectCounter[0]) << "\t";
        }

        Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

        if ((newRed[0] - oldRed[0] != 0) || (newGreen[0] - oldGreen[0] != 0) || (newBlue[0] - oldBlue[0] != 0))
        {
          // Red difference
          if (newRed[0] - oldRed[0] > 0) // Positive red change
          {
            oldRed[0] ++;
          }
          else if (newRed[0] - oldRed[0] < 0) // Negative red change
          {
            oldRed[0] --;
          }

          // Green difference
          if (newGreen[0] - oldGreen[0] > 0) // Positive green change
          {
            oldGreen[0] ++;
          }
          else if (newGreen[0] - oldGreen[0] < 0) // Negative green change
          {
            oldGreen[0] --;
          }

          // Blue difference
          if (newBlue[0] - oldBlue[0] > 0) // Positive blue change
          {
            oldBlue[0] ++;
          }
          else if (newBlue[0] - oldBlue[0] < 0) // Negative blue change
          {
            oldBlue[0] --;
          }

          if (flag[6] == 1)
          {
            tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
          }

          else if (flag[6] == 0)
          {
            tileBuffer[6 - effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
          }

          // tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
        }

        else if (((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0))
        {
          effectCounter[0] ++;  // Go to next tile
          //flag[1] = false;
        }
      }

      else
      {
        flag[1] = false;
        effectCounter[0] = 0;

        if (flag[6] == 1) // Flip flop between left and right updates
        {
          flag[6] = 0;
        }

        else if (flag[6] == 0)
        {
          flag[6] = 1;
        }
      }
      delay(wait);
    }

body:
No, if-else is really the simplest way of dealing with that.

If you wanted to abstract it a little since you have repeated code just with separate variables, you could make a little function

    // Note: set the right parameter variable types here
    // to match your unspecified variables.
    static inline int testUpDown(int a, int b) {
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
    }

    // Inside your flag tests:
    oldRed[0] = testUpDown(newRed[0], oldRed[0]);
    oldGreen[0] = testUpDown(newGreen[0], oldGreen[0]);
    oldBlue[0] = testUpDown(newBlue[0], oldBlue[0]);

If you wanted an inline conditional variant you could do it with this:

    oldRed[0] = ((newRed[0]-oldRed[0]) ? ((newRed[0]-oldRed[0])/abs(newRed[0]-oldRed[0])) : 0);

But who can understand that?  You could always macro it:

    #define UPDOWN(A,B) (((A)-(B)) ? (((A)-(B)) / abs((A)-(B))) : 0

    oldRed[0] = UPDOWN(newRed[0], oldRed[0]);


body:
you can shorten a lot of the vertical space with more compact conditionals, including ternaries to remove double conditionals where one result must follow from another.

For example, you can turn this:

      // Green difference
      if(newGreen[0] - oldGreen[0] > 0)  // Positive green change
      {
        oldGreen[0] ++;
      }
      else if(newGreen[0] - oldGreen[0] < 0) // Negative green change
      {
        oldGreen[0] --;
      }

into just this:

    // Green difference
    int gDiff = newGreen[0] - oldGreen[0];
    if(gDiff) oldGreen[0]+= (gDiff > 0) ?  1 : -1;


body:
For part of this you can use the switch case style
Which looks like

    switch(flag[6]) {
        case 0  //your code here
                 break;       // and exits the switch
        case 1 : cout << '2';
                 break;
        default: //all other cases
    }
There is also the ? syntax that can help

> condition ? result_if_true : result_if_false

If I "refactor" this type of code (really we all get there from time to time) I try to go back to "what I want". From What I understand your code would look like (no code validation this is a educational example)

    int bufferoffset=0;
    int bufferMultiplyer=1;

    if(flag[6] == 0)
    {
       bufferoffset=6;
       bufferMultiplyer=-1;
    }
    oldRed[0]   = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0xff0000) >> 16;
    oldGreen[0] = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x00ff00) >> 8;
    oldBlue[0]  = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x0000ff);

    Serial << (bufferoffset+bufferMultiplyer*effectCounter[0]) << "\t";

    Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

    int redDiff=newRed[0] - oldRed[0];
    int greenDiff=newGreen[0] - oldGreen[0] ;
    int blueDiff=newBlue[0] - oldBlue[0] ;
    if(redDiff!= 0)
    {
      redDiff > 0?         oldRed[0] ++:   oldRed[0] --;
     }
    if(greenDiff!= 0)
    {
      greenDiff> 0?         oldGreen[0] ++:   oldGreen[0] --;
     }
    if(blueDiff!= 0)
    {
      blueDiff> 0?         oldBlue[0] ++:   oldBlue[0] --;
     }

        tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
    }

for more details on switch case see http://en.cppreference.com/w/cpp/language/switch
for more detail on ? syntax https://stackoverflow.com/questions/795286/what-does-do-in-c


body: //when there are multiple if/if-else/nested if/nested if condition then obviously it creates complexity in the code. I think switch is best option to use in such conditions. plz check switch condition if it is feasible in your program. Moreover i will check it in detail if it still not works. Try.........


message:
Understanding schematics: resistors attached to Attiny85 pins V-USB

I'm currently trying to create my own Attiny85 usb thumb(to mimic an joystick). I understand that I have to limit the voltage on the attiny's pins that are connected to the D+/- pins from the usb. In various schematics there are some pull-up resistors used with some zener diodes(that will drop the voltage that exceeds 3.3 V).[![enter image description here][1]][1](taken from [insidegadgets][2])

# Question:
# \#1
I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid an regulator?(as other schematics incorporate in them)

# \#2
Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.

# \#3
An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.007=171 ohms.That resistor attached to the attiny **would** produce a 1.2 drop).

# \#4
There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

  [1]: https://i.stack.imgur.com/7h7Td.png
  [2]: https://www.insidegadgets.com/2011/05/08/playing-around-with-v-usb-for-avr/

body:
> I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid the regulator?

If you have a 5v supply, as in a USB connection, and you want to run off 5v, then you do not need any regulator.

> Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.

Because only that pin needs pulling up to indicate the presence of a device on the USB bus.

> An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.7=1.71 ohms).

You can only use a resistor to drop a fixed voltage of you have a fixed current. The current you quote is the chip's supply current, not the GPIO current, which you cannot know or predict. Also, if you did use a resistor it would operate both ways and the 3.3V coming in would also be reduced so the MCU will not be able to read the data.

Even if you did know the current you would find it was very small so a huge resistor would be needed, which would induce intolerable amounts of noise. It would also violate the USB specifications.

> There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

They are to protect the ATTiny's IO pins. Without those the zener diodes will sink way too much current from the IO pins and damage them. They also act partially as termination resistors for the USB bus (which should be 20Ω).


message:
Why is my Analog Input channel adding voltage to my signal?

*EDIT*: Here are the links to the sensor spec sheet (http://www.omega.com/temperature/pdf/HX71.pdf) and manual (http://www.omega.com/Manuals/manualpdf/M4543.pdf) for your reference.

I'm using a relative humidity (RH) sensor with an Arduino Mega. The RH sensor runs off of +/- 24V  (which is being sourced by a power supply), and outputs a signal from 0-5VDC. Naturally, I am plugging this output signal into my A0 channel. There is a bare Earth Ground wire that is wired to the power supply's earth ground (possible error?) **Arduino's GND is connected to the power supply's EARTH GND, fyi**.

I compared the voltage reading in my Arduino Serial Monitor to a reliable Fluke multimeter, and **the analog input channel is adding ~.2 Volts!**

From some research, I have read about "high impedance" "source impedance" "internal wiring of Arduino" etc, but unfortunately I am failing to grasp the reason *why* this is happening. I'd like to know so then I could figure out a solution on my own.

Below is a schematic of what I'm dealing with so that it may better illustrate my issue (also my code). Thank you for your time, and I appreciate your help!

[![Error drawn out.][1]][1])

    void setup()
    {

    Serial.begin(9600);

    }

    void loop()
     {

      float hs1 = ((( analogRead(A0) * ( 5.0 / 1024.0) ) )* 20.0 );

      Serial.print("RH%");
      Serial.print(":");
      Serial.print(hs1);
      Serial.print(";");
      Serial.println();
      delay(1000);

    }

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

body:
Wow, you guys are gonna get a KICK out of this!

The analog input channel was **not** adding millivolts to my Analog Input signal. I stupidly was not supplying my Arduino Mega with 9V!! I had it running off of the USB port, which was affecting my 5V reference (thank you @majenko for pointing that out!).

I measured the 5V pin and it was fluctuating between 4.41-4.21 volts. My colleague made a comment and I reviewed the Arduino Mega datasheet. It must be supplied with 7-12 volts in order for the 5V to output correctly.

Once I hooked my Power Vin + GND to my power supply, set that at 9V/.08amps my analog input readings were accurate.

**Thank you everyone for your help!**


message:
Can removing lines of code destroy a motor driver and make it catch fire?

I am making a pid line follower robot. So I was tinkering with code to optimize my line follower when i removed two lines of code unknowingly. As soon as I uploaded my code and started the line follower, 4 mosfets on my motor driver smoked and burst into blue flames. Bought a new one and same outcome. Interestingly, The ones corresponding to the left motor alone had this outcome as I removed " return Motorspeed1" and " return MotorSpeed2" from the function corresponding to the left motor. Heres the code :

    signed int MotorSpeed = 70;
    int MotorSpeed1, MotorSpeed2;
    int MotorFunc(signed int a, signed int b){
       if(a >= -10 && a < 0)
       {
          b = -b;
          digitalWrite(_brk_m1, LOW);
          digitalWrite(_brk_m1, LOW);
          digitalWrite(_dir_m1, HIGH);
          digitalWrite(_dir_m2, LOW);
          MotorSpeed1 = MotorSpeed + b;
          MotorSpeed2 = MotorSpeed + b;
          MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
          MotorSpeed2 = constrain(MotorSpeed2, 0, 255);
          analogWrite(_pwm_m1, MotorSpeed1);
          analogWrite(_pwm_m1, MotorSpeed2);
          return MotorSpeed1;
          return MotorSpeed2;
       }
       if (a < 10 && a > 0)
       {
          digitalWrite(_brk_m1, LOW);
          digitalWrite(_brk_m2, LOW);
          digitalWrite(_dir_m1, LOW);
          digitalWrite(_dir_m2, HIGH);
          MotorSpeed1 = MotorSpeed+ b;
          MotorSpeed2= MotorSpeed+ b;
          MotorSpeed1 = constrain( MotorSpeed1, 0, 255);
          MotorSpeed2= constrain( MotorSpeed2, 0, 255);
          analogWrite( _pwm_m1,  MotorSpeed1);
          analogWrite( _pwm_m2, MotorSpeed2);
          return MotorSpeed1;
          return MotorSpeed2;
       }

       else
       {
          digitalWrite(_brk_m1, LOW);
          digitalWrite(_brk_m2, LOW);
          digitalWrite(_dir_m1, HIGH);
          digitalWrite(_dir_m2, HIGH);
          MotorSpeed1 = MotorSpeed+ b;
          MotorSpeed2 = MotorSpeed - b;
          MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
          MotorSpeed1 = constrain(MotorSpeed2, 0, 255);
          analogWrite( _pwm_m1, MotorSpeed1);
          analogWrite( _pwm_m2, MotorSpeed2);
          return MotorSpeed1;
          return MotorSpeed2;
       }

    }

And i called this function in the code using :

        MotorFunc(a,b)

This code ran just fine, But when i removed the return functions from the first if condition, I destroyed 2 motordrivers,
Is this possible?
Edit:
I am updating the whole code:

The main code tab :

         int _dir_m1 = 2;
         int _pwm_m1 = 3;
         int _brk_m1 = 4;
         int _brk_m2 = 5;
         int _pwm_m2 = 6;
         int _dir_m2 = 7;

         int sen1 = A4;
         int sen2 = A3;
         int sen3 = A2;
         int sen4 = A1;
         int sen5 = A0;
         signed int Error = 0;

         int Kp = 20;
         int Ki = 0;
         int Kd = 0;

         void setup() {
         pinMode(_dir_m1, OUTPUT);
         pinMode(_pwm_m1, OUTPUT);
         pinMode(_brk_m1, OUTPUT);
         pinMode(_dir_m2, OUTPUT);
         pinMode(_pwm_m2, OUTPUT);
         pinMode(_brk_m2, OUTPUT);

         pinMode(sen1, INPUT);
         pinMode(sen2, INPUT);
         pinMode(sen3, INPUT);
         pinMode(sen4, INPUT);
         pinMode(sen5, INPUT);

         }

         void loop(){

         signed int a = Sensors();
         signed int b = PID(a);
         MotorFunc(a,b);
           }

And pretty much it. I am leaving out PID as Its not required along with error selection.

The setup is -
Arduino mega connected to 5 ir sensors
12v 9ah battery
500rpm 12v motors johnsons
and the motor driver 20 amp 20v-30v
[![Motor Driver which burst into flames][1]][1]

[Motor driver link with specs][2]

  [1]: https://i.stack.imgur.com/ZFDYr.jpg
  [2]: http://robokits.co.in/motor-drives/dual-dc-motor-driver-20a

body:
It all depends on how the circuit works and how it is controlled.  A basic H-bridge looks like this:

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

Normally you have one MOSFET from each side turned on and one turned off - so for example Q1 and Q4 on to make the motor turn one way, or Q2 and Q3 to make it turn the other. Turning on Q2 and Q4 for example would make the motor "brake".

However, if it is possible for your driver to turn on both Q1 and Q2 at the same time, or Q3 and Q4, then they will form an almost dead short circuit and massive amounts of current will try to flow. At that point things will start to get hot and the Magic Smoke™ will try and escape.

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


body: It isn't possible to say arbitrarily that removing the statements could or could not cause the drivers to burn out. What does the caller do with the value returned by your function? With the return statement removed, the value returned to the caller is unknown. Is there any value which, if returned to the caller, could set the conditions for driver burn-out?


message:
Can't cast char to unsigned char?

byte RSV_Resp_test[3] = {'a', 'b', 0};
    Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));

produces the error

    error: invalid cast from type 'byte {aka unsigned char}' to type 'char'
    Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));
                                                          ^
How can this be an ill-formed cast?  I just need to print the value as a ascii character, not as a number.

body:
    Serial.println(static_cast<char>(RSV_Resp_test[1]));

works.  I still don't understand why the reinterpret_cast errors out.


message:
More speed from ATMEGA328 Internal Clock

I have a board that is designed and produced. It was designed to use an Atmega328 with the internal clock. There is no space on the board to place an external clock. After completing these and testing them I have found that 8Mhz is too slow to complete my main loop actions seamlessly. The main loop involved shifting data out to 20 registers. Is there any way to speed this up without going back to the drawing board on the PCB design? Can another AVR be substituted as a drop in replacement with a faster internal clock? Can the internal clock be made to run faster or doubled to achieve 16Mhz?

The application is a matrix display that has 50 columns and 7 rows. The registers are the display buffers and represent the current state of the display. Because of the multiplexing in the matrix, only 1/5 of the pixels are illuminated at any given time. In order to trick the eyes into seeing all lit at the same time the speed needs to be faster. The display flickers with the interal clock. If I connect and UNO board instead of using the on board ATMEGA328 (QFP) it works good. So the difference between 8Mhz and 16Mhz is visible. If I can double the speed of the display loop than that is a solution. Below is the loop, for reference, latchPin = 8, clockPin = 12, dataPin = 11.

body:
It is 8MHz and not faster.
The only way to make it faster is to add an external crystal with two capacitors and change a fuse for external clock.

Many ATtiny chips can run at higher frequencies with the internal clock. Do you use a DIP package of the ATmega328(p) ?

Did you optimize the code ? The ATmega328(p) has highly optimized code to change an output pin. At what rate do you want to shift out data ?


body:
`shiftOut()` relies on `digitalWrite()`, which is dead slow by AVR
standards. You could probably get a factor 5, or even 10, by
reimplementing `shiftOut()` using [direct port
access](https://www.arduino.cc/en/Reference/PortManipulation) instead.
Using SPI (as suggested in the comments) would be even faster, but you
would need to clock out of pin 13.

**Edit**: here is an attempt at such implementation. Note that it is
completely untested. Note also the small delay meant to avoid the thing
being _too fast_. You may try to play with the delay value.

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

    #include <util/delay.h>

    /*
     * Especialized and faster shiftOut().
     * This assumes no one is touching PORTB at the same time.
     *
     * dataPin = 11 (PB3), clockPin = 12 (PB4), bitOrder = MSBFIRST.
     */
    void myShiftOut(uint8_t val)
    {
        for (uint8_t i = 0; i < 8; i++)  {
            // Send data bit.
            if (val & 0x80)
                PORTB |= _BV(PB3);
            else
                PORTB &= ~_BV(PB3);
            val <<= 1;

            // Toggle clock twice.
            PORTB |= _BV(PB4);
            _delay_us(0.5);
            PORTB &= ~_BV(PB4);
        }
    }


body:
I wrote the following earlier but the moderator deleted:

"
A few things to try.

An external oscillator.

An external rc oscillator.

Optimized code: the code left a lot to be desired.

Optimized hardware: there is no reason you shift out the same value so many times. That's a waste of time.
"

edit: just give you some sense on a 16MIPS ATmega:

1) your code executed in 2.54ms -> a refresh rate of 400Hz;

2) your code software-optimized can be executed in 0.103ms -> a refresh rate of 1Khz;

3) your code both software and hardware optimized can be executed in 0.054ms -> a refresh rate of 2Khz.

what it tells you is that:

1) raising the clock isn't the only way to speed up execution;

2) there is a fundamental limit for this topology on how many shift registers you can drive before it starts to flicker;

3) to drive the most out of your design, you have to pay attention to both software and hardware. that's why embedded engineers get paid a lot of money to do;

BTW, the higher clock rate, the more likely you will run into timing issues in a long chain of shift registers. 20 - 25 shift registers are likely the limit in real life applications.


message:
Program jumps alone from void loop() to another void

//simple alarm system
    int RipSensor1 = 12;
    int RmkeyA = 3;
    int RmkeyB = 5;
    int RmkeyC = 6;
    //--------------------------------------------------------------------------

    void setup()
     {
      Serial.begin(9600);
      pinMode(RipSensor1,INPUT);
      pinMode(RmkeyA,INPUT);
      pinMode(RmkeyB,INPUT);
      pinMode(RmkeyC,INPUT);
      pinMode(13,OUTPUT);
      Serial.println(F("System Is Up & Running")); }
      //----------------------------------------------------------------------

    void loop()
     {
      Serial.println(F("Main Loop Start"));
      digitalWrite(13,LOW);   //for debugging
      if (digitalRead(RmkeyA) == HIGH)
       {
        Rip1Status();
       }
     }
    //----------------------------------------------------------------------

    void AlarmSMS1()
     {
      //send sms to admin1
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Rip1Status();   // return to this void (monitoring)
     }
    //----------------------------------------------------------------------

    void Rip1Status()
     {
      Serial.println(F("VOID Rip1 Start..."));
      while (digitalRead(RmkeyB) == LOW) //Arm mode
       {
        digitalWrite(13,HIGH);
        if (digitalRead(RipSensor1) == HIGH) //when Rip sensor sense motion
         {
          Serial.println(F("Movement ALARM --> PowerUP Relay 1 & 2"));
          long RipTimer1 = 0;
          long Rip01 = 0;
          int z = 0;
          int x = 0;
          while (digitalRead(RmkeyC) == LOW)
           {
            RipTimer1++;
            Serial.println(RipTimer1);   //for debugging
            if((z==0) && (RipTimer1 - Rip01 > 500))   //1st CheckPoint do something
             {
              z = 1;
              Serial.println(F("1st CheckPoint OK"));
             }
            else if((x==0) && (RipTimer1 - Rip01 > 3000))   //2nd CheckPoint go on other void
             {
              x = 1;
              AlarmSMS1();
             }
           }
          Serial.println(F("C Key Pressed --> False Alarm"));    //if button C pressed
          RipTimer1 = 0;
          z = 0;
          x = 0;
          Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
          break;
         }
        else Serial.println(F("Monitoring"));  //for debugging
       }
      Serial.println(F("B Key Pressed --> Disarming"));  //for debugging
      Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
      loop();
     }
I make this code & i have this problem:
Program start & wait for A key pressed to Arm mode. works ok
Press A key go to Arm mode (monitoring). works ok
When its on "monitoring", if i press B key, system disarming then go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, then alarm start and if i press C key then disarming as false alarm and go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, if i left alarm to complete, go to sms void send sms to admin and return to Rip void (monitoring).
But on this point if i press B button to disarm system this happen...

    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    B Key Pressed --> Disarming
    Monitoring Loop ends --> GoTo Main Loop
    Main Loop Start
    3002
    3003
    3004
    3005
    3006
    3007
    3008
    3009
    3010
    3011
    3012.............
Why this happen?
What i am doing wrong?

body:
`loop()` calls `Rip1Status()`, which calls `loop()`, which calls `Rip1Status()`, which calls `loop`(), which calls ....

That process will continue until the stack overflows (runs out of memory) or over-writes some necessary variable. If you just meant for `Rip1Status()` to return to the main loop, delete the `loop()` call at the end of the function. When Rip1Status()` exits, control will automatically return to `loop()` at the statement following the `Rip1Status()` call.


message:
Switching low current AC

What is the simplest way to switch ON/OFF a 60v and 5 mA of current ?
I don't want the common relays for arduinos as they make click noise.

body:
// Following devices could be helpful in you case.

1. Power BJT as a switch (check datasheets if it comes on your required range).
2. Solid state relay is obviously, but cast is little high in this case.


message:
Arduino DUE samples per second with the DAC

I want to know how many samples per second the arduino due DAC can generate, I need to generate an ultrasonic signal (40Khz), the arduino due is not going to do anything else that generate this signail for a very short period of time.

body:
According to the datasheet:

> * 2-channel 12-bit 1 msps DAC

So it's possible to generate 1 million samples per second. Of course that kind of speed would need DMA to drive it smoothly.

Assuming you want to generate a sinewave at 40KHz you have to first ask yourself what resolution (time-wise) you want from that sinewave, since that's the frequency that you need to generate samples for. For instance, if you want 100 samples in your sine wave you'd need to generate those at 4Msps, which you can't. At 10 samples per cycle you'd have 400Ksps which is more manageable, but the quality of the sinewave would be pretty poor.

Or, if you don't *need* a sinewave, if a square wave would do, just use a normal digital IO pin. You can generate MHz then.


body:
With this code, the Arduino DUE was able to generate 250 samples per second approx. I tested it with a signal generator and an oscilloscope. I have found it on this web page http://www.electrosmash.com/pedalshield. All credit is for them.

Here is the code:

<!-- language: c++ -->

    // Licensed under a Creative Commons Attribution 3.0 Unported License.
    // Based on rcarduino.blogspot.com previous work.
    // www.electrosmash.com/pedalshield

    int in_ADC0, in_ADC1;  //variables for 2 ADCs values (ADC0, ADC1)
    int POT0, POT1, POT2, out_DAC0, out_DAC1; //variables for 3 pots (ADC8, ADC9, ADC10)
    int LED = 3;
    int FOOTSWITCH = 7;
    int TOGGLE = 2;

    void setup()
    {
      //ADC Configuration
      ADC->ADC_MR |= 0x80;   // DAC in free running mode.
      ADC->ADC_CR=2;         // Starts ADC conversion.
      ADC->ADC_CHER=0x1CC0;  // Enable ADC channels 0 and 1.

      //DAC Configuration
      analogWrite(DAC0,0);  // Enables DAC0
      //analogWrite(DAC1,0);  // Enables DAC0
    }

    void loop()
    {
      //Read the ADCs
      while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);// wait for ADC 0, 1, 8, 9, 10 conversion complete.
      in_ADC0=ADC->ADC_CDR[7];               // read data from ADC0
      //in_ADC1=ADC->ADC_CDR[6];               // read data from ADC1
      //POT0=ADC->ADC_CDR[10];                 // read data from ADC8
      //POT1=ADC->ADC_CDR[11];                 // read data from ADC9
      //POT2=ADC->ADC_CDR[12];                 // read data from ADC10

      //Add volume feature with POT2
      //out_DAC0=map(in_ADC0,0,4095,1,POT2);
      //out_DAC1=map(in_ADC1,0,4095,1,POT2);

      //Write the DACs
      dacc_set_channel_selection(DACC_INTERFACE, 0);       //select DAC channel 0
      dacc_write_conversion_data(DACC_INTERFACE, in_ADC0); //write on DAC
      //dacc_set_channel_selection(DACC_INTERFACE, 1);       //select DAC channel 1
      //dacc_write_conversion_data(DACC_INTERFACE, out_DAC1);//write on DAC
    }


message:
How to write arduino code which reads the value of a flex sensor?

Since this is this the first time im doing Arduino, im really confused what the code is to:

write a code which reads the value(nae the value 'flexValue') of a flex sensor connected to analog input AN0.

The value should be a 10-bit integer number having value between 0-1023, inclusive.

body:
You should call the function `analogRead()`, and pass the value of `A0` into it because you want to read pin A0. For example:

    flexVal = analogRead(A0);
The function `analogRead()` will return a value from 0-1023, just as you require.

When you call this function, the CPU configures the on-board ADC (analog-to-digital converter) to take a reading from pin A0. The ADC on the Arduino has 10-bit resolution, so it will return a value from 0-1023.


message:
Is it possible to connect NRF24L01 to localhost in laptop without wifi router?

I want to send data from arduino to my localhost port:8080(with ipython notebook) via modul NRF24L01 without WiFi router. Is it possible? If it possible, how to do that?
Thank  you...

body:
It is possible to have 2 NRF24L01 radios to talk to each other without a WIFI router.

However, is it possible to get your notebook to talk to a NRF24L01?  Probably not unless you can write a device driver for it.

You could use two Arduinos each with a NRF24L01, and get one to receive the data and then send it via Serial to you laptop, but you would be better looking at an ESP8266, set that up as an access point, connect your laptop to that network and job done.

(By the way you won't be able to call you laptop localhost)


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

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

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


message:
Arduino Micro vs. Pro Micro

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

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.


message:
Alternative ways for read Serial Output

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

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.


message:
Accessing two MPU-9250 DMP

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

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);


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

#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?

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);`


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

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!

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


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

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

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.


message:
AT command is not responding on serial monitor

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

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());
      }
    }


message:
What if I have burnt my atmega328p?

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

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.


message:
Uno with LCD acting strangely - power issue?

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

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.


message:
PWM water pump flow control - in percent

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?

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);`


message:
Current available SRAM?

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?

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


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

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"

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])`


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

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!

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.