text:
Adding null character to char array
I have this code written and functioning that will write out the chars in cmd to a serial port for an input of ASCII text representing byte values.
void SendCTRL (String &input)
{
  //Adjust Data
  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]);
  }

  //Send Data
  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
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

As the majority of the byte values fed are constant, I'm trying to create similar output for the following code when I feed the function below only the byte values that change frequently:
void Create_Message(int Address, int Data)
{
  //Adjust Data
  Address--;
  byte SvAdd = 1;
  byte FuCode = 6;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
  unsigned int crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
  byte CrcHi = crc & 0xFF;
  byte CrcLo = crc >> 8;
  /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
  * to
  *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
  */

  //Send Data
  unsigned char cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo};
  cmd[8]=0; //Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  lcd.setCursor(0, 1);
  for (int i=0; i< sizeof(cmd)/sizeof(cmd[0]); i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

I'm reading the Values written by RS485.write() and, in both cases, the data is good. However, for the 2nd section of code, the Arduino seems to write out the null-byte while it does not write the byte out in the 1st block. If I remove the allocation for the null-byte in the second code, it does not get a response from my device.
I'm guessing that the issue is that I am not setting my null-byte terminator correctly or otherwise missing something (I'm pretty new here XD )
Update: it seems like using sizeof(cmd)/sizeof(cmd[0]) to determine the send length interfered with data transmission when I set this to a constant the code works just fine.

In the second code example, the value of sizeof(cmd)/sizeof(cmd[0]) is 9, due to the declaration unsigned char cmd[9] ...
Thus, the for loop will write out 9 bytes, with indices 0, 1, ... 8.  Due to cmd[8]=0; earlier in the code, the last byte will be zero.  To prevent that, one might instead use the expression  sizeof(cmd)/sizeof(cmd[0])-1 in the for loop:
for (int i=0; i< sizeof(cmd)/sizeof(cmd[0])-1; i++)
   RS485Serial.write(cmd[i]);

Note, this doesn't explain why it should be so that “If I remove the allocation for the null-byte in the second code, it does not get a response from my device”, although practically anything can happen if you say cmd[8]=0; after allocating only 8 bytes of storage.

I was under the impression that cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo} would make the cmd array equal to {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo,[unallocated]} so that when I said cmd[8]=0; Cmd would be {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo,0} Is that not the case?

To clarify, I also removed the cmd[8]=0 line as well (sorry for the confusion)

Perhaps you meant [uninitialized] where you wrote [unallocated].  But no matter, both are wrong.  cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo} initializes cmd to {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo,0} because it uses the default initializer for unspecified elements, and the default initializer is 0. See eg an answer to Is there a better way to initialize an array? and also see  C++ array initialization,

In addition to James's answer, to print (or send) a null terminated string you do not have to know the length of the string. Just print the characters till you find the null. So this code works better.
for (int i=0; cmd[i] != 0; i++)
{
    RS485Serial.write(cmd[i]);   // Send string someplace
}

//or

int i=0;
while(cmd[i] != 0)
{
    RS485Serial.write(cmd[i++]);   // Send string someplace
}

Ok, I'll do that

@ATE-ENGE you should have not edited your question. New readers are going to get confused :)

Ok, I'll undo that XD


text:
Disable Reset when Com Port Connected/Disconnected
I've noticed that when I open and close the com port my Arduino is connected to, the device resets. This makes the program run the setup profile again and it loses the previous variable states. Is there any way to prevent this?

If you review the Uno schematic, you can see the circuitry that enables an automatic reset when serial communication starts.  The circuitry is intended to allow easy program downloading.
There are two or three ways to prevent that reset:  add a 10 μF capacitor from ground to reset;  use a much-lower resistance for the pullup on reset; cut a trace from the serial-interface pin (eg CTS) that pulls reset.
The first method is relatively easy to implement, and easy to remove whenever you want to install a new program.
References:  Disabling AutoReset On SerialConnection and ArduinoISP on Uno requires 10uF cap -- WHY?, both at Arduino.cc.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
PROGMEM : pgm_read_float_near() equivalent for double? (Arduino Due)
I'm using an Arduino Due where double have a size of 8 bytes. In my software, I use double table const stored in prog memory, I was using an UNO before and used pgm_read_float_near() to retrieve these values. What function should I use?

Arduino Due (ARM Cortex-M3) doesn't need anything like PROGMEM as it has access into the flash memory in the same way as into the RAM. The const qualifier is enough to keep it in program memory only.
The AVR based boards like UNO needs PROGMEM because there are different instructions for fetching data from program memory and g++ is not very advanced in this way (some other compilers supports it directly - for example in gcc you can use __flash and __eeprom instead, but not in g++ as it was rejected for some reasons)
Edit:
Currently there are also AVRs with a new design (they are more like xmegas) and they are having flat address space (emulation) so with single pointer you can fetch RAM, FLASH, EEPROM and so on. But it's limited to the devices with smaller FLASH (all of it must fit into 64kB/16b pointers). In those cases you can just use const for global arrays and it'll be stored in FLASH (and not in FLASH and loaded into RAM upon startup like old AVRs) and string literals doesn't need P_STR / F() macros
For example:

Atmega4809 (nano every, uno wifi r2) and variants: 808, 809, 1608, 1609, 3208, 3209, 4808
Attiny(2/4/8/16/32)(0/1/2)(2,4,6,7) - eg Attiny212 1616 ...
It should be also possible on AVR16/AVR32 devices, but 64kB/128kB ones needs PROGMEM again (compiler can't optimize it into FLASH as you have only snapshot of 32kB in direct address space, but it's possible to change it - however there is also erratum about it not working properly)

“instruntions” ??

Yes, Jmaes, instruntions. They're what you hit microcontrollers with to make them work.

For anyone looking for an equivalent, you can manually copy the bytes into a double like:
double pgm_read_double(const double* address) {
    double result;
    memcpy_P(&result, address, sizeof(double));
    return result;
}

And use memcpy_PF for far addresses. But know that many MCUs have access into the flash memory in the same way as into the RAM, so you don't need to use this at all.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Does the Node MCU v3 (LoLin) not have a builtin led?
Trying a simple led blinking program I could not get the builtin led on a LoLin Node MCU v3 working. The LED_BUILTIN constant is set to pin 16 / GPIO16 / D0.
Reading several articles and QA I think that the Node MCU boards are supposed to have a the on-board led on pin 16. However, if I address this port nothing happens.
With the same code I can blink the data led which is on a RX pin, pin 2.
Is the builtin led missing on the LoLin Node MCU v3, or could it be that the led on my board is broken?

the ESP8266 has a builtin led that is attached to D4 as labeled on LoLin boards which maps to GPIO2. One thing to Note is that the led is active low. In other words ... setting PIN 2 to '0' will turn the LED ON and setting PIN 2 to '1' will turn the LED OFF
Lolin Builtin_Led Picture
This is the only LED on the LoLin boards and differs from other devkits that have an LED on GPIO16.

I have been banging my head against this for a half hour. Lot's of conflicting information due to different manufacturers. The reverse logic is a bit strange but at least it works.

I have put up a blink example demonstrating pin 2 on https://gist.github.com/jhorsman/6a93191ba31a48cf0cea75acd4c20cea

Great it saved my time. I was clueless.Do you know what are the other differences in LoLin board? Any links

@JoyGeorgeKunjikkuru This was helpful to me: https://frightanic.com/iot/comparison-of-esp8266-nodemcu-development-boards/

I have nodeMCU v3 and Pin 2 worked for me.
#define LED_BUILTIN 2

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

The NodeMCU with the CP2102 serial and a slightly narrower pin footprint does have 2 LEDs.
$led1 = BUILTIN_LED;  //D0, 16, BUILTIN_LED: OnBoard LED
$led2 = 2;    //Pin 5 D4/2 Internal LED for LoLin V3

The $led1 = BUILTIN_LED (on GPIO 16) is **not* on the LoLin NodeMCU v3.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Using a MIDI connector both as MIDI In and Out (not simultaneously)
I asked this question also in Electrical Engineering (stack exchange), however on question is more appropriate on this board (question 5). For completeness, I kept all questions intact, but made question 5 bold.
Electrical Engineering StackExchange Question Link: Using a MIDI connector both as MIDI In and Out (not simultaneously),
In my current (Arduino) project I have (currently) 3 MIDI INs and 2 MIDI OUTs. However, it would be nice if I can configure each of the MIDI connectors as IN or OUT by software (Arduino).
The circuits I am using are:

And

What I would like is to use the connector shown in the above picture as MIDI In OR MIDI out. I have not tried it yet, since I have too many doubts and I do not want to break a component. However, I thought about it (with my limited electronic knowledge), and I think:

Pin 2 afaik for MIDI In, normally has +5V. In the MIDI Input circuit it is not connected, but in the MIDI Output circuit, it is connected to GND. I don't think this is good when being used as MIDI out, resulting in a short circuit (?). So I guess I have to make it +5V when used as MIDI Input and GND when used as MIDI Output (so putting HIGH or LOW 'digital' for Arduino).
Pins 1 and 3 remain in both circuits untouched (so I assume I can do the same).
Pin 4 and 5 is a bit tricky, since they are connected. I think I have to use one or two transistors to create two alternative paths for pins 4 and 5 for MIDI Input and Output. Or can I just set a specific voltage on pins 4 and 5 when used as MIDI In or Out? (and what would those values be?).
For the MIDI input, an optocoupler is used, while for MIDI output, directly the Arduino is used. I wonder if I have to use for both an optocoupler (since people might connect it accidentally to a MIDI output from a MIDI device.

5. I'm not sure how to handle the RX and TX pins ... for 5 MIDI devices, I would need to use 5 RX and TX pins, but the Arduino (Mega) only has 4 of each. But this is probably a question for the Arduino board.

Could you check over your question for typos in the pin numbers, please? I got confused at the first part about lin 3 - do you mean pin 2?

@MarkSmith Thanks ... I indeed made a mistake (and also in item 1, where I meant pin 2). In item 3 I only wanted to mention pins 4 and 5.

See the [tag:softwareserial] tag.

@CL: I think I should really do some testing for MIDI with software serial.

I suggest you have a look at the 4051 or 4052 chip (datasheet). The 4051 is a 1:8 analog multiplexer while the 4052 contains two 4:1 multiplexers. So basically it allows you to switch one pin on your Arduino to any out of 4 or 8 MIDI circuits.
In the case of TX, it's really simple. You just need a pullup resistor on each output so that the pins don't float when not switched to.
In the case of RX, you have to make sure that you don't miss any transmissions. If your MIDI sources are not sending simultanously, that's easy as well... but probably they are. In that case you cannot use an existing RX UART. Since MIDI is very slow, you could still switch back and forth between the inputs and catch all the bits (you would be writing a software UART then). But if you're not short of pins, it would be much easier to just use SoftwareSerial for one input.

Thanks for the answer, for output this would work great. I tried before using a software serial, but didn't work out well. However, good to know that at least for output there is a good way.

I'm pretty sure this would also be a good way for RX. It's just more work to implement, but MIDI is really so slow that you could mux between several ports and still catch all the bits. I'm doing serial reading by bit banging at 160 KHz on an ATtiny running at 8MHz, so a 16MHz Arduino should be able to handle roughly 10 MIDI inputs through one multiplexed digital input pin.

Hmm I tried long time ago (this is an old post) and I got regularly missed MIDI messages.

As MIDI is not clocked, it's crucial to get the timing right. You've got 32 microseconds per clock cycle which is not too bad, so once you detect the start bit, the data bits should be sampled at t+32us, t+64us etc. I'm getting curious what your application is :)

My app is initially to build a device that can receive different MIDI channels and 'process'/change these and send it back to other MIDI channels (or different messages). The message processing should be very configurable (so software is more complicated, but I am a programmer).

I decided some time ago to use STM32 since these have more serial ports and are faster (CPU). These have depending on the type 5 or 6 UARTs.


text:
analogRead seems to freeze some seconds the program
I have the following code that reads a RFID reader, it was working perfect without any dealy and then I try to an analog read from a potentiometer using analogRead.
The analog read works fine but then when I hover the card over the RFID it takes about 7 seconds or so to go into the line where I turn on a LED.
Im sure Im doing something wrong with analogReader because this is the first time I use it.

I really appreciate any help

    #include <MicroView.h>

    MicroViewWidget *widget;        // create widget pointer

    #define MAX_BITS 100                 // max number of bits
    #define WEIGAND_WAIT_TIME  3000      // time to wait for another weigand pulse.

    unsigned char databits[MAX_BITS];    // stores all of the data bits
    unsigned char bitCount;              // number of bits currently captured
    unsigned char flagDone;              // goes low when data is currently being captured
    unsigned int weigand_counter;        // countdown until we assume there are no more bits

    unsigned long facilityCode=0;        // decoded facility code
    unsigned long cardCode=0;            // decoded card code

    int sensorPin = A1;    // select the input pin for the potentiometer
    int sensorValue = 0;  // variable to store the value coming from the sensor

    // interrupt that happens when INTO goes low (0 bit)
    void ISR_INT0()
    {

      bitCount++;
      flagDone = 0;
      weigand_counter = WEIGAND_WAIT_TIME;

    }

    // interrupt that happens when INT1 goes low (1 bit)
    void ISR_INT1()
    {

      databits[bitCount] = 1;
      bitCount++;
      flagDone = 0;
      weigand_counter = WEIGAND_WAIT_TIME;
    }

    void setup()
    {

      pinMode(2, INPUT_PULLUP);     // DATA0 (INT0)
      pinMode(3, INPUT_PULLUP);     // DATA1 (INT1)
      pinMode(5, OUTPUT);           // LED

      Serial.begin(9600);

      // binds the ISR functions to the falling edge of INTO and INT1
      attachInterrupt(0, ISR_INT0, FALLING);
      attachInterrupt(1, ISR_INT1, FALLING);

      digitalWrite(sensorPin, HIGH);      // Internal Pull-up
      pinMode(sensorPin, INPUT);          // make pin as INPUT

      uView.begin();                      // start MicroView
      uView.clear(PAGE);                  // clear page
       uView.setCursor(5,0);
      uView.print("TEST");
       uView.setCursor(0,20);
       uView.print("RFID READ");
      widget = new MicroViewSlider(0, 35, 0, 1024);    // make widget as Slider
      //widget2 = new MicroViewSlider(0, 20, 0, 1024, WIDGETSTYLE1);    // make widget as Silder STYLE1
      uView.display();                    // display the content in the screen buffer

      weigand_counter = WEIGAND_WAIT_TIME;
    }

    void loop()
    {

      // This waits to make sure that there have been no more data pulses before processing data
      if (!flagDone) {
        if (--weigand_counter == 0)
          flagDone = 1;
      }

//****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//
      sensorValue = analogRead(sensorPin);    // read sensorPin
      widget->setValue(sensorValue);          // set value of sensorPin to widget
      //widget2->setValue(sensorValue);         // set value of sensorPin to widget
      uView.display();

//****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//

      // if we have bits and we the weigand counter went out
      if (bitCount > 0 && flagDone) {
        unsigned char i;

        Serial.print("Read ");
        Serial.print(bitCount);
        Serial.print(" bits. ");

        if (bitCount == 32){

          // **** AFTER 7 SECONDS I GET INTO THIS CODE ****///

          uView.clear(PAGE);      // clear the page buffer
          uView.setCursor(0,0);

          digitalWrite(5, HIGH);

        }

         // cleanup and get ready for the next card
         bitCount = 0;
         facilityCode = 0;
         cardCode = 0;
         for (i=0; i<MAX_BITS; i++)
         {
           databits[i] = 0;
         }
      }
    }

analogRead() is fine, it takes only about 110 µs, but there are
several other issues with your code that you should fix:

Any variable that is shared between interrupt code and normal code
should be declared volatile in order to prevent the compiler to do
some unsafe optimizations.
Any such variable that is more than one byte in size should be
accessed from the main program with interrupts disabled.
You should take care of not writing into databits[] past the end of
the array.
Counting loop iterations is a very bad way of measuring elapsed time,
as the counting speed will change whenever you change your loop code.
Use micros() instead.

There is also an issue with how you use flagDone. You set it to 1,
then you call analogRead(), MicroViewSlider::setValue() and
uView.display(), then you read it back. What if your ISR has set it
back to 0 in the meantime? I suspect this is the main cause of the
problem you see.
I suggest you use flagDone to inhibit the ISRs: the main loop sets it
to true to tell the ISRs “Let's say we are done with this card. Please
do not touch anything while I process the already received information.”
And later it sets it to false meaning “You can proceed reading bits
now.”
Given the above considerations, I would try something along these lines:
volatile bool flagDone;     // if we are done, pause the reading
volatile uint8_t bitCount;  // number of bits received so far
volatile uint32_t rxTime;   // last time we got a bit

// Interrupt that happens when INTO goes low (0 bit).
void ISR_INT0()
{
    if (!flagDone && bitCount < MAX_BITS) {
        rxTime = micros();
        databits[bitCount++] = 0;
    }
}

// Same thing, but writes 1 instead of 0 into databits[].
void ISR_INT0() { ... }

void loop()
{
    // Safely read rxTime.
    noInterrupts();
    uint32_t rxTimeCopy = rxTime;
    interrupts();

    if (bitCount > 0 && micros() - rxTimeCopy >= WEIGAND_WAIT_TIME) {
        // Assume we are done reading this card.
        flagDone = true;

        // Do whatever with databits[].
        // ...

        // Get ready for the next card.
        bitCount = 0;
        flagDone = false;  // do this last: it re-enables the ISR
    }
}

Appreciate it I will give a try. Do you recommend me to use ArduinoThread library instead?

@VAAA: Not sure I understand in which way you expect ArduinoThread to help here...

you are totally right Im very sorry Im new and I have to understand a lot of things before asking dumb questions. Let me understand your code first :)


text:
fatal error: avr/io.h: No such file or directory
I'm compiling a project on Due that was working correclty using UNO. I get this error : 'avr/io.h: No such file or directory'. Searching across the web, it seams I'm not the only one to get that error when using Arduino Due but didn't clearly figured out why it appears.
Of course, the file is present where it should be, I verified ..\Arduino\hardware\tools\avr\avr\include\avr\io.h
I opened it and see something like that :
...

#if defined (__AVR_AT94K__)
#  include <avr/ioat94k.h>
#elif defined (__AVR_AT43USB320__)
#  include <avr/io43u32x.h>
#elif defined (__AVR_AT43USB355__)
#  include <avr/io43u35x.h>
#elif defined (__AVR_AT76C711__)
#  include <avr/io76c711.h>
#elif defined (__AVR_AT86RF401__)
#  include <avr/io86r401.h>
#elif defined (__AVR_AT90PWM1__)
#  include <avr/io90pwm1.h>
#elif defined (__AVR_AT90PWM2__)
#  include <avr/io90pwmx.h>
#elif defined (__AVR_AT90PWM2B__)
#  include <avr/io90pwm2b.h>
#elif defined (__AVR_AT90PWM3__)
#  include <avr/io90pwmx.h>
#elif defined (__AVR_AT90PWM3B__)
#  include <avr/io90pwm3b.h>
#elif defined (__AVR_AT90PWM216__)
#  include <avr/io90pwm216.h>
#elif defined (__AVR_AT90PWM316__)
#  include <avr/io90pwm316.h>
#elif defined (__AVR_AT90PWM161__)
#  include <avr/io90pwm161.h>
#elif defined (__AVR_AT90PWM81__)
#  include <avr/io90pwm81.h>

...

so I suppose that a line referring to my card is missing or something like that ?
I'm using Arduino 1.6.12

The Due is SAM architecture. avr/io.h is specific to the AVR architecture of the Uno's microcontroller. The compiler will not look in the avr tools folder for that file and even if it did it wouldn't help because that file is not compatible with the SAM architecture.
This error indicates that part of the code you're attempting to compile (probably a library) is AVR specific. You will need to either port that code to the SAM architecture or find an alternative that is already compatible with Due.


text:
What's wrong with my code?
I was trying to do a LED display that turns on a LED at pin 13 that goes on then turns off after a delay then the next pin (which is pin 12 counting down) will turn on and then turn off.
I also put in a potentiometer that can change the delay to make it faster or slower.
Here's the code:
float pinOn = 13;
int outMin = 0;
int outMax = 13;
float delayNum = 1000;

void setup () {
  for (int i=outMin; i<=outMax; i++) {
  pinMode(i, OUTPUT); }
  Serial.begin(9600);
}

void loop () {
  // Reads Potentiometer -- sets delay relative to the Potentiometer input
  int sensorValue = analogRead(A0);
  delayNum = sensorValue;
  // Turns on the Pin designated by 'pinOn'
  digitalWrite(pinOn, HIGH);
  delay(delayNum);
  digitalWrite(pinOn, LOW);
  // Checks if 'pinOn' is 0 which then resets it back to 13 if not 0 then counts down
  if (pinOn = 0) {
    pinOn + 13;
  } else {
    pinOn - 1;
  }
}

All it does is turn on pin 13 for a moment then permanently turns on pin 1 and 0 and it gets stuck like that.

Bugs like this are why everyone should learn to use a debugger, and enable all warnings on your compiler -- every modern compiler will catch if (a = b) and warn you about it if you enable all warnings and, ideally, make it treat warnings as errors. I also think this counts as a "general coding" problem; if you replaced the contents of the blocks with puts("foo") or other non-Arduino C statements, the answer would be exactly the same.

if (pinOn = 0) is doing an assignment (single =) not a comparison (double ==), so pinOn is begin set to 0 each time through the loop. The result of an assignment is the value being assigned. So it's the same as if ( 0 ), which is false.
Now, on to the two branches. pinOn + 13 is a statement and the result is not being assigned to anything. You need an equals sign somewhere:
if (pinOn == 0) { // == means "is equal to"
  pinOn += 13; // same as pinOn = pinOn + 13
}
else {
  pinOn -= 1;
}

Thanks so much! I forgot that the comparator equals is supposed to be '==' not '=' :P it works now thank you!


text:
More than 500 pins
For a project I need 400-1000 pins controlled by one arduino. Each pin should work similar as arduino pin, so something like 5V, 90mA. Is using dozens of shift registers a good idea? And what power source should I connect?
My idea is following:
So one shift register requires 3 input pins to control it, and if one shift register has 12 output pins, I can connect 4 more shift registers to one shift register. Is it a good idea and will it work?

Shift registers can be daisy chained. But why do you need so many pins...?

Please be more specific about what it is you try to make.

Why are you powering the Arduino and shift registers separately? And why the shift registers by batteries? 1000 pins at 90mA each will be at max 90A.

whatever you want to do, there has to be a simpler, better, and cheaper way of getting it done. tell us more and i doubt you'll regret it...

You don't connect shift registers as a tree. That would be awfully slow.
Instead, you connect them as chains. Shift registers are meant to be
chained by connecting the serial out of one register to the serial in of
the next one, while both registers share the latch and clock lines. You
can chain as many as you want this way: a chain of four 8-bit shift
registers behaves like a single 32-bit shift register. See for example
this Arduino tutorial on the
595 to see how the
chaining works.
There is an issue, however, in making long chains: whenever you want to
change the state of one single output you have to shift the whole chain
again. And the longer the chain the longer it takes. Thus it is more
efficient to put in a single chain outputs that you will likely want to
change together, and use independent chains for outputs that are most
likely going to change at different times.
As for the wiring, you need three Arduino pins to drive one chain of
registers: data, clock and latch. But you can share the data and latch
pins between many chains, as long as you have a dedicated clock pin for
each chain. You should then be able to drive n independent chains
using n + 2 Arduino outputs.
As for the power, you have to estimate your power consumption (not just
the shift registers, but also whatever they are sourcing current into)
and find a 5 V power supply big enough to power your whole circuit.

But will shift registers support analog and digital input output pins? And lets say there are 500 pins, what approximate time is needed to update pins state? Is this resulting delay takes microseconds, milliseconds or noticable fraction of a second to update pins? Thanks

@rint: My answer was written thinking in terms of digital outputs. You can find parallel-in serial-out shift registers that can do digital inputs. Neither type can do analog, but you can look into analog multiplexers for that purpose. You may want to time a loop of shiftOut() to get an idea of the time required (one call to shiftOut() outputs 8 bits).

Here is a whole different approach.
Look at how they built the motion-controlled coffee table:
http://www.evilmadscientist.com/?s=LED+coffee+table

It has hundreds and hundreds of connections, so they subdivided the board so they could have distributed Arduinos.
So it is possible to control that many pins, and it may be best to use multiple Arduinos.


text:
I want to make a counter but i don't know what i'm missing or am doing wrong
this is the code i made but it gives me an error about te } and also i need to know how to make delays with this
int ledPin = 4;
int buttonPin=2;
int buttonState = 0;         // variable for reading the pushbutton status

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  if (buttonPin=(LOW);
 {
 Serial.println("someone pressed it");
}
  else
  {
    Serial.println("nothing");
  }
}

thanks for helping!

You forgot bracket here
if (buttonPin=(LOW);

Should be
if (digitalRead(buttonPin)==(LOW)){

To make a delay of 0.5 seconds for example:
delay(500);


text:
Johnny-five driving LCD Matrix or call Arduino library from Johnny-five
I would like to know if it's possible to drive an LED Matrix like this one with johnny-five.
If not, how can i call Arduino library/code from johnny-five.
If I Write method on sketch into the Arduino, can I call them from J5 REPL?

After research, it can't be done, as J5 use firmata to drive the Arduino, the only way is to write a library to use with.


text:
Running out of pins in a 4x7-segment display clock
I've been playing around with the 7-segment displays and so far I've only been able to make 1 working display hooked up to a potentiometer that changes the number on the display with a switch that turns it into a counting-up timer
My main goal is to make a Clock but that uses 4 7-segment displays and I've already used up 7 pins for 1 display so now I either need to make more pins (I'm using Arduino Uno which has 14 Digital pins + 6 if you use the Analog In pins)
or use the 7-segment decoders
if I use the 7 segment decoder that will take up 4 per display which totals up to 16 which is well in range the required amount of Pins
so can someone teach me what is easier to do:
Making more pins using the 8-bit shift registers
or
Use the 7-segment decoders to make space
and if you think one is easier can you tell me how to use them because I have no idea and I've been tinkering with the decoder for the past hour or two
(btw the 7-segment displays are all Common Anode)

A 4-digit 7-segement display needs 4+7 (not 4×7) pins.

I don't have a 4-digit 7-segment display I only have the 4 individual 7-segment displays

You can wire them just like a 4-digit display is internally wired.

butt how tho...

See for example here and here, and read about using a driver circuit.

I still don't understand :P pardon me I'm still a beginner at all of this Arduino stuff
using the 2nd link you told me I can just hook up 7 pins to all A-G of all the 4 7-segment displays and then just activate the display that I will use and move on to the next from there?
Although I have a faint idea I will try to do some more tinkering with those in mind
Thanks for all your help :)

You generally use multiplexing to drive multiple segments. That way you only need 4 + 7 pins. Try googling "multiplexing seven segement".

The basic idea is this:
First, connect segment A of each display together, and all the segment Bs together, and all the segment Cs and so on.  Each "group" is driven by one pin on the Arduino.  For this you will need seven pins.
Your displays will have either a common anode or common cathode - perhaps you have that connected straight to +5v or straight to ground currently.  Instead, you connect the "common" pin from each display to a spare pin on your Arduino - so using another four pins.
Remember the resistors too.
Now, you can light up any segment on any display, by setting the appropriate segment pin and the appropriate common pin to the right values.
Make sense?

Thanks for giving out an Answer but I've already figured it out a while ago with Edgar Bonet's help :P thanks tho


text:
Interruption triggered twice when set to FALLING
I have a simple sketch with a button that triggers an interruption set to happen when the button pin goes from HIGH to LOW. It has debouncing so no repetitions happen when the button is pressed, but sometimes when releasing the button the interruption also fires. Why would that be? Shouldn't the debouncing take care of any micro-rising during the release of the button?
volatile int contador = 0;
int n = contador;

long t = 0;
void setup() {

    pinMode(2, INPUT_PULLUP);
    attachInterrupt( 0, incrementaContador, FALLING);
}

void loop() {
    if (n != contador) {
        n = contador;
    }
}

void incrementaContador() {

    if ( millis() > (t + 50) ) {
        contador++ ;
        t = millis();
    }
}

This same code works correctly when set to LOW instead of FALLING.

Shouldn't the debouncing take care of any micro-rising during the release of the button? - That depends on the debouncing. Schematic please?

Also if you think that "if" in your ISR is good debouncing you're sorely mistaken.

Think about what happens. You press the button, and the ISR triggers on each bounce. It counts once because all the bouncing happens within 50ms. Then, say 100ms later, you release the button. Again bouncing happens, and the ISR triggers on each bounce, and one of them within a 50ms window gets counted. You have no distinction between rising bounce and falling bounce. It's all up-down-up-down-up. The real thing you should be looking for is the final position that hasn't changed for a while.

Thank you for the reply @Majenko. The schematic is just a button attached to pin 2 and ground. I forgot to mention that this code works perfectly when the interruption is set to trigger on LOW instead of FALLING. I checked to see if incrementing the delay in the ISR would help and with 500ms it debounces also the releasing of the button. But why the difference between the two modes. Does FALLING also trigger when 0v is not reached?

This question seems to have been abandoned.

but sometimes when releasing the button the interruption also fires

Yes, well when you release the button it may also bounce. In other words OFF/ON/OFF so that will count as a press. A capacitor over the switch might be better.
Example:


text:
TLS Client ESP8266
My ESP8266 collects data and sends it to a webserver over HTTP. I would like to use TLS for this but I cannot figure out how to get ESP8266 running on the Arduino framework to use this.
My curent code is based on ESP8266HTTPClient and when searching the ESP8266 pages on GitHub 50% of the information tells me that it's impossible to use HTTPS and the other half of the info tells me it's possible but not documented with WiFiClientSecure but that looks like a whole different way of communicating HTTP..
Link: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/WiFiClientSecure.h
void senddata() {
  String testdata = "{\"tickle\": {\"id\": " + String (package.id) + ",\"value1\": " + String (package.value1) + ",\"value2\": " + String (package.value2) + "}}";
  Serial.println("Starting the journey to Salador..");
  http.begin("https://myserver/_db/Salador/upload");
  http.addHeader("Content-Type", "application/json");
  int httpCode = http.POST(testdata);
  if(httpCode > 0) {
      Serial.println("[HTTP] POST... code: ");
      Serial.println(httpCode);

  }
  else {
      Serial.println("[HTTP] POST... failed, error: ");
      Serial.println(http.errorToString(httpCode));
  }
  http.end();
}

I don't think you can easily mix the HTTP wrapper and the WiFiClientSecure. At the moment if you want to do HTTPS you have to do the HTTP portion of the transaction manually by sending the individual headers and then the body, then parsing the response yourself.
It's not that hard, and the example you point to shows you how it can be done - print the headers and body to the client, then read the data back looking for specific things (like a blank line to separate headers from body, etc).

Although: I do see this clue in the BasicHttpClient.ino example:
// configure traged server and url
//http.begin("https://192.168.1.12/test.html", "7a 9c f4 db 40 d3 62 5a 6e 21 bc 5c cc 66 c8 3e a1 45 59 38"); //HTTPS

So maybe if you know the fingerprint of your HTTPS server you can connect directly with HTTPS. How you get that fingerprint though is not something I know yet.

I can get the fingerprint from my browser and will try just adding it to the http.begin()

you have to hard-code the cert info for each domain. it's a PITA to manage if you get new certs, and it's hard to OTA if the trusted server goes down. not all certs fit; 2k is the known max, though depending on the sketch and ram, some 4k ones work as well.

Sounds like it's better to relay through something like a Pi or use a Yun.


text:
can I give the 9v input power for arduino mega 2560 using vin pin?
I am using Arduino mega 2560. I have some doubts about powering my microcontroller.
Can I use the 9v battery to power my arduino through the VIN terminal?
I have uploaded an image. Check whether it is a correct method or not?

you can, but it wastes expensive batteries. 4/9ths of the energy used will be heat. a DC-DC buck converter will only waste about 1/9th of the battery. That's like buy 2 get 1 free; not bad for less than $1 "investment".

Yes!

The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.
The power pins are as follows:
  - Vin. The input voltage to the board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

https://www.arduino.cc/en/Main/ArduinoBoardMega2560
Vin is the same as the external positive power input.

Vin is the same as the external positive power input.; not exactly. The jack also has a diode, to protect against reverse polarity. Vin doesn't have this diode. But other than that, they are the same.

Gerben you are correct. Thanks for your clarification.

@Gerben/anyone: for the newbies, can you link to an example of the right kind of diode that protects against reverse polarity?  Is any old LED a valid diode for this functionality?

A standard 1N4004 or 1N4007 can be found almost anywhere that sells electronics.

Alternatively, you could get an adaptor that allows you plug straight into the barrel jack - hence removing the need for the diode. For example: https://www.jaycar.com.au/2-1mm-dc-plug-with-screw-terminals/p/PA3711

@misterbee The diode is only used for protection against reverse polarity. Connect it up the correct way and you won't need the diode. However, connect it up the wrong way and you could get smoke.

Thanks! Ah, that number is printed on the side of the "diode rectifier" included in the Eleglo Arduino kit.


text:
Grab keys from an ordinary USB keyboard
Arduino USB
I want to write an Arduino Sketch (if there is no other possibility it can also be plain c) , to grab keyboard inputs from my ordinary USB keyboard. Preferably without expensive hardware, but as mentioned, if there is no other possibility, this will do it too.
Is this possible with V-USB? I looked a their website, but it seems like this only supports being slave and to imitate a keyboard.

The USB host shield is what you want.

PS2 is a whole lot easier. And most usb-keyboards  tend to also "speak" PS2, but you millage may vary. This way you don't need any USB host shield. See http://playground.arduino.cc/Main/PS2Keyboard and  http://pinouts.ru/InputCables/usb_ps2_mouse_pinout.shtml for the pinout.

@Majenko does it again.  That USB Shield is great.  https://www.arduino.cc/en/Main/ArduinoUSBHostShield

As suggested in the comments, you have two options:
As suggested by Majenko, you can use the Arduino USB Host Shield:

Alternatively you could use a PS2 keyboard instead (as suggested by Gerben). Arduino already has a library to handle PS2 keyboards, so the implementation of it would be easy. For reference (and example program)
playground.arduino.cc/Main/PS2Keyboard
If you do not have access to a PS2 keyboard or just want to use a USB keyboard, Gerben further suggests that most USB keyboards can be converted to PS2 keyboards with an adapter:

The keyboard must be able to support both formats (USB & PS2).
The following webpage shows the connections needed to go from USB to PS2:  USB to PS/2 adapter pinout

Gerben & Majenko, let me know if you would like to post your own answer and I will remove your content from my answer. Otherwise thank you for your suggestions in the comments and I hope I have done your suggestions justice.

I am able to use this library: https://github.com/techpaul/PS2KeyAdvanced and USB's data +/- connected to pins 2+3 of an arduino to read keys on standard keyboards.
keyboard.begin( 3, 2); // D3= data+, D2= data-

A standard keyboard is one which doesn't need a driver to work on any computer. I'd tried several libraries, serial keyboard adapters, and ps2/usb converters, and this method works best. Since the ps2-USB converter is just a physical pin change with no logic, standard USB keyboards just magically with with the PS2 libraries; even caps lock and what not...


text:
How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?
I have been trying to generate a PWM wave of 38 Khz (13 microsec= ON period , 13 microsec= OFF period).  Currently I am using Timer 0 to generate the PWM wave , however i am confused as to how to prescale the 16Mhz input clock frequency so that i can get 38 Khz from it .
The code is as follows -
#include<avr/io.h>
#include<util/delay.h>

uint8_t  dutycycle;
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        DDRG |= (1<<PG5);

        // Clear o/p on Match and Fast PWM Mode
        TCCR0A |=(1<<COM0A1) | (1<<WGM01) | (1<<WGM00) | (1<<COM0B1);// COM0A1/0b1 are the ouput ports , and WGM01 and WGM02 are used for fast PWM mode
        TCCR0B |=(1<<WGM02) | (1<<CS01);//WGM02 is used to set the fast pwm mode with max value stored in OCRA. CS01 is used to prescale the clock frequency to 16Mhz % 8 .
        OCR0A = 52;

}
void dutycycleA(uint8_t dutycycle)
{
    OCR0B = (dutycycle * 52)/100 ;
}
int main()
{
        pwm_init();

        while(1)
        {
            dutycycle=50;
            dutycycleA(dutycycle);
            _delay_ms(1000);
        }
}

So , the code is supposed to keep checking the value of OCR0B with the timer value and if it is less than that , then the output is logic HIGH , and if it is same as the timer value , then it'll be logic LOW . the duty cycle is given as 50 so that a pulse waveform of 50% duty cycle is reached .
However I am unable to obtain 38Khz output .
Please help me figure out where I have gone wrong and also suggest corrections to my approach , if wrong .
Thank you .
PS - I am using Eclipse Neon platform.

It appears that you didn't set any Clock Select bits.  Per datasheet,

clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped.

That could account for getting no output at all, if that's what's happening.  [I had overlooked (1<<CS01) in your TCCR0B setup.]
You have the COM0A1 and COM0B1 bits set, and you apparently assume COM0A0 and COM0B0 are clear. (Note that in the code below, I say TCCR1A = ... and  TCCR1B = ... instead of using |=, because |= is not reasonable to use for initial setup).  In the #7 fast PWM mode that you selected via WGM bits, this would lead to OC0A and OC0B clearing on their respective Compare Matches and setting at BOTTOM, which looks more or less ok for the OC0B pin, if you have OCR0B set to about half of OCR0A.  If the OC0A pin clears, however, it probably gets set again a cycle later, if I understand correctly.  (However, I'd want to actually test the code, with oscilloscope connected, to say for sure.)
Note that the OCR0A count of 52 and prescaler of 8 will set up a counting frequency of 1600000/(52+1)/8 Hz, ie about 37735.85 Hz, while a count of 51 would give 38461.54 Hz.  If accuracy matters, you can use simpler and more accurate code like the following.  It uses a prescale of 1 and count of 209, to generate a toggle frequency of 1600000/(219+1) Hz, ie about 76190.48 Hz, and a square wave frequency of about 38095.24 Hz.   Note, this code is written for timer 1; it should be straightforward to adapt to timer 0, because 209 is less than 255, the upper limit of TCNT0.
// Generate a constant frequency on PB1, using Fast PWM - jw May 2017
enum { OC1Apin = 9 };    // Arduino digital pin #9 = OC1A = PB1

void setup() {  // Set up timer 1
  noInterrupts();               // Turn off interrupts during setting
  TIMSK1 = 0;                   // Turn off timer 1 interrupts
  // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
  TCNT1 = 0;                    // Zero the counter
  TCCR1A = 1<<WGM11 | 1<<WGM10  // for Fast Pwm with TOP from OCR1A
    | 1<<COM1A0;                // To toggle OC1A PB1 D9 on Compare Match
  TCCR1B = 1<<WGM13 | 1<<WGM12// for Fast Pwm with TOP from OCR1A
    | 1;                      // Start timer 1 with prescale 1
  // Set OCR1A *after* setting up TCCR1A & TCCR1B
  OCR1A = 209;                // Gen. about 38095.24 Hz
  pinMode(OC1Apin, OUTPUT);
  interrupts();
}
void loop() {}

Edit 1: Here are some of the differences between this code and that shown in the question, aside from using timer 1 instead of 0:
• Initialization of TCCRxA and TCCRxB registers here is done using Register = expression forms, rather than  Register |= expression forms.  Just OR-ing your bits in may be a problem if some other CS bits are set.  For example, in the Arduino environment, initialization for millis() will set a prescale factor of 64, by setting both of the CS00 and CS01 bits, so that when you say TCCR0B |=(1<<WGM02) | (1<<CS01); you end up with both of the CS00 and CS01 bits still set, and a prescale of 64 instead of 8.
• TCCR1B = ... | 1;  // Start timer 1 with prescale 1 sets the CS00 bit and leaves the CS01 and CS02 bits clear, selecting prescale 1, while TCCR0B |= ... | (1<<CS01); selects a prescale factor greater than 1.
• The code shown here generates a square wave because it toggles a pin at a constant rate.  The code in the question sets OCR0B to 26, which will give 27 clock-cycles to half of each output cycle, and 26 clock-cycles to the other half.
• The code shown here generates a frequency of about 38095 Hz, which is about 0.25% high, vs a frequency 0.7% low for the code in the question.

Edit 2: One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle if appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:
volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

To output a specified number of cycles n, set the mode of TogPin to OUTPUT and set TogCounter to 2·n.  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.
To generate a sequence like m1 cycles on, n1 off, m2 cycles on, n2 off, etc, you could set up an array containing m1, n1, m2, n2, etc; then each time TogCounter runs down, toggle TogPin from INPUT to OUTPUT or vice versa, and load the next array entry into TogCounter.

I have analysed your code and to me it seems that , both are identical . Just that you have used timer 1 with no prescaler and therefore  OCR1A=209 , whereas I have used Timer 0 with Prescaler of 8 and therfore OCR0A = 51 (corrected) . Have i missed any changes that you have added ?

another thing that i have noticed is , you are setting the timer frquency to 238 Khz , so that on match you will just toggle the level ( using COM1A0) . I have done it differently by settng timer freq =38 Khz and instead of toggling , I am just setting it to 0 once half of that freq i.e 38 Khz is reached . thus , i will get On and Off freq = 382 Khz. thereby achieving what you have tried to do . Only difference is I am using OCR0B to output the pwm , as i did not want to change the value of OCR0A from the setup() part . I don't see anything that I have done differently than yours .

@BoudhayanDev, see edit 1

Okay so besides the Or operation mentioned in first point , what i need to change is - select Toggle mode using CS10/11/12 . I'll give it a try.
Also , i was thinking , I'll use ICR1 register to hold the Top value instead of OCR1A . so in that way OCR1A will be free to output the pwm wave . Is it fine if i do it or should i continue with OCR1A to hold the Top value and OCR1B to output the pwm wave ?

I'm not sure what you mean by  “output the PWM wave”; I thought you were trying to output a 38KHz square wave, which is what the code I posted should do.  With that code, one sets up the square wave frequency by the value in OCR1A, after which it rolls out a square wave on OC1A with no further program interaction needed.   Are you instead trying to put varying PWM modulation onto a 38KHz carrier, rather than genning a square wave?

Thanks for the explanation , your code works and so did my original code . Generating the 38Khz frequency worked with my original code by just replacing the OCR0A value to 51 instead of 52 as suggested .
However , your approach worked too . Only difference is the precision of the square wave .
Additionally , can you suggest a way to output only a certain number of pwm pulses . For ex - with the 38Khz wave that's generated , i want to output only 6 On-Off pulses of it followed by complete logic low . As in "fixed number" of 38Khz pwm pulses only and not continuous pulse train.

@BoudhayanDev, see edit 2

thanks it worked. I have just resettled CS pins after a specific period of time to 00 . That specific period of time during is the time  during which the pulses are generated .

A few ways to get there. 38khz has a period of 421 ticks on a 16mhz Mcu. So
Approach 1. Use the pwm module to Generate it.
Approach 2. Use the timer overflow interrupt to generate it. Simply flip the output pin in the isr.
Approach 3. Use the compare interrupt to generate it. In the isr increment the compare match register by 120 and then flip the output pin.
All of them are fully supported by your chip. The first approach once set consumes no CPU processing power.
edit: this link, https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/, will hopefully provide some inspiration to you. It is for a different application but the gist of the problem is the same.
here is the output, adopting it to generate a 38Khz (37,679Hz to be exact) pulse train on a user specified pin using timer2 compare ch b interrupt.

i think you will benefit a lot in getting the code going on your own but if you really struggle, I can provide you the code as well. but you get a lot more if you try to get it going on your own.

Can you elaborate your Approach 2 and 3 wit certain code examples ?


text:
P I D AND GY80 10 DOF
I am running the program for GY80 10 DOF , and runs fine . Date is printed on the serial monitor
How ever I have failed to use this program for my WalkerBot
(walker bot is a Robotic suit that I want to build for 4 years old my grand son He can not walk due to C P )
Unless the PID is not introduced in the program it will not be good for Balancing of the walker Both the program is as under , and my further questions are in comments
I need help Please
I tried to use the Code Control to insert the codes But it did not work , I may be excused for that Please
the codes
  #include <Wire.h>
  #include <GY80.h>

     GY80 sensor = GY80(); //create GY80 instance

  void setup()
  {
    // initialize serial communication at 115200 bits per second:
    Serial.begin(115200);
    sensor.begin();       //initialize sensors
  }

     // How to envelop this program with PID
     // where the gyro output is supposed to maintain the vertical position of the //bot , and the accelerometer will be doing countermeasure of tilts
// unless they both are on a feedback with PID this bot will not balance
//as the servomotors if do not respond in runtime the bot will fall
void loop()
{
    GY80_scaled val = sensor.read_scaled();       //get values from all sensors
    // print out values

    Serial.print("Mag:");                         //magnetometer values
    Serial.print(val.m_x,2);
    Serial.print(',');
    Serial.print(val.m_y,2);
// tried to get some output from here for using in PID but failed
if(val.m_y,2 >2 ||val.m_y,2<0){Serial.print("Output has been managed");}
but there was no output
    Serial.print(',');
    Serial.print(val.m_z,2);
    Serial.print(' ');
    Serial.print("Acc:");                         //accelerometer values
    Serial.print(val.a_x,3);
    Serial.print(',');
    Serial.print(val.a_y,3);
    Serial.print(',');
    Serial.print(val.a_z,3);
    Serial.print(' ');
    Serial.print("Gyro:");                        //gyroscope values
    Serial.print(val.g_x,1);
    Serial.print(',');
    Serial.print(val.g_y,1);
    Serial.print(',');
    Serial.print(val.g_z,1);
    Serial.print(' ');
    Serial.print("P:");                           //pressure values
    Serial.print(val.p,5);
    Serial.print(' ');
    Serial.print("T:");                           //temperature values
    Serial.println(val.t,1);

    delay(250);        // delay in between reads for stability
}

It is a mess Sorry I failed to organise It

I don't see a question in either the title or in the text.

why this program is  causing erratic movements? , making the test bench fall immediately , 2. Why the motors do not react to the tilt of the Gyro Board.

Code Gorilla Thank you for making the post neat , I felt very embarrassed when I failed to make it look elegant and had to post it like a grade 1 kindergarten student . I appreciate Thanks

I am sorry, but I may not have understood your post, but I think the problem is your code doesn't work and you don't know why.  I think the problem is with this line:
if(val.m_y,2 >2 ||val.m_y,2<0){

It is because it is not valid code, I suspect its a cut and paste error and should be
if(val.m_y > 2.0 || val.m_y < 0.0){

the ,2 you use in the print statements specifies the number of digits to print after the decimal point (I think).


text:
How to choose SDA/SCL pair on Arduino Due?
On Arduino Due, there are two pairs of SDA/SCL pins that I can use for I2C. There is SDA0 and SCL0  at, respectively, pins 20 and 21 and another near AREF. How do I choose which one of them I use? I also read that pins 20 and 21 have built-in pull-up resistors, is that true?

The easiest/quickest way would be to experiment.  Attach an I2C device and use I2CScanner to detect it, then repeat with the other pins.  As to the pull-up you could use a volt metre to test that (I think)

Pins 20 and 21 are the default I2C pins. A lot of libraries assume you use these, and would require some extra work to get working with SDA1/SCL1.
They also have their pullup resistors already present on the board of the Due (see schematic).
So just use pins 20 and 21, unless you have a good reason to use the other.

How to choose SDA/SCL pain on due from software.
wire.h has two instances of TwoWire i.e. Wire and Wire1.
Wire uses
#define PIN_WIRE_SDA         (20u)
#define PIN_WIRE_SCL         (21u)

and Wire1
#define PIN_WIRE1_SDA        (70u)
#define PIN_WIRE1_SCL        (71u)

observe which instance is used by your library
e.g.
#define WIRE Wire1 or #define WIRE Wire

if library is using Wire then its default i2c at pin 20 and 21.
if library is using Wire1 then its i2c at pin 70 and 71 near AREF.
make changes accordingly. if you want to use default i2c use "Wire" instance or
if you want to use i2c near AREF use "Wire1".
most important don't forget to modify Wire1.begin() or Wire.begin() accordingly.
as mentioned in earlier comment second i2c (pin 70 and 71 near AREF) doesn't have pullup resistor handle it while using second i2c.


text:
How to manage dependencies?
I want to include a dependency like Logging. On its page it says:

Download zip file
Put the Logging folder in "libraries\".

I don't want to believe (with a Maven mindset) that this is the way we manage dependencies in Arduino projects. That means, everybody who checks out my package would have to repeat those steps locally (or do you include "libraries\" in the version control) What's the best practice for dependency management?

Nope, that is what everyone does.

Libraries is what libraries are. This is not Maven. This is Arduino. It's simplistic so that people without knowledge of microcontrollers can make an LED blink. If you want real IDE facilities then use a real IDE.

Well, I'm using the first hit in Google for Arduino IDE, but this doesn't help me with dependencies. Making a LED blink doesn't necessary require a library and I agree that things should be simple. That's the very reason why I ask for  dependency management.

Look for C++ IDE or G++ IDE instead. And for crosscompiling

Arduino is meant to be easy way for non-technical people and so it hides as much as it can from plain view to be simple.
For simple project it works at the cost of overhead of copying libraries here and there and using Arduino's "IDE". Calling programs "sketches" and manipulate it to hide, that it is in C++. And so on and so on.
If you want to make more complicated projects, version control, good environment and such, you need to leave "simply Arduino way" and start using more powerful and complicated tools.
I personally use
https://github.com/sudar/Arduino-Makefile
https://github.com/ladislas/Bare-Arduino-Project
and have it in GIT repositories.
This way I can share libraries between projects in group, also links to libraries outside the tree works, as well as gits submodules, both allowing you to have updated libraries from 3rd party aviable to all projects, also those old ones.
I still use a lot of Arduino (like setup/loop, digitalRead and such), but also I use "normal" g++ constructs on the way. Later I will diverge even more to plain C/g++/.. code probably, using some RTOS or so, but now my needs are not so far yet. (google "arduino rtos" I am currently reading https://github.com/greiman/NilRTOS-Arduino )
Arduino is not meant to be "best practice" anyway. It is meant to be "fast and easy way to do something, when you know nothing". And it works, as anybody and his dog can start with Arduino and if interested, he can go more far on his own, or he can stick with easy and have fun anyway.

If you want the project to be self contained you can put the library dependencies in the sketch folder. So the folder structure of the Foo sketch with the Logging library dependency would look something like this:
Foo
|_Foo.ino
|_src
  |_Logging
    |_Logging.h
    |_Logging.cpp

And in Foo.ino you will include the library like this:

#include "src/Logging/Logging.h"

Unfortunately some libraries use the incorrect include syntax which still works when the library is installed in one of the libraries folders but not when located in the sketch folder. The Logging library does use the correct include syntax but sometimes to put libraries in the sketch folder you will need to fix this. For example, let's say you have a library named Bar and in Bar.cpp you see this:
#include <Bar.h>

That won't work because if installed in the sketch folder Bar.h will not be located in one of the standard include paths so you need to edit Bar.cpp and change the include syntax to:
#include "Bar.h"

Which will cause the local folder to be searched for the included file.
The downside to this system is that you may end up with multiple copies of a library so it's more work to update or modify each copy. Of course that can also be a benefit because each project can have its own known-working version of the library that will not be affected by any updates you may make to the same library used in other projects.
I generally just add instructions for how to install library dependencies in the usual manner to the documentation for a project. That should be within the capabilities of the average Arduino user. If a specific version of a library is necessary then you document that. However, there are cases where I have wanted to hand over a self-contained project to someone who is not familiar with the use of the Arduino IDE and that is when I have used the system described above for all necessary 3rd party libraries.


text:
Dynamically switching pin out
I have a connector with 10 pins, and a bus which uses 2 of the 10 pins.
What I need to do is, in software, attach my arduino to 2 of the 10 pins. I cannot wire it directly as the 2 pins required may be in a different position in different environments.
What are my options?
EDIT: Just some background. I have to connect to an OBD II port of a vehicle and cannot to the CAN bus. On some vehicles is may not be on the standard pins in the OBD connector, so I would like to be able to programatically switch the pins being used, in software.

Could you connect all 10 pins to the Arduino and select which of them to use in the Arduino software?

No, mainly due to the bus requirements - think SPI, only works on certain Arduino pins.

If there are other requirements not stated, it would be useful to edit them into the question. I can think of a few ways of doing this. Whether any of them will be suitable depends on what you're trying to do.

Fair point. I tried to be as generic as possible to keep it simple, but I have added background in case it helps.

Probably you need two SP10T switches, where you can programmatically decide which of the SPI pins will be sent to which of the 10 outputs which are connected to the 10 pin bus.


text:
LED sequence control by button
I want to make sequential LED by using arduino that controlled by button.
If I press + button, LED will increase from L1 to (L1 and L2 is HIGH), then I press button again, L1, L2, and L3 will be HIGH. If I press again, all the LED (L1, L2, L3, L4) will be high.
Same case if I press “ – “ button, LED will be lower from the previous state. Which mean that if L1, L2, and L3 is HIGH. There will be L1 and L2 only HIGH if I press ‘ – ‘ button. I dont how to do it. This is code for increase but I dont know how to make it reverse flow.
const int buttonPin = 2; // the pin number of the pushbutton input pin
int ledPins[] = {3, 4, 5,};
 // variables will change:
 int buttonState = 0; // variable for reading the pushbutton status
 int buttonPressCount = 0;
 int numberOfLED = 3;
 void setup() {
  // initialize the LED pin as an output:
  for (int i = 0; i < numberOfLED; i++) {
   pinMode(ledPins[i], OUTPUT);
  }
  pinMode(buttonPin, INPUT);
 }
 void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
   for (int i = 0; i < numberOfLED; i++) {
    if (buttonPressCount % numberOfLED == i) {
     // turn LED on:
     digitalWrite(ledPins[i], HIGH);
    } else {
     // turn LED off:
     digitalWrite(ledPins[i], LOW);
    }
   }
   buttonPressCount++;
   delay(400);
  }
 }

My original answer was probably over-kill....Just keep track of how many leds are lit:
int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
byte num_leds_lit = 0

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        digitalWrite(ledPins[i], i < num_leds_lit ? HIGH : LOW);
    }
}

Then, on button press, increase the count:
if (num_leds_lit < num_leds) {
    num_leds_lit += 1;
    set_leds();
}

Then to turn the leds off with the other button press:
if (num_leds_lit > 0) {
    num_leds_lit -= 1;
    set_leds();
}

------------------------- Original answer
There are a few ways to do it. One way would be to use a bitmask. I would write a function to turn the leds on/off
// Each bit represents the state of one LED (0 == off, 1 == on)
byte led_bits = 0;
int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
// Need a mask to make sure we don't set too many bits
const byte led_mask = 0xFF >> 8 - num_leds;   // 00000111B in this case

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        // Turn on/off based on state of bit
        digitalWrite(ledPins[i], (1 << i) & led_bits ? HIGH : LOW);
    }
}

Then, on button press, set the mask:
led_bits << = 1;          // Shift left (001 -> 010)
led_bits |= 1;            // Set lsb    (010 -> 011)
led_bits &= led_mask;     // Ensure max bits: (1111 -> 0111)
set_leds();

Then to turn the leds off with the other button press:
led_bits >>= 1;          // Shift right (011 -> 001)
set_leds();


text:
Split flash Arduino nano
I need to update the firmware over-the-air for Arduino nano. For that I need to split the flash into two so that one of the partition that contains the original code cannot be erased while re-flashing and the other partition will contain the segment in which the re-flashed program would appear.
The board reboots from the first partition before the flashing initiates, during flashing the code in the first partition would be active and the board reboots from the new code in the second partition after the flashing is complete.
I don't have any idea how to play around with the flash splitting in arduino and any help would be appreciated.

You'll need to look into creating your own bootloader. As only the bootloader can write to flash.

According to your plan it will be quite hard to do........ But infact you could do one thing that is change the arduino's bootloader a bit that is increasing the timeout of  the bootloader where it decides to whether go for flashing or go for proccessing the program.....


text:
I need to restart Arduino IDE after each compilations
I'm using the Arduino Due and testing an I2C Scanner, the I2C Scanner works correctly but each time I want to upload a newer version of the code I get this error message :
No device found on COM11
Send auto-baud
Set binary mode

What I need to do in this case is : remove USB, restart the Arduino IDE, reconnect USB, then it works again, one time...
It seems related to this problem : Serial port on mac only works after restarting arduino IDE
I'm not sure but What's maybe also symptomatic is I need to systematically push the restart Button of my board in order to receive something in the Serial Monitor, could it be related ?
Here is the I2C Scanner code I'm using :
// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(1000);           // wait 5 seconds for next scan
}

IDE version? Native or UART port?

IDE is 1.6.12, I use the Native port

And if you try the current version, 1.8.2?

I finally solved the problem, but it's really specific and I don't know if should be on Stack Exchange. Maybe it could give some clues if someone has a similar problem one day...
I was using pin 20 and 21 on my Arduino Due which are supposed to have built-in pull-up resistor. That's what I've read everywhere and it has been said again recently in the answer of an another question I've asked : How to chooce SDA/SCL pair on Arduino Due ?.
Solution : Since I'm using SDA1 / SCL1 with Wire1 everything works like a charm. The value I get from the device are correct, no need anymore to restart the board and I can recompile again and again without any problems.
Edit : In fact, it work significantly better but I still had to use pullup resistors with these inputs. The goal was to use the MPU 9250 and it seems more stable now.


text:
How do I erase internal EEPROM on a Arduino Pro Mini
I'm working on Arduino pro mini.
and I store some data in internal EEPROM.
So, I want to erase certain data from 0x00 to 0x28 address in EEPROM.
void loop()
{
 ...
 ...
 if(erase_eeprom_flag==1)
 {
   addr_uu=0;
          erase_eeprom_flag=0;
          for(kk=0;kk<28;kk++)
          {
              EEPROM.update(addr_uu,0);

              addr_uu=addr_uu+1;

          }
          Serial.println("OK");
          Serial.println(addr_uu,DEC);
          addr_uu=0;
      }
  }

But I got a data like(28 times '0' and other data 'xxx') "0000000000000000000000000000xxxxxxxxxxxx".
ex : 20170519    --->   expected data: 00000519
                        (inappropriate data: 000020170519)
So, here actually push "0" / add at begin operation happen but I want to remove data from those address.
Please tell which Arduino function help me for solving my issue.

You are clearing 28 decimal bytes, but your address range is 28 hex bytes, or 40 bytes of data.  Hence, the last 12 characters are untouched.

41 bytes (decimal), counting the zero-th byte. Regardless, good catch.


text:
How do i generate exact number of PWM pulses in arduino?
So my code here generates a PWM wave of 38Khz on Port B pin 7 of arduino Mega 2560 . For that I have used a prescaler of 8 and then set the ICR1 register value to 51 . I have also set the WGM10 ,WGM11, WGM12 and WGM13 bits to 1 , to enable fast PWM mode with Top reference value as ICR1 contents . Similarly , COM1A1  is set , to enable clear output on compare equal else high . CS11 is set to high to enable the prescaler 8 .
My code is as follows -
#include<avr/io.h>
#include <avr/iomxx0_1.h>
#include<util/delay.h>
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        TCCR1A =  (1<<WGM11) | (1<<WGM10) | (1<<COM1A1);
        TCCR1B =(1<<WGM12) | (1<<WGM13) | (1<<CS11);
        ICR1 = 51;
}

void pwm_generate()
{
    OCR1A = (50 * 52)/100 ;
}
int main()
{
pwm_init();
pwm_generate();
}

What I require from the program is that , it should stop producing pwm pulses once a sufficient number of pulses are transmitted . For example - The program should output 7 pwm pulses of 38Khz and then it should give logic 0 as output for specified time period . And then after that specified period , it should produce 38 Khz pwm wave again of say, 5 pulses and then again logic 0 for certain duration . And so on ...
How do i achieve this ?
PS- This program is actually being written to simulate a pwm wave required by the IR transmitters in TV remote . The PWM pulses represent the ON period and the Logic 0 conditions would represent the gap in between two successive train of PWM pulses.
Picture of waveform for reference -

There's a whole IRremote library to do that for you.

I don't want to use any libraries.

It's not the number of carrier cycles that matters but the time the pulses are on or off for _ and that not accurate to a pulse. The carrier is just to get the signal through a band-pass filter at the receiver end.

One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle, whichever is appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:
volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

To output a specified number of cycles n, set the mode of TogPin to OUTPUT and set TogCounter to 2·n (or to n if counting cycles instead of toggles).  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.
To generate a sequence like m1 cycles on, n1 off, m2 cycles on, n2 off, etc, you could set up an array containing m1, n1, m2, n2, etc; then each time TogCounter runs down, toggle TogPin from INPUT to OUTPUT or vice versa, and load the next array entry into TogCounter.

Thank you. I have used the CS reg to set the port to normal and forced logic 0 through it after specific number of pulses were generated . Though I haven't used interrupt , your explanation was helpful .

simple:
1) generate a pulse train of 38Khz -> many ways to do that;
2) put a resistor on the pulse train -> something like 1K will do it;
3) on the other end of the resistor, put a GPIO pin on it; configure it as input, but write a '0' to it;
4) route the clock input of a timer to that GPIO pin; set it to trigger an isr on a given number of pulses -> many ways to do that;
5) in the isr set up in 4), turn the gpio pin in 3) to output to disable the pulse train; input to enable the pulse train.
6) done.

Can you elaborate with the isr code example ?


text:
Issues while making ESP8266 as web server
I have programmed ESP8266 with below program. I used USB to TTL convert to program ESP8266. This is how I wired my circuit:
USB TTL---------------- ESP8266 ESP-01
GND-----------------------GND
TX---------------------------RX
RX---------------------------TX
3.3V-----------------------VCC & CH_PD
GND------------GPIO0
#include <ESP8266WiFi.h>

const char* ssid = "shiv";//type your ssid
const char* password = "manmohan@12345";//type your password

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request

  int value = LOW;
  if (request.indexOf("/LED=ON") != -1) {
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1){
    value = LOW;
  }

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.print("Led pin is now: ");

  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("

");
  client.println("Click here turn the LED on pin 2 ON
");
  client.println("Click here turn the LED on pin 2 OFF
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

It was successful, here are the logs:
Archiving built core (caching) in: C:\Users\williams~1\AppData\Local\Temp\arduino_cache_375631\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____feb0d75f3cf4e05271af4f91549cd009.a
Sketch uses 230073 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 32376 bytes (39%) of dynamic memory, leaving 49544 bytes for local variables. Maximum is 81920 bytes.
Uploading 234224 bytes from C:\Users\williams~1\AppData\Local\Temp\arduino_build_189179/sketch_may14d.ino.bin to flash at 0x00000000
................................................................................ [ 34% ]
................................................................................ [ 69% ]
.....................................................................            [ 100% ]

Once this was completed, I opened serial monitor and it was empty there, baud rate was 115200. It is weird, Isn't ?
I followed this tutorial https://create.arduino.cc/projecthub/ROBINTHOMAS/esp8266-esp-01-webserver-7248ca and on serial monitor it should be like below snapshot. What wrong I am doing ? Can anyone help me.

Tying GPIO0 to ground puts the ESP into programming mode, allowing you to flash it.  To actually run the code, pull it high - that is, disconnect it from ground and connect a resistor (about 10k) between GPIO0 and +3.3v.
Do the same with RST.

I disconnected GPIO0 to ground, then restarted Arduino software then selected port COM5 then open serial monitor then still same result .. here is my settings http://imgur.com/a/kT4kS

Here is serial monitor snapshot http://imgur.com/a/T4tXg

You might need to pull it high, as I explained in the answer. You might also need to pull RST high in the same way.

Thanks! I resolved it by connecting with Arduino, it worked :) +1

Could you explain what you did please, for my interest and for future reference?

I have posted an answer how I resolved it

Thanks @Mark Smith. I used UART to flash new firmware to ESP8266. I connected Arduino and ESP8266 in this way to test ESP8266 new firmware:
Arduino ---------------- ESP8266 ESP-01
GND-----------------------GND
TX---------------------------TX
RX---------------------------RX
3.3V-----------------------VCC & CH_PD
Then I opened Serial Monitor on 115200 baud rate and it started to work as expected. Cheers!


text:
Arduino Mega Shield Library for Eagle CAD
I'm a noob to PCB designing and electronic stuff. I want to design a pcb shield which is compatible with an Arduino mega 2560. I'm using Eagle CAD. I checked the sparkfun library but I couldn't find a way to design Mega Shield. Can anybody give me a library or any alternative way to do this?

You should try Circuit Maker instead.

Alright Thanks @Jeroen3 I'll give a try. Is it comes with inbuilt libraries for Mega shields?

Try KiCAD, there are plenty of templates for Arduino, Raspberry, BeagleBone etc.

Since you're new user, perhaps it's easier to take an existing project and modify it for your need.
For Eagle, examples can be found on Github.

https://github.com/zortness/rocket-mega-shield
https://github.com/practicalarduino/ProtoShieldMega

However, due to recent developments in the PCB EDA world I would suggest you take a look at Circuit Maker. It's more fit for sharing an collaborating designs and libraries. You can easily fork an existing board and use their community parts repository.


text:
Storing a 2 dimensional Array in PROGMEM
I am running a Mega 2560 processor board.
I have a large "unsigned char" database currently stored in a 2 dimensional array in SRAM.  I have plenty of room in program memory and need to move the database to PROGMEM.  It appears that the rules around how to use PROGMEM have changed and the documentation does not reflect the change. I have found a way to store the array in PROGMEM and can access the data statically (ARRAY[0,1]).  If I try to access the array dynamically, (ARRAY[var1,var2]), I get junk.
Since I have seen some questions what I mean by "static" and "Dynamic" I gladly add the following examples:
//Array initialization

const static unsigned char __attribute__ ((progmem)) Image_1d_Array[234]={
  0x00, 0x0e, 0xf8, 0xff, 0xdf, 0x03, 0xc0, 0x1d, 0x60, 0x1f, 0x60, 0x00, 0x03,
   0xdb, 0x01, 0x00, 0x08, 0xe3, 0x07, 0x00, 0x0e, 0x00, 0x1e, 0x30, 0x00, 0x00,
   0x00, 0x0e, 0xf0, 0x07, 0xfc, 0x01, 0xc0, 0x39, 0x00, 0x1f, 0xe0, 0x00, 0x03};

void setup:
  int i;
  char myChar;

//  Static read.  This will give me the correct values
  Serial.print("Image= "); Serial.println(Image_1d_Array[0],HEX);
  Serial.print("Image= "); Serial.println(Image_1d_Array[1],HEX);
  Serial.print("Image= "); Serial.println(Image_1d_Array[2],HEX);
  Serial.print("Image= "); Serial.println(Image_1d_Array[3],HEX);
  Serial.println("");

//  Dynamic read.  This will give me the junk values
  for(i = 0; i <=11; i++){
     Serial.print("AImage= ");
     myChar = pgm_read_byte_near(&Image_1d_Array + i);
     Serial.println(myChar,HEX);
    }

I can't even get a single dimensional array to work dynamically.
Does anybody understand the new rules to access the array?? The following data structures from the Arduino reference manual are no longer supported

prog_char - a signed char (1 byte) -127 to 128
prog_uchar - an unsigned char (1 byte) 0 to 255
prog_int16_t - a signed int (2 bytes) -32,767 to 32,768
prog_uint16_t - an unsigned int (2 bytes) 0 to 65,535
prog_int32_t - a signed long (4 bytes) -2,147,483,648 to * 2,147,483,647.
prog_uint32_t - an unsigned long (4 bytes) 0 to 4,294,967,295

Please edit your question and explain what you mean by the phrases  “access the data statically” and “access the data dynamically”.  You might need to add   a Minimal, Complete, and Verifiable example of code so people don't have to waste time guessing what you did or what you meant.   § AFAIK,  “the rules around how to use PROGMEM have changed” is false.

I tested on an UNO and it works fine if you remove the &.

Accept Edgar Bonnet's answer to close your question.

You wrote:
myChar = pgm_read_byte_near(&Image_1d_Array + i);

Here &Image_1d_Array is the address of the array. Its type is “pointer
to an array of 234 unsigned chars”. When you add i to this pointer,
per the rules of pointer arithmetic, you are actually adding to the
address i times the size of the array.
What you actually mean by &Image_1d_Array is “the address of the first
element of the array”, which can be written &Image_1d_Array[0]. Or you
could rely on the usual “decay to pointer” semantics, and simply write
Image_1d_Array, as suggested  in Johnny Mopp's comment.
Now you should have noticed that both Image_1d_Array and
&Image_1d_Array behave as pointers to the same memory address, only
they have different types. See the
C FAQ and references therein
for more on this distinction.
Note that the usual way of doing what you want is:
myChar = pgm_read_byte_near(&Image_1d_Array[i]);

Thanks for the info, I thought the "i" in "(&Image_1_Array+i)"   was adding an offset of "i" to the Array not "i * Array size".   Big difference!!

@KenKloster: As a general rule, (size_t)(&foo + i) always means (size_t)&foo + i * sizeof foo. Note that size_t is just an integer type large enough to hold a pointer.


text:
SoftwareSerial too slow for MIDI?
I tried to use the SoftwareSerial library for MIDI (by 47 effects), but it seems I get regularly corrupted/unexpected messages.
The circuit I'm using works perfectly when I connect it with the HardwareSerial solution (so the problem must lay in software).
What I see is:

When I press notes and release notes, LED 13 goes on and off correctly.
When I use Serial.print for debugging I get correct messages. However, in the example below I removed the print statements to have a minimal example).
When I use SoftwareSerial, LED 13 goes on and off for every note correctly. However, when I send many messages (for example by aftertouch/pitch bend which send a lot of messages in a short time), I noticed Note On/Off commands with 'random' values are sent.

Some sources say SoftwareSerial should work for MIDI, however, so far it is far from perfect. Do I make some mistake?
(btw, the baudrate of MIDI is 31.250 bps, when I use pitchband several hundreds of bytes per second are sent, so far within the MIDI spec).
The sketch I use is:
#include <MIDI.h>  // Add Midi Library
#include <SoftwareSerial.h>

SoftwareSerial swSerial(2, 11); // RX, TX

MIDI_CREATE_INSTANCE(SoftwareSerial, swSerial, midiSw1);

#define LED 13    // Arduino Board LED is on Pin 13

void setup()
{
  pinMode (LED, OUTPUT); // Set Arduino board pin 13 to output

  midiSw1.begin(MIDI_CHANNEL_OMNI);
  midiSw1.setHandleNoteOn(MyHandleNoteOn);
  midiSw1.setHandleNoteOff(MyHandleNoteOff);
}

void loop()
{
  midiSw1.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
  digitalWrite(LED, HIGH); //Turn LED on
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity)
{
  digitalWrite(LED, LOW); //Turn LED off
}

I've experienced the exact same problem. In my experience SoftwareSerial isn't fast enough to handle quick, successive MIDI messages. I found I got the best results by using the hardware serial for MIDI and using SoftwareSerial + another Arduino for debugging. Although this was the best setup, it still wasn't perfect. Even the hardware serial dropped/corrupted messages once in a while.

digitalWrite might be too slow. Try replacing it with PORTB |= 0x20; and PORTB &= ~0x20;. But there's nothing much you can do to speed up all the MIDI handling code.

@Mazaryk ... I already use a Mega which has 4 hardware serials, so far I use 3 for MIDI, one for debugging (for now, later can be the 4th MIDI). And when the 4th is used for MIDI I probably will use another Arduino as debugging. I did a lot of testing and so far I never got dropped/corrupted messages ... and CL proposed to use the even better H11L1 opto couplers instead of the 6N138 which I use now.

@CL: Thanks ... everything to speed up might be good ... however, since the hardware serial solution worked well with digitalWrite and the software serial not, I still think it is too unpredictable if I have to use such 'tricks'.... later I want to do also additional processing which might make the software solution unworkable (again).

The problem with SoftwareSerial is that while it is receiving a packet the Arduino is unable to do anything else - that includes reading bytes from the RX buffer, so it will easily overflow if you send things too rapidly. With HardwareSerial you are able to read from the buffer while it's receiving data, so overflowing is less of a problem.
As soon as the START bit of a packet is received it enters an ISR and reads each of the remaining 9 bits of data (including the stop bit) in a tight loop. That ISR doesn't exit until the whole packet has been received and stored in the RX buffer. If another byte is sent straight away there is little time between the ISR finishing and it being triggered again. The rest of the code, including the MIDI parsing routines which read data from the RX buffer, are then starved of CPU cycles and can't run properly. Send too many bytes together and the limited RX buffer (64 bytes) fills up and overflows, and you lose data.
Another issue with SoftwareSerial is that it has to capture the START bit at the moment it arrives. Any delay in capturing that edge will result in a drift in the bit sampling timing. If there is anything else that is using interrupts at the same time (such as the millis() timer) will delay the triggering of the PCINT interrupt used for the START bit detection. Even the SoftwareSerial interrupt itself has a certain amount of time after it has finished receiving the packet where it stores it in the RX buffer and returns from the interrupt routine. If the next packet arrives before the ISR is ready to service it there will be a delay - and any delay is bad.
Personally I am of the opinion that SoftwareSerial should never be used for anything, ever. If you need more serial ports then you either need a more powerful chip or you need more than one chip and get them communicating together through another higher speed hardware channel (SPI or I2C, for instance).
SoftwareSerial is only suitable for sending short bursts of data (since it blocks completely while sending) or receiving very short messages sent infrequently.

Very helpful information (as always) ... I tried to make the buffer 128 bytes but I didn't see any improvement. Of course I can make it 256 of maybe 512, but probably it's just 'delaying' the time before getting into problems if I read your explanation.

If you're sending lots and lots all the time then yes, all you will be doing is delaying the time before you see problems. Also there is always the chance that if the next packet comes too fast the ISR won't be able to respond fast enough and you may lose the start of the next packet, triggering part way through on the next falling edge within it.

Maybe in the future (if my project will grow) I might have to go to another board (giving me 8 hardware serials). Currently I use a SD shield, planning to use a WIFI shield and possibly a USB (host) shield, also need a prototype board for additional components (several opto couplers etc). So maybe 2 Mega's would be good :-)

Maybe even three ;) You can never have too many. It can be good to split a project down into component blocks and have them separately controlled and managed. Maybe have one central master controller than tells all the others what to do.

Yes sounds perfectly clear to me :-) ... I don't know if you are familiar with MIDI, but note on/offs will not give a problem, but CC messages (like pitchbending/aftertouch result in a lot of bytes, well within the baudrate of MIDI which is 31250 bps, but probably too slow for SoftwareSerial).

That also sounds like a very cool idea ... but remember, this is the first Arduino project I do :-) ... on the other hand if the project will slowly grow it's very good to learn a lot about Arduino's/microcontrollers and electronics.

Yeah, I know MIDI quite well. As I mentioned in a comment above it's not just the quantity that can be a problem but the gap between successive packets. Even just two packets sent too close together can be problematic.

And the 'problem' is that I don't mind about losing a CC message, but a note off message being unhandled results in a note that sounds forever (unless changing the sounds on a synth) ... this is totally unacceptable in a live music situation.

Absolutely. It can be useful to program a "kill switch" which stops all sounds in an emergency. Just in case.

A kill switch is not something that is handy too (in my case) ... I want to let the MIDI box (as I call it) to respond to missages coming from synths and processing them and sending messages back ... so the box might be even out of sight for myself while playing.
But I could make a MIDI message that results in such kill (notes) functionality.

Yeah, it doesn't have to be a physical button directly connected - that's why I used quotes ;) Just some signal that can be sent to say "shut the hell up". Maybe get it to respond to a note you never play (C8, or something) so it's right there in front of you all the time at the keyboard. You may even end up incorporating it in your performances ;)

Let us continue this discussion in chat.


text:
GPS module not working with sensor
I am connecting my Soil Moisture Temperature Sensor SHT10 with GSM Module SIM900A and GPS GY-GPS6MV2. Individually, all components work properly and give proper values. But when I interface all three components with Arduino, only Temperature sensor seems to work and GPS does not give any values.
Even If I connect only SHT10 and GPS with Arduino Uno (without GSM), only SHT10 gives values but GPS doesn't.
My code is:
#include <AltSoftSerial.h>
#include <TinyGPS++.h>
#include <SHT1x.h>

AltSoftSerial gpsSerial (11,12);

TinyGPSPlus gps;

#define dataPin 6
#define clockPin 7
SHT1x sht1x(dataPin, clockPin);
float TEMP, HUMID;

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

void loop()
{
TEMP = sht1x.readTemperatureC();
HUMID = sht1x.readHumidity();
Serial.println(TEMP);
Serial.println(HUMID);
gps_value();
}

void gps_value()
{
while(gpsSerial.available())
{
gps.encode(gpsSerial.read());
}

if(gps.location.isUpdated())
{
Serial.println("Latitude: ");
Serial.println(gps.location.lat());
Serial.println("Longitude: ");
Serial.println(gps.location.lng());
Serial.println("Altitude Feet: ");
Serial.println(gps.altitude.feet());
Serial.println("Horizontal Dilution of Precision: ");  //lower the better
Serial.println(gps.hdop.value());
Serial.println("");
}
}

What is happening here ?
Datasheet of SHT10

DId you try to connect the GSM and GPS modules without connecting the temperature sensor?

@Majid_L Yes, I have done that. And it works.

You should share the temperature sensor circuit and the power supply you are using. From the info you have given till now I think it is a problem related to hardware not software. It could be over loading the power supply or maybe the arduino is getting reset.

@Majid_L I am powering Arduino with my PC itself.

As already mentioned this seems to be a current related problem. You are powering your Arduino over Usb. The sensors themselves do work fine. Yet connecting all of them seems to draw too much current so they won’t work properly. (See this post for more information on current.

You could have used SoftwareSerial instead of AltSoftSerial.Since you are using AltSoftSerial please go through its library file to check how you need to deal with it.
For Software Serial you need to use predefined Rx , Tx pins of Arduino rather than defining any other pins of it for Rx,Tx
for connecting those to Rx Tx of tempterature sensor.
For GPS try to define any 2 pins of Arduino as Rx Tx so that you can connect them to Rx Tx of GPS.Hope this helps you.

NEVER use a software serial library on the HardwareSerial pins (RX pin 0 and TX pin 1).  And SoftwareSerial is the worst alternative.  See this answer for more info.