text:
Problem with my Arduino project
I am making a smart bin which automatically sense (with the help of IR sensor ) and dispose the trash by moving with help of DC geared motor 12V 60 RPM and it also detects for obstacles with the help of ultrasonic sensor which is placed at the front of the bin. Once the bin is empty the motor has to spin in the reverse direction. My questions is that there is something wrong in my code and am not able to solve it.
The issue that I am having is that when I run the code the bin was perfectly working as checking whether the bin is empty or not at the start and check for obstacles. If both are clear it will start move and whenever it detects any obstacles, the bin will stop the motor and checks again if any obstacles present, else it will start move and dispose the trash from the bin. The problem is when I code to reverse the motor direction to bring back the bin to original state the relay in relay board making a trrrrr sound.
Project technical specifications:

Arduino Uno
60 RPM 12V DC geared motor
4 channel relay board with 2 relay active for two motors
Ultrasonic sensor
Infrared module
Plunger to open the door placed inside

My sketch:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins

LiquidCrystal lcd(10, 11, 5, 4, 3, 2);
int motor_fwd = 7;
int motor_rev = 8;
int plung_rly = 6;
int irsensor = 9;
const int trigPin = 13;
const int echoPin = 12;
int mtr_time = 10;
int mtr_time_rev = 1;

void setup()
{
    digitalWrite(motor_fwd, LOW);
    digitalWrite(motor_rev, LOW);
    digitalWrite(plung_rly, LOW);
    digitalWrite(irsensor, LOW);

    // initialize the relay1 pin as an output;
    pinMode(motor_fwd, OUTPUT); // initialize the relay2 pin as an output;
    pinMode(motor_rev, OUTPUT); // pinMode(irsensor, INPUT);
    pinMode(plung_rly, OUTPUT);
}

void loop()
{
    irsen_chk_low();
    delay(500);
    irsen_chk_high();
    delay(500);
}

void irsen_chk_low()
{
    if (digitalRead(irsensor) == LOW) {
        lcd.begin(16, 2);   // Print a message to the LCD.
        lcd.print("bin Empty");
        delay(500);
        digitalWrite(motor_fwd, LOW);
        if (mtr_time_rev >= 1) {
            mtr_time_rev = mtr_time_rev - 1;
            {
                digitalWrite(motor_rev, HIGH);
                delay(5000);
                digitalWrite(motor_rev, LOW);
                delay(5000);
                int mtr_time = 10;
            }
        }
    }
}

void irsen_chk_high()
{
    if (digitalRead(irsensor) == HIGH) {
        lcd.begin(16, 2);   // Print a message to the LCD;
        lcd.print("Bin is full");
        obs_detection();
        delay(500);
        digitalWrite(motor_fwd, HIGH);
    }
}

void obs_detection()
{
    long duration, inches;
    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);
    inches = microsecondsToInches(duration);
    cm = microsecondsToCentimeters(duration);
    lcd.begin(16, 2);
    lcd.print(inches);
    delay(100);
    if (inches <= 10) {
        digitalWrite(motor_fwd, LOW);
        delay(200);
    } else {
        if (mtr_time >= 1) {
            mtr_time = mtr_time - 1;
            digitalWrite(motor_fwd, HIGH);
            delay(200);
        } else {
            int mtr_time = 10;
        }
    }
}

long microsecondsToInches(long microseconds)
{
    return microseconds / 74 / 2;
}

You'll need to tell us more than "something is wrong with my code" - what specifically doesn't work the way you expected it to? What have you tried yourself? How is your project connected to your Arduino? It would also be very helpful if you would format your code by highlighting it and clicking the "{}" code-formatting symbol. It's pretty hard to read right now.

yes i am new to stack exchange am doing it...

when i run the code the bin was perfectly working as checking whethere bin is empty or not at the start and check for obstacles, if both are clear it will start move and whenever it detects any obstacles, bin will stop the motor and checks again if any obstacles present , else it will start move and dispose the trash from the bin . the problem is when    i code to reverse the motor direction to bring back the bin to original state the relay in relay board making a trrrrr sound ..

Hint: Check statement "int mtr_time = 10 ;" in blocks. How does that work according to C/C++?

okay if i remove that code, does the motor start spin in reverse direction ??

I've reformatted your code to make it more readable. Two notes: 1. mtr_time_rev = mtr_time_rev - 1; can be shortened to mtr_time_rev--; and 2. Why are the following lines put into a block?

Firstly, if you added some comments to the code to explain what each part is doing, it would be easier to figure out what is happening. Secondly, as @MikaelPatel and ott state, why are there odd blocks of code nested in braces { and }? Again as Mikael states, you need to check the logic of your code, w.r.t. to these blocks. Thirdly, does the motor start spin in reverse direction?... dunno, you tell us :-)

guys thanks for your suggestions, i have added for loop for reversing the motor upto a value :)

I love the trrrr description! I'd love to see it in action (about the point opf failure). Certainly not a requirement, but a short video may get that over any translation barrier :)


text:
Arduino clone CH340G (ATmega328P), MIDI over USB
I just bought my first Arduino compatible device, and I am greatly enjoying it. I finally could not resist the urge after going to an Arduino meetup, where someone showed me their Teensy connected to their laptop and reacting to MIDI signals over USB.
Not knowing anything, I bought my clone and soon learned about the whole CH340G limitation where it doesn't "just work" (I cannot simply use the USBMIDI Arduino library), and instead I need to run a software MIDI-serial converter command (ttymidi) in order to send the signals to my Arduino clone.
I've been reading up a bit (the amount of information out there is perhaps too vast and often outdated or simply doesn't exactly solve my problem) and have learned of V-USB and the project V-USB-MIDI but I am really out of my element here and do not know how to approach this to get it all working (since it is not just an Arduino sketch and .h header). Or even if this is a solution to my problem. I've read about some solutions which require using an AVR via some of the pins (as opposed to over USB) since you have to reprogram the chip in such a way that it no longer is programmable over USB once the sketch is uploaded, but if I understood it correctly, you can't do even this on the CH340G.
In any case, are there any examples of getting this working? A sketch or something? I downloaded the latest V-USB release, but I really don't want to make a mistake that will brick or otherwise ruin my device.
Basically: I want to just upload my MIDI sketch (with whatever necessary modifications or code) such that I do not need ttymidi to have the device recognized as a MIDI device (over USB) that I can just "plug 'n' play".

The CH340G is a clear USB to "UART TTL" converter. Some Arduino's or types of them use another AVR chip for the serial connection and can be reprogrammed. And some have the USB stack in the chip.
AFAIK the CH340G is not reprogrammable. Best option would be to just get an Arduino that has a reprogrammable USB interface.

"Horses for courses." Get a USB based MCU board not a UART based MCU board and do it properly.

@Mattia - Thanks for all of the suggested edits, most of them are very high quality. However, some have been a little inconsistent, and not as thorough as others. For example, could you take a look at the edits you made in this post, and the additional edits that I made when I reviewed your edit? Also, could you be a little more descriptive in your "Edit Summary", i.e. "fixed typos, spelling, inlined links", etc., as it makes reviewing the edits easier. Please note that I am not trying to discourage you in any way - like I said, your edits are generally very good. Keep up the good work :-)

@Greenonline sure, I got your point!

@Mattia - Thanks... Like I said, you are doing a great job! :-)

V-USB bit bangs some GPIO pins so that they speak the low-speed USB protocol.
This does not use the 'normal' USB connection through the CH340; you would have to solder a separate USB cable to those GPIO pins.
Programming would be no problem; the V-USB code is just normal code that runs on the MCU. (Programming through ISP pins would be required on hardware where USB communication and programming is handled with a second AVR MCU; in that case, the USB/MIDI code would run on that second MCU.)
Low-speed USB is not supposed to be used for MIDI, and as a software emulation, V-USB does not work very well, or efficiently.
If you want to create a USB device, you should use an MCU that actually supports USB in hardware, such as the ATmega32U4 or AT90USB646 used on some Teensies.

Does that mean it cannot be done with my at328p/ch340g without extra hardware?

The CH340 is a fixed serial-port device; this cannot be changed in software.

I have now purchased a couple of USB to TTL converters like this: http://www.ebay.ca/itm/181847253057?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT and this: http://www.ebay.ca/itm/191674164272?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT  would connecting these to some digital pins on the Nano enable me to do what I am trying to do, over this USB connection?

The PL2303 is a fixed serial-port device; this cannot be changed in software.

Your problem is that the ATmega328 itself does not have built-in USB support. If you want to have USB/MIDI support, you could rip apart a USB/MIDI interface and connect it to your ATmega; alternatively, replace your board with a Teensy.

You mean since the USB-MIDI device has HID support, right? Which is what the CH340g and FTDI chips don't have that the atmega16u2 (etc) can be flashed to have? In other words, it's not sufficient to have a USB-Serial/TTL interface chip, it would have to be a chip that does HID, right?

The protocol that USB-MIDI devices speak is not called "HID" but "USB MIDI". But yes, you need a chip that speaks that protocol, or a chip that has USB support and can be programmed.

source: Stack Exchange

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

sort: votes


text:
Arduino and DC Motor control board
I've this PWM Module - 6V-90V 15A Pulse Width PWM DC Motor Speed Controller Switch which I use to control a peristaltic pump (ordinary DC motor), now I want to replace the potentiometer with an Arduino in order to create a soft-start for the pump by pressing a button.
The control is a 0-5V input from the potentiometer, and the description says "you can external drive" and "It could use of PLC controls speed of motor", unfortunately I cannot provide datasheets or schematics.
Is it possible? Or I need a digital pot?
How should I wire it? The 3 cables from the board to the pot are: ground, 0-5V and 5V

Or you may exchange the whole controller with a power mosfet module connected to your arduino. And use pwm directly from your arduino.
http://store.arduino.cc/product/T010020

(Welcome on Arduino.StackExchange) The problem seems to be on the potentiometer. But you're right. (When you can, you should place such an enhancement as a comment, not an answer. But you'll need some more "points".)

Maybe add some more info to make it a non-link only answer, possibly a schematic?

Functionally you can replace the potmeter with a digital potmeter.
If your arduino runs on 5 volt, you can simply connect the grounds and the wire connected to the middle of the pot to a pwm pin.
If the pwm pin does not work smoothly use a RC filter. That is a resis  tor and a capacitor.  As explained here instructables
If your arduino runs on 3.3 you can still use the rc filter but you need to add a bridge.

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


text:
Using two ultrasonic sensors for counting cars when they enter to a garage
I want to use two ultrasonic sensors for counting incoming cars to a garage. What I want is: When both sensors detect the object then the counter should increase.
Can anyone help me and give me an example?

If you have two sensors, you use analogRead.
int sensor1 = A0;
int sensor2 = A1;
int distance = 50; // or whatever you want here
bool car_passing = false;

void setup(){
    int counter = 0;
}

void loop(){
    if(analogRead(sensor1) < distance &&
       analogRead(sensor2) < distance &&
       !car_passing)
    {
        car_passing = true;
        counter++;
    }

    if(analogRead(sensor1) > distance){
        car_passing = false;
    }
}

To prevent the counter keep counting while the car is passing by, we need to make a boolean, so the counter does not wait for count again, before the car has passed.

In order not to count kids in a Kettcar, big dogs or birds, a smarter algorithm should be used to define, what a car is and what not.

@ott that is true. Personally I wouldnt go for two ultra sonic sensors. But yea, that is what he asks for.


text:
Roadblock using template functions
As part of a larger project, I'm trying to create a simple template function that will take an array and a value, both of the same type, and fill the array with the value. I'm running into the error quoted below:
"specializing member '::Fill_With' requires 'template<>' syntax"
Below is the offending code fragment:
// Simple function to fill an array with a specified value.
template <class T> void Fill_With(T target_array, T value){
    int Array_Size = sizeof(target_array) / sizeof(T);
    for(int l = 0; l < Array_Size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With<int>(array1, k);

I've read numerous other forum posts on the error message, but haven't quite been able to figure out what I'm missing. I've read that I need to include a blank "template<>" header before the function declaration but that didn't seem to solve the issue.
What am I doing wrong? Thanks!

See this SO question: How to write a template function that takes an array and an int specifying array size

Let's start by getting rid of the templates, as they make things more confusing. In the following, I replaced T with int.
void Fill_With(int target_array, int value){
    int Array_Size = sizeof(target_array) / sizeof(int);
    for(int l = 0; l < Array_Size; ++l){
        target_array[l] = value;
    }
}

Let's try it out! I pasted this into the Arduino IDE and compiled it. Here is the output:
sketch_aug01a/sketch_aug01a.ino: In function 'void Fill_With(int, int)':
sketch_aug01a:4: error: invalid types 'int[int]' for array subscript
         target_array[l] = value;
                       ^
exit status 1
invalid types 'int[int]' for array subscript

This is telling us that we're trying to subscript (that's the term for the [] syntax) a variable of type int with a variable of type int. In C++, a pointer to the start of an array has type int *, not int. Let's fix the type of target_array in the function signature:
void Fill_With(int *target_array, int value){

It compiles, but if you ran it you would quickly run into a bug:

When given an expression, the sizeof operator will return the number of bytes in the type of the expression. The type of the expression target_array is int *, so sizeof(target_array) == sizeof(int *). On 32-bit systems, sizeof(int *) == 32/8 == 4.
When given a type, the sizeof operator returns the number of bytes in the type. So sizeof(int) gives the number of bytes in an int, which is guaranteed to be at least 2 bytes (16 bits), but is usually 4 or 8 (it depends on the system).

Together, this means that Array_Size ends up being some small number like 0 or 1, regardless of the contents of target_array. To fix this, you can instead pass in the length of the array as a parameter:
void Fill_With(int *target_array, int array_size, int value){
    for(int l = 0; l < array_size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With(array1, 4, k);

Now you can put the templates back in:
template <class T> void Fill_With(T *target_array, int array_size, T value){
    for(int l = 0; l < array_size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With<int>(array1, 4, k);

By the way, C++ already has this function built in. It's called std::fill. Here's how to use it:
#include <algorithm>

int array1[4] = {1,2,3,4}, k = 0;
std::fill(array1, array1 + 4, k);

Thanks a ton for the detailed explanation. I'm still pretty noobish so the breakdown was great.
FYI, after some tinkering and research, it does not appear that  or std::fill are supported by Arduino, which is kind of a bummer. Thankfully I can just create the template function the correct way.


text:
Due: Write to digital pin when ADC is running
I have a problem writing to a digital pin on Arduino Due while my ADC is running.
I have the following code:
 #undef HID_ENABLED

// Arduino Due ADC->DMA->USB 1MSPS
// by stimmer
// from http://forum.arduino.cc/index.php?topic=137635.msg1136315#msg1136315
// Input: Analog in A0
// Output: Raw stream of uint16_t in range 0-4095 on Native USB Serial/ACM

// on linux, to stop the OS cooking your data:
// stty -F /dev/ttyACM0 raw -iexten -echo -echoe -echok -echoctl -echoke -onlcr

// source: https://gist.github.com/pklaus/5921022
// applied patch 1 from: http://forum.arduino.cc/index.php?topic=137635.msg2526475#msg2526475
// applied patch 2 from:  https://gist.github.com/pklaus/5921022 comment on Apr 2, 2017 from borisbarbour

volatile int bufn,obufn;
uint16_t buf[4][256];    // 4 buffers of 256 readings

void ADC_Handler(){     // move DMA pointers to next buffer
  int f=ADC->ADC_ISR;
  if (f&(1<<27)){
   bufn=(bufn+1)&3;
   // patch 2 start
   //ADC->ADC_RNPR=(uint32_t)buf[bufn];
   ADC->ADC_RNPR=(uint32_t)buf[(bufn+1)&3];
   // patch 2 end
   ADC->ADC_RNCR=256;
  }
}

void setup() {
  SerialUSB.begin(0);
  while(!SerialUSB);

  pmc_enable_periph_clk(ID_ADC);
  adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
  ADC->ADC_MR |=0x80; // free running

  ADC->ADC_CHER=0x80;

  NVIC_EnableIRQ(ADC_IRQn);
  ADC->ADC_IDR=~(1<<27);
  ADC->ADC_IER=1<<27;
  ADC->ADC_RPR=(uint32_t)buf[0];   // DMA buffer
  ADC->ADC_RCR=256;
  ADC->ADC_RNPR=(uint32_t)buf[1]; // next DMA buffer
  ADC->ADC_RNCR=256;
  // patch 1.2 start
  //bufn=obufn=1;
  bufn=1;
  obufn=0;
  // patch 1.2 end
  ADC->ADC_PTCR=1;
  ADC->ADC_CR=2;

  // this doesn't work:
  pinMode(52, OUTPUT); //
  digitalWrite(52, HIGH); //
}

void loop(){
  // patch 1.1 start
  while((obufn + 1)%4==bufn);// wait for buffer to be full
  // patch 1.1 end
  SerialUSB.write((uint8_t *)buf[obufn],512); // send it - 512 bytes = 256 uint16_t
  obufn=(obufn+1)&3;
}

Pin 52 says 0 V.
With this function, I can pull the digital output voltage to 1.58 V:
void digitalWriteDirect(int pin, boolean val){
  if(val) g_APinDescription[pin].pPort -> PIO_SODR = g_APinDescription[pin].ulPin;
  else    g_APinDescription[pin].pPort -> PIO_CODR = g_APinDescription[pin].ulPin;
}

Any ideas?

I found the problem: The Arduino had been waiting for the SerialUSB Connection.
The Serial connection has not been established because I was running the Arduino without running the corresponding Python script. That script would have opened the Serial connection.
When running the Python script, the Arduino Due then works as expected.

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


text:
sprintf() to assemble String and float pieces locks up
I'm trying to parse many variables into a URL so that I can update a website through a simple HTTP API with sensor data. After talking to a buddy of mine, he suggested going with the code below.
When I put this in, the Arduino Yun boots up. I see the L13 red LED turn on, but then it hoses. When I comment out the sprintf(); line, everything works fine — except no URL is parsed.
I've tried to debug to the best of my ability and am looking for thoughts on what may be happening.
I'm not sure how much code to post without posting the whole 130 line sketch, so I'm just dumping the parts from the loop that is trying to piece together the URL.
  // Get update time
  Process date;
  date.runShellCommand("date --utc \"+%Y-%m-%d%%20%H:%M:%S\"");
  String utcDateString = "";
  while (date.available()) {
    char d = date.read();
    utcDateString += d;
  }

      char url[512];
      url[0]='\0';
      float humid, baro, windspeed, raingauge;
      int winddir;
      Serial.print("humid: ");
      Serial.println(humid);
        Serial.print("baro: ");
      Serial.println(baro);
        Serial.print("windspeed: ");
      Serial.println(windspeed);
        Serial.print("raingauge: ");
      Serial.println(raingauge);
        Serial.print("winddir: ");
      Serial.println(winddir);
 //sprintf(url,"http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=123456&PASSWORD=xxxxxx&dateutc=%s&temp=%2.2f&humidity=%2.2f&baromin=%f&winddir=%d&windspeedmph=%3.2f&rainin=%3.2f&softwaretype=Custom%%20Arduino&action=updateraw",
//         utcDateString,Thermistor(analogRead(0)),humid,baro,winddir,windspeed,raingauge);
        Serial.print("url: ");
      Serial.println(url);

double Thermistor(int RawADC) {
  double Temp;
  Temp = log(11100.0/((1024.0/RawADC-1)));  // Was 10000... Manually dialed down to increase accuracy. 9400 is a good value. Changing again to match wunderground
  Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
  Temp = Temp - 273.15;            // Convert Kelvin to Celcius
  Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
  return Temp;
}

Here's the output from those Serial.print() calls:
humid: 0.00
baro: 0.00
windspeed: 0.00
raingauge: 0.00
winddir: 0
url:

I'm not sure how else to debug this because when I uncomment sprintf(); the Yun locks up and I have to press the 32U4 Reset button and power cycle the Arduino to get it to work again.

This variable:
String utcDateString = "";

Is a C++ String, not a character array like sprintf() is expecting.  To convert this string to a character array such that sprintf is expecting, you must use .c_str() in your sprintf, i.e.:
sprintf(foo,"This is a format for %s", utcDateString.c_str());

Doing this should prevent the sprintf line from causing a memory fault.

Well spotted. I was surprised to see that the Arduino's String class actually supports c_str() now. I'm fairly sure it didn't support it in the past, and it doesn't seem to be documented.

Yep, that seems to have cleared it up

Looks like %f isn't wired up for performance reasons.  You can convert floats to strings first using dtostrf().


text:
Is there any way I can turn off the 5V pin?
I'm trying to find a way I can toggle the 5V pin to turn on/off. I want the voltage to pass to another wire at a certain point. It should be off and then when something happens, the 5V should turn on.
How can I do this?

This sounds like an X-Y problem.  Can you give some background on why you want to turn off the 5V pin?  There may be a better way to accomplish your goal.

Can you provide a schematic which will illustrate your project better? Isn't the 5V pin hardwired to be "on" permanently.? You could add an external transistor to switch the circuit connected to the 5V pin, but I don't thin that you can switch the pin on the board itself. I might be wrong though.

For energy-efficient switching (along with relatively high-current capability), I recommend using a Darlington transistor connected to one of the output pins (digital for on/off, analogue for variable). Then you would just call  pinMode(A0, OUTPUT); followed by digitalWrite(A0, HIGH); Here is a sketch I made demonstrating what I mean:

Note that a normal transistor would draw more current from the Arduino's pin, which could be bad for the Arduino, and which would waste energy.

There isn't programmatic control of the 5V pin, it is hard wired to the USB or the output of the Vin Voltage regulator.
You might try something from How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino? to control the low side of the external device.  If you need high-side control, maybe an opto-isolator would be a good solution.

If I'm understanding you correctly, you want a 5 V output that is under programatic control. Do you know how much power you want to pull from the pin?
If the demand is fairly low, you could use one of the digital pins directly – they will supply about 40 mA on an "official" Arduino.
If you need more power, then you could use the pin to switch an external device such as a transistor or a relay.

You don't really want to do that. The 5V pin is on the power bus of your Arduino board. If it were possible to turn it off, the entire Arduino would shut down.


text:
Using Modbus-RTU with Arduino and temperature controller
I'm trying to connect with a 4 channel temperature controller using Arduino Modbus Library.
This is a part of my temperature controller datasheet. It has register for read PV of each channel.

I have studied example code of the library and now i'm trying to read PV of each channel.
So, I have modified the example code as below,
#include <ModbusMaster.h>

    // instantiate ModbusMaster object
    ModbusMaster node;

    void setup()
    {
      // use Serial (port 0); initialize Modbus communication baud rate
      Serial.begin(19200);

      // communicate with Modbus slave ID 2 over Serial (port 0)
      node.begin(2, Serial);
    }

    void loop()
    {
      static uint32_t i;
      uint8_t j, result;
      uint16_t data[6];

      i++;

      // set word 0 of TX buffer to least-significant word of counter (bits 15..0)
      node.setTransmitBuffer(0, lowWord(i));

      // set word 1 of TX buffer to most-significant word of counter (bits 31..16)
      node.setTransmitBuffer(1, highWord(i));

      // slave: read (4) 16-bit registers starting at register 2 to RX buffer
      result = node.readHoldingRegisters(1, 4);

      // do something with data if read is successful
      if (result == node.ku8MBSuccess)
      {
        for (j = 0; j < 4; j++)
        {
          data[j] = node.getResponseBuffer(j);
        }
      }

    }

My questions are,
Explain below lines in the code
          // set word 0 of TX buffer to least-significant word of counter (bits 15..0)
      node.setTransmitBuffer(0, lowWord(i));

      // set word 1 of TX buffer to most-significant word of counter (bits 31..16)
      node.setTransmitBuffer(1, highWord(i));

I didn't  pass any request to slave, So, can I get the 4 PV value like this?
If not, please explain how can I do it.

The setTransmitBuffer calls are for writeMultipleRegisters, which you removed from the example.
The first parameter of the readHoldingRegisters is the address of the register. The second parameter is the count of registers to read.
Your sketch doesn't show the retrieved data. You have no indication of success or fail.

As I understood, setTransmitBuffer  using for initializing the TX buffer.Am I correct?
Retrieved data stored in RX buffer. can't we get data using getResponseBuffer?

you have data[j] = node.getResponseBuffer(j);

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


text:
Identical statements, different outcome
First a little background on me and my project. Most of my programming experience is with PHP and javascript. I have just recently started looking at C and C++ for this Arduino project. My project is a weather station that feeds its data to a web based database in real time. I will be writing the code for a web site that will access this data base and present the data in realtime. I am currently working on the temperature section of my weather station. It is an RTD coupled to a constant current circuit and feeds a varying voltage to analog pin 5 on my Arduino Uno. My problem is with the code. I have a working code but I decided to make it object oriented so that I could reuse it in other projects. Here is the code that works.
const unsigned int RTD_PIN = A5;
const float MVOLTS_CTS = 4.882813;
const float OHMS_DEGREE = 0.3851;
const unsigned int SAMPLES = 10;
const float MILLI_AMPS = 19.125;
unsigned long currentMillis;
unsigned long oldMillis = 0;
unsigned long timeBetweenSamples = 1000; // milliseconds between samples
int measurement[SAMPLES];
int read_index = 0;
int total = 0;
int average_cts = 0;
boolean initialized = false;
float degC = 0;
float degF = 0;

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < SAMPLES; i++) {
    measurement[i] = 0;
  }
}

void loop() {

  // Reset the counter when we go over the
  // set number of samples
  if (read_index >= SAMPLES) {
    read_index = 0;
    initialized = true;
  }

  // only take a measurement if one second has passed
  currentMillis = millis();

  if (currentMillis - oldMillis >= timeBetweenSamples) {
    // subtract one element from the total
    total = total - measurement[read_index];

    // take a measurement
    measurement[read_index] = analogRead(RTD_PIN);

    // add the new measurement back into the total
    total = total + measurement[read_index];

    // take an average of the readings
    average_cts = total / SAMPLES;

    // calculate degrees
    degC = (average_cts * MVOLTS_CTS / MILLI_AMPS -100) / OHMS_DEGREE;
    degF = degC * 1.8 + 32;

    // print results only if all elements of measurement[] are filled
    if (initialized) {
      Serial.print(degC);
      Serial.print(" degrees C ");
      Serial.print(degF);
      Serial.print(" degrees F ");
      Serial.println(average_cts);
    }

    read_index++;
    oldMillis = currentMillis;

  }
}

And this is the code that doesn't work.
#include "Arduino.h"
#include "Sensor.h"

    Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) {

     sensorPin = analogPin;
     samples = numSamplesInAverage;
    _sampleRate = sampleRate;
     int measurement[samples];

     // initialize the measurement array
     for (int i = 0; i >= samples; i++) {
       measurement[i] = 0;
     }

  }

  int Sensor::update() {

    if (read_index >= samples) {
       read_index = 0;
     }

     // only take a measurement if sample rate has been exceeded
     // and return a rolling average
     currentMillis = millis();

     if (currentMillis - oldMillis >= _sampleRate) {
       //subtract one element from the total
       total = total - measurement[read_index];

       // take a measurement
     measurement[read_index] = analogRead(sensorPin);

       // add the new measurement into the total
       total = total + measurement[read_index];

       // take an average of the readings
       average_cts = total / samples;

       // increment the read_index
       read_index++;
       oldMillis = currentMillis;

      return average_cts;
     }

     // return false if the sample rate has not expired
     return false;

  }

It seems like the issue is with this one line of code on line 34.
measurement[read_index] = analogRead(sensorPin);

When this line has not been remarked out the read_index only goes to 4 before it resets to 0 and it does it at the rate of program execution instead of every second like expected.
If this line is remarked out the the read_index is incremented from 0 to 9 once every second as expected.
Here is where the read_index is defined.
#ifndef Sensor_h
#define Sensor_h

#include "Arduino.h"

class Sensor
{
   public:
     Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate);
     int update();

   private:
     unsigned int sensorPin;
     unsigned long currentMillis;
     unsigned long oldMillis;
     unsigned long sampleRate; // milliseconds between samples
     int read_index = 0;
     int total = 0;
     int average_cts = 0;
     int samples;
     unsigned long _sampleRate;
     int measurement[];
};

#endif

and this is the Arduino sketch that calls update()
#include <Sensor.h>

Sensor rtd(4, 10, 1000);  // instantiate a Sensor object
int cts;

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

void loop() {

  rtd.update();

  Serial.println(rtd.read_index);
}

can anyone tell me why this works in my procedural code but not the objected oriented code?

Where is read_index defined? Please post all your code.

Where is "update" called? Please post all your code. You have posted a complete sketch that works, and snippets that don't work.

Sorry @Nick Gammon it is late.

How big is measurement in the class version...?

You have made a few fundamental errors with your class.
Firstly you have not provided a storage size (number of elements) for the measurement array class member variable:
class Sensor
{
   public:
     Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate);
     int update();

   private:
     // ... cut ...
     int measurement[];           // <<-- How big is this?!
};

Then it seems like you try to dynamically allocate the space for it in your constructor:
Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) {

    sensorPin = analogPin;
    samples = numSamplesInAverage;
    _sampleRate = sampleRate;
    int measurement[samples];    // <<-- Here
    // ... cut ...
}

BUT that's not what you are doing.  What you are doing there is creating a new local variable (local to just that one single function) called measurement with an array size of samples.  As soon as you leave the constructor that variable is thrown away.
You haven't touched the class member variable measurement at all.  So, when you do:
measurement[read_index] = analogRead(sensorPin);

you are storing the read value into an array of no size that points nowhere.  And of course that then causes a crash because you're writing to memory that you shouldn't be writing to.
If you want to be specifying the number of array elements in the constructor you need to be learning about dynamic memory allocation using malloc() and free() and all the pitfalls that go along with using those on a small microcontroller with very tight RAM constraints.
For an example of how it can be done you should take a look at my Average Library which uses dynamic allocation to allocate the array memory in the constructor and free it in the destructor.

Thank you for taking the time to answer this for me. I will have a look into it when time allows.

Well spotted. I elaborated on how to do that in my reply, because what I wanted to say was too long for a comment.

I was going to add to Majenko's excellent answer, but what I want to say is too long. :)

Change:
int measurement[];

to:
int * measurement;

and then in the constructor do:
measurement = new int [samples];

And check that measurement is not NULL, in case there is not enough memory.

Also, this is wrong in two ways:
// initialize the measurement array
for (int i = 0; i >= samples; i++) {
  measurement[i] = 0;

It should be:
// initialize the measurement array
for (int i = 0; i < samples; i++) {
  measurement[i] = 0;

You need to test less than, and you don't test equals (that would initialize one too many).

You should also have a destructor that frees the memory, ie.
delete [] measurement;

When would this destructor come into play? How and when should I call it?

The destructor is automatically called when an instance of the class is destroyed. This is when you do things like free memory you allocated. You don't call it directly.
An example:
class Sensor
{
public:
  // constructor
  Sensor(int analogPin, int numSamplesInAverage, unsigned long mysampleRate);
  // destructor
  ~Sensor ();
  // call to update samples
  int update();

private:
  unsigned int sensorPin;
  unsigned long currentMillis;
  unsigned long oldMillis;
  unsigned long sampleRate; // milliseconds between samples
  int read_index;
  int total;
  int average_cts;
  int samples;
  int * measurement;
};

Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long mysampleRate)
  {
  sensorPin = analogPin;
  samples = numSamplesInAverage;
  sampleRate = mysampleRate;
  read_index = 0;
  total = 0;
  average_cts = 0;
  measurement = new int [samples];

  if (measurement == NULL)
    exit (1);  // can't continue

  // initialize the measurement array
  for (int i = 0; i < samples; i++) {
    measurement[i] = 0;
  }

}  // end of constructor

// destructor
Sensor::~Sensor ()
  {
  delete [] measurement;
  }  // end of destructor

Can you please explain how these two line of code work int * measurement and measurement = new int [samples];

int * measurement creates a pointer to an int (called measurement). However pointers can also point to the start of an array (or indeed, to the middle of an array) of ints. So this variable will hold the start of your array of ints.
measurement = new int [samples]; allocates the memory for this array - in this case "samples" lots of ints.
Once the memory is allocated you can treat the pointer as an array, eg.
measurement [5] = 42;

For more detail about this see So what is meant by the "equivalence of pointers and arrays" in C? and also Google: pointer vs array.
Also Google: new and delete with reference to the C++ language.

When would this destructor come into play? How and when should I call it?

See amended answer.

If the Arduino is constantly calling the update() function it doesnt seem to me that the instance would ever be destroyed. So is a destructor even necessary?

In your case, with the object at global scope, no it will never be destroyed, so the destructor is not necessary. If you were to put the object instantiation into a function, then it would be necessary. It is a good idea to have a destructor if you allocate memory, otherwise one day you (or someone else) will use your class in a place where it will be needed.

Thank you. I will give this a try later and let you know how it turns out.

This has worked great i voted Majenko's answer as the correct answer only because he had a more thorough answer that will probably help more people but  in the end your suggestions are worked for me. One more question though. Can you please explain how these two line of code work int * measurement and measurement = new int [samples];

That's fine - he spotted the problem, I just elaborated on his solution. See amended answer. You can vote for mine as well if you like it (you can vote for both of them).


text:
Voltage on open circuit jumping on Arduino R3
I am working with a bunch of sensors and everything is fine so far, but I figured on analog PINS 4 & 5 the output voltage read is 0.09V higher than on 0-3... for my Sensors this is a crucial issue.
So I unplugged everything to see whats happening and found the voltage (which would supposedly be 5.0V as nothing is connected) varies, too.
PIN 0   PIN1   PIN2   PIN3   PIN4   PIN5
4.9365,4.8631,4.8045,4.7507,5.0000,5.0000
4.9218,4.8436,4.7752,4.7165,5.0000,5.0000
4.9120,4.8289,4.7605,4.6970,5.0000,5.0000
4.9316,4.8583,4.7898,4.7263,5.0000,5.0000
4.9462,4.8729,4.8045,4.7410,5.0000,5.0000
4.9169,4.8387,4.7654,4.7019,5.0000,5.0000
4.9022,4.8192,4.7507,4.6823,5.0000,5.0000

So i thought, OK, maybe my board is broken, but another one delivers similar results with NOTHING plugged in...
why is this?
All I do is analogRead on my PINs and multiply with 5.0/1023.0...
I appreciate every hint.

The voltage isn't expected to be 5V with nothing plugged in; it's floating and like all floating inputs, is subject to noise due to its high impedance. It could be anything really, though a lot of inputs tend to float high.

Please edit question & show the code [and circuit?] that made the output

@TisteAndii ok, but why is the PIN 4 & 5 showing 5V then? Gimme a second, cannot do circuits on my phone. It is a simple voltage divider.


text:
Generating a short pulse after a delay
I am trying to use one of the hardware timers on the arduino uno to generate a short pulse some number of microseconds after receiving a pulse on an input.
Currently my code looks like this:
uint16_t pulse_delay = 12000; //half-microseconds
uint16_t pulse_length = 20;

void setup(){
  pinMode(8, INPUT);
  pinMode(9, OUTPUT);
  TCCR1A = 0;
  TCCR1B = _BV(ICNC1)  //input capture noise cancel
      | _BV(ICES1) //positive edge
      | _BV(CS11); // /8 prescaler
  TIMSK1 = _BV(ICIE1); //enable input capture interrupt
}
void loop(){}
ISR(TIMER1_CAPT_vect){
  TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
  TIMSK1 |= _BV(OCIE1A); //enable match interrupt
  OCR1A = pulse_delay; //pulse begin time

  TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                        //the interrupt isn't run immediately
}
ISR(TIMER1_COMPA_vect){
  TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
  TCCR1A = _BV(COM1A1); //clear OC1A on match

  OCR1A = pulse_delay + pulse_length;
}

This code should theoretically do the task, but it doesn't produce any output at all - to my oscilloscope it looks like the output pin just stays low.
However, if I replace the last line (OCR1A = pulse_delay + pulse_length;) of the compare match interrupt with the following two lines, it outputs a pulse just fine. The issue with this is that it uses significantly more CPU time, and it can only count time from when the interrupt starts so if the interrupt is executed late the pulse will be longer.
  delayMicroseconds(pulse_length);
  TCCR1C = _BV(FOC1A); //manually trigger match event

All that the first version is doing differently is triggering the match event via an 'alarm' set on the timer, rather than waiting to trigger the match manually.
Why does the first version not work, and how can I make it work??

Just a quick guess, which I may develop into a complete answer when I have time, a little bit later: do TIFR1 = _BV(OCF1A); right before TIMSK1 |= _BV(OCIE1A);.

Also just a guess. Instead of  OCR1A = pulse_delay + pulse_length I'd just try OCR1A = TCNT1 + pulse_length;

@6v6gt I have tried that and it also fails. It also has the problem that it lengthens the pulse by the amount of time spent waiting for interrupts to be re-enabled in case the interrupt is triggered during a noInterrupts() block.

Expanding on my comment, after checking experimentally that this was
indeed the issue.
Short answer
You should do
TIFR1 = _BV(OCF1A);  // clear interrutp flag

right before
TIMSK1 |= _BV(OCIE1A);  // enable match interrupt

Explanation
Whenever the timer reaches the value stored in one of its “compare
match” registers, this triggers a “compare match” event, which has the
effect of raising the corresponding interrupt flag (OCF1A in your
case). If the associated interrupt is enabled, that fires an interrupt
request, and the flag is automatically cleared when the CPU starts
executing the interrupt vector.
However, if the interrupt is not enabled, the flag just stays set. If
you later enable the interrupt when the flag is already set, the
interrupt request is sent immediately. This is not what you want, you
want the interrupt to fire only on the next match. For this to happen,
you have to clear the interrupt flag prior to enabling the interrupt.
The interrupt flags have a very non-intuitive behavior: you clear the
flag by writing a logic one to it. Thus the line:
TIFR1 = _BV(OCF1A);  // clear interrutp flag

For completeness, I would also clear ICF1 before enabling ICIE1,
although this seems to not be critical for the working of your program.
Also, as a side note, be aware that the timer can increment while the
CPU is in the middle of executing TCNT1 = TCNT1 - ICR1;. If you want
the cleanest possible timings, leave the timer free-running and just set
OCR1A to the appropriate values: ICR1+pulse_delay, then
ICR1+(pulse_delay+pulse_length).

Thank you! I've been pulling my hair out over this, but this finally works!

In case you are interested, I've finished packaging the library this was for: https://github.com/AJMansfield/TriacDimmer


text:
Arduino program only works when run as root
Uploading simple sketches seems to work when I run the Arduino program as root (sudo). I would like to run it as a regular user. Has anyone faced the same problem before and fixed it?
Here is what I obtained from lsusb:
$ lsusb
Bus 002 Device 022: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)

And the Arduino program identifies it as /dev/ttyACM0. Here are its permissions:
$ ls -l /dev/ttyACM0
crw-rw---T 1 root dialout 166, 0 Mar 14 22:03 /dev/ttyACM0

Here is the output from id
groups=1000(abhiram),20(dialout),24(cdrom),25(floppy),29(audio),
30(dip),44(video),46(plugdev),105(scanner),110(bluetooth),112(netdev)

When I upload an sketch from the examples, as a regular user, I encounter this error:
avrdude:stk500_recv(): programmer not responding

Any suggestions are welcome.

See if this helps, section "SET THE PERMISSION"

And +1 for not accepting the situation to run the IDE as root, but trying to figure out how to properly solve the issue.

What is the exact error you get when you try to run the IDE under a non-privileged user? You may need to enable verbose output in the Preferences menu.

Ensure you are connecting to the correct device, by unplugging, then wait for a few seconds, then replug, then check the output of dmesg for the device file that is registered.

Checked that, the device is discovered properly as /dev/ttyACM0: USB ACM device. So, it doesn't seem like problem to me.
On the other hand, the logs from compiling and uploading( had to enable them in Preferences), seem promising. I just can't seem to copy them from the arduino program :(. (may be they are writing to a file somewhere?)

What happens when you avrdude -p atmega328 -carduino -P /dev/ttyACM0 -b 57600 -D -Uflash:r:/tmp/project.hex:i ? Double check the device and baudrate.

I see what you mean, I had to change the command a little bit. Here is what it looks like /usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build6432672958845434451.tmp/Blink.cpp.hex:i And it works when I run it as a regular user :). Not sure why it borks with the arduino tool though.

The baudrate is odd, I'd expect 57600, at least that is what I use to connect to an Arduino. Did you find that baudrate in the Arduino logging? I am using another board though, that may explain the difference.

The easiest solution is to add yourself to the dialout group.
First make a note of the output from id. Save it in file (not in /tmp as that gets cleaned out on a reboot). If you look at the output, you'll notice that your user is signed up for several groups and those groups represent extra privileges on the system. By default your Arduino is assigned to the group dialout because it registers as a serial interface and in the old days these were often used to ... dial out, using a modem.
To add yourself to the dialout group, issue the following command:
sudo usermod -a -G dialout $USER

Don't forget the -a flag (for appending groups rather than replacing) or you will have entirely different problems. This is the reason for making a copy of the id output to a file, so in case you do mess up at least you know what your user was configured like before.
Then log out and log in and it should work from that point.
Optionally you can double check the output for id against the output you saved before.

thanks @jippie, for the thoughtful answer. I have added myself to the dialout group, but the problem still seems to persist. I have modified my question with the output from the id command.

My impression from your update is that the exact cause of the problem has shifted to the next issue. You are on your way to solve it. What happens when you cat /dev/ttyACM0? Does it throw an error?

No, the device file seems to empty, when I cat it.

Empty is OK, as long as you don't get an error message.

The oft-repeated advice to "just do sudo usermod -aG dialout <username> never worked for me, and I finally figured out why. On my machine, /dev/ttyUSB0 is of the group serial and not dialout, so adding my username to dialout did nothing.
# ls -l
# crw-rw---- 1 root serial 188, 0 Mar 31 20:52 /dev/ttyUSB0
                    ^^^^^^ (group-name)

Finally: sudo usermod -aG <group-name> <username> fixed it for me.
Embarrassingly, this is also explicitly mentioned here under "SET THE PERMISSION". Sigh.

Yes, it's worth checking the actual owning group.  Also the device file can be either a ttyUSB# or a ttyACM# (or theoretically anything) depending on the board type, kernel driver, and ultimately configuration of udev or whatever creates the nodes.

It's also mentioned at https://www.arduino.cc/en/Guide/Linux#toc6

This happens to me.
In my case, I had upgraded the version of arduino and seems the preferences file was causing the problem.
Just delete ~/.arduino/preferences.txt file (with Arduino IDE closed).
Steps:

Close Arduino IDE
execute this:
rm ~/.arduino/preferences.txt
Launch Arduino IDE

This worked for me, hope it works for someone else.
I am using Linux Mint 17 and I upgraded from Arduino 1.05 to Arduino 1.06 by extracting the Arduino IDE, I am not using the one in the repo.
(Of course, after adding your user to the corresponding group as mentioned by others, but if that wont help you try this)

Possibly related to this, one side effect of running tools as root is that you can end up leaving behind temporary, config, or project files which your ordinay account cannot modify or clean up.


text:
Programming arduino via bluetooth module issue
I followed a tutorial on how to setup arduino and bluetooth so it can be programmed without usb cables. I didn't use capacitors or resistors asthere doesn't seem to be a need for them. I have the serial output appearing on arduino serial console via bluetooth (no usb cable connected). Since the is a working connection that means it is working to a point. However when trying to upload I get "avrdude: stk500_getsync(): not in sync: resp=0x4c" error.
I didn't connect pin 32 of hc-05 to arduino reset pin yet, could that be the issue? I don't actually need arduino to be reset since I can just kill the power to it manually at least for now. I also used 9600 as baud rate instead of 115200 as in the tutorial, because my arduino code used 9600 but maybe I misunderstood this and it actually needs to be 115200 regardless or my baud rate in arduino code?
What else could be the cause?
Edit 1:
From the answer by @sachleen I changed the baud rate as per the tutorial and soldered pin 32 of the hc-05 module to rst pin of arduino.
After baud rate change opening arduino serial console no longer outputs anything. Why did this happen? I was getting serial output before when baud rate of hc-05 was 9600.
After soldering the rst pin arduino also seems to reset after serial console is opened. I did not add the capacitor, is it required and if so why? I also excluded resistors since it seems they are only for voltage reduction from 5v to 3V (my arduino is 3.3V version).

have you fixed it?

@emj365 I have but unfortunately it was so long ago I just don't remember. I should have added the answer before I forgot but I forgot to do that too :) Will add the answer if I come across this issue again. I do remember it was a simple issue.

@emj365 Still don't remember for sure. What Arduino model are you using and what baudrate?

Thanks for tried. I used a fake Uno and changed ESP8266(new and very cheap) baud rate to 115200.

@emj365 Well, I used a Bluetooth module so it may be a different issue but then again it may be the exact same issue. Try 57600 baudrate as that's what I have in my old Arduino sketch. Also what is the baudrate for the ESP8266 module?

Sorry I made a mistake, I use Bluetooth too. The module should be HC-05. I've configed the baud rate 115200 to upload the program to Arduino. Also, I tried to use logic level converter. Failed, still have no idea about it. Maybe 115200 is too high for Bluetooth. And I tried reset Arduino when upload, it never work.

I bought a 3.3v Arduino Uno still failed.

Did you try the different baud rates as per my last comment? If still no luck I will try to retrace my steps and do a proper write up on this.

I wrote the tutorial you were following so maybe I can help. When I was building the circuit initially I used some of the other tutorials out there on Arduino Bluetooth programming which don't have a lot of the extra resistors and capacitor.  However, I couldn't get any of those to work reliably.  Using a circuit simulator and some trial and error, I ended up with the circuit shown in the tutorial which worked for me.
While there "doesn't seem to be a need for" some of the extra passives, if your circuit doesn't work without them, perhaps there is a need for them after all? ;-) Now, I have heard from other people that they were able to leave out certain bits so it seems that there is some variability in the hardware. But we're talking four passives to ensure reliable operation, so why leave them out?
Anyway, a couple of points:

Pin 32 on the HC-05 becomes active upon Bluetooth connection.  We configure the pin to be active low so we can use it to auto-reset the Arduino upon serial connection to emulate what happens with the normal USB connection.  You can leave out the connection to pin 32 only if you want to have to manually reset the Arduino to program it.
The 115200 baud rate is the rate for programming the Arduino and is set by the Arduino bootloader.  It is possible to re-flash the bootloader with a different configuration if you needed to for some reason.
So, the programming baud rate is fixed in the bootloader, but the communication baud rate is configurable in software using Serial.begin(). However, the HC-05's baud rate has to be the same as the Arduino's, so you need to stick with the same baud rate for both programming and communication (115200 by default).
There are two resistors involved with the reset, R3 and R2.  I believe R2 is only necessary for 5V Arduinos to act as a voltage divider with R3.  However, R3 should be included for any voltage Arduino. See this Atmel design note - "The reset line has an internal pull-up resistor, but if the environment is noisy it can be insufficient and reset can therefore occur sporadically ... This pull-up resistor makes sure that reset does not go low unintended." R3 should be 4.7k or greater; most designs stick with 10k.
The capacitor C1 is necessary because Pin 32 stays low the entire time Bluetooth is connected.  If you connect RST to Pin 32 directly, the Arduino will just stay reset until the Bluetooth connection drops and nothing will work just as if you held down the reset button and never let go.

With C1 in place, when Pin 32 goes low it will momentarily discharge C1, pulling RST low and resetting the Arduino. C1 will immediately begin charging through R3 back up to VCC which will restore RST to high, bringing the Arduino out of reset.  The values of R3 and C1 affect the timing of the reset and must be chosen appropriately.
Don't forget R1.  I can't remember the reason it is helpful, but it has something to do with the Arduino/Atmel UART.  I found the recommendation for adding it one day on an Atmel discussion board and it has solved a non-working circuit for me many times.

Hope that helps!

Thanks for taking your time to explain though I don't understand why at least some of this info wasn't in the original tutorial. There was barely any text there at all :)  You are also wrong on some points and far too vague on others. First of all 115200 baud rate is one reason why it didn't work for me. Arduino Pro Micro uses 57600 baud rate. I also did not need to use any resistors and I used a 450 nf capacitor and probably almost any value would have worked. R1 and R3 may be useful but I never had issues without them.

There's also a serious limitation that was not mentioned with the tutorial as it will reset when pairing or opening  serial console. There is a way to fix this and I will share it when I get it to work properly.

The baud rate depends on model of arduino you are using. For Pro-Micro; Pro-Mini and Nano that I use I had to change to 57600 baud as that is what the dll (downlineloader) avrdude forces this baud rate:
avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware/tools/avr/etc/avrdude.conf"

     Using Port                    : \\.\COM40
     Using Programmer              : arduino
     Overriding Baud Rate          : 57600

For Mega the overriding Baud Rate is 115200.

Both of those things will cause issues.
It needs to reset when its downloading a new sketch. You can manually reset it at just the right moment, but if you don't get the timing right, you'll get that issue.
The baud rate you set in your code for serial communication becomes irrelevant when you're loading a new sketch as that's set in the bootloader. Keep it at 115200 like the tutorial suggests.

Ok, I changed the baud rate but now I am not getting any output from serial console at all. Why? Will try to solder the pin to the module now.

I connected the arduino reset pin to pin 32 of hc-05 module but still unable to program it. It also seems to reset or seizes executing code for a while when serial console is opened but still no output. I did connect the rst pin directly, I am not sure what to make of the diagram showing capacitor and resistors relating to rst pin. My arduino is the 3.3V version so I dont need a voltage divider.

Have you got the TX from the Bluetooth module linked to the RX pin of the Arduino?
If you have you need to unhook it whilst uploading. A better solution is not to use the TX RX pins of the Arduino and use serial software instead.
Here's a simple tut but it spreads over a few pages:
http://ianlangelectronic.webeden.co.uk/#/arduino-bluetooth/4583456314
A Bluetooth baud rate bigger than 9600 is not recommended. The Arduino struggles to keep up if it's much faster than this.

Whilst you link may answer the question, it would be preferable to include the essential parts of the linked here, and provide the link for citation. Can you please edit your answer? Thanks!

I am using rx/tx, yes. Why would this cause problems exactly? I changed baud rate to 57600 of the bt module and was able to program OTA. It has to be specific baud rate as each arduino has it's own baud rate requirement for programming. Will try your link later.

The tutorial you linked to will only allow serial communication, but not for the Arduino to be programmed, via Bluetooth.  9600 baud is a good recommendation for a safe upper limit when using SoftwareSerial but doesn't apply when using the UART.

The easiest way to program your arduino via bluetooth (HC-05) is the following steps
1: change the baud rate of the bluetooth module to 57600 using software seriel, and that is all you need to do with your bluetooth, and when you use the software seriel sketch you do not need a ftdi converter, this is how you do it (  https://www.youtube.com/watch?v=zoJUAjW3vQ0 )
2: next step is to make a very simple and small circuit for the reset pin of your bluetooth module like the one in this youtube link ( the circuit I am talking about is a circuit made of a NPN transistor, a 0,01 capacitor and a 10 k resistor. the circuit is like a signal inverter or something. (https://www.youtube.com/watch?v=xXUKfTNHkKE). you will find the circuit in the middle of the video.
I have done it and it works,
thanks for reading
Arman


text:
Supply 5V to Arduino
I am building a quadrocopter with an Arduino Uno as control unit. I know I can supply 5 volts to the 5V pin, but my ESCs produce 5.5 volts, which I measured with my multimeter. Will this voltage drop to 5 volts when I connect the Arduino and if not are 5.5 volts to the 5V pin a problem?
Edit:
My Arduino was running well for a couple of days on this setup with 5.5 volts to the 5V pin but died yesterday. By dying I mean the ATmega doesn't execute any code anymore, the L LED doesn't blink, and even a loopback test fails, which is a sign of a defective USB connector. But I am faced with the same challenge. Should I run my Arduino on 14.4 Volts from my 3S LIPO to Vin or supply 5.5 volts to the Vin pin?
Actually I just realised when I measure the voltage from the ESCs they deliver 9 point something volts for half a second when connecting the multimeter, I guess this voltage spike killed the Arduino.

Do you mean 5V to VIN pin?

I'm going to assume you are using the UNO model - or any other board based around the Atmega328p.
According to the datasheet the voltage limits are 1.8v to 5.5, with an absolute maximum of 6v.
You should be fine - but if you are able to get the voltage down closer to 5 volts, I would recommend doing that instead.

Okay - it looks like that voltage spike might be the cause of death for your board.
As an answer to your question though - I would recommend applying the 14.4 volts to vin, as 5.5 volts is not enough (the regulator needs 6 volts as a minimum, and the absolute maximum is 20 volts).
Just make sure you apply the 14.4 volts to the vin pin and NOT the 5v pin, as that would kill the board.
Please tell us how it worked out - good luck!

Actually I just realised when i measure the voltage from the escs they deliver 9 point something volts for half a secound when connecting the multimeter ...

Yes, that won't be good for it. I suggest a LDO (low dropout) 5V voltage regulator. Something with a 0.5V dropout will get rid of that extra 0.5V and also handle the initial spike.

Most Arduinos won't mind 5.5v if your are sure that is the max. The ATmega328 is design to be used from 2.7V to 5.5V so that is the very max. No, the voltage will not drop down to 5V when you connect it to the Arduino but I believe you are quite safe with 5.5V. Just don't make a short because you'll be pushing your ATmega328 to it's designed max. You might wanna look at the datasheet for it. All it specs are in there.

You're better off applying that 5.5V to the Vin pin. You may end up with slightly less than 5V at the Arduino, but it'll tolerate that much better than going above 5.5V on the 5V rail.

It's going to yield ~4.4V on output pins and the 5V pin. This never caused me any problems with transistors etc. OP should just use that value for any calculations.


text:
What does this error mean?? Arduino Due loop warning
I am getting this error on compilation of the code given further below;

warning: iteration 3u invokes undefined behavior [-Waggressive-loop-optimizations]
leds[XY (x, y)].r = redarray[x][y];
note: containing loop
for(uint8_t x=0; x < MatrixWidth; x++){

Code:
 // the header files for the RGB data

#include <FastLED.h>
#include "redarray.h"
#include "greenarray.h"   //g data header file (hex or dec)
#include "bluearray.h"   //b data header file (hex or dec)*/

 //matrix parameters

#define MatrixWidth 36 //columns (x)
#define MatrixHeight 1 //rows (y)
#define numled (MatrixWidth * MatrixHeight)

//pin details

#define datapin 7

#define clockpin 8

CRGB leds[MatrixWidth * MatrixHeight];

const bool  MatrixSerpentineLayout = true;

void setup() {

   FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
   FastLED.clear();
         }

void loop() {
   for(uint8_t y=0 ; y<1 ; y++){
     for(uint8_t x=0; x < MatrixWidth; x++){
         leds[XY (x, y)].r = redarray[x][y];
         leds[XY (x, y)].g = 0;
         leds[XY (x, y)].b = 0;

         FastLED.show();
         delay(50);
     }
   }
 }

  uint16_t XY( uint8_t x, uint8_t y)
  {
      uint16_t i;

      if( MatrixSerpentineLayout == true) {
          if( y & 0x01) {
          // Odd rows run backwards
          uint8_t reverseX = (MatrixWidth - 1) - x;
          i = (y * MatrixWidth) + reverseX;
    } else {
         // Even rows run forwards
         i = (y * MatrixWidth) + x;
    }
}
   return i;
}

The following is redarray header -
//RED
const byte redarray[3][36] PROGMEM = {
{0x00,  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
};
How to remove this warning. The redarray is not being read properly by arduino. THe above code should make the 36 LEDs turn off (black) as per the header file. They are randomly lit red... I am totally perplexed!
Plz help if somebody can.
Thanks!

MatrixWidth is 36. redarray[] has 3 elements. The compiler has detected that your code will likely blow up on the 4th go through the loop. Make sure your code is accessing the dimensions correctly.

(great name btw! :P) ...I referred to this link http://www.tutorialspoint.com/cplusplus/cpp_multi_dimensional_arrays.htm and it says that the brackets around indvidual elements are optional. So, by that , my redarray is a 3 row 36 column array. Which one is correct? Any could you please tell how to access the dimensions correctly. I am stuck on this since quite a long time. the leds[XY(x,y)]= redarray[x][y] ....is this accessing of array and allocating to leds correct???? Thanks!

What do you mean which is correct? Your first dimension only has a fixed 3 elements. Attempting to access beyond that is a bug.

I declared my redarray as { {r,r,r,r...36 elements}, {e,e,e,e,e...36 elements}, {t,t,t,t,...36 elements} }; in three rows...isn't that a 3*36 matrix? On the link, it is defined like this only....each row within {} ?? Thats my confusion....

You're too mired in trivialities. Your first dimension has three elements. If you try to access it with a value greater than 2 then your code may blow up.

Varquez-Abrams ..i do understand the point you are trying to put across, however, I cannot spot the mistake still.. Or what correction i need to make..Sorry brother... Would have to think more about it... I asked this yesterday something like this too, did the changes but now a new error.will have to see... Thanks though...

What values can x take on?

So, here i what I understand or see - y takes only one value 0 and that is the first row of the matrix. X goes from 0-35 (36 LEDs) and thus I am calling out the entire first row of the matrix (which itself is one row only). redarray is 3*36. based on my understanding that signifies 3 rows with each row having 36 elements(rows are explicitly defined). And thus I am mapping one-to-one with the leds and redarray. But in reality that aint happening. I am wrong I know..trying to figure out sir

The problem you're having is that you're thinking of it in "rows" and "columns", and that is hopelessly confusing you. Think in dimensions and their order instead.

I completely understand the left hand side of the line leds[XY(x,y)] but i am confused ( and u r right abt the rows and columns thing.. M lost there only) about the redarray part. How does Arduino "move" through this array with the given for loop? The ans to this depends on how does one define "elements" in a 2D array? A one D array is linear ( one dim) so a [m][n] array is a 1D array of length m replicated n times in the other dimension. I think i get what u r saying.. But then how do you define a 3*36 array if my style of decl is wrong? Thanks

You've already defined the 336 array. But you're treating it like a 363 array.

After thinking about your last comment, I finally managed to see the mistake - on RHS i.e. redarray[x][y] ..In place of this it should be redarray[y][x] I got the correct pattern. And I also realised that where I was getting lost, leds[XY(x,y)] employs the coordinate system concept as per FastLED. I was getting confused between this coordinates and dimensions of array. It works perfectly now. Thank you so much and more than that..thanks for not telling me directly the mistake..but through hints ;) :) ..I learnt something. I hope I am correct now. :P :)


text:
RFID/NFC Tag get data from wordpress MySQL
I have a local workshop for students to teach them 3D printing/woodworking
I want to know if its possible to create RFID/NFC tags using wordpress data from MySQL or HTTP/HTTPS.
Web Scenario :
I have a wordpress website where I setup a gamefication plugin.
Each time a student takes a quiz/posts on forum he gets a "x" number of points that are accumulated on his profile.
I want to know if I can get a RFID/NFC tag to get that number of points.
Each member has a RFID/NFC tag card and with that card he can get access to different things around the workshop .
Workshop Scenario :
For each tool there will be a lock , RFID/NFC reader and a LCD display screen.
When a student want to access that tool he needs a number of points on the wordpress gamefication script that are transfered to the RFID/NFC card.
If he has the needed points a text on the LCD screen will appear with something like " You have access to this tool" and the tool will be unlocked .
Else if the user doesn't meet the needed points the LCD screen will show "You don't have the needed points for this tool, please visit [URL] to get more info" and the tool will stay locked.

I need only info if this is possible, not the way to do it.
[ In case you are kind to hand me some guides on where to start to will be great! ]

Thanks and waiting to see if this is possible!

From what I can tell it's absolutely possible but will take some considerable development time and around $30-$70 of hardware per NFC terminal. Please note I would strongly not recommend this as a first project as it has a lot of individual components that all have to work together flawlessly and each is different. Properly done this will be complex software and hardware wise although more so from the hardware side of things.
Hardware wise you need/terminal:

LCD display (I would recommend segmented for simplicity and cost)
Wifi or ethernet shield/breakout and ethernet cable if the board is not wifi compatible
Arduino (MKR1000 has wifi built in), Feather (Adafruit's boards that are frequently Arduino software compatible and have many shields available and guides written on how to use them), or cheap Arduino knock off (preferably not this option as giving money to arduino.cc, Adafruit, or other designers is important if we want new boards regularly)
NFC breakout or shield (Google/DuckDuckGo/Bing RFID-RC52 for an economical option, they're ~$4 on Ebay)
Power supply corresponding to the requirements of the chosen board + shields + breakouts
NFC tags
Lock able to be unlocked by a servo. If you expect security in absence of supervising shop manager (aka just to be safe, assume dishonesty in people using the shop) from this system, the locks need to be better than a Masterlock as those are insecure to even simple soda can shims. The rotary masterlocks can also be reduced to 100 possible combinations and then the combo can be brute forced easily from there so if you get a rotary based lock system make sure the assembly covering the dial is not easily removed.
Servo or stepper powerful enough to actuate locks
Servo or stepper driver breakout board

Then you'd just want to have the public key (note I don't mean a "public key" in the general cryptography sense but on that subject, you do want the key encrypted) to the user stored on the NFC tag and then use the arduinos+electronics to read the tags and see point values. User data from wordpress could be downloaded periodically to the boards so the individual checks don't use network resources and the system works offline.


text:
Arduino EEPROM retains old data after flashing with a new program
I have a custom 5V 16Mhz Arduino Uno (a breadboard Uno of sorts) that runs the grbl firmware. After the initial flashing I can see all the settings (through the serial monitor) and everything works. However, if I make any changes to the firmware files and re-flash it, I can see that the old settings values have not been replaced with the new ones. I can only assume that these values are in the EEPROM and are not being erased on every re-flash cycle. I then tried the eeprom_clear program from Examples in the Arduino IDE and then re-flashed with the new firmware settings, after which I can see the new settings values.
I did some digging and found that the EESAVE fuse is responsible for this. However the Uno does have this fuse bit unprogrammed (set to 1). Why then am I able to see the old EEPROM settings and have to explicitly run an eeprom clear program before re-flashing with the updated firmware?

I'm pretty sure Arduino IDE isn't uploading eeprom at all. And for example in Platform IO CLI, there is different command to upload eeprom data instead of flashing program memory.

The IDE isn't. The program is setting values in the EEPROM. I simply want to clear the EEPROM everytime a new program is uploaded.

Also posted at http://forum.arduino.cc/index.php?topic=469061

save the old built date to eeprom and on boot, if it's different than the current build, run your clear routine

Flash isn't EEPROM. When you reprogram the flash it doesn't touch the EEPROM.
It's controlled by the -U... flag to avrdude:
avrdude ... -Uflash:w:<hex file>

If you want to set the EEPROM to something specific you can use avrdude to program an EEPROM file if the bootloader supports it (not sure it does, so you may need a programmer for it):
avrdude ... -Ueeprom:w:<hex file>

I do not want to program the EEPROM. I simply want to clear its contents whenever I re-flash the Uno with a new program. When you burn the Arduino bootloader this bit remains unchanged and hence whenever the IDE runs avrdude with an -e parameter it erases the flash and the eeprom. Am I right? If so, this does not seem to be the case with my Uno and I'm hoping to understand why.

It's all to do with what the bootloader is capable of. You're not programming the board, you're uploading firmware for the board to program itself - it's a very different scenario.

You could add a "reset to factory settings" button - if it's held in while the power is turned on (or the board reset, or programmed, etc) it wipes the EEPROM.

The -e parameter in avrdude should only erase the EEPROM if the fuse bit
Preserve EEPROM memory through the Chip Erase cycle; [EESAVE=0]
is not set. However it appears it is not possible to SET this fuse bit. (at least not with AVRDUDESS.


text:
Running Pthreads (POSIX) on an Arduino
So I have a project where I need to run pthreads (coded in C) on an Arduino Uno. I've written and compiled the code and the output is what we need when I use a C compiler. But I'm having trouble running it on the board. I've installed the Pthreads library in the libraries folder of the Arduino, but it still gives me erroneous errors.
I'm jumbling back and forth without finding a solution, can anyone give me any tips?  It's become so annoying that I'm thinking of buying a Pi.
Any help is much appreciated.
Edit: let me rephrase: the professor wants us to implement pthreads on an Arduino or Pi. I didn't decide pthreads is the solution, it is the requirement.

Try something more minimalistic but with the necessary functionality. Please see, for instance, https://github.com/mikaelpatel/Arduino-Scheduler

As Mike points out, only limited threading is supportable.  If you really want pthreads you need something more along the lines of a raspberry pi or similar device built around a tablet, set-top-box or router chip running a traditional operating system, or at minimum a very large MCU with a lot of resources like the largest versions of an ARM Cortex M4 or M7.  Essentially you either need to adjust your goals, or look outside the realm of Arduino.

I might be helpful to show us these errors you get.

That comment of yours about buying a pi which was inappropriately removed by someone else was the most insightful thing in your post.  While the pi has a number of implementation-level issues, it is in concept a far more appropriate choice for something that needs true multi-threading.

pthreads might be a requirement, but as you edit clarifies, Arduino is not.  Of the two options allowed, pick the pi.  You'll fight with SD cards and many other things, but threads will work about the same way as on an ordinary Linux.  Though the way you have stated the assignment is unclear - are you supposed to create and use some pthreads, or are you supposed to implement support for them from scratch?

Please add information about the compiler errors and show how you have implemented the API. How much of the API do you have to implement?

I need to run pthreads ...

You probably don't need to run pthreads. This sounds like an X-Y problem.
What you are probably saying is "I need to do multiple things at once" (such as flashing LEDs whilst taking ADC readings, or play sounds at the same time as moving a vehicle forwards).
You could get better answers if you described the project (X) and not your proposed solution (Y) which you think is pthreads.
I have a web page about How to do multiple things at once ... like cook bacon and eggs which goes into this sort of thing in some detail.
Some example code from that page which blinks different LEDs at different rates is:
// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop

It's become so annoying that I'm thinking of buying a Pi.

Sure you can do that. You can buy a Mac or a Windows PC. You can buy 5 Arduinos. But if you want to learn how to do multiple things on an Arduino you can learn how to manage a "state machine" and do it all on $5 of hardware.

As an example of what can be done see this post about a retro arcade game called Toorum's Quest written by Petri Häkkinen and run on an Atmega328P (same chip as in the Arduino Uno).
Hardware and screenshots:

In his code (which I compiled using the Arduino IDE to test it) he has:

Multiple sprites on a TV screen with a resolution of 104x80 with 256 colors.
Sprites are multiplexed so you can have as many as you want on the screen.
He moves them around according to game logic
He plays music and sound effects at the same time
He reads from a game controller

Sad part the project specifies use of POSIX on either an Arduino or Pi, and for budget constraints, i ended up with an Uno.

You still haven't said what you are trying to do. Did the project specify that you had to use pthreads?


text:
ESP8266 Programming using ESP-01 to USB converter
I am new to ESP8266. To ease out the task of programming esp8266, I bought this:  ESP-01 ESP8266 Programmer CH340G Chip USB WiFi Wireless UART GPIO0 Adapter.

Configured Arduino Interface to run AT commands in the serial monitor.
I flashed ESP8266 with the basic blink LED example. It worked fine for some time and later on gave this error.
warning: espcomm_sync failed

When i tried to flash another program on to ESP8266, I am getting the following error.
Sketch uses 221,995 bytes (51%) of program storage space. Maximum is 434,160 bytes.
Global variables use 31,568 bytes (38%) of dynamic memory, leaving 50,352 bytes for local variables. Maximum is 81,920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I could only find one article regarding this adapter.
There he made a custom bridge soldering GPIO 0 to GND for ESP8266 Flashing.
So should i make a removable bridge for the same, to upload a new program.
Is there any other way to simplify this task?

Thank you for the post you made! You should auto-answer this post with the post link "Check how to solve it [here]" and mark it as the correct answer.

I have this exact same module and what really puzzles me is that someone designed and manufactured this product, which simply does not work as advertised.

I know this is an old post, but I just recently tried to use this adapter myself and ran into the same issue. I was able to modify the adapter to use it for flashing the ESP-01.. For all of you still looking for answer, I've written instructable here https://www.instructables.com/id/USB-to-ESP-01-Board-Adapter-Modification/

Finally I made a breadboard connection joining ESP8266's GPIO 0 and GND to Programmer's GND for flashing the chip
For more info

Additional Reference:
Programming ESP8266

Many thanks, you saved me a lot of time! Btw an even simpler way would be fitting a small copper wire plugged in gnd and gpio-0 and then putting the esp01 on top of it

Just solder a jumper to the adapter according to this image (bottom side):

If you want to use programming mode, just switch to connect GND and GPIO0. Switch back to use GPIO0 as IO pin (you may attach your F-F Dupont cable to the floating pin).


text:
Detailed analyse of memory usage
When compiling a sketch, after linking, the build outputs a kind of forecast on RAM usage, e.g.:

Minimum Memory Usage: 1456 bytes (71% of a 2048 byte maximum)

Is it possible to somehow get a breakdown or itemization of these 1456 bytes and details on exactly where in my code, or in included libraries, they are used?

Since you seem interested about RAM, rather than flash usage, I suggest
you look at the symbol table of your compiled program, which will be
more telling than the disassembly. On my Linux system, I usually do the
following:
avr-nm -Crtd --size-sort the_program.elf | grep -i ' [dbv] '

avr-nm is the utility for displaying the symbol table. It is normally
packaged with the Arduino IDE. It is invoked here with the following
options:

--size-sort is quite explicit
-C means “demangle the C++ names”
-r means “reverse sort”, i.e. sort from largest to smallest
-td means “display numbers in decimal rather than hexadecimal”

This will output the list of all symbols that have a size, in three
columns: size, type and name. You are only interested in the symbols
that consume RAM, i.e. those of type b (BSS, or uninitialized data),
d (initialized data) and v (vtable), either in upper or lower case.
The grep command is a standard Unix utility which is used here to
extract only the relevant lines from the output of avr-nm.
Example output for a small program:
00000068 B tx_buffer
00000068 B rx_buffer
00000034 B Serial
00000016 V vtable for HardwareSerial
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000002 b loop::last_print
00000001 b timer0_fract

The first 4 entries come from the Serial object. The 3 entries
starting with timer0_ are used by the Arduino timekeeping functions
(millis(), micros() and delay()). The entry named
loop::last_print is a static local variable I declared in loop().

That looks promising, but I will have to wait until tonight to try it. Will it only list the 'local' name of the variables? I suppose that e.g. the tx_buffer and rx_buffer variables listed in your example are actually HardwareSerial::_tx_buffer and HardwareSerial::_rx_buffer? Might omitting the -C option give any hint on the variable's class name?

@jarnbjo: You get the full name of the variable, e.g. loop::last_print is a local variable from loop() named last_print. The serial buffers are actually outside HardwareSerial in my version of the Arduino core, and HardwareSerial has no static variables, so you see no HardwareSerial::foo. The per-instance variables are part of the sole instance Serial and are not listed separately. Omitting -C will only hurt readability, e.g. it will print _ZZ4loopE10last_print instead of loop::last_print.

I see. The fields in the HardwareSerial class were the closest match I could find for tx_buffer and rx_buffer in the current version of the library source code and I didn't consider that you might have an older library version. That makes sense.

This solved my problem. I had expected the compiler optimizer to be much more clever than it obviously is and I had lots of dependencies linked into the binary, which are never used. Without much more than deleting unused library files saved me almost 500 bytes of RAM usage.

Looking at an assembly listing of your code is the most direct method for finding out details of space allocation.  On my Ubuntu Linux system, I use a shell script (that is, a file containing shell commands) like the following to produce an assembly listing of the most-recently-compiled .ino file, which must be in the working directory when the script executes:
#!/bin/sh
# Look for .ino in current directory, and find recent /tmp/build...
item=*.ino
[ -z "$item" ] && echo ino file not found && exit
BDIR=/tmp/$(ls -t /tmp | egrep -m1 build.*tmp)
BASE=$(basename $item .ino)
avr-objdump -S -I$PWD $BDIR/$BASE.cpp.elf > $BASE.ino.asm

All the stuff before the avr-objdump line allows the script to find out the name of the current .ino file and the name of the /tmp/ subdirectory where the .ino's .elf file is found.
You can also use avr-objdump to get a more concise size listing, as follows, where $BDIR and $BASE are as in the script above and represent the build directory in /tmp/, and the basename of the .ino file.
avr-objdump -C -d $BDIR/$BASE.cpp.o| egrep -C2 '^Disassembly' | egrep -v '^--|^$|^Disassembly' | less

This will produce a list with two-line entries like the following, in which each line beginning with 00000000 is a subroutine name, and the next line shows the last line of its compiled code.  In this example output, the setup_PowerDown() routine has 0xA4 bytes of code, ISR __vector_13 has 0xC6 bytes, keepAlive() has 0x10 bytes, etc.
00000000 <setup_PowerDown()>:
  a4:   08 95           ret
00000000 <__vector_13>:
  c6:   18 95           reti
00000000 <keepAlive()>:
  10:   08 95           ret
00000000 <eeWrite1(unsigned char, unsigned char)>:
  3a:   08 95           ret
00000000 <eeWrite2(unsigned char, unsigned char)>:
  18:   0c 94 00 00     jmp     0       ; 0x0 <eeWrite2(unsigned char, unsigned char)>
00000000 <parValidate(unsigned char, unsigned char, unsigned char)>:
  64:   08 95           ret
00000000 <loadSettings()>:
  e0:   08 95           ret
00000000 <applySettings()>:
  84:   08 95           ret

Some IDEs provide symbol table information that includes sizes of routines, stack frames, and data.  I don't know if that's available via Arduino IDE, AVR-libc, or GNU Binutils.  The symbol table provided by avr-readelf -s (as in following command) provides quite detailed symbol information that seems quite useless in its raw form.
avr-readelf  -s  $BDIR/$BASE.cpp.o

The methods described above are somewhat ad hoc, and depend on files left after avr-gcc or avr-g++ run.  I don't know of any “official” methods for getting the information you want to see.

You can automatically generate a "map" file every time you compile. This gives you a full breakdown of how everything is linked together by the linker, including the size of each section and other useful debugging information.
A simple modification to platforms.txt in hardware/arduino/avr is all that is needed.  Find the line starting compiler.c.elf.flags= and add to the end of it:
 -Wl,-Map,"{build.path}/{build.project_name}.map"

If you like you can replace {build.path} with a hard-coded path, such as your desktop, and the .map with .txt to allow it to easily be opened by notepad or whatever you use (assuming Windows, of course).

Also very helpful, but do you happen to know why the avr-nm tool suggested by Edgar in his answer lists memory usage, which is not accounted for in this generated map. avr-nm e.g. lists 64 bytes used by an rxBuffer (full name _ZL8rxBuffer), which is not listed in the map, and which I am not able to find in any dependency.

This was a great question and helped me recently as I'm building quite an extensive Arduino app using a Nano (ATMega328 and 32K of program memory).
At one point I was almost out of program memory and I was a bit shocked.
I didn't think the code was that large.
My Tests and Results
With the comments I read through the posts on this answer I decided to build a blank app and examine the results as I added libraries etc.  Here are my results (Using Arduino IDE 1.8.13):

 blank sketch takes up 444 bytes of program storage space (max is 30720 bytes).

Sketch which includes 6 libraries✔ uses up 6218 bytes
<LiquidCrystal_I2C.h>, <Wire.h>,<ds3231.h>,<SD.h>,<EEPROM.h>,<SoftwareSerial.h>

adding one line Serial.begin(9600); uses 6324 bytes NOTE: 6324 - 6218 = 106 bytes even though I only added 19 bytes (the characters for that line).

Adding on more line Serial.print("a"); results in 6342 bytes used. That's 18 more bytes (6324 - 6342 = 18) which is the exact number of characters I added with that line (including semicolon).

Adding a 2nd line with Serial.print("a"); results in 6358 (16 bytes)

Adding a 3rd line of Serial.print("a"); results in 6374 (16 additional bytes).

I hope this helps a bit. I'm going back to my app now and removing all the Serial lines I used for debug output.  They're just eating up program memory now.
Actually, I'll probably even use the conditional compilation (shown in this SO answer) so I can still print when in debug.
 Blank sketch means one with only the void setup() {} void loop() {} structures and nothing else.
✔ These are the libraries which I am using in my project.
 I came back and added these additional lines with the amount of Program Memory used because there was a comment that lines of code do not impact memory at all. Of course they do.  At some point all Program Memory is used up and your program will no longer fit into flash.  This is what I was having a challenge with as my extensive program (which includes sensors, LCD, sd card, and bluetooth) continues to grow.

The length of a line of source is completely unrelated to memory usage.

@DaveNewton Yeah, I should've thought about that since it must be counting the compiled bytes, right? is it the bytes added to .elf, maybe?

Also, I'm not sure it's completely unrelated, because more source code means larger program and larger binary size in the end. Otherwise why would you reach a limit as your program grows and why would the IDE warn you about the size of your app all the time?

What I said was that the length of a line of source is unrelated to memory usage--for example, if the exposed instance of the serial driver was ThisIsTheRealSerialDriverInstanceInUse.print("a"); the compiled size would be (assuming no debug symbols) the same as S.print("a"). Obviously a larger program is... larger--but there's a difference between the size of source code in bytes (the human readable form) and the size of the executable.

In other words, counting the characters in a line of source, while it may coincidentally align with memory usage, it's just that--a coincidence.

Thanks for the additional information.

To expand on Dave Newton's comment: A short line of code that invokes a heavyweight library can have a huge impact on the size of the binary. If you add variables that store temporaries that the compiler has to evaluate anyway, that makes your source grow but has zero effect on the size of the binary. If you add local variables to cache volatile data, your source still grows but the binary actually shrinks!

@EdgarBonet Thanks for additional info. I'm just attempting to discover how to "clean" my code to the extreme since I am getting to limits of program space.  I wish there was a bit more guidance on this but it's a lot of trial and error.

Also, as I'm cleaning my code I got to a point where it was at 23436 bytes of prog mem.  I removed all Serial.begin(), Serial.print() etc calls and recompiled and prog mem went to 23110 so this would be your point.  But I'm not sure how removing code would actually make the program memory usage go up?? And, yes, I'm confirming that I only removed code.  Very weird.

Just removing code on its own will almost never make the binary size increase; I don't think anybody said it would. There are multiple resources available for optimizing general code for size (and Arduino as well) and a lot of compilation/linker games that can be played as well.

I'm sorry I got all mixed around on my numbers thinking lower number meant less avail space. Phew...been staring at this too long.  Removing code does seem to help the number go down -- but not directly of course.  Thanks for discussing this with me.

Removing code does directly decrease binary size; every time you remove a call it decreases the binary size by the number of bytes of binary code it takes to implement the call (the call instruction, parameter wrangling, etc). Once compiler/linker games start being played you can often removed unused library code as well.


text:
I2C to UART bridge as breakout or in DIP package
For a project, I need to connect more than one device to an Arduino through a serial port with hardware flow control (RTS/CTS).
Sparkfun used to make breakout boards for the SC16IS750, but this product is discontinued and I can't find any place to order it. There are also plenty of ICs doing what I need, but I am not keen on soldering SMD components and I cannot find any products coming in e.g. an old fashioned DIP package.
Does someone know about an available breakout board or a DIP packages I2C to UART bridge? Since the device will be battery powered, I would prefer a dedicated low-power circuit instead of a programmed microcontroller as suggested by majenko.

How about an ATMega328P programmed to do what you want...?

@Majenko Why didn't I think about that. It would actually work, but since I need the bridge to be always on in a battery-powered device, the power consumption of the ATMega328P is at least disadvantageous. I would prefer a dedicated circuit. I'll edit my question and add the power requirement.

An ATTiny would reduce the power a little - so would employing sleep modes and wake on I2C or UART interrupts.

Yes, sleep modes should do it.  Note that hardware flow control is not incompatible with software serial in concept, though there might be a few details to work out.  There may also be dual-UART ATmegas available in large DIP packages.

You really should invest an hour or two in learning to solder SMD device though - it is not hard at all, and will remove these extreme limitations you face.

According to what I read, a 'wake on UART activity' concept won't work. After waking up, the ATMega will take some time to resume normal operation and at least the first byte of the UART transmission will be lost. Using such an approach requires control of the transmitter. which must first send a dummy 'wake up byte' on the UART, delay for a short period to wait for the ATMega to run properly and then start the real transmission. Since I cannot change the protocol used by the connected devices, this will not work.

Less expensive option?
Have no personal experience, but was Googling for a way to add second hardware UART to Arduino Uno. https://www.embeddedadventures.com/i2c_to_uart_mod-1025.html

Perhaps what you're looking for:
http://sandboxelectronics.com/?product=sc16is750-i2cspi-to-uart-bridge-module

From that page:

SC16IS750 I2C/SPI to UART Bridge Module
This module is designed to enable I2C/SPI to UART conversion. It works in I2C/SPI slave mode and interfaces with devices working in I2C/SPI master mode. There are also 4 extra GPIOs for IO expansion. NXP SC16IS750 is used as the key component on this module. Flow control and modem signals are also supported.
This module is useful when extra UART interface is needed. Due to the multi-slave characteristics of I2C and SPI, many UART interfaces could be added to the system at the same time.

@MichaelWilkinson Please consider posting a little summary, because your post will be worthless when the source you are linking to changes or is deleted.

Agreed - links go dead in time. Please summarise your answer so that it stands on its own. At least mention the part number, and maybe post a photo of it.