text:
A/C doesn't detect IR codes sent from Arduino
I have an IR receiver and an IR LED I got from a kit (I don't have the datasheets for them).
I uploaded an Arduino sketch to record my A/Cs IR codes. Those were NEC encoded 32bit integers.
After recording the codes, I tried retransmitting them. The A/C unit failed to detect the signals.
Troubleshooting a bit, I sent the code from the Arduino the receiver sketch from the previous step - it received them successfully.
All the above steps used the IRRemote Arduino library
The question is, what could explain this behavior?
A few possibilities I had in mind:

IR frequency. Could it be that the detection circuit worked with the default settings but transmitting wouldn't?
IR wavelength. Any chance the A/C side doesn't detect my IR pulses at all?
Decoding/Encoding of the NEC protocol in IRRemote. If there is no standard for the NEC protocol, the Arduino and A/C implementation might be a little different.

Is it an NEC air conditioner? I think the IR library has a "raw" mode - you could try that, which more exactly replicates exactly what it received. I think your solutions (1) and (2) are a little unlikely, but feasible.

You could try a different library: http://tech.cyborg5.com/irlib/

range. The ir led you use could be far weaker than the one in the remote. Try placing the arduino right next to the AC unit.

@NickGammon It's not a NEC air conditioner. It just uses the NEC IR protocol. As for your RAW mode suggestion, I tried it, but the raw receiver generates both negative and positive values. I'll try to give it another try and try the other library as well. Thanks!

HI I have put my answer on the link below. https://stackoverflow.com/questions/44528781/clone-remote-using-arduino-with-the-irremote-library/45955124#45955124 Please let me know if it works for you. Let me know if you need help.

Simple brightness is also an issue. Have you tried various positions of the LED with respect to the sensor? Lowering the current-limiting resistor value?

Hi i have done the same thing. I was using this to get the AC codes for the GREE AC. I find it with two weeks struggle and a forum called AnalysIR. If you find any issue in this code below or method let me know.
AC codes are usually long and those doesn't come right with the code which you used above so i am giving you the sample code to run in the Arduino sketch so that you can test.
   #define LEDPIN 13
  //you may increase this value on Arduinos with greater than 2k SRAM
  #define maxLen 800

       volatile  unsigned int irBuffer[maxLen];
       //stores timings - volatile because changed by ISR
       volatile unsigned int x = 0;
       //Pointer thru irBuffer - volatile because changed by ISR

     void setup() {
     Serial.begin(115200); //change BAUD rate as required
     attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);
    //set up ISR for receiving IR signal
     }

 void loop() {
   // put your main code here, to run repeatedly:

   Serial.println(F("Press the button on the remote now - once only"));
    delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
digitalWrite(LEDPIN, HIGH);//visual indicator that signal received
Serial.println();
Serial.print(F("Raw: (")); //dump raw header format - for library
Serial.print((x - 1));
Serial.print(F(") "));
detachInterrupt(0);//stop interrupts & capture until finshed here

for (int i = 1; i < x; i++) { //now dump the times
  if (!(i & 0x1)) Serial.print(F("-"));
  Serial.print(irBuffer[i] - irBuffer[i - 1]);
  Serial.print(F(", "));
                     }

   x = 0;
   Serial.println();
   Serial.println();
   digitalWrite(LEDPIN, LOW);//end of visual indicator, for this time
   attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for            receiving IR signal
        }

      }

  void rxIR_Interrupt_Handler() {
    if (x > maxLen) return; //ignore if irBuffer is already full
     irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

    }

Once this is done you will get the right code to send it to the AC.
A little Tricky part
once you will receive the codes of raw values you will have to little modify it for example i got the raw values and i converted it into the array.
What i received for example
Raw (16): -27750, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628
To Convert the above raw values into array remove first value which is -27750 and put 3800 instead of that. Below is the array sample.**
unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
};
Now sending these values to the IR transmitter use this code below.
      #include<IRremote.h>
       IRsend irsend;
       int KHz = 38;                    // default frequency

      unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
        };

    void setup()
   {
     Serial.begin(9600);
     irsend.enableIROut(38);
   }

    void loop()
   {

    for (int i=0; i<1 ; i++){
    irsend.sendRaw(data, sizeof(data) / sizeof(int),38 );
    delay(40);
          }

 }


text:
Why doesn't analogWrite() work
Can anybody tell me why these analogWrite() statements are being ignored. The code is entering the "if"statements because the Serial.println() statements are being executed.
    class Pwm
{
  unsigned long previousMillis = 0;
  unsigned long currentMillis;
  int LED;
  int DELAY;
  int up;
  int down;
  int x;

  public:
  Pwm(int led, int Delay) {

    int LED = led;
    pinMode(LED, OUTPUT);

    DELAY = Delay;
    up = 1;
    down = 0;
    x = 0;

  }

  void Update() {
    currentMillis = millis();
    if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    Serial.println(x);
    if (x == 0) {
      up = 1;
      down = 0;
    }
   }
  }

};

// create Flasher Objects
Flasher red(12, 1000, 250);
//Flasher yellow(11, 500, 500);
//Flasher green(10, 250, 1000);
//Flasher blue(8, 250, 500);

// create PWM Objects
Pwm pin9(9,8);

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

void loop()
{
  red.Update();
  //yellow.Update();
  //green.Update();
  //blue.Update();
  pin9.Update();
}

if I load this code everything works fine. I only have issues with the OOP method.
int LED = 9;
int DELAY = 8;
int up = 1;
int down = 0;
int x;
unsigned long currentMillis;
unsigned long previousMillis = 0;

void setup() {
  pinMode(LED, OUTPUT);
}

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis >= DELAY && up == 1) {
    analogWrite(LED, x);
    x++;
    previousMillis = currentMillis;
    if (x == 256) {
      up = 0;
      down = 1;
    }
  }
  if (currentMillis - previousMillis >= DELAY && down == 1) {
    analogWrite(LED, x);
    x--;
    previousMillis = currentMillis;
    if (x == 0) {
      up = 1;
      down = 0;
    }
  }
}

Does pin 9 on you board support PWM?

Yes the second sketch works just fine and uses the same pin as the first

Ermm... yes...doh

The constructor in your Pwm class declares a local variable LED which it sets equal to the parameter led. You use the member variable LED in other methods, so you probably meant to set the member variable of the same name, not create a local.
Remove the int from before LED = led in the constructor.

So by creating the local variable LED in the constructor the update() method doesnt see pin 9 being set to output? Please correct me if I'm wrong. I can't make changes to my sketch until later. I will let you know how it turns out.

@beewrangler Yes that's correct.  C++ lets you declare two variables with the same name at different 'scopes' (some compilers warn you).  Put simply scope is between the braces {}, you know of global variables and then function variables, they are two examples of scope.  You have define LED as a class member (class scope) and then LED as a function variable (function scope).  The lowest level of scope takes precedence, function level, and when you are outside the constructor, but inside the class (i.e. update()) then the class member is used.  Good spot Mark.

As stated above by Mark Smith I had my LED variable scope wrong. His suggestion has fixed my problem. Thank you

source: Stack Exchange

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

sort: votes


text:
how to change variable when a button connected to pin 2 is pressed
Hi i am writing a code where, i have to switch a variable called toggle from 0 to 1 to 0.... every time the button is pressed (the button is on a 2 pin). I am a little lost as I am new to arduino need some help. Thank you

What you need is to detect a transition. That is, either:

It was closed and is now open.

Or:

It was open and is now closed.

To do that you need to "remember" the previous state of the switch and detect a change, like this:
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
bool toggle;

void setup ()
  {
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    toggle = !toggle;   // toggle the variable
    delay (10);         // debounce
    }  // end of state change

  // other code here ...

  }  // end of loop

For more information see my post about switches.

Go here --> Built-In Examples. Read the examples for Button, Debounce, and Digital Input Pullup. Digital Input Pullup is the best single one of those 3 I think, but read them all.
Those 3 are key.
Also, I wrote a buttonReader (debouncing) library here.
Sounds like you're a beginner, so check out Adafruit's tutorials here.
And lastly, I've compiled links to all my knowledge at the bottom of my article here.

You might want to make your answer a little bit more substantive than simply including links to sites that may or may not exist by the time someone else looks at the question.

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


text:
Arduino Pro Mini lower BOD problem
I am planing to build a project where an arduino pro mini 3.3V runs on 2 aa batteries. The standard brown out detection shuts it down at about 2.7/2.8V where it could run on lower voltages too.
So I changed the efuse to get the BOD down to 1.8V. I connected a serial to usb converter and used avrdude:
avrdude -c avrisp -p m328p -P COM5 -b 19200 -U lfuse:w:0xff:m -U hfuse:w:0xda:m -U efuse:w:0x06:m

Then I tried to upload a program using the arduino 1.0.3 IDE but I got this error:
avrdude: stk500_getsync(): not in sync: resp=0x1c

With 1.6.4 I got another error:
    avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x75
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1c

After some googling I tried some lower baud rate (the standard seems to be 57600). With 19200 everything worked with avrdude, so I created a new entry in the boards.txt
    ##############################################################

pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328 BOD 1.8V

pro328.upload.protocol=arduino
pro328.upload.maximum_size=30720
pro328.upload.speed=19200

pro328.bootloader.low_fuses=0xFF
pro328.bootloader.high_fuses=0xDA
pro328.bootloader.extended_fuses=0x06
pro328.bootloader.path=atmega
pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
pro328.bootloader.unlock_bits=0x3F
pro328.bootloader.lock_bits=0x0F

pro328.build.mcu=atmega328p
pro328.build.f_cpu=8000000L
pro328.build.core=arduino
pro328.build.variant=standard

And burned a bootloader using the 1.0.3 IDE again. After that I could upload a blink program. My goal is to upload a mysensors sketch though and that doesn't work. I am getting an error
avrdude: verification error, first mismatch at byte 0x0002
         0x69 != 0x61
avrdude: verification error; content mismatch

Mysensors seems to have general problems with old arduino IDEs so I tried to use the newer 1.6.4 but I can't define my own board there and if I try it without I get hte out of sync error (because it's still using the wrong baudrate I guess).
I also tried using another arduino uno as ISP => same results
How can I fix this? Is there a way to define my own board for 1.6.x?
Whats the standard way of doing this and why does the change of the efuse results in me not beeing able to program the mini any longer?
Thanks for every answer/help!

When you go below (or above) the manufacturer's voltage/clock specifications, expect some problems. One chip may work another will not.  Remember the lower the voltage normally the slower the clock needs to be.  The CPUs are cut from a wafer (size and geometry specific) which may contain many thousand CPU die, they are at different locations on the wafer they will be a little different and they make more then one wafer.
Check the data sheet, it will show what clock speed will work at what voltage.  As the CPU clock changes so will your baud rate so plan on recalculating that if you change the clock. Example:  If you are operating with a 16MHz clock and change it to 8MHz the baud will be exactly 1/2.  If at 9600 it will be 4800 unless you modify the clock dividers.
Your error indicates a potential baud rate problem. One of the funny things that happens when the voltage is above/below the manufacturer's speck not all instructions operate properly over temperature. Clock problems should be expected.


text:
Split RGBW hex String into integers
I have a program where the Arduino receives hex Strings that represent a RGBW color (similar to css for example). My goal is to create that color by using pwm, so I need to convert that one hex string into four integer values between 0..255 to use for the pwm.
Whats the best/easiest way to do this?
Example:
void incomingMessage(const MyMessage &message) {

    // h = hex value
    // message = e.g. (h) #112233AB
    redval = ?; // h11 => 17
    greenval = ?; // h22 => 34
    blueval = ?; // h33 = 51
    whiteval = ?; //AB = 171

    analogWrite(RED_PIN, redval);
    analogWrite(GREEN_PIN, greenval);
    analogWrite(BLUE_PIN, blueval);
    analogWrite(WHITE_PIN, whiteval);

}

I don't like using the String class because it can cause memory fragmentation. This would do it by just using C-style strings:
byte fromhex (const char * str)
  {
  char c = str [0] - '0';
  if (c > 9)
    c -= 7;
  int result = c;
  c = str [1] - '0';
  if (c > 9)
    c -= 7;
  return (result << 4) | c;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  const char * test = "#112233AB";

  byte redval   = fromhex (& test [1]);
  byte greenval = fromhex (& test [3]);
  byte blueval  = fromhex (& test [5]);
  byte whiteval = fromhex (& test [7]);

  Serial.println ((int) redval);
  Serial.println ((int) greenval);
  Serial.println ((int) blueval);
  Serial.println ((int) whiteval);

  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

Output:
17
34
51
171

That does not do any validation (that the string is indeed 9 characters long, and contain hex characters) but I'll leave that for you to do. :)

So you basically want to convert a pair of hexadecimal digits into a numeric value.  You also want to extract those values from a string.
The latter can be done using the String.charAt() method.  That allows you to extract individual characters from your string.
Then you need to convert those into a number.  There's a number of ways that could be done.
strtol()
The strtol() function takes three parameters - the first is a C string (NULL-terminated char array) which contains the number you want to convert, the second you can ignore, and the third is the base to convert from.  So you could use something like:
char temp[3] = { char1, char2, NULL };
int val = strtol(temp, NULL, 16);

Discrete functions
It's simple enough to write a function that converts a single hex digit into a value 0-15:
unsigned char h2d(unsigned char hex)
{
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

It's then simple enough to use that to make a function that takes two hex digits and converts them into a number:
unsigned char h2d2(unsigned char h1, unsigned char h2)
{
    return (h2d(h1)<<4) | h2d(h2);
}

There's as many ways of doing it as there are of skinning a cat (as the saying goes).  Every way has benefits and drawbacks though.  Of the two I have shown, to compare them:

The first is "safer" as it has more error checking and can cope with other things besides hex values
The second results in much smaller code but results with values other than hex digits are undefined.


text:
Arduino to Thingspeak using WiFly-RN171 (Firmware 4.0)
I am attempting to use an Arduino Uno+WiFly setup to send data to Thingspeak.
I have tried a few libraries by now. But nearly all of them don't have a working WebClient example (WebServer works fine).
I am using Arduino 1.6.3 IDE for Arduino UNO R3 + Wifly-RN171 with Firmware 4.0
The libraries I have tried (found through Google and forums):

https://github.com/sparkfun/WiFly-Shield/tree/master/Libraries/Arduino
A ThingSpeak example is given but the execution stops when WiFly.begin() is called. I tried WebClient and WebClient(Faster) examples from the same library and they are both stuck at the same line: WiFly.begin().
I believe this could be compatibility issue (WiFly firmware version/Arduino) but am unsure how to fix it.

Note: There seems to be a few versions for the SparkFun WiFly library from my search results. I tried whatever I found but only listed the latest one since if it is indeed a compatibility issue a newer version should be more likely to work.
https://github.com/Seeed-Studio/WiFi_Shield
This one has a http example which I am attempting to use to send data to Thingspeak through http get/post. I am getting 'Bad Request' from their nginx server. Any help in the right direction will be much appreciated.
I hosted the sketch I tried here: codebender.cc/sketch:276925

p.s. I am not allowed to post >2 links due to reputation so the last one is plain text.
p.s.s Can someone with higher reputation help me add the new tags {thingspeak, wifly, rn171}

I solved my problem by sending a GET request to a hosted PHP script which in turn updates Carriots by means of a Curl request.
My PHP Script
<?php
$humidity=$_GET['humidity'];
$data = array("protocol"=>"v2", //Compose JSON stream
              "at"=> "now",
              "device"=>"DEVICE_NAME",
              "data" => array ("humidity" => trim($humidity)),
              "checksum" => "");
$data_string = json_encode($data);

$ch = curl_init('https://api.carriots.com/status'); //Compose the HTTP request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'carriots.apikey: YOUR_API_KEY',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch); //Send the stream

Note:

I switched to Carriots from ThingSpeak due to personal preference.
This is by no means a standard way to send stream to Carriots.This
involves additional effort which slows down transmission of data but
I decided that this setup will be enough for a hobby project.
A good understanding of how POST requests are built should allow me
to skip the extra PHP script completely.


text:
Dust sensor for Arduino in open and windy environment
I intend to create a DIY dust sensor, specifically Particulate Matter up to 10 micrometer in size (PM10) using Arduino UNO for the region surrounding a building which is located next to a factory that produces wood-based products. Is there any specific sensor that should suit my need, that is to collect and measure dust particles in an open environment and possibly a windy condition?
Any implementation ideas are also welcome.

A popular option is the Shinyei PPD42 sensor. There are a few well-documented blogs that describe how to connect it to an Arduino. Some of the users determined that the sensors are more accurate when a fan is placed on the unit to blow air through it, but this might not be necessary in an outdoors and windy environment.
I have two of these sensors hooked up to an Arduino, one monitoring indoors and one outdoors. I found that the indoors unit needed a fan on it to help it detect particles better (otherwise I was getting too many zeros). But the outdoors unit seems fine without the fan.
I mainly followed this blog's instructions for the code:
http://www.howmuchsnow.com/arduino/airquality/grovedust/
I think I read a few months ago that the next best sensors are in the $200 range.
I have a Dylos DC1100 dust monitor (considered very accurate) and it usually correlates with my Shinyei readings. But I'm pretty sure I introduced some "magic numbers" into my code to make the Shinyei readings match more closely with the Dylos. The entire process wasn't easy for me, and it took me weeks to get everything to behave the way I wanted.

It depends on how far you want to go.  If you are looking for something cheap, than a GP2Y1010AU0F will only cost you a few pounds.  Or you could step up to £30 GBP or even £1000GBP.
Since you are looking at using an Arduino and not a PC then I'm guessing the GP2Y1010AU0F would be a good idea.  I haven't tried it but this site should steer you the right way: http://arduinodev.woofex.net/2012/12/01/standalone-sharp-dust-sensor/


text:
Arduino based SPI programming of LT1257 not working
I am trying to talk to an LT1257 using an Arduino Nano Atmega328. I am not using the default slave select pin. I am using pin 5 as chip select for the DAC. The LT1257 data sheet shows this timing diagram. What I inferred from this diagram is that SCLK can be used to clock in the data and it remains in the shift register and is loaded into the DAC register only when Load is pulled low.

I wrote this snippet to load a 0x0000 to the DAC. However, when I probe the output voltage it is ~1.02V. The DAC uses an internal reference of 2.048V. So I think this must be the default 1/2*FS output when the DAC powers on.
Please review my code and point the errors. (At the DAC output I have a 1k resistor connected to ground).
#include<SPI.h>
#define SCLK 13
#define MISO 12
#define MOSI 11
#define DAC_LOAD 5

#define DAC_SPI_CLOCK_SPEED 1000000 //Upto 1.4MHz

void setup()
{
Serial.begin(9600);
init();
SPI.begin();
dac_write();
}

void init()
{
pinMode(SCLK, OUTPUT);
pinMode(MOSI, OUTPUT);
pinMode(MISO, INPUT);
pinMode(DAC_LOAD, OUTPUT);
digitalWrite(SCLK, HIGH);
digitalWrite(MOSI, HIGH);
digitalWrite(DAC_LOAD, HIGH);
}

void dac_write()
{
SPI.beginTransaction(SPISettings(DAC_SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE0));
delay(10);
SPI.transfer(0x0000);
delay(10);
digitalWrite(DAC_LOAD, LOW);
delay(10);
digitalWrite(DAC_LOAD, HIGH);
delay(10);
SPI.endTransaction();
}

void loop()
{
while(1)
{
Serial.println("Ping!");
delay(1000);
}
}

Notice that SPI.transfer() transfers one byte (8 bits) only, not 12 as you'd want.

I tried SPI.transfer16() too and that didn't work either.

Probably unrelated, but: From the diagram, the clock seems to be idle high => SPI mode 3. Also, what is MISO connected to? If nothing, use or enable a pull-up or -down on that input.

Plus: Apparently !LOAD must be asserted during the last falling edge of the clock line, see t6 and t7. You'll have a hard time trying that with the hardware SPI. You probably have to go with software bit-banging.

I read the LT1257 data-sheet more carefully. There is a pull down nmos at the output of the DAC. So when uninitialized, the output of LT1257 should be ~0V. So the output I was measuring (~1.02V) is spurious. I suspect I damaged the IC. I tried the same code on a different LT1257 and it worked. I can confirm now that this code is working.

For a master to select an SPI slave to transmit data to it [the slave], the Slave Select pin is held low.

Do you see any reference to the SS signal in the timing diagram?

OK. The OP refered to an SPI device with slave select pin and I assumed a standard 4 wire SPI device. The datasheet refers to the protocol as '3 wire cascadable serial'.  Anyway, here is description of an apparently successful attempt to interface an LT1257 to an Arduino link


text:
Help understanding code to build circuit for plant reader
I'm working a design project that measures the tiny changes of conductivity in a plant. (To visualize how a plant reacts to its environment) I'm working with Arduino to realize that. Two wires are hooked up to the plant to measure the changes and are connected to the Arduino. I haven't worked with Arduino before but a friend got me the code from his plant reader (he got help too and doesn't know how to build it anymore). I do understand most of it but I just don't manage to translate the code he gave me into a circuit on the Arduino bread board. I use processing to visualize the measurements afterwards.

Who can help me building the circuit. I don't get what's happening at pin13. Thank you for helping me :)

Please copy and paste the code into your question (edit the question to do this). That makes it much easier to read and comment on it.

Pin13 is attached to the onboard LED.
So when you see a reference to it, it means that the program is turning the light ON/OFF. You do not need to do any wiring with it.
But the logic seems strange: it turns the LED off only when the analog reading is out of range (and it resets the stress).
It seems to imply that once the plant is stressed, it will stay stressed :-)
Btw, as side note: posting the code in ASCII form would allow people to quote/comment on it. The screenshot is not very good for that purpose.
What cannot be figured out from the code, is how to instrument your plant.
If your friend has a working setup, you could try to replicate it.
At least post a few pictures.


text:
Using two MIDI inputs with Arduino UNO (with one serial)
Would it be possible to use TWO MIDI inputs (and a MIDI output) on an Arduino having only one RX/TX serial port? Timing will be somewhat critical so a software serial port is not usable probably. I need to listen continuously to both MIDI (in) ports not to miss messages.
Or is it better to use an Arduino Mega having 4 serial ports?

Use a Mega. SoftwareSerial is shaky at best and cripples everything else while it runs, and there really is no substitute for real hardware UARTs.
Alternatively look around and see if you can find a board based around the ATMega328-PB (note the "B") which has a second UART built in.

I can find the IC, but It's in SOP format, and since I have barely 0 soldering experience, the safest way is to go for a Mega for now. But nice to know there is an alternative.

FYI: I went for a Mega and now use 3 UARTS without any problem (leaving the 4th for debugging).


text:
Serial speed for debugging/logging
I have a sketch where I want to check my nRF24L01's and they work great.
However, due to Serial.print(ln) statements I noticed there is a lot of delay. Is this normal?
I mean, is it better not to user Serial.print at all during speed checks?  (probably not).
What other options would be best? Some I can think off:

Put all debugging info in an array and print it later (downside: more programming needed, probably special logging class)
Print less (bad solution I think, also makes logging more difficult to read)
Use another Arduino (so sending it by other means, via Wire or so? Never tried this, but I think this might be the best solutions.
I couldn't find any print that does not wait until ready sending (which would cause minimal 'downtime' for the running sketch.

I did not try the third option but I think that would be ideal (but cost another Arduino). Since in my project I eventually use multiple AVRs (mostly Arduino's), I was thinking about sending all logging info to one Arduino and let that Arduino print out everything, that means, only one serial monitor, and no delays (or barely) for all others (where it matters).
Do you think this is the best for logging/debugging? Or are there better methods for use with an Arduino?

Option 5: Run Serial at a much higher baud rate. You should be able to go at 1MBaud quite happily.

@Majenko ... With the Arduino IDE I just can chose 250000 baud, should I use a better serial port monitor?

Hell yeah. That thing is ghastly.

I just learned a new word :-) ... going to check for better ones

@Downvoter, can you instead of downvoting all my posts, explain WHY you downvoted, so I may improve the post.

I use a couple of techniques to measure code timing or to instrument it with mimimally disturbing time-critical code:

Run the code-under-test in a loop of N times, taking the difference in the system clock before and after the loop. If the code-under-test is short enough that the loop housekeeping timing might significantly affect the measurement, I'll unroll part of the loop - cut and paste several repetitions of the code-under-test into the loop - to reduce the relative effect.
Toggle an output pin at entry and exit of the code segment-under-test. Measure the pulse width with an oscilloscope, or with a DVM that includes frequency and duty-cycle measurement and calculate the pulse-width from that. I write directly to the I/O port to keep the influence of the software probes (added code) to a minimum.
If I'm trying to collect debugging data without disturbing the code timing, then as you suggest, I store the raw data in an array (raw, to keep it small), dump the raw data in hex to the terminal after the test-run, and expand/interpret it on my PC (to address your point 1., more programming needed). You'll still need some extra programming but it will be in a separate domain (your PC), it can be big, dirty, and slow, and requires less disturbance to your embedded source-code.

Thanks for all those options ... for my test 3 will suffice, 1 I also use indeed for very small timing checks, 2 is also interested, hope my oscilloscope can handle it :-)

(sorry for my late acceptance).

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


text:
Logging small capacitance
I'm measuring capacitance of a system using a multimeter, and found that the value is very small (fluctuate from 50pF to 100 pF). The system is dynamic so the capacitance changes over time.
Now I need to log this value to some text file (csv for example). How could I do this with Arduino? If it's resistance, I could have built a simple voltage divider and sense the voltage using ADC. Also C is very small, I haven't been able to construct some measuring circuit for C.

How much precision is required? Do you need to have a precise measure of the capacitance, or detecting a trip condition would be good enough? What is your application?

It's a capacitive sensing application.

Because the capacitance to be measured is well below 1 nF (50-100 pF), you'll encounter serious problems trying to measure it with the ADC of the Arduino due to its input capacitance (14 pF according to datasheet). Add the stray capacitances of wires, headers and the Arduino board itself and you'll easily end up with 25 pF input capacitance, which is in the same order of magnitude of what you're trying to measure (= A VERY BAD THING).
What to do, then? Well, the main options are these...
Use an external measurement circuit
This would mean including active devices (op amps, comparator, timers...) and precision passive components. A true HW-based solution.
The accuracy of the measurement in this case would be entirely up to the design (circuit topology and component selection) of the external circuit. The circuit would provide either an analog voltage or a signal whose frequency could be measured by the Arduino without introducing any additional significant errors.
An example using a 555 timer (an additional 4 pF compensation capacitor is needed between OUT and TH for improved accuracy):

Source: Use Analog Techniques To Measure Capacitance In Capacitive Sensors, an article by Martin Tomasz published in Electronic Design.
Think of the external circuit as a "sensor" or as a signal conditioning circuit for a "sensor" (the capacitance to be measured). In fact, the dynamic capacitance you're trying to measure probably comes from a sensor (moisture, humidity?), isn't it?
Connect the capacitor directly to analog pins of Uno and calibrate the readings
It may sound amazing, but something as simple as this works (at the expense of accuracy, of course):

How's that? Because the input capacitance problem that we detected at the beginning is big enough to seriously impair accuracy, but doesn't make the measurement completely unfeasible. Thus, we can calibrate that effect out and still have a valid (although with reduced accuracy) measument in the target range (50-100 pF).
The calibration is done through some hardcoded default values in the following Arduino sketch (source here from braulio777). For better accuracy you should calibrate the values of IN_STRAY_CAP_TO_GND and R_PULLUP in the sketch by comparing measurements of some capacitors with their already known capacitance values (provided you can do this).
//Digital Capacitance Meter
//Measuring from 0.000pF to 1000uF

#include <LiquidCrystal.h>
LiquidCrystal lcd(11, 9, 5, 4, 3, 2);
const int OUT_PIN = A4;
const int IN_PIN = A0;
const float IN_STRAY_CAP_TO_GND = 24.48;
const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
const float R_PULLUP = 34.8;
const int MAX_ADC_VALUE = 1023;

void setup()
{
  pinMode(OUT_PIN, OUTPUT);
  pinMode(IN_PIN, OUTPUT);
  lcd.begin(16, 2);
  }

void loop()
{
    pinMode(IN_PIN, INPUT);
    digitalWrite(OUT_PIN, HIGH);
    int val = analogRead(IN_PIN);
    digitalWrite(OUT_PIN, LOW);

    if (val < 1000)
    {
      pinMode(IN_PIN, OUTPUT);

      float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);

      lcd.setCursor(0,0);
      lcd.print("Capacitance = ");
      lcd.setCursor(0,1);
      lcd.print("                ");
      lcd.setCursor(0,1);
      lcd.print(capacitance, 3);// for the best precision
      lcd.print("pF ");

    }

    else
    {
      pinMode(IN_PIN, OUTPUT);
      delay(1);
      pinMode(OUT_PIN, INPUT_PULLUP);
      unsigned long u1 = micros();
      unsigned long t;
      int digVal;

      do
      {
        digVal = digitalRead(OUT_PIN);
        unsigned long u2 = micros();
        t = u2 > u1 ? u2 - u1 : u1 - u2;
      }

      while ((digVal < 1) && (t < 400000L));

      pinMode(OUT_PIN, INPUT);
      val = analogRead(OUT_PIN);
      digitalWrite(IN_PIN, HIGH);
      int dischargeTime = (int)(t / 1000L) * 5;
      delay(dischargeTime);
      pinMode(OUT_PIN, OUTPUT);
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(IN_PIN, LOW);

      float capacitance = -(float)t / R_PULLUP
                              / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

      lcd.setCursor(0,0);
      lcd.print("Capacitance = ");
      if (capacitance > 1000.0)
      {
        lcd.setCursor(0,1);
        lcd.print("                ");
        lcd.setCursor(0,1);
        lcd.print(capacitance / 1000.0, 2);
        lcd.print("uF ");

      }

      else
      {
        lcd.setCursor(0,1);
        lcd.print("                ");
        lcd.setCursor(0,1);
        lcd.print(capacitance, 2);
        lcd.print("nF ");

      }

    while (millis() % 1000 != 0);
}
    }

The example code above outputs measured values to an LCD display. For your intended application, the best option probably is to write data to an external SD card.
Disclosure: I have not tested the code above myself.

For capacitance as small as pF, The RC time constant method yields dirty results on an Arduino board.
You can use the Arduino pins built in small capacitance (which is in Pf itself) to create a "capacitance divider" circuit and calculate much like you would resistance from a voltage divider circuit.
See this excellent post by Nethercott for reference
Arduino capacitance meter

Nice find,+1! I'm surprised how precise this method seems to be, considering it's based on the parasitic pin properties. Though I suppose this only works well with good EMI shielding or in EMI-free conditions.

Thank you :-)
I imagine you are right, though i never had the chance to stretch this method to its limits. From my experience with it, i was able to produce satisfactory results using an Arduino Uno board & 15cm long regular jumper wires in a day-to-day environment.

Measuring small capacitance value via RC constant estimation essentially requires precise time measurement. ATmega chips have TCNT1 timer which can be programmed to increment each clock cycle, and can be stopped by a comparator using bit ACIC in ACSR register. Running a counter at 16 MHz will give you a resolution of 62,5 ns which is enough for capacity measurements in picofarad range. Here's an example of code which uses this measurement technique.
AnalogRead is about 1000 times slower, so you'll be limited to nF range if you use it.
Note that you should calibrate your system when measuring such a small capacitance. This is done by running a measurement with your probes connected but without the target system. You will then subtract this capacitance value (typically 20-50 pF, depending on the probes you use) from your raw measurements to obtain the capacitance of your system alone.

Each Arduino capacitance meter relies on a property of resistor capacitor (RC) circuits- the time constant. The time constant of an RC circuit is defined as the time it takes for the voltage across the capacitor to reach 63.2% of its voltage when fully charged. Larger capacitors take longer to charge, and therefore will create larger time constants. The capacitance in an RC circuit is related to the time constant by the equation:
TC = R x C
where
TC = time constant in seconds
 R = resistance in ohms
 C = capacitance in farads
Rearranging the equation to solve for capacitance gives:
C = TC/R

simulate this circuit – Schematic created using CircuitLab
Example: 1 megohm * 1 microfarad = 1 second

Each capacitance meter has an RC circuit with known resistor values and an unknown capacitor value. The Arduino will measure the voltage at the capacitor and record the time it takes to reach 63.2% of it’s voltage when fully charged (the time constant). Since the resistance value is already known, we can use the formula above in a program that will calculate the unknown capacitance.
As your Capacitance is too Small in Pico Farad Range so you can directly measure Capacitance through your analog pin like this way...
 You said that your capacitor in dynamic in nature so you have to take atleast 10 values and average it to get accurate value.
Code for measure Low capacitance in pF range
const int OUT_PIN = A5;
const int IN_PIN = A0;
const float IN_STRAY_CAP_TO_GND = 24.48;
const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
const float R_PULLUP = 34.8;
const int MAX_ADC_VALUE = 1023;

void setup()
{
  pinMode(OUT_PIN, OUTPUT);
  pinMode(IN_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    pinMode(IN_PIN, INPUT);
    digitalWrite(OUT_PIN, HIGH);
    int val = analogRead(IN_PIN);
    digitalWrite(OUT_PIN, LOW);

    if (val < 1000)
    {
      pinMode(IN_PIN, OUTPUT);

      float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);

      Serial.print(F("Capacitance Value = "));
      Serial.print(capacitance, 3);
      Serial.print(F(" pF ("));
      Serial.print(val);
      Serial.println(F(") "));
    }
    else
    {
      pinMode(IN_PIN, OUTPUT);
      delay(1);
      pinMode(OUT_PIN, INPUT_PULLUP);
      unsigned long u1 = micros();
      unsigned long t;
      int digVal;

      do
      {
        digVal = digitalRead(OUT_PIN);
        unsigned long u2 = micros();
        t = u2 > u1 ? u2 - u1 : u1 - u2;
      } while ((digVal < 1) && (t < 400000L));

      pinMode(OUT_PIN, INPUT);
      val = analogRead(OUT_PIN);
      digitalWrite(IN_PIN, HIGH);
      int dischargeTime = (int)(t / 1000L) * 5;
      delay(dischargeTime);
      pinMode(OUT_PIN, OUTPUT);
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(IN_PIN, LOW);

      float capacitance = -(float)t / R_PULLUP
                              / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

      Serial.print(F("Capacitance Value = "));
      if (capacitance > 1000.0)
      {
        Serial.print(capacitance / 1000.0, 2);
        Serial.print(F(" uF"));
      }
      else
      {
        Serial.print(capacitance, 2);
        Serial.print(F(" nF"));
      }

      Serial.print(F(" ("));
      Serial.print(digVal == 1 ? F("Normal") : F("HighVal"));
      Serial.print(F(", t= "));
      Serial.print(t);
      Serial.print(F(" us, ADC= "));
      Serial.print(val);
      Serial.println(F(")"));
    }
    while (millis() % 1000 != 0)
      ;
}

And what about the load capacitances of the arduino pins?

According to the ATmega328 datasheet it's around 14 pF. Too close to the measuring range for comfort. Plus any stray capacitance due to wires and to the Uno board and headers.

−1: This method is not really suitable for such small capacitances: you would need an insanely large resistance value, otherwise the time constant would be too short for making a good measurement. If you want to do an RC time constant measurement, you should instead use the method described in Dmitry Grigoryev's answer.

Yeah you are right. But I have tasted it and giving me good result not so precise and accurate but satisfactory. Cool down dude I have given him a generalized Idea not the solutions for his problem.

You gave “an idea”, and then a piece of code that does something very different from that idea. If you authored that code, why don't you explain what it actually does? If not, why don't you give credit to the original author?

The standard way to measure a resistance with an Arduino is to build a
voltage divider by putting it in series with a known resistance. I have
tried the same approach for measuring capacitances, and it turns out it
works well in the 100 pF range! The circuit is like this:
  ┌───────────── Arduino digital output
  │
──┴── known
──┬── cap
  │
  ├───────────── Arduino analog input
  │
──┴── unknown
──┬── cap
  │
 GND

The only catch is that you have to do the measurement relatively fast,
otherwise you would be measuring the ratio of the leakage resistances.
Here is the measurement protocol:

Set both pins to OUPUT LOW in order to discharge both capacitors.
Delay for one or two CPU cycles to make sure they are fully
discharged.
Set the analog input pin to INPUT mode: this will make it high
impedance and isolate the node connected to it.
Set the digital output to HIGH: this will charge the two capacitors
in series to 5 V.
Delay for one or two CPU cycles for the voltage to stabilize.
Take an analog reading.

Now you can derive the capacitance from the reading using the same
formula you would use with resistors, only with impedances (or, simply
1/C) instead of resistances:
C_unknown = C_ref × (1024 − reading) ÷ reading;

The same formula can be derived by considering that the node connected
to the analog input, which includes one plate of each capacitor, has
zero net charge.
A few things worth noting:

You will get the best resolution by choosing the reference capacitance
close to the one you want to measure.
The delays are not actually needed: as the capacitors charge and
discharge very fast, a single CPU cycle is about 24 time constants.
If you were to measure large capacitances (several nanofarads) with
this setup, you would want protective resistors in series with the
Arduino pins, but then the delays become mandatory. In the
100 pF range I would not worry about the in-rush currents.
If the delay in step 5 is too long, your measurement will be affected
by the leakage of the caps and the analog input pin.
You need not worry about the 14 pF cap on the sample and hold
circuit: it will slightly affect the very first measurement but,
once that cap is charged, subsequent measurement will not be affected
as long as the unknown cap does not change to much between consecutive
measurements. You do need to calibrate out the stray capacitance of
the pin and probes.

(fluctuate from 50pF to 100 pF).

a few ways for such small values -> assuming you can really read it like a capacitor.
1) form a lc tank and measure its frequency -> most effective in measuring small value capacitance. but needs precision inductor / calibration, and is subject to parasitics.
2) charge / discharge it via a CCS: and measure the time. simplest as a ccs can be formed via a large resistor. not effective with really small capacitance;
3) charge transfer: using the capacitance of the adc. very effective against small capacitance: < 10x of adc capacitance. needs calibration.
each has its own problems.

What is CCS??


text:
AVR dude not working in javaFX
I am working on an Project in which i have to upload hex file from java to arduino uno i wrote the code in java its working but only when i call it in main method. But when i call it when button is pressed it doesn't upload the hex.
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws IOException {

    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
    Parent root = loader.load();
    MainController controller = (MainController) loader.getController();
    Scene scene = new Scene(root,485,355);
    primaryStage.setScene(scene);
    primaryStage.setTitle("Hello World!");
    primaryStage.show();

    controller.Init(primaryStage);
    controller.searchForPorts();
    controller.disableControls();
}

public static void main(String[] args) {
     Avr avr = new Avr();
    avr.start();
    launch(args);
}

}
Working fine like this but when called on button pressed event doesn't work.
public class Avr extends Thread {
String avrdude;
String avrconf;
String hex ;

MainController main;
void setup() throws IOException{
    Path avrpath = Paths.get("avrdude.exe");
    Path hexpath = Paths.get("sketch_may13b.ino.hex");
    Path avrconfpath = Paths.get("avrdude.conf");
    Path realavrpath = avrpath.toRealPath(LinkOption.NOFOLLOW_LINKS);
    Path realhexpath = hexpath.toAbsolutePath();
    Path realavrconfpath = avrconfpath.toAbsolutePath();

    avrdude = realavrpath.toString();
    avrconf = realavrconfpath.toString();
    hex  = realhexpath.toString();

    avrdude = avrdude.replace("\\","\\\\");
    avrconf = avrconf.replace("\\","\\\\");
    hex = hex.replace("\\","\\\\");
    main = new MainController();

    String port ="COM3";
        runCommand(new String[]{avrdude, "-C"+avrconf,"-v","-v","-v","-v","-patmega328p","-carduino","-P"+port,"-b115200","-D","-Uflash:w:"+hex+":i"});

  }
  void runCommand(String[] cmd){

try {
Runtime.getRuntime().exec(cmd);
}
        catch (IOException e) {
      System.out.println("something went wrong: \n");
      e.printStackTrace();
  }

  }

@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        setup();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}


text:
Arduino shuts off and doesn't turn on after couple hours
I use a mega 2560, pir sensor and a SG90 9g Servo motor in my project. Basically while the pir outputs high, the Servo Motor rotates from 0 to 180 degrees.
Here is how everything is wired up:
PIR sensor:
Data: pin 24
Vcc: 5 volt
Gnd: Ground
Servo:
PWM pin: pin 11
Vcc: 5 volt
Ground: ground
The arduino mega has two 5 volt and ground pins, one next to the analog pins and other at tho bottom bar of pin, where pins 22 and up are. I connected the Servo to the first 5v and gnd and the pir to the second.
My power source is my nexus 5 charger(5v 1.8 or 2 A).
My code:
Servo myservo;

    void setup() {
      myservo.attach(11);
     pinMode(24, INPUT);
    }

    void loop() {
     if(digitalRead(24) == HIGH){
       myservo.write(0);
       delay(500);
       myservo.write(180);
       delay(500);
     }
    }

All of this works fine for the first ~10 hours. After that the arduino just shuts down. The power led of the arduino isn't lit up. Disconnecting the adapter and reconnecting it or pressing the reset button of the arduino doesn't work.  I Have to wait for a couple of minutes with the adapter disconnected and reconnect it. After that it works fine for the next ~10 hours.
Seems like a hardware issue, but I'm not sure what exactly fails and why.

You should not route power for the servo through the Arduino.  It needs its own connection to a supply capable of handling its stall current, which may well exceed an ampere.

I assume your charger is connecting to the USB port of the Mega2560.
That USB port has a polyfuse (actually a special type of positive-coefficient thermistor) which is normally rated at around 500mA (polyfuses are a bit woolly with their ratings since they are heat based).
If you are drawing near that limit of current the fuse will be gradually heating up. I would think that after 10 hours it may have reached its threshold temperature and thus switches the power off.
Disconnecting the power and allowing it to cool down would then make the board work again.
How can you test it?  Well, next time it switches itself off try bypassing the polyfuse (tweezers would be good to do that with) to see if the power LED turns on again.

Yes, it's connected to the usb port. The polyfuse indeed seems like a logical place to look for the issue. I will try your suggestion. Thanks.

I'm just going to hazard a guess: Your 5v line isn't staying at 5v because of the servo. They draw massive amounts of power quickly, and can wreck a lot of havoc. Many times electronics "kinda" work after voltage drops, but will lock up or glitch eventually.  (To get confirmation that this is the problem, monitor your 5v power with an oscilloscope. Set a trigger at 4.5v and try to capture the voltage drops.)
If that is the problem, you need better isolation on your digital power (running the arduino) and your analog power (running the servo.)  Two ideas to try (you may need both):
1)  Get a big cap (say 100 uF or more), then put it across your power to the arduino. If it's big enough, it will prevent your 5v from sagging. It may be expensive to get a big enough cap.
2) Instead of connecting your servo directly to 5v, put a small resistor (say 10 ohm) between them.  Now when he tries to suck all the power, it will get resistance, which will limit the current. The bigger the resistor the better the isolation, but too big will prevent your servo from working. (And may heat up your resistor).

The power led of the arduino isn't lit up.
The power LED is implemented in hardware, basically, if it's not lit, it won't work.
Find the problems' (power?)source
After the 10h operation, your Arduino isn't on anymore.
Does the power supply still have 5V available at that point? Or does your Arduino's chips get hot or short-circuit the supply?
Exclude as much variables as possible
You don't know what the problem is, it could be:

The supply
The Arduino
The Servo
The PIR

Try another supply (preferably through the barrel jack, since it's regulated) (The supply may have some "protection" to avoid it being on too long).
Try another Arduino (unlikely?).
Try no servo & pir connected. (They may draw too much current, so the Arduino shuts down or create electrical noise.)

Yes, I'm trying out a new supply now, the difficulty with finding the problem is that every time I change something, I have to wait for 10 hours to see if there is difference :(.  The arduino doesn't get hot, I tested that.

@MeesterPatat, atleast you can do something else in that 10 hours ;)
But yeah, welcome to the world of testing ;D It might be a good idea to make "test cases" or atleast think very well of what you're going to test, what the result should be and why ;)


text:
Can I connect an output pin to an input pin to measure it's voltage on a single board?
So just bought an arduino Uno and I've been playing around with it. I want to connect one of the input pins to one of the PWM outputs and measure the output from there by sending it to my computer through Serial and then plot it in python.
Sorry if this is a basic question.
Thanks

PWM pins don't give an analog value. They are either 0v of 5v. Your idea is possible, but you'll receive almost exclusively 0's and 1023's.

ok cool, I'm just worried that I'll burn out the board...

That won't happen here. Just be careful to never connect two pins that are both outputs (as setting one to HIGH and the other to LOW would create a short). If you want to be super-save, you could put a resistor between the two pins (e.g. 1kΩ) instead of a wire.

PWM are digital output pins, and it seems that you wish to measure analog equivalent voltage generated by PWM output. If so, you'd need a filter.
Construct a unity gain op-amp based RC filter with cut-off frequency significantly smaller than PWM clock frequency. This will generate a analog waveform that can drive analog circuits. You could connect this to ADC input pin.
You could Google "Active low pass filter" for a lot of schematics and formula.
BUT
To be able to faithfully reproduce analog signal captured through ADC on a computer screen graph, your ADC sample rate must be more than ~2.5 times analog signal's bandwidth.
If your sample rate is close to Nyquist rates,  you'd need to filter (interpolate) your digitized signal in software to generate a smooth graph. This is a bit involved in maths and software. Otherwise you'd only get a "spikey" waveform.
Or preferably have a sample rate > 10 times analog bandwidth. This will give large enough sample counts to reliably show analog data without much processing.

nope not interested in an "analog equivalent voltage". I just wanted to measure the PWM waveform, and wasn't sure if by using the same board for measuring and generating (of the signal) I could potentially burn it out

Usually digital waveforms are better captured by counters + interrupts, because exact voltage level is usually of no concern. i.e. for all transitions (hi->lo, lo->high), trigger interrupt. In ISR record a timer counter value and store. Capture timer clock needs to be (much) faster than PWM clock


text:
Can i run brushless ESC from any digital pin of arduino
{assume arming is done}
Can i connect the brushless ESC to any digital pin and give writemicroseconds() to it? Will this work. because i have connected my 4 ESC's to "~" pins. so i thinks that other will not work.

It should work.
The Servo library doesn't use hardware PWM, so you can connect them to a non "~" (PWM) pin.

Yes, RC servos can be attached to non-PWM pins, but  a “brushless ESC” is not an RC servo but instead  a PWM-controlled Electronic Speed Control for brushless DC motors.


text:
How to read 6 RC remote channels using Attachinterupt for every channel
How can i use the attach interupt command and read rc channels in background. I am in doubt that attach interupt is only applied to 2 pins just and cant be used to get data from other pins.

Please spell out what you mean by "rc channel"; eg add a link to a specification for rc channels.  Note, the Uno has plenty of pin-change-interrupt pins, which can be used (eg) for software-serial i/o [with one software-serial channel active at once, in typical software-serial implementation]

I mean external interupts,(radio control channels).

You can use PCINTs. The only downside is that they all share one single interrupt routine (ISR).

Bilal, please edit the question and spell out what you mean by "radio control channel".  Is it an input? An output? Are you talking about controlling RC servos?  Edit the question and add a link to an actual specification.

I already tell you what you should investigate in your other question on the same topic. If you'd read the entire answer there you would know the answer to this question already.

I am not sure what you are asking but you can have as many interrupt sources on a single interrupt pin as you want.  When the interrupt happens in your ISR (Interrupt Service Routine) you simply check each one and process the ones that are valid.  Be sure to do one final check before exiting as another could happen while servicing the first one.
Gil


text:
How to read RC receiver channels without using pulsein() command with arduino
I am building a quad-copter, the problem is of stability and for better stability lesser sampling time is required. For lesser sampling time I need to have faster loop() function. But the Pulsein() command takes very large time which in turn expands the sampling time. Is there any method to read the rc channels in background and read them from an integer.

Why not have a look at some of the open-source ATMEGA-based quadcopter firmwares, at least to examine for ideas?  I don't know if you will find some that are based on the Arduino libraries, but you should find some that will run on the hardware.  That said, fundamentally you cannot measure pulses faster than they occur, which is typically a repetition rate of only around 50 times a second.  You can write code which accomplishes other things while waiting for the pulses, but you can't speed them up unless you change the receiver, for example directly talking to the 2.4 GHz chip.

The keyword you are looking for here is interrupt.  What is a pulse but a signal that goes from low to high followed by going from high to low, with some period of time between them?
Instead of sitting there waiting for the pulse to arrive then measuring how long it is, which is essentially what pulseIn() does, you need to attach the signal to an interrupt pin.  Then you write an interrupt routine that triggers when the signal changes from one level to another which looks to see what the level actually is.
If the signal has risen from low to high then you record the time it happened.  If the signal has fallen from high to low then you look what the time is, and subtract the time you remembered from when the signal rose.  That difference is then the width of the pulse, which you can store in an integer to read in your main loop.
If you have a number of signals you want to monitor you might want to look into using the pin change interrupt which allows you to use any pin as an interrupt source.

While you can use interrupts to allow potentially accomplishing other things while waiting for the pulses, they won't permit an input-based control loop to run at a higher rate than the inputs themselves arrive at - for a legacy PWM output, that is typically in the neighborhood of 50 Hz repetition rate.  Of course it is possible to run the on-board stabilization algorithm at some multiple of the radio data rate, if desired.

@ChrisStratton I think you are misinterpreting the question. When he talks about "sampling" I am assuming (and I think quite rightly) that he is talking about sampling something else - accelerometers maybe - since he says waiting for the pulses slows down the sampling that he is doing, and it's the sampling he needs to do faster, not the reading of the pulses.

I agree with Majenko here. pulseIn blocks, which is what I gather he is trying to avoid. Using interrupts would help in this situation.

yes i am using accelerometer, for faster data reading. can i use interupts for all of 6 channels in RC reciever

@Majenko I have read your answer and got information from it. but Now the problem i am asking in other quesstion is how to read multiple channels with one interupt. thats the headache now,

@BilalAyub And in this answer I mention that if you have lots of channels to read you should investigate the pin change interrupts.

that is not easy work, i have asked the other question for that type of help

Simple enough: Step 1: ask google for library. Step 2: install library. Step 3: Write interrupt routine to check which pins have changed.

You may find my answer to another question –  Read RC receiver channels using Interrupt instead of PulseIn – useful.  It includes the sketch shown below, which is intended for background timing of four RC channels attached to pins A0-A3.  See the other answer for further comments about the code, example output, etc.
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}


text:
Bluetooth module as MCU?
Can I use Bluetooth Low energy devices as micro controllers directly instead of communicating to Arduino e.g. HM-10/11 or even HC-05/06 ? If so what are limitations e.g. can  I hook sensors or control other stuff like LEDs or transistors with PWM ?

I have built a motion sensor, which consists of Arduino, Bluetooth Low energy HM-11, battery and sensor itself. It worked just fine, but one guy told me that Arduino may be completely unnecessary and that Bluetooth module could replace its functionality !
I then started digging for information, and either it's impossible or I am terrible at googling. Everything I found was info about some kind of development kits for HM-10/11, also pin outs of those boards. They do have some IO pins, which can mean it's possible, but I found no tutorials nor examples on how to program those boards and use with other components.

What do the datasheets say?

Funny how one letter 's' can change everything, the keyword here is datasheet(S). it turns out that there are multiple datasheets, and one i checked had no detailed information and so i gave up easily. However after your reply I checked datasheet once again , coincidently it was another datasheet, and this time it was MUCH more detailed, I even found keywords in it which i pasted in Google, and found some neat material. Going to read further and see if those modules can work the way I want.

im searchin for a long time how can i program it in the aim of building alarme watch or thermometer without arduino becaus there is same input can be used as analog input and PWM please if you have some idea about this help me

All bluetooth modules will need some sort of mcu to handle the requirements of the protocol stack, and it seems common that there will be at least a couple of GPIO which can be used directly if your sensor requirements are simple. At the other end of the spectrum, you will find there are also mcus with a full set of peripherals - enough to support a couple of sensors and a small display for example. Remember, the wearables market is likely bigger than the hobby electronics market.
Limitations are most likely to be in the area of ease of use (as you hint at with your question), and possibly the toolchain which you would need to use (unlikely to be arduino compatible). Also, the bluetooth stack typically takes a reasonable proportion of these wearables focused devices, so there is not a big amount of ram/flash or CPU cycles to spare even if you opt for a part which is more than 'just' a serial-to-bluetooth bridge.

Actually, while most bluetooth modules have an internal MCU, there are some that do not.  Also, while there are now some with an internal MCU on the market where tools are provided that allow just about anyone to reprogram them, for others the intent is that only the manufacturer or their industrial partners are able to do that, with the device being fixed-function when used by anyone else.

authors: Светодиодные решения


text:
Using Arduino as a pc remote controller
I would like to create a simple remote controller (IR) with my Arduino Nano that would control my PC. (Volume up/down, stop, play and that sort of things...)
I have no problem with creating 'hardware part' and Arduino script, that would send commands through serial as a reaction to IR signals.
I can imagine python script that would react to commands received on the serial port.
My problem is: "How can I detect on which port should I listen to?" What is the right way to do it?

What operating system is on the computer?

And following a different route, could you have the device  emulate a USB keyboard? Many Arduino-like devices can do that. There are standard keys for play, volume etc.

@MarkSmith The arduino Leonardo has that ability, though I have never used it, and cannot speak to it's functionality.

Both Linux and Windows I guess, though Windows will be the preferred one.

i used node.js to monitor the serial port. based on the it codes coming in, it would execute small EXEs made with autohotkey to press keys/combos like VOL_UP.

@dandavis Thanks a lot. I can do that with python as well, only question is, how does the script which port to listen to... :(

well, when i re-assigned the "ftdi"'s COM port in windows, it stuck as COM10, even after rebooting, so that part was easy for me. there might be better ways, that's just what i got running one sunday...

@dandavis I ended up hoping that the COM port will stay the same. (If not, really easy to change port in python script)

Since I can not commemnt due to low reputation, I'm "commenting" here.
You can search for LIRC and WinLIRC


text:
Using two pins to sum maximum available current
I have a theoretical question about using digital pins of arduino. The specification of Arduino Uno (or any other I guess) says, that maximum current from digital pin is 40mA. If I would need more than 40mA and less than 80mA, can I use two pins to supply enough power to the sensor or would it burn the pins in the end?
Thanks

You could also hook the sensor up to the 5V rail of the Arduino?

I know, as I have written, it is only a theoretical question. I was more interested in arduino internals than real usage of this...

40mA is the absolute maximum current allowed. The recommended steady-state current is 25mA, so you'd need three or four IO pins to remain safe.
Theoretically, yes, that should be possible. However in practice doing such things is problematic.  You have to ensure that there is no point at which the sensor is being powered by less than the required number of IO pins, which means turning them all from off to on at the same time (doing them one at a time means you start with the full load through just one pin then start sharing it around). That means ensuring that all your pins are on the same port and using direct port manipulation to control all the pins at once.
It is far better, more reliable, and simpler to program, to just slip a simple p-channel MOSFET in there with a pullup on the gate to control the 5V power to the sensor. Pull the gate low and the sensor gets all the power it needs.

You also have to make sure that the maximum current draw for the port in use is not violated, as those have their own separate limits.

@IgnacioVazquez-Abrams Yep. And don't forget the maximum current on a power or ground pin...


text:
Water measuring
After recent flooding of my apartment (pipe burst) I got an idea of automatic water flow watch. I would like to measure or just watch if water flows on main water intake. Arduino will know at what time of day (during nights and when nobody is home) the water flow is a problem and will send me an sms or whatever alarm. Measurement will be better to enable you to go to the bathroom, so the alarm will be raised only after certain amount of water.
The main problem is how to measure the water, are there any water-meter that can communicate with arduino?

Yes. Places like Seeed, Adafruit, etc all sell water flow meters.

This even tells you how: http://www.seeedstudio.com/wiki/G1/2_Water_Flow_sensor

I have an electronic water flow meter which uses a turbine wheel inside the pipe. Ostensibly there is a magnet on one or two or all four of the blades, which is read by a hall-effect sensor inside the meter. The specifications require 3 gallons per minute, which may be lower than you wish.
http://catalog.gpi.net/item/chemical-and-water-meters/01-series-electronic-digital-meters/01n31gm-nylon-water-meter?plpver=1001
If the flow rate is acceptable, you could add your own hall-effect sensor outside the pipe and connect an appropriately programmed Arduino to perform the tasks you require.
Alternatively, one could create via 3d modeling software an equivalent design to be printed by an online service or a friend with a printer. For balance purposes, a magnet in each vane would be advised.
Years ago, I had a speedometer for a kayak, about the size of one's thumb. It used the same technology, although the sensor was about two inches away on the upper side of the hull, while the tiny propeller was on the bottom. Apparently small magnets spinning create sufficient disturbances in the force to be read by mass produced sensors, even more than a decade ago.

The utility company probably already placed a meter at your apartment.
Mine has a spinning dial, that's half metal, half plastic. I've had a photo-reflective sensor attached to it that so I could detect the change in amount of light being reflected (metal vs plastic). Every peak meant one liter.
Mine also has a rotating magnet, but I wasn't able to read that using a hal-effect sensor, or the magnetometer on my phone.

Your post brings up an interesting thought. If the magnet in the utility meter could be read from "outside" the casing, it could also be slowed or otherwise affected, changing the rates charged for water use. I suspect the flow meter I posted is not authorized for utility use and less likely to be shielded.

@fred_dot_u There is probably some geared reductions going on. Also the water pressing against the turbine inside has quite some force. You have to apply a lot of force to slow it down. Doing so will probably not even have any effect, other than a reduced water pressure in the house, resulting in less water flowing out of the faucets. If you want free water, have look at the datasheet of your meter. Most meters have a reduced accuracy low flowrates. So having a dripping faucet fill a bucket, will probably not be measured by the meter.So at the end of the day, you'll have a bucket of free water

Other than the aforementioned end user type meter, I don't have a utility based one. I'm inclined to agree with your assessment.


text:
String class summation disappears the right operand
I intend to create a function to jsify sensors' content and save it on a SD-card or send through a http client. Except for the Serial.println's, the function is transcripted below.
String jsonificar(vector<vector<String>> sujeito){
  String json_txt = String(""), chave, valor;
  String chave_str, valor_str;

  json_txt+=String("{");
  for(unsigned int i = 0; i<sujeito.size(); i++){
    if(sujeito[i].size() != 2){
        Serial.println("Cada conteudo deve conter 2 textos!");
    }
    else{
        chave = sujeito[i][0];
        valor = sujeito[i][1];
        Serial.println(chave);
        Serial.println(valor);
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += chave;
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += ":";
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += valor;
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);

        if(i != sujeito.size() - 1){
          json_txt += String(",");
        }
    }
  }

  json_txt+="}";
  Serial.println(json_txt);

  return json_txt;
}

The output on serial follows:
Output:

Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"    <===
{\"Chave1\":\"Valor1\",\"\"
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\":}

The arrows show the spots where the logs are different from expected: the keys and values provided are "Chave1", "Valor1", "Chave2", "Valor2". So, the key-value should be "Chave2":"Valor2". Would you have a grasp of this behaviour? I look forward for the answer!

How did you get std::vector into Arduino? It doesn't compile for me.

The same way one would use in default C++ appplication: using namespace std;   You have  answered your own question unpurposely ;P

The Arduino core implementation for AVR does not have these C++ STL types. Are you using an additional library like https://github.com/mike-matera/ArduinoSTL ?

Yes, I use ArduinoSTL. I also use PlatformIO as IDE and it says vector comes from namespace std.

You must be using this above library, no doubt. It does not work without it. I compiled this code and it ran without an error. Have a look at: https://pastebin.com/LPTYDje5

Note that you are constructing strings which uses dynamic memory allocation. What MCU are you on? Arduino Uno? You can see that my minimal test sketch works, so if it doesn't in your case, you ran out of memory. What exact sketch are you using?

`#include <Arduino.h>
#include <unity.h>
#include "../src/utils.h"
vector vetor_auxiliar1, vetor_auxiliar2;
vector<vector> vetor_mestre;
`

`void test_jsonificar(){
vetor_auxiliar1.push_back(String("Chave1"));
vetor_auxiliar1.push_back(String("Valor1"));
vetor_mestre.push_back(vetor_auxiliar1);
vetor_auxiliar2.push_back(String("Chave2"));
vetor_auxiliar2.push_back(String("Valor2"));
vetor_mestre.push_back(vetor_auxiliar2);

String resultado, esperado = String("{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"}");
resultado = jsonificar(vetor_mestre);

TEST_ASSERT_EQUAL(1, esperado.compareTo(resultado));

}
`

`void setup() {
Serial.begin(9600);
UNITY_BEGIN();
}
void loop() {
RUN_TEST(test_jsonificar);
UNITY_END(); // stop unit testing
}`

Okay you should have edited your question with that code but when I run that (wihtout the unity testing framework) I get the behaviour that it crashes after the third iteration (when put into a loop). I would just use the https://github.com/bblanchon/ArduinoJson library to construct these JSON strings in a more memory-efficient way than concatinating Strings which uses loads of heap (https://pastebin.com/h2eE3sgc)

Ok, I will do so. Thank you for the consulting.

Your "disappearing string" has the following cause: Out-of-Memory.
You are constructing lots of String objects in your code and are concatinating to one. That uses memory on the heap for each String (and realloc() when the String memory must be expanded).
Consider the following test sketch which includes your code but also adds a memory leak by 150 bytes in each iteration:
#include <Arduino.h>
#include <ArduinoSTL.h>
using namespace std;

extern unsigned int __heap_start;
extern void *__brkval;

/*
 * The free list structure as maintained by the
 * avr-libc memory allocation routines.
 */
struct __freelist {
    size_t sz;
    struct __freelist *nx;
};

/* The head of the free list structure */
extern struct __freelist *__flp;

/* Calculates the size of the free list */
int freeListSize() {
    struct __freelist* current;
    int total = 0;
    for (current = __flp; current; current = current->nx) {
        total += 2; /* Add two bytes for the memory block's header  */
        total += (int) current->sz;
    }
    return total;
}

int freeMemory() {
    int free_memory;
    if ((int) __brkval == 0) {
        free_memory = ((int) &free_memory) - ((int) &__heap_start);
    } else {
        free_memory = ((int) &free_memory) - ((int) __brkval);
        free_memory += freeListSize();
    }
    return free_memory;
}

String jsonificar(vector<vector<String>> sujeito) {
    String json_txt = String(""), chave, valor;
    String chave_str, valor_str;

    json_txt += String("{");
    for (unsigned int i = 0; i < sujeito.size(); i++) {
        if (sujeito[i].size() != 2) {
            Serial.println("Cada conteudo deve conter 2 textos!");
        } else {
            chave = sujeito[i][0];
            valor = sujeito[i][1];
            Serial.println(chave);
            Serial.println(valor);
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += chave;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += ":";
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += valor;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);

            if (i != sujeito.size() - 1) {
                json_txt += String(",");
            }
        }
    }

    json_txt += "}";
    Serial.println(json_txt);

    return json_txt;
}

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

String myStr = "";

void loop(void) {

    Serial.print(F("Free Memory:"));
    Serial.println(freeMemory());

    //force a memory leak by allocating appending to a global String
    myStr +=
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    vector<vector<String>> v =
            { { "Chave1", "Valor1" }, { "Chave2", "Valor2" }, };

    jsonificar(v);
    delay(1000);
}

From the output we can see the exact point where we have enough memory and the result is correct, and where we don't have enough memory and the string just "disappears" because there was not enough memory to allocate it:
Free Memory:911
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"}
Free Memory:761
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"

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


text:
Arduino nano / uno analog pin
I'm working on a project where I need 7 analog pins.
I read the datasheet of Ardnuino Uno : 6 analog pins available.
So I decided to use an arduino mega with 16 analog pin available.
Then I saw the arduino nano had 8 analog pins.
But when I read the datasheet, both arduino uno and nano use Atmega328
In my final project, I will not use the board but only the pdip chip (analog pins are from pin number 23 to 28).
Is it possible to "convert" another pin of the pdip to be an analog pin ?
Thank you

If you want to stick with DIP parts, add an external ADC such as MCP3008, a 4-channel ADC with 10-bit resolution and fast SPI interface. Available at Digikey, easy to read from.

No, this is not possible. The datasheet of the ATmega328P
states it has:

8-channel 10-bit ADC in TQFP and QFN/MLF package
6-channel 10-bit ADC in PDIP Package

If you want to use a bare chip, it won't be possible with a PDIP
package.

A Nano and some ProMinis have all 8 analog input pins available from the 32-pin TQFP Atmega328P package. An Uno only has 6 of the 8 available in the 28-pin DIP package. Instead of the bare 28-pin DIP, use one of the 32-pin TQFP parts, on a breakout board, or as a packaged 'system' board; a Promini is the 328P with resonator and voltage regulator, connect to it with external FTDI module for programming/debugging; the Nano which goes a step further and adds a USB interface chip.


text:
Serial communication between Python & Arduino:
I need to transfer information between pyton script and arduino.
Data is always built like this "wheelbase:1000"
wheelbase can be another word and 1000 can be another value, : is always the separator
Here is my python code:
import serial.tools.list_ports
import serial
import time

ports = list(serial.tools.list_ports.comports())

for p in ports:
    print(p)

mcustring = str(ports[0]).split(" ")[0]
print(mcustring)

mcu = serial.Serial(mcustring, 9600)
mcu.timeout = 0.1

def write_read(x):
    mcu.write(x.encode())
    time.sleep(0.05)
    data = mcu.readline()
    return data

num = "wheelbase:1000\n"

for i in range(10):
     print(i)
     num = "wheelbase:1000"
     value = write_read(num)
     print(value) # printing the value
     time.sleep(1)        # wait 0.5 seconds
     num = "wheelbase:500"
     value = write_read(num)
     print(value) # printing the value
     time.sleep(1)

value = write_read(num)
print(num) # printing the value
time.sleep(1)

mcu.close()

and here is my arduino code:
String SerialRead1;
String SerialRead2;
double Wheelbase = 0;
double Level0 = 0;
double Gradient = 0;

void setup() {
  // put your setup code here, to run once:
Serial . begin ( 9600 ) ;        // turn on Serial Port
pinMode(LED_BUILTIN, OUTPUT);

}

void loop() {

  while (Serial.available() > 0) {
  SerialRead1 = Serial.readStringUntil(':') ;
  SerialRead1.trim();
  SerialRead2 = Serial.readStringUntil('\n') ;
  SerialRead2.trim();

  Serial.print ( "string1: " ) ;
  Serial.println(SerialRead1);
  Serial.print ( "string2: " ) ;
  Serial.println(SerialRead2);

  }

  if (SerialRead1 == "wheelbase"){
   Wheelbase = SerialRead2.toDouble();
  }

  if (SerialRead1 == "level"){
   Level0 = SerialRead2.toDouble();
  }

  if (SerialRead1 == "gradient"){
   Gradient = SerialRead2.toDouble();
  }

if (Wheelbase == 1000) {
    digitalWrite(LED_BUILTIN, HIGH);
}
else
{
    digitalWrite(LED_BUILTIN, LOW);
}

}

Here is my serial outpout:
COM6 - USB-SERIAL CH340 (COM6)
COM6
0
b''
b''
1
b''
b'string1: wheelbase\r\n'
2
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
3
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
4
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
5
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
6
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
7
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
8
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
9
b'string2: 500\r\n'
b'string1: wheelbase\r\n'

I don't understand why , for i=0 qnd i = 1 the dqtq is not correctly transfered/received.
The LED blink correctly for i = 2 to 9


text:
Uno with LCD acting strangely - power issue?
I've got a Uno (Elegoo UNO R3) running with
- Ethernet shield (Kuman K15),
- 4 relay board (Elegoo 4 Channel DC 5V Relay Module with Optocoupler )
- Matrix Orbital 2041 LCD connected via I2C (11mA typical, 90mA with backlight)
- A series of buttons connected
The Uno is currently running plugged in via USB to my macbook pro.
All of these devices are powered by the 5V pin on the Arduino.
The LCD goes wonky from time to time, and other times will work fine, it starts flashing the backlight, and just behaves oddly, sometimes even rebooting, when buttons are pushed (which activate the relays).
I'm wondering if this a power issue, perhaps the Uno isn't able to supply enough current to run everything.
My reading indicates that the USB port should be able to provide ~400mA, and when on an external supply I should able to draw 900 mA when using an external power adapter.  However even with on an external supply (12v, 2A) I still have these issues.
Any thoughts would be much appreciated.
Thanks

I have found that my UNOs act MUCH better when given a proper power supply instead of trying to run them from USB power.  Have you tried that?

System resets can be caused by power droop and by noise at the Reset pin, among other reasons.  The problems mentioned could be due to power issues, or to electrical noise, or to wiring issues.
The total current draw apparently could approach or exceed the 400 mA mark mentioned in the question.  With all four relays on, and coils drawing 50 mA each, that's 200 mA.  LCD backlight and Arduino current make another 100, after which the ethernet shield could bring the total above 400 mA.
However, having the problems persist even with an external supply in use would suggest the root of the problems isn't power – if, of course, the external supply actually is supplying power directly to some of the peripherals, rather than via the regulator on the Uno.
When relays switch, they typically produce an electrical noise pulse.  If this is the problem, it could be mitigated using ferrite beads, chokes, noise filters, etc.  Using a separate power supply for +5 V to the board also should help.
Wiring issues include ground bounce and ground loops.  If you are using a breadboard, there may be poor ground or power connections.  Check that the grounds of peripheral devices and external supplies are solidly connected by decent wire and/or connected at a common point.

At this point I've tried providing the LCD with its own 5 volt power source, and that has helped satabalize the display.  However with a lot button pushing quickly (and correspondingly switching the relays on/off) I'm still able to get it to reset.
My relay board has a jumper which disconnects the relay power from the input power - pulling that jumper seems to help. thanks for your suggestion on powering the relay board separately, that seems to be the fix.


text:
How to power Arduino and shields with 4 rechargeable AA batteries?
To start, I am a software guy, and I really want to ensure I not going to destroy any components. I previously looked at power through a USB power bank, but the issue with these is that they turn themselves off with low current pull.
My question is: I have a number of Arduino shields and would like to power them with 4 rechargeable AA batteries, and therefore would like some advice on what to use without frying any electronics.
The rechargeable batteries I have are these 1.2V AA (NiMH). Going on their rated value they should supply 4.8V. Testing the 4 batteries in serial gives me 5.3V overall, or around 1.325V per battery at full charge.
So if the batteries provide more than 5V, I cannot safely plug them into the 5V pin on the Arduino. But if the batteries could potentially provide around 4.8V to 5.5V plugging them into VIN means that the voltage regulator will take too much power, reducing the overall voltage to be too low for all of the shields (Which require 5V). What should I do in this situation?
This is a list of the current equipment that will require power:

Arduino Mega 2560
SIM900 GPRS/GSM Shield
Sparkfun GPS Logger Shield
Sparkfun Wifi Shield - ESP8266

The shields will be stacked on top of each other.

Check the absolute maximum ratings for the main ICs and modules on those boards - you will most likely find that they are fine up to 5.5V, except those that take 3.3V of course. The only issue you may have at 5.5V is a 3.3V device sending data to the Arduino may not have a high enough voltage on the HIGH logic level to register on the Arduino so will need a level shifter.

Hey, I asked a very similar question and just saw yours. Did you end up using an UBEC?

I did end up using a UBEC and it worked great!

Most 5V devices will function fine at up to 5.5V - however, check the datasheets for the major components and modules on the boards.
The main thing to watch though is that a 3.3V device, which can normally communicate fine with a 5V one, may not be able to. The problem is that the logic HIGH signal from the 3.3V device may be below the threshold for a logic HIGH on the Arduino:
V_IH = 0.6Vcc = 0.6 x 5 = 3V

V_IH = 0.6Vcc = 0.6 x 5.5 = 3.3V

Thus a 3.3V device would have to output at the very minimum 3.3V as a logic HIGH in order for it to register as one on the Arduino, which may be a problem...
You can easily drop the battery voltage by 0.7V though by inserting a single silicon diode (such as the trusty 1N4001) in series with the batteries. That will take your voltage down from your measured 5.3V down to 4.6V which will improve matters somewhat.
However, it is important to note that you have so far measured the open circuit voltage of the batteries. That is, the voltage with no load on them. The voltage will most likely be lower once they are actively driving the Arduino etc.
The Arduino itself will be fine running off 5.3V, so I suggest you power just the Arduino direct into the 5V pin from the batteries and measure the actual voltage while powering the Arduino. That will give you a more accurate voltage reading. Then, if needed, you can add the diode to drop it by 0.7V.

The sim module I am using (this one) lists a max voltage of 5.2V. The other 2 boards say they take Arduino 5V and regulate it down to 3.3V (can't find a max voltage). Would it potentially be better to use 6 of the same AA batteries in the VIN pin, giving around of 7 - 8V regulated down to 5V on the Arduino?

Using the in-built regulator is wasteful. You'd be better off using a switch regulator from 6 batteries (search: UBEC).

So using a UBEC such as this would allow me to wire from 6 AA batteries -> UBEC -> 5V Arduino pin, with a maximum available current of 5A for Arduino and shields (of which I should only need max 2A)?

Yep, that would be ideal. Feed it at least 6.6v and you will get lots and lots of 5v power.

Make sure you have a UBEC with low quiescent current. I found one that had 20mA of quiescent current, which would by itself drain the batteries in 3.5 days.

@Gerben That's still far better than an LDO though...

Also, all 3 shields have level shifting circuitry, so the logic HIGH threshold problem described here doesn't apply in this case.

@Gerben That's good then - it should be OK with just the batteries into 5V then as long as the loaded voltage drops fractionally from the OC voltage, which I would expect it to.

@Majenko  quiescent current of the LDO on the Mega (NCP1117ST50T3G) is around 6mA

@Gerben ... as long as the level shifters work in both directions, and not just to drop the 5V down.

@Gerben Add to that the losses from the voltage regulation...

@Majenko Kind of depends on how much the uC is sleeping. If it sleeps a lot, those extra 14mA of current can make a bit difference. So it (as always) depends. PS The level shifting was with mosfets, or dedicated ICs. No resistor divider nonsense.

@Gerben A rubbish UBEC us usually somewhere between 80 and 90% efficient. An LDO barely manages to break 60% efficiency, and then only if the input voltage is only slightly higher than the output voltage.

@Gerben But if sleeping is involved, as well as shutting off power to peripherals, then you need a better regulator that can switch between PWM and PFM at low current draws.

@Gerben My regulator of choice for battery operation is the TC105 - 57µA quiescent, 92% efficient. Runs a sleeping PIC32 off a PP3 for a year.

@Majenko To confirm, feeding the power through the arduino 5v pin allows the full 5A of current to be available to all shields on the stack, whilst also safely powering all shields with the 5v?
As the docs for the SIM900 state that I should be powering with external power, this setup does do that, just via the 5v pin instead of the jack connector?

Yep. Just don't melt the pins with too much current...