text:
SoftwareSerial returns garbage when powered externally
I'm currently working on a project with the ESP8266 and Arduino Nano, and when I power the device via USB they talk to each other via SoftwareSerial just fine. I use the Arduino IDE Serial Monitor to monitor this communication. But when I power it with a 15 V wall wart to Vin it returns mostly garbage, again I can tell this with the Arduino IDE Serial Monitor (I know I shouldn't connect two power supplies at a time). When powered over 5 V USB everything is great. Why would I have a problem only when connected to an external power supply?

Have you measured this wall wart? 15V is high for Vin, and it might be noisy conceivably. Try a different one. Preferably lower voltage.

I did measure it. 15v is whats coming out. How would i check noise?

Put the meter on AC voltage and see if you get any reading. Try a different wall-wart. Recommended input voltage is 7 to 12 V.

@NickGammon i dont have another voltage supply. Can i use a voltage divider?

Voltage dividers are not recommended as voltage regulators. Are you using a level shifter for communicating with the ESP8266? Plus, can you measure what voltage is on the 5V pin when you are powering the Nano from the wall-wart?

@NickGammon im using a voltage divider for comm to esp. Yes i will measure it. What am i looking for?

Let us continue this discussion in chat.

"Voltage dividers are not recommended as voltage regulators" - correct that to "Voltage dividers cannot be used as voltage regulators". It's not a question of recommendation, it's simple Ohm's Law that they cannot work.

Just to add my two pence quickly. Is it just that you need to have a common Ground? Try connecting the grounds of both devices together

If you check the specifications they stat 12VDC is the max.  Your on board regulator is probably very hot and either shutting down or allowing the voltage to sag.  You can get a 9V wall Wart for under $5.  the 9V will keep the on-board regulator much cooler and add reliability.


text:
DC motor not start?
My aim is to create a simple obstacle avoiding robot using Arduino.
I have used L293D motor shield to drive the DC motors and supply it all with 12 V. I am using a sonar module to detect the obstacles. I have used an IR Receiver to control the motors of the robot.
From the serial prints I can tell that every IR signal is received and the expected functions are called. Unfortunately, when I press the button to start the motor, the motor does not start.
When I remove IR Receiver and start robot the code works fine.
In my code posted below I have commented some code so that it only calls the startFan() function.
What is wrong with my code? And how do I fix it?
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
#define MAX_SPEED 75 // sets speed of DC  motors

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(3, MOTOR12_1KHZ);
AF_DCMotor motor3(2, MOTOR12_1KHZ);

Servo myservo;

boolean goesForward = false;
int distance = 100;
int speedSet = 0;

int DisObstaclePin = 0; // This is our input pin
int DisObstacle = HIGH; // HIGH MEANS NO OBSTACLE

int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 11
int power_status ;

IRrecv irrecv(receiver);           // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'

//----( SETUP: RUNS ONCE )----//
void setup()
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");

  int power_status = 0;
  motor3.setSpeed(150);
  motor3.run(FORWARD);

  pinMode(DisObstaclePin, INPUT);
  myservo.attach(9);
  myservo.write(115);
  delay(1000);

  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  DisObstacle = digitalRead(DisObstaclePin);
  delay(100);

  irrecv.enableIRIn(); // Start the receiver

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  Serial.println("Begin loop");
  delay(1000);
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    Serial.println("wada");
    translateIR();
    irrecv.resume(); // receive the next value
    delay(500);
  }

 /* else {
    if (power_status == 1) {
      Serial.println("POWER ON");
      int distanceR = 0;
      int distanceL =  0;
      delay(40);
      if (distance <= 25 || DisObstacle == HIGH)
      {
        Serial.print("Turning");
        moveStop();
        delay(100);
        moveBackward();
        delay(300);
        moveStop();
        delay(200);
        distanceR = lookRight();
        delay(200);
        distanceL = lookLeft();
        delay(200);

        if (distanceR >= distanceL)
        {
          turnRight();
          moveStop();
        } else
        {
          turnLeft();
          moveStop();
        }
      } else
      {
        moveForward();
        Serial.print("Forword");
      }
      distance = readPing();
      delay(50);
      DisObstacle = digitalRead(DisObstaclePin);
      delay(50);
    }if (power_status == 0) {
       Serial.print("POWER OFF");
    }
  }
  */

}/* --(end main loop )-- */

/*-----( Functions )-----*/
void translateIR() // takes an action based on the IR code received
{
  switch (results.value)
  {

    case 0xFF30CF: Serial.println("Movement-ON- 1");
      power_status = 1;
      break;
    case 0xFF18E7: Serial.println("Movement-OFF -2");
      power_status = 0;
      break;
    case 0xFF10EF: Serial.println("Fan-on-3");
      startFan();
      break;
    case 0xFF38C7: Serial.println("Fan-off-4");
      stopFan();
      break;
    default:
      Serial.println(" other button   ");
  }
  delay(500); // Do not get immediate repeat
} //END translateIR

int lookRight()
{
  myservo.write(50);
  delay(500);
  int distance = readPing();
  delay(100);
  myservo.write(115);
  return distance;
}

int lookLeft()
{
  myservo.write(170);
  delay(500);
  int distance = readPing();
  delay(100);
  myservo.write(115);
  return distance;
  delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if (cm == 0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  delay(100);
}

void moveForward() {

  if (!goesForward)
  {
    goesForward = true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);

    motor1.setSpeed(100); //set the speed of the motors, between 0-255
    motor2.setSpeed(100);
    delay(100);
    motor1.setSpeed(55); //set the speed of the motors, between 0-255
    motor2.setSpeed(55);
  }
}

void moveBackward() {
  goesForward = false;
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);

  motor1.setSpeed(100); //set the speed of the motors, between 0-255
  motor2.setSpeed(100);
  delay(500);
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(BACKWARD);
  delay(300);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(FORWARD);
  delay(300);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

void startFan() {
  motor3.setSpeed(150);
  motor3.run(FORWARD);
  Serial.println("FAN  start  ");
  delay(2000);

}

void stopFan() {
  motor3.run(RELEASE);
  Serial.println("FAN  stop  ");
  delay(2000);
}

==============After change pin attachment =============================
I will change my code as follow and remove , 0,1 pin attachment sensor. Now code like below.
  #include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#define TRIG_PIN A4
#define ECHO_PIN A5
#define MAX_DISTANCE 200
#define MAX_SPEED 75 // sets speed of DC  motors

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor3(2, MOTOR12_1KHZ);
AF_DCMotor motor2(3, MOTOR12_1KHZ);

Servo myservo;

boolean goesForward = false;
int distance = 100;
int speedSet = 0;

int DisObstaclePin = 2; // This is our input pin
int DisObstacle = HIGH; // HIGH MEANS NO OBSTACLE

int receiver = 13; // Signal Pin of IR receiver to Arduino Digital Pin 11
//int power_on;
int fan_status,power_on;

IRrecv irrecv(receiver);           // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'

//----( SETUP: RUNS ONCE )----//
void setup()
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");

  power_on = 1;
  fan_status = 0;

  pinMode(DisObstaclePin, INPUT);
  myservo.attach(9);
  myservo.write(115);
  delay(1000);

  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  DisObstacle = digitalRead(DisObstaclePin);
  delay(100);

  irrecv.enableIRIn(); // Start the receiver

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  Serial.println("Begin loop");
  delay(1000);
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    Serial.print("Start reciving");
    translateIR();
    irrecv.resume(); // receive the next value
  }

  //delay(2000);
  if (power_on == 1) {
    Serial.println("POWER ON");
    int distanceR = 0;
    int distanceL =  0;
    delay(40);
    if (distance <= 25 || DisObstacle == HIGH)
    {
      Serial.print("Turning");
      moveStop();
      delay(100);
      moveBackward();
      delay(300);
      moveStop();
      delay(200);
      distanceR = lookRight();
      delay(200);
      distanceL = lookLeft();
      delay(200);

      if (distanceR >= distanceL)
      {
        turnRight();
        moveStop();
      } else
      {
        turnLeft();
        moveStop();
      }
    } else
    {
      moveForward();
      Serial.print("Forword");
    }
    distance = readPing();
    delay(50);
    DisObstacle = digitalRead(DisObstaclePin);
    delay(50);
  }

  if (fan_status == 1) {
    startFan();
    delay(50);
  } else {
    stopFan();
    delay(50);
  }

 // irrecv.resume(); // receive the next value
}/* --(end main loop )-- */

/*-----( Functions )-----*/
void translateIR() // takes action based on IR code received
{
  switch (results.value)
  {
    case 0xFF30CF: Serial.println("Movement-ON- 1");
      //power_on = 1;
      break;
    case 0xFF18E7: Serial.println("Movement-OFF -2");
      //power_on = 0;
      break;
    case 0xFF10EF: Serial.println("Fan-on-3");
      fan_status = 1 ;
      break;
    case 0xFF38C7: Serial.println("Fan-off-4");
      fan_status = 0;
      break;
    default:
      Serial.println(" other button   ");
  }
  delay(500); // Do not get immediate repeat
} //END translateIR

int lookRight()
{
  myservo.write(50);
  delay(500);
  int distance = readPing();
  delay(100);
  myservo.write(115);
  return distance;
}

int lookLeft()
{
  myservo.write(170);
  delay(500);
  int distance = readPing();
  delay(100);
  myservo.write(115);
  return distance;
  delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if (cm == 0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  delay(100);
}

void moveForward() {
  if (!goesForward)
  {
    goesForward = true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);

    motor1.setSpeed(100); //set the speed of the motors, between 0-255
    motor2.setSpeed(100);
    delay(100);
    motor1.setSpeed(55); //set the speed of the motors, between 0-255
    motor2.setSpeed(55);
  }
}

void moveBackward() {
  goesForward = false;
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);

  motor1.setSpeed(100); //set the speed of the motors, between 0-255
  motor2.setSpeed(100);
  delay(500);
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(BACKWARD);
  delay(300);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(FORWARD);
  delay(300);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
}

void startFan() {
  motor3.setSpeed(30);
  motor3.run(FORWARD);
  Serial.println("FAN start  ");
  delay(100);
}

void stopFan() {
  motor3.setSpeed(RELEASE);
  Serial.println("FAN  stop  ");
  delay(100);
}

Now I notice the M1 motor is not working. My question is also same as this:  Motor shield question But I couldn't understand how to resolve it using my code. Other trouble I notice, a lot of the time the IR Receiver receives my signal. It executes without noticing a new signal. Sometimes it catches my signal.

You use L293D motor shield, but using AFmotor (Adafruit driver motor) libs, which is odd. Posting Schematics would help.

Don't cross post on other SE sites.

@gre_gor Thank ,I removed it. but I still not received any considerable answer.

After reading @dpw's post can you confirm the version of the AdaFruit motor shield you are using?  And the version of AFMotor library that you are using?  v1 and v2 are not cross compatible.

@Matt I check the library content as A4990MotorShild , but AFMotor I couldn't find any version number. And also , I check code without IR RECEIVER all Motors are working fine.

You are using the I2C pins for the ultrasonic sensor(?) would changing them to A0 & A1 be possible.  (Its unlikely to be the problem, but...)

@Matt yes ,i used ultrasonic sensor and I will change and come with comment.

I haven't seen error on your code, what is the output of serial monitor from your edited code? After a bit browsing, perhaps the problem lies with the "irrecv.recume()"

@dpw ,sir now my trouble motor-shield not running(power) M1 motor after , i put IR Receive. When come to the loop it ,only run one motor.With out IR Receiver every thing working perfectly. my question also same as this http://help.wickeddevice.com/t/motor-shield-question/87 but ,I haven't use this kind of library. so , i didn't understand what should i do.

Based on this thread:

https://forums.adafruit.com/viewtopic.php?f=31&t=27069
https://stackoverflow.com/questions/18705363/arduino-uno-pwm-pins-conflict
http://forum.arduino.cc/index.php?topic=97133.0

Both AFmotor library and IRremote are using timer feature. And in addition, IRremote also use TIMER_RESET, which probably causing the motor not function as expected (on comment section)
So the solution available is :

Use another library to drive motor, or you can make you own. See this tutorial.
Edit the library (IRremote or AFmotor) timer configuration (as you can found in the last post of the link I posted)

source: Stack Exchange

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

sort: votes


text:
Why doesn't the Ethernet W5100 shield work on Gigabit switch?
I have an Arduino Uno with an Ethernet Shield based on the Wiznet W5100 chipset :
It worked like a charm until I had to move it to another location and plugged it to a Gigabit switch. I had no link, the plug LEDs were off, or just on for a fraction of a second then off again.
I tried several switches, router and Internet boxes (french Freebox), and I ended up with the conclusion that it doesn't work when plugged onto a Gigabit switch. On every 10/100 switches, it works.
BUT
I also have a W5100 small module not designed like the shield :

This one is working on Gigabit switches !!!
I did see another post here : WizNet W5100 not connecting to modern switches and routers, where someone told the lower bits of the first MAC Address byte should be 00. So I changed the MAC address to 08:af:01:00:00:03 with no more luck, the shield still doesn't get connectivity.
I googled for this but didn't find any resources. I'm surprised this hasn't come over, knowing that so much ethernet shields are out on the market!
I tried a second shield (like the first picture), same issue : no connectivity on Gigabit switches.
I know other old NICs or laptops that don't support Gigabit are working correctly with Gigabit switches that should "pull down" the port to 100 instead of 1000.
Does anyone have an answer about why it doesn't work and how we can have an Arduino work when connected to a Gigabit switch? (other shields?)

The fix for this is to solder a 120 Ohm resistor between pins 1-2 and 3-6 of the RJ45 socket (where pin 1 is closest to the left side of the socket when looking at the top of the board. (Credit to keithsw1111 for the fix)
See https://forum.arduino.cc/index.php?topic=372779.0 for full details.
I know this was asked a long time ago however this post comes up quite high on a google search of the issue so its good to have reference to the fix.

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


text:
Stepper motor moves initially but after idle time, clicks and doesn't move for a while
I am using the Accelstepper library to control a stepper motor, according to commands input via Serial.
It works as expected for the first time when I start Serial Monitor and send command.
When left idle for some seconds (> 10 seconds), the motor makes clicking sounds for the first few commands(without moving) and then it starts working again as expected. The longer I leave it, the more commands it misses.
It gets resolved if I restart Serial Monitor on UNO.
#include <Arduino.h>
#include "AccelStepper.h"

#define STEPPER_X_STEP_PIN 2
#define STEPPER_X_DIR_PIN 3

enum Direction { FORWARD, BACKWORD } direction;

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

void blockingRunSpeedToPosition();

AccelStepper stepper(AccelStepper::DRIVER, STEPPER_X_STEP_PIN, STEPPER_X_DIR_PIN);

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(200.0);
  stepper.setAcceleration(50);
}

void loop()
{
  // print the string when a newline arrives:
  if (stringComplete) {
      // clear the string:
      inputString.trim();
      if(inputString == "x") {
          direction = FORWARD;
          blockingRunSpeedToPosition();
      }
      inputString = "";
      stringComplete = false;
    }
}

void serialEvent() {
    while (Serial.available()) {
        char inChar = (char)Serial.read();
        inputString += inChar;
        if (inChar == '\n') {
          stringComplete = true;
        }
    }
}

void blockingRunSpeedToPosition()
{
    int steps = 400;
    stepper.setCurrentPosition(0);
    stepper.move(steps);
    while (stepper.distanceToGo() != 0) {
           stepper.run();
    }
}

I think there is no issue with the code or my Arduino connection since the motor runs fine in the beginning.
I tried the above code on Arduino MEGA, UNO, different motors with different drivers. The problem persists.
I think it is something to do with motor excitation (energized coils).
Please give me some hints and pointer to debug the issue, since I don't know where to look. I am an intermediate programmer and robotics hobbyist.
Here is the video demo of the issue.
I am using:

Arduino MEGA - ATmega2560
NEMA 23.
Rino stepper motor.
Arduino Pin 2 is Step and 3 is Direction.
Driver Vcc is connected to 5V pin.
48 volt, 5 Amps SMPS.
Ubuntu 16.
Accelstepper library

Reopening the serial monitor probably resets your Arduino, clearing problematic state in the code.  Your program is not very well architected - there's no real point to the expensive String operations you do, or to using the serial event to set a flag you read  in the main loop.  Consider handling everything in the main loop on a character-by-character basis.

Just checked, restarting serial monitor fixes the problem only on UNO. On mega restarting doesn't effect.

Will the code keep responding to commands as intended, as long as you don't leave it idle for >= 10 sec?


text:
Can I use atmega328P without capacitors?
I need to use atmega328P without arduino board, so far I know that I will need 16MHZ Quartz Resonator and two 22nf capacitors. However, I have seen that other people are using atmega328P without capacitors.
What is the role of those capacitors? Can I use atmega328P without capacitors?

You need 22pF (picofarad) capacitors, not 22nF.

You also need power supply bypass capacitors.

you can use it without caps and with a crystal, at half speed, but maybe half price too

Those specific capacitors form part of the resonant clock oscillator circuit. If you are using a quartz crystal then they are required. You can't do without them.
If you use a 16MHz ceramic resonator, however, they don't need the capacitors (they're built into the resonator).
Also, if you have your ATMega328P on a breadboard the capacitance of the board itself is sometimes enough to "get it working", though as soon as you transfer your circuit to a permanent PCB it will suddenly stop working for no apparent reason.

One could also use the build-in 8MHz RC oscillator, and remove the crystal entirely.

@Gerben Indeed. Or use an external clock source, like a MEMS oscillator.


text:
ESP8266 PHP Web Server
I need my ESP8266 web server to load my website files with .php extensions. So far I managed to load .htm .css and .js files from my SD card, but when I upload PHP files on my SD card, they won't run. How can I do that?

I am using Wemos D1 mini, documentation doesn't say anything about PHP

golly, that would be really really handy. too bad it's not possible.

You can still achieve that by getting a Raspberry PI and running Linux server on it. Then you will be able to install:
PHP + MySQL + phpMyAdmin and many other features

It sounds like you are trying to put a PHP file on an SD card that the ESP8266 will serve itself.
This is not possible, as no one has, and probably never will, port PHP to the Espressif 8266 platform.
Your device can serve .htm .css and .js files because it's just a matter of streaming the file content to the client. But PHP requires that an application on the server run the PHP code, and then send the resulting output to the client.

Thank you for that information! Looks like I need to buy a Raspberry PI and install Linux server on it


text:
Submit data from HTML form to ESP8266
I need to submit HTML form from my remote website to my ESP8266 server using POST method. I'm looking for something like that :
    <form action="my esp8266 IP" method="POST">
        <input type="text" name="foo" value="go">
        <input type="submit">
    </form>

Can I use IP address in action attribute?
How can I detect and print received data on ESP8266 side?

Can I use IP address in action attribute?

Sure, if your ESP8266 is either on the same internal (behind a NAT router) subnet as your web server, or your ESP8266 has a public IP address.

How can I detect and print received data on ESP8266 side?

By parsing the data as it comes in through the socket.
If your ESP8266 is on your home network and your website is out on the internet somewhere you will have to arrange some form of port forwarding through your router (outside the scope of this site) and have some way of your website tracking your (most likely dynamic) home IP address. Again, outside the scope of this site.
It is much more common to use protocols such as MQTT or another RESTful API to have your ESP8266 check in with a remote server to request updated data and instructions, rather than a web server blindly pushing the information directly to the ESP8266.  This is because:

Putting your ESP8266 directly (or indirectly through port forwarding) on the internet is a security nightmare, and
Putting all the pieces of the jigsaw together to make it work reliably is not trivial.


text:
Assign string to an array value
I need to assign a string to an array value:
char mystr[3] = "Hello";
But when I run this code on arduino simulator: tinkercad.com, I get this error:
1:17: error: initializer-string for array of chars is too long [-fpermissive]
Why I'm getting this error?

You have asked the compiler to allocate 3 char of memory, and then you ask it to fill that memory with 6 bytes of data (5 characters, plus null-char for termination.)


text:
Send an multidimensional array of values from one arduino to another through serial port
I have connected two arduinos using pins: RX and TX and managed to send a string as an array of values:
//sender

char mystr[6] = "hello";

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

void loop() {
  Serial.write(mystr);
  delay(1000);
}

And receive it:
//receiver

char mystr[6];

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

void loop() {
  Serial.readBytes(mystr,5);

  if(mystr[0] == 'h' && mystr[1] == 'e' && mystr[2] == 'l'){

    for(int i = 0;i < sizeof(mystr);i++){

      Serial.print(mystr[i]);

      if(i == sizeof(mystr) - 1){
        Serial.print("\r\n");
      }
    }
  }
  delay(1000);
}

That worked fine! But I need to send and receive something like this:
int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

How can I do that?

CSV seems to match your needs.

Use two for loops to send the multidimensional array, and two for loops to receive the multidimensional array.
Sending:
int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      Serial.print(a[x][y]);
   }
}

Receiving
for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      a[x][y] = Serial.read(); // Not sure about the exact prototype
   }
}

If the sizes are fixed (like in your case 3 and 4), than you don't have to send the dimensions, just sent the values in order: 0, 1, 2, 3, 4, ... like above.
And when receiving them you know the first four values belong to row 0, next four values to row 1 etc.
If you need dynamic sizes, first send the number of rows and columns and than the values.
In that case instead of 3 and 4 define two constants and use them:
#define NR_ROWS 3
#define NR_COLUMNS 4

int a[NR_ROWS][NR_COLUMNS] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < NR_ROWS; x++)
{
   for (int y = 0; y < NR_COLUMNS; y++)
   {
      Serial.print(a[x][y]);
   }
}

This doesn't work. Serial.print sends the integer as a string and Serial.read() then reads the ASCII value of a single digit. This makes it impossible to receive numbers with multiple digits like 10 and 11.

The code also never checks if Serial.read() returns -1. Which happens because it gets desynced from the previous problem. Or it could happen during the array transmission, because nothing guarantees that the array gets transmitted in a single chunk.

And the array consists of int elements, so it should send and receive two bytes per element.


text:
Can I remove soldered atmega328P from arduino board, using hot air gun, without damaging it?
I need to remove atmega328P from arduino board and the best tool what comes up to my mind is a hot air gun. What is the maximum temperature that atmega328P can withstand?

A decorating style hot air gun? No, definitely not. You need a proper reflow station, or you will end up melting everything.

The SMD version or the DIP version? The DIP can be desoldered, one pin at a time, with e.g. a solder-sucker/solder-pump. I've desoldered SMD chips by putting the entire board into a (old) pan, an heating it on a furnace. Crude, but works when in a pinch.

new boards are under $5, is an hour or two of time for an uncertain outcome worth it?

This really seems like it would be more appropriate on [electronics.se].

You are likely to damage the connectors and displace small surface mount components before you damage the chip.  A heat gun would not be recommended if you want to preserve the board, but it could with skill be used to salvage the chip.  For a DIP package you should heat from the underside, and that can be an option for surface mount as well.

web search reveals the peak reflow temperature is 260°C
the chip will withstand that for 15 seconds or so
here is an example graph of a reflow oven temperature during the reflow process

This is of course a specification under which the manufacturer is willing to say the chip will work.  Often for personal/experimental use things far, far worse are survivable.

@Kirill there is no practical guidance here.  Oven reflow and hot air rework are very different operations and it's all but certain that anyone using a temperature controlled hot air station would set it notably higher than this implies.   So it's sad to see you pick this as an answer.

The idea of using a simple "heat gun" (such as this) will fail on two fronts:

You can't control the temperature. It will get too hot and you will damage the chip.
You can't control the hot air. It will melt all the plastic items on  the board (the connectors, etc) and you'll just end up with a big blob of bubbling plastic.

You need a proper reflow station. These are to a heat gun what a soldering iron is to a blow torch. They are temperature controlled, so you can select a specific temperature (with reference to the datasheet of the component you want to (de)solder), and have interchangeable nozzles to allow you to accurately direct the heat where it is needed.
I use the (cheap) Atten 858D+.

Actually, you can control the temperature with either a heat gun or a blow torch, by controlling distance and time.  Both have a long tradition for salvaging ICs for hobby re-use off boards to be scrapped (especially in the DIP era), but yes, damage to plastic connectors is probable, and with a torch, the PCB substrate as well.  Also vile smoke.

@ChrisStratton You can't control the heat accurately. There is no feedback, other than "it feels too hot" - and you can't really tell the difference between 200C and 400C and still keep the skin on your hand.

Untrue.  You know it's hot enough when the chip you've been lightly pulling on comes out.  You also see the solder change appearance, and quickly learn other ways of judging - just as you do when using a precision hot air tool.  Doing it from the reverse side of the board also simplifies things greatly, since you get the board and the pins which need to be hot, hot faster than the package.

@ChrisStratton And all the other components fall off too, or blow off because there's far too much air being blown, and the connectors all turn to syrup. While it is possible, on some boards, and with plenty of practice, to use a decorating heat gun, in general it's a really bad idea.

As said right at the beginning, it's often useful for salvaging chips at the cost of the board.

@ChrisStratton You can do the same putting the board upside down in the oven and whacking the temperature right up. There is, of course, a higher chance you will kill the chip by using such crude tools as these.

The ATMega328P comes in 2 packages. DIP(Dual Inline Package) and SMD(Surface Mount Device)
The Hot Air Gun method is only best applicable to the SMD version. I would recommend you to not focus on what temperature the board can withstand, but try to practice on the hot air soldering techniques.
First try to practice removing SMD components on a separate PCB so you can be familiar with the hand movements and the techniques in safely removing SMD components. When you are familiar enough with the hand movements and techniques, then that is the best time to work on your Arduino Board.
After doing this you should be able to remove and SMD components from any type of circuit boards.
PS. Be sure to use a lot of soldering paste when using hotair reflow ;)

Actually, in some ways a heat gun is more applicable to a DIP, and that's one of the few cases I might use one rather than a precision hot air tool.  The cost of likely damage to the rest of the board.

Thats correct. if the DIP is soldered on the board and has many more than 4pins, then the heat gun will come in handy. Still each person has its own way/learned technique by practice to remove components using different tools :)


text:
Using Arduino Uno as USB to serial converter
Can I use my Arduino Uno as a USB to serial converter to program my Raspberry pi 0 over serial communication?
My idea: Computer connects to Arduino via USB > Arduino connects with Raspberry pi 0 via GPIO pins.
How do I go about this?

Have you heard about SSH?

You probably can - but what are you trying to achieve? What's wrong with the normal methods which makes you want to do it this way?

I have the Raspberry pi 0 without WiFi, so SSH is no option for me. I would like to communicate with it over serial line. Since I have an Arduino anyway, I thought that might work to program the pi.

You may also put Arduino in a reset state then Rx & Tx lines of serial converter will be free.

If you load an empty program in your arduino, and make the folowing connections:
Pi  -->  Arduino
Pin 8 --> Pin 1
Pin 10 --> Pin 0
Gnd --> Gnd
than you should see your linux console in the arduino serial program is you set the baudrate to 115200.
This method will work for the raspberry pi models without wifi.
On the wifi models the pins on the pi will be different.
The Arduino uses FTDI usb-to serial converter. This converters uart side is connected to the AVR-chip via pin 0 and 1. If you load an empty program in your arduino, it wil not use these lines. Now you can connect directly to the FTDI chip thru this pins. The converter does not care if it is communicating with the arduino or the pi over these lines.

The Arduino uses FTDI usb-to serial converter. This converters uart side is connected to the AVR-chip via pin 0 and 1. If you load an empty program in your arduino, it wil not use these lines. Now you can connect directly to the FTDI chip thru this pins. The converter does not care if it is communicating with the arduino or the pi over these lines.

The Arduino uses FTDI usb-to serial converter. ... that is not true for UNO

They changed the FTDI with a compatible Atmel part between revisions, but the concept stays the same as with the FTDI.

In the arduino ide, go to file > examples > arduino as isp.
Might be a good starting point.
Seems like a lot of work though. If I were in that situation then I'd either use an ethernet cable and SSH, or, use a mobile phone as a WiFi hot-spot.

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


text:
Arduino ProMini green led flashing and unable to reset
so I'm using a promini running on solar power. For some reason, after sometime it gets stuck with the green led flashing and only by cutting power can I reset the promini. Even the reset button doesnt work. Exactly like in this post "Watchdog timer stuck in restart loop? (green led flashing)". However, the strange thing is that I am not even using a watchdog timer. So what could be the cause of it? Could it be due to the lack of power from my solar panel?
Here is my code
#include <SPI.h>
#include <RF24.h>

int green = 8;
int red = 6;

// ce,csn pins
RF24 radio(9,10);

// init data buffer to hold a sensor type byte and one uint16_t sensor data
unsigned char data[3] = {
  0};
unsigned long count=0;

void(* resetFunc) (void) = 0;//declare reset function at address 0
void setup(void)
{
  pinMode(4, OUTPUT);
  digitalWrite(4,HIGH);
  pinMode(5, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(red, OUTPUT);
  pinMode(3, OUTPUT);

  Serial.begin(57600);
  Serial.println("**************V1 Send Sensor Data***********");
  radio.begin();
  radio.setPALevel(RF24_PA_MAX);
  radio.setChannel(0x4c);

  // open pipe for writing
  radio.openWritingPipe(0xF0F0F0F0E1LL);

  radio.enableDynamicPayloads();
  radio.setAutoAck(false);
    radio.setDataRate(RF24_1MBPS);
  radio.powerUp();
  Serial.println("...Sending");

}

void loop(void)
{
  digitalWrite(5,HIGH);
  delay(50);
  uint16_t sensorValue = analogRead(0);
  digitalWrite(5,LOW);

  Serial.println(sensorValue);
  if (sensorValue > 600){
    digitalWrite(red,LOW );
    digitalWrite(green,HIGH);
  }
  if (sensorValue >= 0 && sensorValue <= 300){
    digitalWrite(red,HIGH);
    digitalWrite(green,LOW);
  }

  //assign identification to the node.
  // In use = A & B;
  data[0] = 'B';
  //do the bit shift to put uint16 into uint8 array
  data[1] = sensorValue >> 8;
  data[2] = sensorValue;
  Serial.print(count);
  Serial.print("   |   Identity: ");
  Serial.print(data[0]);
  Serial.print("   |   ");
  Serial.print(" data[1]: ");
  Serial.print(data[1]);
  Serial.print("  |  data[2]: ");
  Serial.print(data[2]);
  digitalWrite(3,HIGH);
  // print and increment the counter
  radio.startWrite(data, sizeof(uint16_t)+1);
  Serial.print("  | Temperature sent:  ");
  Serial.println(sensorValue);
  digitalWrite(3,LOW);
  // pause 5 seconds
  delay(5000);
  resetFunc();  //call reset
}

Thank you so much!

Have you measured the Vin voltage when this happens?

Your solar system must not provide more voltage than the Arduino is designed for, and when the voltage falls too low the system must reset properly - usually by using a brownout detector function.


text:
Fog Machine - On Command
I work with a marching band, and we want to use fog machines for a particular part of the show. I know how to code/program in Arduino, however I am not great in the electrical and technical end. I own two fog machines, and the issue is that we need them to start fogging on command without delay (at least not a long delay, just not early and not late). We cannot exactly stop the show in the middle of a competition to say "wait, the fog is coming soon." We also need them to stop fogging on command.
I have read this article, Motion Triggered Fog Machine and it seems simple enough, however, I do not need or want it to work with a motion sensor. I suppose the easiest way you could help me is to either point me to a tutorial or tell me how to modify that tutorial to my own needs.

we need them to start fogging on command; Where do the commands come from. A human pressing a button? A PC running some software? DMX controller? Smartphone? Without some additional info, we can't add anything that isn't already in the instructable you mentioned.

@Gerben Well, it would be nice if I could do it from a smartphone.

So basically you don't know yet. How then, are we supposed to be able to help you?

@Gerben I need help figuring out the best option. I need it as simple and easy as possible so that when the fog is necessary it is sent out, and when we need it to stop it stops.

What determines if it is necessary or not? Easiest solution is to just press the on/off button on the fog machine. You give us no information, but expect us to provide you the golden solution.

@Gerben it is necessary to send it out at particular parts of the show, and it is necessary to stop it at certain parts. You're making it more difficult than it has to be. My question was simply, for a show that requires fog to start and stop on command, what is the best option?

Perhaps use a small wireless board like the NRF24L01 (available for around $1 each on eBay). Have one at the fogging machine, similar to the Instructable, but instead of a sensor, you turn the machine on and off when a command arrives. For example, send "0" to turn it off and "1" to turn it on. There are examples with the NRF24L01 library.

Then you have an Arduino in the wings nearby where you press a switch when you need to turn the fogging machine on (this would transmit the signal).

Great modules those.  I have some with power amplifier and SMA antenna. I haven't found the maximum range yet, but it's certainly measured in the hundreds of meters.

@Nick This is wireless also?

Yes, they are wireless transceivers. They communicate using SPI so you would need another Arduino (or similar) to send the command. A small one (like a Mini or Micro) could fit into a small box. The transceiver is pretty small - 30 mm long and 15 mm wide.

@Nick So, I can use this along with the instructable by simply using this instead of the sensor. And, you're saying I would need two arduinos?

Well not exactly "simply using this" - you would need to change the code to read from the transceiver instead of reading from the sensor. You would need an Arduino at each fog machine, and one to have with you to command the others when to turn the fog on and off.

@NickGammon Okay, thank you, I will look more into this.

@NickGammon I suggest that you'd link the maintained fork of RF24 (by TMRh20) instead of the outdated maniacbug's one.


text:
Json gets corrupted after first HTTP request
I'm a web developer and I started building a small environment logger that will post to my website`s API. I'm really new to this kind of coding so bare with me.
Since yesterday, the whole Arduino started to acting funny. After the first or second request to the server(with already tested code), I started sending corrupted JSON data.
{
  ":12": "module3",
  "10-7 18:26": {
    "1": {
      "": 21.50,
      "26:12": 55.50,
      "measured_at": "2015-10-7 18:26:12"
    },
    "2": {
      "": 21.10,
      "26:12": 55.70,
      "measured_at": "2015-10-7 18:26:12"
    }
  }

Where it should be
{
  "modulename": "module3",
  "environments": {
    "1": {
      "temperature": 21.40,
      "humidity": 55.60,
      "measured_at": "2015-10-7 18:25:52"
    },
    "2": {
      "temperature": 21.20,
      "humidity": 55.80,
      "measured_at": "2015-10-7 18:25:52"
    }
  }
}

The second JSON is from the initial request to the server. The first one is the corrupted one. I tried stopping all kinds of parts from the code, without any luck, except when I enter the measured_at manually (without getting the data from the RTC.)
#include <DHT.h>

#include <elapsedMillis.h>

#include <DS3231.h>
#include <Wire.h>
//Json Library
#include <ArduinoJson.h>

#include <Ethernet.h>
#include <SPI.h>

#include <LiquidCrystal.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS
EthernetClient client;

const String module_name = "module3";

DHT dht1;
DHT dht2;

DS3231 clock;
RTCDateTime dt;

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

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

elapsedMillis timer0;
const long interval = 10000; // READING INTERVAL

int connected_sensors = 0;
float t1 = 0;  // TEMPERATURE VAR
float h1 = 0; // HUMIDITY VAR
float t2 = 0;
float h2 = 0;

int nc = 0; //Network connection simulation INI

byte temp[8] = { //icon for thermometer

  B00100,
  B01010,
  B01010,
  B01110,
  B01110,
  B11111,
  B11111,
  B01110
};

byte humi[8] = { //icon for water droplet
  B00100,
  B00100,
  B01010,
  B01010,
  B10001,
  B10001,
  B10001,
  B01110,
};

byte sconnect[8] = { //icon for connection
  0b00000,
  0b11111,
  0b10001,
  0b10001,
  0b11111,
  0b00100,
  0b11111,
  0b00000
};

void setup() {
  Serial.begin(9600);
  clock.begin();
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  Serial.println("Terrarium Serial");
  // Print a message to the LCD.
  lcd.print("Weather v0.1");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print("Sensor loading...");

  lcd.clear();
  lcd.print("Network check...");

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP"); //There is a problem with DHCP
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("DHCP ERROR");
    lcd.setCursor(0, 1);
    lcd.print("Please Restart");
    for (;;)
      ;
  }
  nc = 1;

  delay(2000);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(Ethernet.localIP());
  lcd.setCursor(0, 1);
  lcd.println("Ready!");

  Serial.println(F("Connected!"));
  Serial.println(Ethernet.localIP());

  delay(4000);
  lcd.clear();

  lcd.createChar(1, temp);
  lcd.createChar(2, humi);
  lcd.createChar(3, sconnect);

  dht1.setup(15);
  dht2.setup(16);

  h1 = dht1.getHumidity();
  t1 = dht1.getTemperature();

  h2 = dht2.getHumidity();
  t2 = dht2.getTemperature();

  delay(2000);

  //Display the statics on the display
  lcd.setCursor(2, 0);
  lcd.print(module_name);
  lcd.setCursor(9, 1);
  lcd.write(2);
  lcd.setCursor(15, 1);
  lcd.print("%");
  lcd.setCursor(2, 1);
  lcd.write(1);
  lcd.setCursor(8, 1);
  lcd.print((char)223);

  timer0 = 0; // clear the timer at the end of startup

}
void CheckSensors() {

  if (timer0 >= interval) { // READ ONLY ONCE PER INTERVAL
    timer0 -= interval;

    dt = clock.getDateTime(); //get current time

    h1 = dht1.getHumidity();
    t1 = dht1.getTemperature();

    h2 = dht2.getHumidity();
    t2 = dht2.getTemperature();

    DataSend(); //send data
  }
}

//Print the changeable values on the display
void LcdPint() {
  lcd.setCursor(0, 0);
  if (nc == 1) {
    lcd.write(3);
  } else if (nc == 0) {
    lcd.print(" ");
  } else if (nc == 2) {
    lcd.print("E");
  }

  lcd.setCursor(10, 1);
  lcd.print(h1);

  lcd.setCursor(3, 1);
  lcd.print(t1);

}

//Construct the JSON response
JsonObject& prepareResponse(JsonBuffer& jsonBuffer, String measured_at) {

  JsonObject& root = jsonBuffer.createObject();
  root["modulename"] = module_name;

  JsonObject& environmentsObject = root.createNestedObject("environments");

    JsonObject& environmentsOne = environmentsObject.createNestedObject("1");
    environmentsOne["temperature"] = t1;
    environmentsOne["humidity"] = h1;
    environmentsOne["measured_at"] =  measured_at;

    JsonObject& environmentsTwo = environmentsObject.createNestedObject("2");
    environmentsTwo["temperature"] = t2;
    environmentsTwo["humidity"] = h2;
    environmentsTwo["measured_at"] =  measured_at;

  return root;
}

void writeResponse(EthernetClient& client, JsonObject& json) {

  char buffer[256];
  json.printTo(buffer, sizeof(buffer));

  if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
    client.println("POST /v1/sensors HTTP/1.1");
    client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/json");
    client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
    client.println("Connection: close");
    client.print("Content-Length: ");
    client.println(strlen(buffer));
    client.println();
    client.println(buffer);

    nc = 1;
  } else {
    nc = 2;
    Serial.println("connection failed");
  }

  while (client.connected())
  {
    if ( client.available() )
    {
      char c = client.read();
      Serial.print(c);
    }
  }
  Serial.println();
  client.stop();
  //End  post request

}
void DataSend() {

    //This is the part that I think crashes my entire code. I tried using the helper with the RTC library that I use
    //but that made things worse.

    String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& json = prepareResponse(jsonBuffer, measured_at);
    json.prettyPrintTo(Serial);

    writeResponse(client, json);

}

void loop() {
  CheckSensors();
  LcdPint();
}

It even restarts the whole Arduino. I think this may be a conflict of some sort... I wonder why it shows up now, when I used it for 2 days straight a few weeks ago.

Chances are you're running out or memory.  All that String use certainly doesn't help - get rid of those and things can only improve.

This line, for instance: String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second; will be making swiss cheese of your heap.

I would suggest ditching the JSON library as well, and just building the output up a bit at a time using client.print() - you don't have to send it all in one string, just do it a bit (even a character sometimes) at a time.

Please tell me how you managed to format the code properly... I tried with that <-- language --> thing and i got nothing.
Also I tried removing  the measured_at and added another library, but that didnt help much either ...
http://www.rinkydinkelectronics.com/library.php?id=73
This one i added and still...
I`m a web dev, I write Javascript, this is really frustrating :D Could anyone show me a tutorial for proper ways to write for the Arduino .. I dont know.. I dont want to beg for someone to do it for me...

To format code you indent it by 4 characters (or highlight it and press the {} button above the editor).  To do it inline you place backticks around it (your code = your code)

Oh but the json helper is so nice :D Helps a ton with pretty code. The only string I have is the measured_at var. Can that take up so much RAM to stop the arduino?

Avoid String like the plague. Here's why: http://hacking.majenko.co.uk/the-evils-of-arduino-strings

I think that i`m getting over my league with this project of mine .... Eighter my code is really bad or the Uno is not suitable for my project (if I want to add more sensors).

The Uno can be a very capable board - you just have to remember that it is not a computer and has incredibly limited resources. Wait for my answer for some more pointers.

Oh great! What about splitting the code into function and files. I`m used to writing javascript and using Require.js and I cant stand code in one place :D Does that slow down the Arduino as Well ?

That makes no difference.

Great, good to know.

You have used 461 out of 2048 of your RAM bytes for string literals alone. At the very least, use the F() macro where you can, eg.
client.println(F("POST /v1/sensors HTTP/1.1"));
client.println(F("Host: api.terrariums.eu")); // SERVER ADDRESS HERE TOO
client.println(F("Content-Type: application/json"));
client.println(F("Authorization: Basic bW9kdWxlMzoxMzIxMzI="));
client.println(F("Connection: close"));
client.print(F("Content-Length: "));

Ditto for Serial.print and lcd.print where you are printing strings.
After that, what Majenko suggested is a good idea. Using a custom library is well and good, but JSON is easy enough to output directly. Just make a small function to do it for you.

Problem now is the Content-length... How do I calculate it ?

Do you absolutely need it? If you do, instead of building up the entire content first, I suggest two passes.
First pass outputs to a dummy class which simply calculates the length, second pass actually outputs. Something like this:
// outputting class that just counts output
class DummyOutput : public Print
{
private:
  unsigned long length_;

public:
  void begin ()
    {
    length_ = 0;
    }
  virtual size_t write (byte c)
    {
    length_++;
    return 1;
    }
  unsigned long getLength () const { return length_; }

};  // end of DummyOutput

DummyOutput countOutput;  // instance of DummyOutput

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

  Print * outputter;  // where to write to

  for (int pass = 1; pass <= 2; pass++)
    {
    randomSeed (1);
    switch (pass)
     {
     case 1: outputter = &countOutput;
             countOutput.begin ();
             break;

     case 2: outputter = &Serial;
             break;
     } // end of switch

    // generate some output
    for (int i = 0; i < 25; i++)
      {
      outputter->print (random (5000));
      outputter->print ('\n');
      }

    switch (pass)
     {
     case 1: Serial.print (F("Content-length: "));
             Serial.println (countOutput.getLength ());
             break;

     case 2: break;
     } // end of switch

    }  // end of for loop
  }  // end of setup

void loop ()
  {
  }  // end of loop

Output:
Starting
Content-length: 121
1807
249
73
3658
3930
1272
2544
878
2923
2709
4440
3165
4492
3042
2987
2503
2327
1729
3840
2612
4303
3169
2709
2157
4560

By generating the same output in two passes you can first just calculate the length (without outputting) and the second time you can output that length first, and then output the actual data.

I already did the json with print only, as ugly as it is it works. Problem now is the Content-length... How do I calculate it ?

See amended reply.

In all probability you are either running out of memory, or the libraries you are using (and the fact that you are abusing String objects) is fragmenting your heap to such an extent that your whole 2KB of RAM is being used and you are ending up with a stack-and-heap collision.
You have to remember that the Arduino Uno only has 2KB of RAM.  It's not a computer, and has no OS, and as such you have to unlearn much of what you know about programming and do things slightly differently.
The first problem you have is with your String abuse.  This line:
String measured_at = (String) dt.year + "-" + dt.month + "-" + dt.day  + " " + dt.hour   + ":" + dt.minute + ":" + dt.second;

will be doing horrible things to your heap.  The String class dynamically allocates memory on the heap to store the string content.  The operations you have there inadvertently create a rather alarming number of temporary Strings which are then thrown away at the end.  Every temporary String dynamically allocates RAM on the heap and can potentially lead to heap fragmentation.
For instance the numeric value dt.second is first converted to a String and memory allocated to store the content.  Every concatenation results in a new String with its dynamic allocation, etc.  Quite messy really.
Secondly, who knows what dynamic memory the ArduinoJSON library is using - quite a lot would be my guess - every tag, every value, etc, would need to be stored in memory somewhere, and unless they statically allocate a huge chunk of RAM (wasting most of your precious resource) they will be doing dynamic allocation - and that will make matters much worse.
So how would you get around it? It's actually quite simple - you need to think more about spoon-feeding a baby instead of preparing a 5 course banquet.
Instead of building up big objects with lots of data in them and sending them all out in one big chunk you need to just send little bits at a time.  There is absolutely no reason to use things like ArduinoJSON if all you are doing is sending data.
For instance to send the JSON data you could do something like this:
  if (client.connect("api.terrariums.eu", 80)) { // REPLACE WITH YOUR SERVER ADDRESS
    client.println("POST /v1/sensors HTTP/1.1");
    client.println("Host: api.terrariums.eu"); // SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/json");
    client.println("Authorization: Basic bW9kdWxlMzoxMzIxMzI=");
    client.println("Connection: close");
    client.println();

    client.println("{");
    client.println("    \"modulename\": \"module3\",");
    client.println("    \"environments\": {");
    client.println("        \"1\": {");
    client.print("            \"temperature\":
    client.print(t1);
    client.println(",");
    client.print("            \"humidity\":
    client.print(h1);
    client.println(",");
    client.println("        },");

Etc.  You get the drift.
You notice I removed the Content-length header?  That's because you don't know how long the content will be now (one drawback), so to signal the end of the transmission you will have to close the connection (I don't recall if client has a way of only half closing - just the TX portion) to signal to the web server that you have finished.  However, if you know how long your numbers will be (say you format them to a specific number of characters) then your body size would always be the same and you can hard code a Content-length header.
Also - do you really need to send the time and date?  Surely the computer has a better idea of what the current time and date is than the Arduino - just use the computer's internal clock.

Really nice, thank you. I decided that it was a good idea to have the date as it will store when the measurements were taken. Ofc I can use the moment when the code enters my API but I thought this wouldnt be a problem at that time.

Use the same trick for sending the date and time then. Instead of pre-formatting it as a String, just send each individual entry with  a separate client.print().

Ok. Will keep you updated.

How should I close the connection when I cant send a Content-length header?

Client.stop does that.

I did it but I got no response from the server then.
BTW using F() I got the original code down to 50% memory usage and it works now. But I will try to follow your advice.

I always forget about F() - I rarely actually use the Arduino, instead using a board that uses the Princeton monolithic memory architecture not the Harvard split bus architecture, so F() does nothing for me.


text:
Arduino declaring class in h and cpp file Undefined Reference
I am trying to compile my project, but unfortunately get errors.
I created class and separated implementation and declaration (cpp file and h file)
Here they are
sensor.h
#ifndef SENSOR_H
#define SENSOR_H
#include <stdint.h>
#include "Arduino.h"
// Sensor types
enum SensorType {
  ANY_SENSOR,
  UNKNOWN_SENSOR,
  WATER_SENSOR,
  TEMPERATURE_SENSOR,
  VIBRATION_SENSOR,
  INTERCOM_SENSOR,
  HUMIDITY_SENSOR,
  PIR_SENSOR,
  SOUND_SENSOR,
  LIGHT_SENSOR
};
class Sensor {
  public:
  // Variables declaration
    uint32_t sensorId;
    SensorType sensorType;
    float currentValue;
    bool isEnabled;
    float criticalLowerLevel;
    float criticalUpperLevel;
   // Methods declaration
    Sensor();
    Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper);
    String toString();
    bool isCriticalLevelRised() {
      return (this->currentValue >= this->criticalUpperLevel || this->currentValue <= this->criticalLowerLevel);
    };
    void enable(bool enable);
    void toggle();
    static String convertSensorTypeToString(SensorType sensorType);
};

#endif

And cpp file
#include "sensor.h"
Sensor::Sensor()
{
  this->sensorId = 0;
  this->sensorType = UNKNOWN_SENSOR;
  this->currentValue = 0;
  this->isEnabled = false;
  this->criticalLowerLevel = 0;
  this->criticalUpperLevel = 0;
}
Sensor::Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper) {
  this->sensorId = id;
  this->sensorType = type;
  this->currentValue = currentValue;
  this->isEnabled = isEnabled;
  this->criticalLowerLevel = lower;
  this->criticalUpperLevel = upper;
}
void Sensor::enable(bool enable) {
   this->isEnabled = enable;
}
void Sensor::toggle() {
  this->enable(!this->isEnabled);
}
String Sensor::toString()
{
  String response = "";
  response += F("Sensor id is ");
  response += this->sensorId;
  response += '\n';
  response += F("Sensor type is ");
  response += convertSensorTypeToString(this->sensorType);
  response += '\n';
  response += F("Sensor current value is ");
  response += this->currentValue;
  response += '\n';
  response += F("Sensor isEnabled is ");
  response += this->isEnabled;
  response += '\n';
  response += F("Sensor criticalLowerLevel is ");
  response += this->criticalLowerLevel;
  response += '\n';
  response += F("Sensor criticalLowerLevel is ");
  response += this->criticalUpperLevel;
  response += '\n';
  return response;
}
String Sensor::convertSensorTypeToString(SensorType sensorType) {
  switch (sensorType) {
    case UNKNOWN_SENSOR:
      return F("UNKNOWN SENSOR");
    case ANY_SENSOR:
      return F("ANY_SENSOR");
    case WATER_SENSOR:
      return F("WATER_SENSOR");
    case TEMPERATURE_SENSOR:
      return F("TEMPERATURE_SENSOR");
    case VIBRATION_SENSOR:
      return F("VIBRATION_SENSOR");
    case HUMIDITY_SENSOR:
      return F("HUMIDITY_SENSOR");
    case PIR_SENSOR:
      return F("PIR_SENSOR");
    case SOUND_SENSOR:
      return F("SOUND_SENSOR");
    case LIGHT_SENSOR:
      return F("LIGHT_SENSOR");
    default:
      return F("UNKNOWN TYPE");
  }
}

And I got following errors
ketch/NodeIntercom.ino.cpp.o: In function `sendSensorMessageToMaster(RF24Mesh*, SensorDataMessage*, char, unsigned int, bool)':
/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h:48: undefined reference to `Sensor::toString()'
sketch/NodeIntercom.ino.cpp.o: In function `handleSetSensorDataRequest(RF24NetworkHeader*)':
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:97: undefined reference to `Sensor::toggle()'
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:89: undefined reference to `Sensor::enable(bool)'
sketch/NodeIntercom.ino.cpp.o: In function `SensorDataMessage':
/home/iron/Arduino/What'sHappening/NetworkMaster/common.h:40: undefined reference to `Sensor::Sensor()'
sketch/NodeIntercom.ino.cpp.o: In function `__static_initialization_and_destruction_0':
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:35: undefined reference to `Sensor::Sensor(unsigned long, SensorType, long, bool, long, long)'
collect2: error: ld returned 1 exit status

What I am doing wrong ?
Please help.
EDIT
Yes main sketch compiles perfectly where this files are located.
But I don't want to duplicate common files in my all my arduino sketches withing the project, they are the same for whole project. Here my files location
--ArduinoProjects
---NodeIntercom
----NodeIntercom.ino
---MasterNode
----MasterNode.ino
----sensor.h
----sensor.cpp
----common.h

So this files are only located in MasterNode directory
And I tried to include them like this
#include "/home/iron/Arduino/What'sHappening/NetworkMaster/common.h"
#include "/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h"

And in common.h I include sensor.h
Also tried to include directly, but still the same
But headers files included as above works perfectly.
What is the right way to solve this problem, I don't want to duplicate this class in each folder whenever I change it.
If there is no way, maybe create symbolic link (I am using linux) ?
PARTIAL SOLUTION
Just use symbolic links in the sketch directory and this works perfectly

where are these files located? in the sketch folder? in a library?

The Arduino build preprocessing cannot locate the sensor source and header files if they are located in another sketch directory. The files needs to be moved to separate directory if shared (as a library).
--Sketchbook
---NodeIntercom
----NodeIntercom.ino
---MasterNode
----MasterNode.ino
---libraries
----Sensor
-----Sensor.h
-----Sensor.cpp

The Sensor header is included with
#include <Sensor.h>

in the sketches that needs to use it.

There is nothing wrong with that class and its code (as far as I can tell) - it compiles perfectly fine.
What is probably wrong is that the IDE isn't picking up the code and compiling it in to your project.
Is this class part of the sketch, or is it a separate library that you are writing?  If the latter you have to ensure that the IDE knows about it, and it can only look for it when you load the IDE, so if you haven't restarted the IDE since creating the library you must do that so it can find the new library.

Thank you for answer. I just created manually this class and want just to separate logic, I am not writing a library, just simple class.
I think the problem is that this files are located inside another sketch directory MasterNode this is main node sketch.
I have updated my question please see it

You're trying to use files from one sketch in another sketch? That's not going to happen. It can't be done. If you want to share files between sketches then they must be as a library. There's no two ways about it. Create yourself a library and put your shared files into it.

Thank you for explanation, I have just used symbolic links and this works perfectly !

See my post about How the IDE organizes things.


text:
How to upload Arduino sketches to Atmel chips
I am new in this Arduino coding world and I was trying to make a project. I normally used Arduino Unos all the time, but I was facing a problem and that is that the Arduino Uno has only 13 digital pins and 6 analog pins, and some of my friends advise me to use an Arduino Mega, but that costs too much, some to my friends also tell me that I could use only a Atmel chip, which will save money.
But the problem is that I can not burn these chips without a burner. I see online that Arduino Uno has Arduino ISP options also that will allow you to bootload or upload Arduino sketches to those kind of chips, but I have been trying for over 3 months and I cannot figure out how to do that
At present I am working with the ATmega8 chip.
This is my problem:

Using stk500v1 but the problem is not resolved

How many pins do you need? It is actually 19 digital pins and 6 analog pins. The analog pins can be used as digital pins. A typical issue when using an Arduino as an ISP is forgetting to use a resistor or capacitor connected to the reset pins to avoid reset and running the bootloader. The ATmega8 might be an issue as well. Which core are you using for that?

@MikaelPatel I need 22 digital pins and 7 analog pins, I am using 10 mf capacitor in arduino capacitor VCC side is Arduino RESET and GND side is Arduino GND

@MikaelPatel: I did not find any core?

Seems like the atmega8 is an older AVR chip and compatible with the pins on atmega328 https://www.arduino.cc/en/Main/Standalone. Smaller memory size and the same number of pins (digital/analog).

@MikaelPatel: Sir at this time I am just testing how it works, When I figure out I will us ATmega 16 ARV Chip

Try option "-cstk500v1" instead of "-c arduino".

@MikaelPatel: OK sir

The problem is not solve
http://www.softbazz.com/jja.jpg

Time to check the wiring from the Uno to the ATmega8.

Arduino pin name: reset: 10: , MOSI: 11:, MISO: 12:, SCK: 13:       Atmega Chip pin: 1 (PC6), 17 (PB3), 18 (PB4), 19 (PB5)

And I also using 10uf capacitor

Add option "-v" to get more info from the upload.

I hate to be that guy, but a USBasp clone costs little and would likely be delivered long before 3 months had passed.

@IgnacioVazquez-Abrams +1 for saying it before I cracked. Fortunately I was out most of the day.

Do not really see how that would help :) This is all about helping with hardware debugging (as I see it). Small steps forward to understand where the problems are. Even better would be to just sent the HEX file off to a company that did all the work for you. But where is the fun in that.

It wouldn't solve the problem, but it would get the job done. Which is why I posted it as a comment instead of an answer.

You say the problem "needs 22 digital pins and 7 analog pins" which is 29 pins. ATmega8/16/328 come in 28 and 32 pin packages. Several pins are used for ground and power, and the reset pin should be left free too. So it is not possible to have 29 pins. So what is your plan to create 29 I/O pins? The options are: a) use multiple ATmega chips, b) use some sort of I/O extender (e.g. shift register, multiplexer, etc), or c) use a different chip?

First thing you need to do in this situation is to crank up the verbosity level on the invocation of avrdude. You do this by adding one or more -v flags to the command line. With -v -v -v -v, you get maximum verbosity.
From your two logs, it appears that the initial handshake with the microcontroller was successful (which would indicate that your connections were good), but then the signature reading turns out quite badly. This is a rather unusual combination which makes me wonder whether you may have misidentified what microcontroller you have.

I was just trying in our way, and this is the result,

http://www.softbazz.com/main.html

That confirms that the initial handshake was good, so your connections must be OK, but that somehow a nonsense signature was read. This is puzzling. Unfortunately, the ATmega8 is quite old, so I'm not sure what could be going wrong here.


text:
How to properly reverse DC motor direction with 2 limit switchws
Hello i am trying to reverse a dc motor direction upon hitting either limit switch. but noting is working can some one point me in right direction. all example i find use stepper motors and step count.
const int sw2 = 2;          //Up Limit switch
const int sw3 = 3;          //Down Limit switch
const int ic1_2 = 8;        //TA8409S IN2
const int ic1_1 = 9;        //TA8409S IN1
const int enable = 10;      //TA8409S Enable (motor)
int sw2State = 0;
int sw3State = 0;

void setup() {
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(ic1_1, OUTPUT);
  pinMode(ic1_2, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, 1);
  Serial.begin(9600);
}

void loop() {
  tilt_up();
}

void tilt_up()
{
Serial.print("up Started\n");
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, HIGH);
  sw2State = digitalRead(sw2);
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
    Serial.print("sw2 pressde\n");
  }
}

void tilt_down()
{
  Serial.print("down Started\n");
  digitalWrite(ic1_1, HIGH);
  digitalWrite(ic1_2, LOW);
  sw3State = digitalRead(sw3);
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
    Serial.print("sw3 Pressed\n");
  }
 }

If you want to reverse the movement you sould remember where you are going. This, along with the brackets correction suggested by @MikaelPatel and @NickGammon, leads to this code:
boolean moving_up = true;

void loop() {
    if (moving_up)
        tilt_up();
    else
        tilt_down();
}

void tilt_up()
{
    digitalWrite(ic1_1, LOW);
    digitalWrite(ic1_2, HIGH);
    if (digitalRead(sw2State) == LOW) {
        moving_up = false;
        Serial.println("sw2 Pressed");
        Serial.println("down Started");
    }
}

void tilt_down()
{
    digitalWrite(ic1_1, HIGH);
    digitalWrite(ic1_2, LOW);
    sw3State = digitalRead(sw3);
    if (digitalRead(sw3State) == LOW) {
        moving_up = true;
        Serial.println("sw3 Pressed");
        Serial.println("up Started");
    }
}

This also fixes recursion, which would make the processor run out memory eventually.

@Gerben as I also wrote on the other answer, even with the original code there SHOULD not be any recursion problem, since (hopefully) sw2 and sw3 will never be engaged together (and so calling tiltDown - which is only done when sw2 is engaged - should not call tiltUp. Anyway the original code does not have the behavior the poster wanted

void loop() {
  tilt_up();
}

void tilt_up()
{
...
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
...
  }
}

...

void tilt_down()
{
...
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
...
  }
 }

You are recursing here. loop calls tilt_up which eventually calls tilt_down which calls tilt_up and so on until you - rather quickly - run out of RAM.
Rewrite so that you are not doing that.

Also see what @MikaelPatel told you in your other question. You have the brackets in the wrong place.
  if (digitalRead(sw2State == LOW)) {

should be:
  if (digitalRead(sw2State) == LOW) {

No, he is not recursing too much because (hopefully) sw2 and sw3 will never be engaged together. The problem here is that the motor will move towards sw2, then hit it, reverse for one cycle and then go "up" again. See my answer to get what (I guess) is the behavior the OP wanted

@frarugi87 :  Your code certainly looks much better, as the main loop now controls which direction it is going.

I got it to work!!!
do not know if it is the right way ... but it works. thank you all for your input/advice. here is the new working code:
/*

 */

// set pin numbers:
const int sw2 = 2;           // Down limit
const int sw3 = 3;           // Up Limit
const int ledPin =  13;      // Pwr L.E.D
const int ic1_2 = 8;         // TA8409S IN2
const int ic1_1 = 9;         // TA8409S IN1
const int enable = 10;       // TA8409S Enable (motor)

int sw2State = 0;            // Down Limit State
int sw3State = 0;            // Up   Limit State

void setup() {
  // Setting L.E.D and Motor In, Enable pins as an output:
  pinMode(ic1_1, OUTPUT);
  pinMode(ic1_2, OUTPUT);
  pinMode(enable, OUTPUT);
  pinMode(ledPin, OUTPUT);
  // Setting limit switches pins as inputs
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  // Enables motor
  digitalWrite(enable, 1);
  //Starts program down
  down();
}

void loop() {
  // reads the state of the limit switches
  sw2State = digitalRead(sw2);
  sw3State = digitalRead(sw3);

  if (sw3State == LOW) {
    down();
  }
  if (sw2State == LOW) {
    up();
  }
}

void up() {
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, HIGH);
}

void down() {
  digitalWrite(ic1_1, HIGH);
  digitalWrite(ic1_2, LOW);
}

void err() {
  digitalWrite(enable, LOW);
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, LOW);
}


text:
Using different ADC channels
How could the same code be used with different ADC channels?
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 100;

volatile int resultsV [MAX_RESULTS];
volatile int resultsI [MAX_RESULTS];

volatile int resultNumber;

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

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);
  OCR1A = 338;
  OCR1B = 338;   // 39 = 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  //  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering
}

// ADC complete ISR
ISR (ADC_vect)
{
  resultsV[resultNumber++] = ADC;

  //resultsI[resultNumber++] = ADC;

  if (resultNumber == MAX_RESULTS)
  {
    ADCSRA = 0;  // turn off ADC
  }
}

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void loop () {

  while (resultNumber < MAX_RESULTS)
  { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.print( resultsV);
    Serial.print("   ");
    Serial.print( resultsI);
    Serial.println();
  }
  resultNumber = 0;
  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF) | bit (ADPS2) | bit (ADATE);
  // turn ADC back on
}

To use a different channel you'd change ADMUX.  See the datasheet to determine what it should be.

From what I understand, you want to read two ADC channels
simultaneously. First, you have to understand that you cannot read them
exactly at the same time, as you have a single ADC. What you can do,
however, is read them one after the other: you read the V channel, then
the I channel, then the V channel again, etc. This means you will have
to change the multiplexer setting (the ADMUX register) in between the
readings. The most convenient place to do this is within the ADC ISR,
the logic of which becomes:

Save the value that has just been read
switch the multiplexer to the other channel
turn off the ADC if you are done.

Example code (not tested):
const byte PIN_V = 0;  // A0
const byte PIN_I = 1;  // A1

// ADC complete ISR.
ISR(ADC_vect)
{
    if (ADMUX & 7 == PIN_V) {
        // We have just read the V channel.
        // Save the value and switch to the I channel.
        resultsV[resultNumber] = ADC;
        ADMUX = bit(REFS0) | PIN_I;
    } else {
        // Otherwise we completed a (V, I) pair, we can increment
        // resultNumber.
        resultsI[resultNumber++] = ADC;
        ADMUX = bit(REFS0) | PIN_V;
    }

    // Turn off the ADC when done.
    if (resultNumber == MAX_RESULTS)
        ADCSRA = 0;
}

Note that this example assumes you do the readings in the (V, I) order.
Thus, within setup(), you have to initialize the multiplexer for the V
channel, as in
ADMUX = bit(REFS0) | PIN_V;


text:
Arduino Nano ATmega328P bootloader difference
There are two ATmega328P bootloaders, old and current.  What is the difference between these bootloaders?
I'm aware that Nanos sold by Arduino use the new bootloaders but I haven't been able to find any release notes about the bootloader.

from what I can see, the "old" bootloader is ???/bootloaders/atmega/ATmegaBOOT_168_atmega328.hex and the new one is ???/bootloaders/optiboot/optiboot_atmega328.hex - ??? depends on your system, but should be easy to find - online, see https://github.com/Optiboot/optiboot

I bootload all my '328P chip based boards as 16 MHz Arduino Uno, then I don't need to worry about selecting the right board type.

The bootloader currently shipped on the official Arduino Nano boards and selected via the Arduino IDE's Tools > Processor > ATmega328P after choosing Tools > Board > Arduino Nano is the same version of optiboot used by the Arduino/Genuino Uno:
https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L152
nano.menu.cpu.atmega328.bootloader.file=optiboot/optiboot_atmega328.hex

https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L72
uno.bootloader.file=optiboot/optiboot_atmega328.hex

The bootloader selected via Tools > Processor > ATmega328P (Old Bootloader) is the "ATmegaBOOT" bootloader.
As used by the Nano hardware definition, there are two significant differences between the two bootloaders:

Optiboot will not go into an endless reset loop after a watchdog reset. ATmegaBOOT will.
Optiboot expects the upload communication at 115200 baud. ATmegaBOOT, 57600. This is the reason why the old boards don't work with the Tools > Processor > ATmega328P selection and vice versa.

There is another very significant difference between the two bootloaders that, sadly, you will not benefit from with the new Arduino Nano board/hardware definition: Optiboot will fit in a 0.5 kB boot section, while ATmegaBOOT requires a 2 kB boot section. Unfortunately Arduino forgot to change the BOOTSZ fuse accordingly and so the opportunity to free up 1.5 kB of precious flash memory for the users of the Nano was lost. The willingness of Arduino to knowingly release flawed hardware has historic precedent.

I haven't been able to find any release notes about the bootloader.

Arduino's release notes have not yet adapted to the fact that hardware packages may be released independently of IDE releases ever since Arduino IDE 1.6.2. There is a note about the bootloader change in the IDE release notes for the next IDE release:
https://github.com/arduino/Arduino/commit/ec179e5af67b7f1eeb5e46d22034798f8b24b7cb
Other than that, you can consult the commit history:
https://github.com/arduino/ArduinoCore-avr/commit/1b14cc07331268e95eddcce2cc67e29ed667e62f

Can the nano be flashed with either bootloaders or are there hardware differences that the booloader depends on?

There are no hardware differences. If you're flashing the bootloader my advice is to do so with Tools > Board > Arduino/Genuino Uno selected because then you get all the benefits of optiboot, including the 1.5 kB extra flash memory. Just remember that you need to have the Uno board when you use your Nano after that.

*Uno board selected

It might be worth noting: I have just received a Nano "clone" of AliExpress, which (unusually for a clone) has a FT232R (instead of a CH34x), which means that it works nicely on my Mac. However, I found that I had to select the old bootloader to be able to upload sketches - which seems contra your post (stating that the new bootloader is used for the Nano). However, as my Nano is a clone, I guess that anything goes.


text:
How can I read servo motor readings via serial communication?
I'm new to serial communication. I tried to make Arduino talk to MATLAB, but certain values are allowed to be received like 100 and 101. I tried other values but didn't work. The problem is with ASCII code but I tried to subtract what is read by 48 but failed.
This is the Arduino code that I found on Google and edited it for my servo motor problem:
#include <Servo.h>
const int servoPin = 3;
int recValue; // received value from MATLAB
Servo Servo1;

void setup()
{
  Serial.begin(9600);
  Servo1.attach(servoPin);
}

void loop()
{
  if (Serial.available() > 0)
  {
    recValue = Serial.read();
    if  (recValue == 100)
    {
      Servo1.write(0);
      delay(1000);
    }
    if (recValue == 101)
    {
      Servo1.write(90);
      delay(1000);
    }
  }
}

So how can I read the correct angles that I received from the MATLAB via serial communication? Thanks.

What exaclty are you getting from Matlab over serial?

When using recValue as 100, the motor rotates to the 0 position and if 101, the motor rotates to 90 degrees. When I change recValue to any number, I get nothing from MATLAB and the motor does not rotate to any position in the two cases.

I don't understand, what exactly you want to achieve. Your comment states the exact functionality, that is provided by your code.  When you want to control the sensors angle from Matlab, send an actual value to the Arduino and use it in Servo1.write()

Sorry for not being clear. For example, I want to make the motor rotate 45 degrees. I should write 45 in MATLAB and then it can convert the value to 45 so that I can use Servo1.write(45) afterwards. I will edit the code but I want to know how to convert the value that I receive from MATLAB in order to be the exact 45 value.

Serial.parseInt()?

chrisl is quite right. You need to understand how MATLAB is talking to your Arduino. I suspect it is sending a sequence of characters for each servo angle instead of a single character.  In your code you are waiting for 100 and 101, which are the ASCII 'd' and 'e' characters, and then acting immediately you have read one character. See if the servo will turn if you send 'd' or 'e'. If that works then what you need to do is read a whole line of ASCII characters e.g. '9' (which is 57) and '0' (which is 48) followed by a delimiter e.g. newline (13)
At the beginning of line you can set int angle = 0 and each time you read a character multiply your angle by 10 and add in the new value by subtracting 48 from it.
When you reach the delimiter you can then send the angle to the servo.
Oh - and make sure MATLAB is talking at the right baud rate.

Thanks a lot. I tried to send 'd' and 'e' and the motor really turned. But I still don't understand how the last few sentences. How can I delimit '9' and '0' to become 90?

I now understand that we're making a map between 0-9 values to 0-90 degrees but how can I do that in Arduino? Is this done for the recValue variable in Arduino? or servalue in MATLAB?

If you want to send 90 to the Arduino it will be sent as the character 9 (which is 57) and then character 0.  You will only get a single character at a time in each iteration of your loop. The first time Serial.available() is true Serial.read() will return value 57. Subtract 48 from that to get 9 and store in a variable declared as int angle. The next time Serial.available() is true (which may be a few loops() later) you will read 48.  So then angle = angle * 10 + (value - 48) gives you the angle to send to your servo. You can send to the server when you get a non-digit character from MATLAB

Yes, but what is the value Serial.read()? Is this what we get from MATLAB via serial communication between it and arduino?

Serial.read() will collect the next available ASCII character sent from MATLAB to the Arduino. It only returns one character at a time so if you had sent the number 125 from MATLAB you would need to call Serial.read() three times to get the '1', '2' and '5' characters. You then need to recombine them as I said above to get a single integer of 125 to send to the servo

Rather than trying to get MATLAB to talk to the Arduino immediately, why don't you try just using the Serial connection from your PC. You can type characters in on the Serial monitor and process your keystrokes one by one using Serial.read(). You can then print debugging information using Serial.write() so you can get some idea what is going on in the code.

Let us continue this discussion in chat.

I'm assuming, that you are sending the angle value as a 1-byte value, so no ASCII encoded numbers. This is how the code in your question works, so it should be right.
You don't have to convert anything here. The Serial.read() function already returns an integer value and you are saving it to an integer variable. But in your code you only care for 2 different states (100 and 101), instead of the actual angle value. Now you only have to replace your if-statements and write this value directly to the servo:
Servo1.write(recValue);

EDIT:
You doesn't seem as you know how serial communication (to be exactly USART) functions. So I will explain further:
The data, that is send over serial is just a stream of bytes. All content, that get transmitted are converted to a stream of bytes. Every byte has a numerical value. For example a byte with the bit-content 00100000 has a numerical value of 32. But at some point in history it was necessary to send text with a byte stream. So someone invented ASCII, which assigns a character or control command to every numerical value from 0 to 127. So if you send a byte with the numerical value of 32, you could mean the actual numerical value 32, or you could mean the ASCII equivalent to 32, which is the space character. This is just an interpretation of the byte data, that flows through the serial interface.
So you have to investigate, in which kind you are encoding the angle value. If you use fwrite() in your Matlab code, you are most likely sending the byte value, which you can simply use as described above. If you use fprintf(), you are sending the angle value as an ASCII encoded string. The value 32 from above would then occupy 2 bytes with the characters 3 and 2, which correspond to the byte values of 51 and 50. In this case you should add a delimiter character at the end in fprintf() (for example the newline character "\n") and use Serial.parseInt() to get the angle value from the string.
You can read more of this in many tutorials about Serial communication that you can find in the internet. Also refer to the example, that come with the Arduino IDE.

What do you mean by 1-byte value? Because I tried many ranges from 0 to 180 degrees and the motor still does not rotate.

I have also added delay(1000) after Servo1.write(recValue)

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


text:
Print output on 16x2 LCD and Serial Monitor
I'm trying to print an int on both an LCD and the Serial Monitor, but its only being displayed on the LCD. The Serial Monitor is printing question marks.
Here is my Arduino code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
int x = 10;

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

void loop()
{
  x++;
  lcd.setCursor(0, 0);
  lcd.print(x);
  Serial.print(x); // print Serial
}

reduce your code to print to serial monitor only and try again .... post your results .... note: question mark ? .... exclamation mark !

If you are using clasical UNO, then pins 0 and 1 are Serial. Declaring lcd(1,... make LCD use the pin 1 too, so Serial is confused and garbled.
Use other pins for lcd and adjuct the wires acordingly.

@aloush You should select the green tick next to the vote button in the left if you think this answer solved your problem.


text:
Datalogger with interruputs
I'm trying to do a data logger. Writes into SD card has to stop when millis()=1000. Maybe I have a problem between millis() and my interrupt, because datalogger doesn't stop after millis()=1000. I'm working with Arduino Mega.
#include <SPI.h>
#include <SD.h>
volatile unsigned int cuenta = 0;
unsigned char contador = 0x00;
const int chipSelect = 53;
long currentMillis = 0;
long previousMillis = 0;
long interval = 1000;

void setup() {
  DDRA = B11111111;
  cli();//stop interrupts
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 10000khz increments
  OCR0A = 25;// = (16*10^6) / (1000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);
  sei();//allow interrupts
  //periodo de cada pulso 255ms del tren total de pulsos aproximadamnte 255ms
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  Serial.println("card initialized.");
}

ISR(TIMER0_COMPA_vect) {
  cuenta++;
  if (cuenta > 9) {
    PORTA = ++contador;
    cuenta = 0;
  } else {
    PORTA = 0X00;
  }
}

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis <= interval)
  {
    String dataString = "";
    for (int analogPin = 0; analogPin < 1; analogPin++) {
      int sensor = analogRead(analogPin);
      dataString = String(sensor);

      if (analogPin = 1) {
        dataString += ",";
      }
    }
    File dataFile = SD.open("datalog2.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      Serial.println(dataString);
    }
    else {
      Serial.println("error opening datalog.txt");
    }
  }
}

The millis() function is based on a counter which is incremented by
the Timer 0 overflow interrupt. Since you reconfigured
that timer to never overflow, that counter is not incremented anymore.
If you want to configure an Arduino timer for your own purposes, you
have to either:

use any timer other than Timer 0, or
loose the Arduino standard timekeeping functions: millis(),
micros() and delay().

I would favor the first option, especially on the Mega which has quite a
few spare timers.


text:
Unknown type name 'IRsend'
In the C file in simplesample_mqtt.c, which connects Arduino to the Azure IoT hub, I need to use the IRsend and IrRemoteESP8266 libraries to send an infrared signal with Azure IoT hub.
 #include <IRremoteESP8266.h>
 #include <IRsend.h>
 IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

I don't have any problem when I use this code in my main Arduino file. But when I use these includes in a C file (simplesample_mqtt.c), I get this error from line 3: "unknown type name 'IRsend'".

error full info :
Arduino: 1.8.2 (Windows 10), Board: "NodeMCU 0.9 (ESP-12 Module), 80 MHz, 115200, 4M (3M SPIFFS)"

In file included from sketch\simplesample_mqtt.c:29:0:

C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:1: error: unknown type name 'class'

class IRsend {

C:\Program Files (x86)\Arduino\libraries\IRremoteESP8266\src/IRsend.h:29:14: error: expected '=', ',', ';', 'asm' or 'attribute' before '{' token

class IRsend {

simplesample_mqtt.c:31: error: unknown type name 'IRsend'

IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

simplesample_mqtt.c:31: error: expected declaration specifiers or '...' before numeric constant

IRsend irsend(10); // An IR LED is controlled by GPIO pin 4 (D2)

exit status 1
unknown type name 'IRsend'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

error: unknown type name 'class' Classes only exist in C++. Try changing the file extension to ".cpp".

And if that doesn't work, make sure the class in IRremoteESP8266.h has a ; after the closing }

I solved this problem. The reason for this is because main Arduino is c++ and simplesample_mqtt.c is c code and we have to use c++ code in c code:
In main Arduino file you have to declare function like this :
extern "C" void TurnOn();
void TurnOn()
{
    digitalWrite(RELAY_SONOFF, HIGH);
    digitalWrite(LED_SONOFF, HIGH);
}

and use this function in c code:
void TurnOn();
EXECUTE_COMMAND_RESULT TurnOn(ContosoAnemometer* device)
{
    (void)device;
    TurnOn();
    (void)printf("Turning fan on.\r\n");
    return EXECUTE_COMMAND_SUCCESS;
}


text:
Powering on the PC
I located the two pins that are responsible for powering up the PC. They are connected to the Power On button and one pin has an output of 5 V while the other is the ground.
So far so good, the problem is when I connect the 5 V one to the Arduino VIN and a ground cable from the PC power source to the Arduino GND, instead of powering my board, the PC starts and then promptly stops, as if I pressed the power button and did not release it.
It seems that electricity passes through the Arduino without powering it. I tested the VIN and GND pins with a normal breadboard power source and they are not broken, as the board starts up with no problem.
Why is the computer starting up instead of powering the Arduino? How can I use my Arduino to start up the PC?
My plan was to power the Arduino with the 5 V pin and send a digitalWrite(somePin, HIGH) for a short amount of time to the ground pin from the PC that would normally be connected to the power button, thus "closing" the circuit like the normal case button would.

Please edit your post (click "edit") and add context and a question.  You have listed some things you have done but have not said what you want to do or what your question is.

Also asked at http://forum.arduino.cc/index.php?topic=489895

I located the two pins that are responsible for powering up the PC - where did you locate them?

and send a digitalWrite(somePin, HIGH) for a short amount of time to the ground pin - you want to send 5V to ground? Why?

@NickGammon by checking the wire that goes from the ON button to the motherboard.

I think this is actually a valid question - while it takes some knowledge of the PC power supply to understand it, editing that into the question for clarity to unfamiliar readers would come pretty close to putting the answer into the question.  One could, however argue that it is off-topic as it is about the PC power supply, not really about Arduino.

The two pins aren't +5V power and ground.
One of them will be what you think, the other will be a signal wire with a pull up/down.
So if the ground wire really is ground then the other wire is the button input and is pulled up with a resistor, probably in the 10k region.
You can't power an arduino with a ~10k resistor in series with the power, it's just not going to work. But it will pull enough current to make it look like the button is pressed all the time.
What you need to do is:
1) Find out which pin is the signal pin. The easiest way to do this is find some other ground point on the computer (e.g. from one of the HDD power connectors) and measure the voltage from that to the button wires when the button is pressed. If both wires go to 0V then it's the wire that's normally +5 that is the signal, if they go to +5 then it's the wire normally at 0V that's the signal.
2) Fine a real power source. Most PC power supplies have an always on supply that will be at 5V when the PC is off. Use that to power the arduino.
3) Now you know which wire is the signal wire and have a usable power source you can connect the signal wire to one of the arduino pins and drive it to the correct state. Ideally you'd do this via an open collector type interface so that you don't get two different things pulling to very slightly different idle levels.

The signal you found is called PS_ON and it is an active_low input which should be momentarily grounded by a switch to toggle the PC power supply's on/off state.
Trying to use this instead as a power source for the Arduino loads it, causing it to drop, the Arduino to brown out and release it, and then the process repeats.
As @Andrew mentioned, you need to find the 5v standby power supply output, and use that as the Arduino's power source instead.  This is called VSB.  Since it is already regulated to 5V, you can't pass it through the Arduino's Vin as it will not meet the regulator's dropout voltage needs.  Instead you should route it in as an external 5v source, much as done with the USB power input.
To activate the signal, you'll then want to use a digitalWrite() to briefly set the output low (not high).
However, when you are not driving it low, rather than driving it high (to a voltage potentially higher than the power supply pulls it up to), what you should do is simulate an open collector output by changing the pin mode to an input, without pullup.

I suspect that you plan won't work.  The Arduino's digital pins only support 20-40mA.  I think you would be better using the Arduino to control a transistor or relay and interfacing that with the switch.


text:
Dust sensor code with a few errors
I'm fairly new to this and I'm having trouble with a code for a dust sensor. Getting a couple of errors. I downloaded this code from GitHub.
Anyone have any idea how to fix any of these errors? Any help is appreciated.
Sorry if this formatted wrong, this is also my first post. Thanks for your time
// SDS011 dust sensor example
// -----------------------------
//
// By R. Zschiegner (rz@madavi.de).
// April 2016

#include "SDS011.h"
#include<SoftwareSerial.h>
SoftwareSerial myserial(0, 1);
SDS011(byte pin_rx, byte pin_tx)
float p10,p25;
int error;

SDS011 my_sds;

void setup() {
  my_sds.begin(0, 1);
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
}

void loop() {
  error = my_sds.read(&p25,&p10);
  if (! error) {
    Serial.println("P2.5: "+String(p25));
    Serial.println("P10:  "+String(p10));
  }
delay(100);
}

here are the errors I'm getting
code:10: error: expected ')' before 'pin_rx'

 SDS011(byte pin_rx, byte pin_tx)

             ^

C:\Users\Nick\Desktop\code\code.ino: In function 'void loop()':

code:26: error: 'p25' was not declared in this scope

   error = my_sds.read(&p25,&p10);

                        ^

code:26: error: 'p10' was not declared in this scope

   error = my_sds.read(&p25,&p10);

                             ^

exit status 1
expected ')' before 'pin_rx'

You have to use the begin command. Instead of:
SDS011(byte pin_rx, byte pin_tx)

...

SDS011 my_sds;

Use
SDS011 my_sds;

(Thus remove the first line: SDS011(byte pin_rx, byte pin_tx)).
And in setup add:
my_sds.begin(0, 1);

This follows the library function of SDS011:
void begin(uint8_t pin_rx, uint8_t pin_tx);

Other errors: because you forgot the ; in
SDS011(byte pin_rx, byte pin_tx)

the next line:
float p10,p25;

is misinterpreted, and p10 and p25 are not known. Therefore errors are shown while trying to use p10 and p25.
These errors will go when changing the begin code as described earlier.

Your code should be like below; there are multiple syntax and semantic errors in the code you have posted;
Below is the edited and working code;
#include <SDS011.h>

float p10,p25;
int error;

SDS011 my_sds;

void setup() {
  my_sds.begin(0, 1);
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
}

void loop() {
  error = my_sds.read(&p25,&p10);
  if (! error) {
    Serial.println("P2.5: "+String(p25));
    Serial.println("P10:  "+String(p10));
  }
  delay(100);
}