text:
Change delay function to millis function to play music
I'd like to write a code by changing the delay function in the music playing code to the millis function, do you know how?
#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 8; thisNote++) {

    // to calculate the note duration, take one second divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    // stop the tone playing:
    noTone(8);
  }
}

void loop() {
  // no need to repeat the melody.
}

Have you looked and understood the BlinkWithoutDelay example, that comes with the Arduino IDE? Have you tried some of the many tutorials about millis(), that are available on the web? If yes, what exactly are your problems in changing the code accordingly?

Does this answer your question? Playing Melody with Tone() without using delay()

Why do you want to get rid of the delay()? Your tone() call delays (blocks while playing) as well...

@DataFiddler, it is one of the basic examples in IDE, not a code by OP

I still consider my question "why?" valid. If you use blocking tone() calls, creating the "pizzicato" effect via a small delay() is straightforward.
The call noTone(8);is wrong (=unnecessary) here, BTW.
@chrisl's hint regarding BlinkWithoutDelay is good, if you change to non-blocking tone() creation as well. And if you need other things faster than a tone duration.

@DataFiddler, yes, there is an answer in the duplicate question


text:
ADS1115, ZMPT101b and Arduino Uno listing program for AC measurement
I got problem in my result where my ADC read cannot give the biggest and the lowest ADC Value if I am using ADS1115. meanwhile, when I am not using ADS1115 I can get the biggest and the lowest ADC Value using a listing program that I use before. Thank u, need for help.

]

why did you post pictures of the code? .... how do you expect anyone to run the program and test it?

what do you need help with? .... you did not ask any questions.

@jsotola no, i post the pictures of the code to ask if anything wrong in my code. my question is, why i cant get biggest and lowest value of my ADC if i using ADS1115? the value is just same the biggest and the lowest.

The practice on this SE is to post code as text (e.g. so that others may copy/paste and help you by providing correct code), not as images.

is the ADS1115 fast enough to measure AC? are you using some sort of RC filter and bridge?

The ZMPT101b is a transformer which converts voltage. You can read the output with analog pin.
The ADS1115 is an analog to digital converter. It reads the analog voltage the same way as the analog pin of your Arduino does. The result then can be read over I2C as a register value. You can't read it with analogRead.
So you can use the ADS1115 to convert the analog output of the ZMPT101b.
To read the digital value from the ADS1115 with Arduino, use the Wire library or find a library for the ADS1115. For example this one.
I use ADC121 with Wire library. I initialize it in setup()
  const byte REG_ADDR_RESULT = 0x00;
  const byte REG_ADDR_CONFIG = 0x02;

  // initialize the Wire library
  Wire.begin();
  Wire.setClock(400000);

  // configure the ADC
  Wire.beginTransmission(I2C_ADC121);
  Wire.write(REG_ADDR_CONFIG);
  Wire.write(REG_ADDR_RESULT);
  Wire.endTransmission();

  // set the 'result' register as default
  Wire.beginTransmission(I2C_ADC121);
  Wire.write(REG_ADDR_RESULT);
  Wire.endTransmission();

and then in code I read the value with this function
unsigned short adcRead() {
  Wire.requestFrom(I2C_ADC121, 2); // request 2 bytes
  byte buff[2];
  Wire.readBytes(buff, 2); // read 2 bytes
  return (buff[0] << 8) | buff[1]; // get the result as 16 bit number
}

source: Stack Exchange

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

sort: votes


text:
analogWrite(PIN, 1023) <> digitalWrite(PIN, HIGH)
This question is very similar to this one.
I'm using an ESP8266 for which the maximum analogWrite value is 1023 rather than 255 for some other Arduino boards, but I believe the principal is just the same.
I'm driving 3 LEDs directly from 3 outputs via current limiting resistors.
When I turn them on using analogWrite(PIN, 1023) they are not quite a bright as when the same LED is driven by the same pin using digitalWrite(PIN, HIGH). Which leads me to think that either 1023 does not give a 100% duty cycle or the maximum voltage in the analog case is less than that in the digital one.
Is this to be expected? Are the pins significant (4,5 and 14)?
Another similar Q&A would lead me to believe they should be the same.

Try checking the voltage across the pin but mostly the voltage is lesser by 0.1 while using pwm than just settings the pin High.

Try measuring the current, and see if there is a difference. It might be true. I know, for example, the STM processors have a low and high-speed outputs, and those have different current handling characteristics. If this is an issue in your application you could buffer the output, by driving an transistor connected to the LED, instead of driving the LED directly.

default max is 255. https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output

The default range was originally 1023 so it is a a little bit different from version to version

sorry, yes it is 1023. the doc is changed for 3.0.0

I can confirm that 1023 does indeed give 100% duty cycle. I connected an output of my D1 Mini to my oscilloscope and got a steady voltage.
I can also confirm that the same voltage is output for digitalWrite() and analogWrite().
However the output drivers may not be the same. With analogWrite() it may be using a weaker output driver that can't deliver as much current, so the voltage droops slightly more than it would with digitalWrite(). However even with a 470Ω resistor connected between the output and GND (the smallest value I had easily to hand in a through hole variant) I see no variation in the voltage at all.
So if there is some variation then it might be some variable that is showing a variation in your specific unit but not mine.

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


text:
Slowly increase speed using PWM arduino
I'm trying to control the speed of a DC motor using PWM. Here is my code so far:
int motor = 9;
int fadeValue = 5;

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

void loop() {
  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
    analogWrite(motor, fadeValue);
    delay(100);
  if (fadeValue==245) {
    fadeValue=255;
    break;
  }
}

I want the motor to slowly increase it speed then stay high. However, the loop keep repeating.
Thanks in advance guys.

Your code is very creative. We're missing the part where loop() is called...

I believe the Arduino compiler abstracts away the main() function. The loop() function is automatically called continuously. Also, this question probably belongs in the Arduino SE.

Here's the Arduino AVR Boards loop() call: https://github.com/arduino/Arduino/blob/1.8.1/hardware/arduino/avr/cores/arduino/main.cpp#L46

Could you also change the order the loop is in? So the code would look like this instead:
void loop() {
  if (fadeValue == 245) {
    fadeValue=255;
    analogWrite(motor, fadeValue);  // motor will stay at highest value
    }
  else {
      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
        analogWrite(motor, fadeValue);
        delay(100);
        }
  }
}

So now, the loop will run until fadeValue == 245, at which point the loop will not advance to the for loop because the "if" in the if/else statement is satisfied. I'm not actually sure if this will work, but it's an idea.

So now, the loop will run until fadeValue == 245 - no, it will run until fadeValue is greater than 245 which means the test for it being equal to 245 at the start of loop won't be met.

However, the loop keep repeating.

That's the whole point of loop(). If you want some code to run only once after the program starts put it in setup():
int motor = 9;
int fadeValue = 5;

void setup() {
  pinMode(motor, OUTPUT);

  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
    analogWrite(motor, fadeValue);
    delay(100);
    if (fadeValue == 245)
    {
      fadeValue = 255;
      break;
    }
  }
}

void loop() {
}

Why does it eat my code indentation after I submit the answer? Annoying, I haven't experienced that on other SE sites.

@zuzu -- you should put all the details of what you need in the question to avoid unnecessary answers...

If you want void loop() to only run once and don't want to put your code into setup() for some odd reason, just as an infinite while loop at the end with a delay inside like this:
void loop()
{
  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10)
{
    analogWrite(motor, fadeValue);
    delay(100);
  if (fadeValue==245)
{
    fadeValue=255;
    break;
  }

While(1)
    Delay(1000);

}

it can be put in the loop(): putting it in the setup(), if the speed-up period is long, isn't practical or feasible in some applications.
you can use a loop counter or time counter to slow down the ramp-up without tying down the mcu, like this:
  time_now = time(); //take a reading of current time. or millies()
  if (time_now < TIME_RAMPUP) { //still need to ramp it up
    if (time_now > time_prev) { //need to increment motor speed
      time_prev+=TIME_INC;
      motor_dc+=PWM_STEP;  // you may wish to bound the dc here
      analogWrite(MOTOR_PIN, motor_dc); //increase dc
    }
  }

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


text:
I can't receive data from Arduino through Bluetooth
I am developing an app that controls an Arduino robot. For that I need to communicate through Bluetooth. That means sending and receiving data. Why receiving? Because I also have sensors on the robot. I am already able to successfully connect with the Arduino Bluetooth bridge and send data, but I can't receive data from the Arduino. If someone can help me, I will appreciate it.
Here is the  main Java code:
public class MainActivity extends AppCompatActivity {
    Button  forward_btn, forward_left_btn, forward_right_btn, reverse_btn, reverse_right_btn, reverse_left_btn, btnConexao, turbo;
    public static final int SOLICITA_ATIVACAO = 1; // é o codigo numero 1, é diferenciado o codigo pq pode haver varias solicitações na msma tela
    public static final int SOLICITA_CONEXAO = 2;
    BluetoothAdapter meuBluetoothAdapter = null; //declarar o meu adptador bluetooth
    BluetoothDevice meuDevice = null;
    BluetoothSocket meuSocket = null; // faz transiçao dos dados
    TextView myLabel;
    Thread workerThread;
    byte[] readBuffer;
    int readBufferPosition;
    volatile boolean stopWorker;
    boolean conexao =  false; //variavel para a conexao que indica se a conexao está em andamento ou nao
    private OutputStream outputStream  ;
    private static String MAC = null;
    private  InputStream mmInputStream;
    final int RECIEVE_MESSAGE = 1; // Status  for Handler
    Handler h;
    private StringBuilder sb = new StringBuilder();
    byte [] command = new byte[256]; //string variable that will store value to be transmitted to the bluetooth module
    UUID MEU_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); // canal de comunicaçao bluetooth, UUID- ID do canal
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      forward_btn = (Button) findViewById(R.id.forward_btn); //definir botoes e associar ao ficheiro xml
      forward_left_btn = (Button) findViewById(R.id.forward_left_btn);
      forward_right_btn = (Button) findViewById(R.id.forward_right_btn);
      reverse_btn = (Button) findViewById(R.id.reverse_btn);
      reverse_left_btn = (Button) findViewById(R.id.reverse_left_btn);
      reverse_right_btn = (Button) findViewById(R.id.reverse_right_btn);
      btnConexao = (Button) findViewById(R.id.btnConexao);
      turbo = (Button) findViewById(R.id.turbo);
      myLabel = (TextView) findViewById(R.id.label);
      forward_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) { // comandos bluetooth correspondentes do arduino
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "1".getBytes();
              try {
                outputStream.write(command); //transmite o valor do comando para o modulo bluetooth
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      reverse_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "2".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
              }
            }
          }
          return false;
        }
      });

      forward_left_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "3".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
              }
            }
          }
          return false;
        }
      });

      forward_right_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "4".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      reverse_left_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "5".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      reverse_right_btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "6".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      turbo.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
          if (conexao) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
              command = "9".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
              command = "10".getBytes();
              try {
                outputStream.write(command);
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
          return false;
        }
      });

      meuBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //obter o adaptador do dispositivo e definir como meubluetoothADpt
      if (meuBluetoothAdapter == null) { //se o adptador for "null", ou seja nao tem adptador
        Toast.makeText(getApplicationContext(), "O seu dispositivo nao possui bluetooth", Toast.LENGTH_LONG).show();
      } else if (!meuBluetoothAdapter.isEnabled()) { // != não, so o bluetooth nao tiver ativao, pedir permissão
        Intent ativaBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(ativaBluetooth, SOLICITA_ATIVACAO);
      }

      btnConexao.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          if (conexao) {
            try {
              meuSocket.close();
              conexao = false;
              btnConexao.setText("Conectar");
              Toast.makeText(getApplicationContext(), "Bluetooth foi desconectado", Toast.LENGTH_SHORT).show();
            } catch (IOException erro) {
              Toast.makeText(getApplicationContext(), "Ocorreu um erro ao desconectar:", Toast.LENGTH_SHORT).show();
            }
          } else {
            Intent abreLista = new Intent(MainActivity.this, ListaDispositivos.class);
            startActivityForResult(abreLista, SOLICITA_CONEXAO);
          }
        }
      });
    }

    void beginListenForData () {
      final Handler handler = new Handler();
      final byte delimiter = 10; //This is the ASCII code for a newline character
      stopWorker = false;
      readBufferPosition = 0;
      readBuffer = new byte[1024];
      workerThread = new Thread(new Runnable() {
        public void run() {
          while (!Thread.currentThread().isInterrupted() && !stopWorker) {
            try {
              int bytesAvailable = mmInputStream.available();
              if (bytesAvailable > 0) {
                byte[] packetBytes = new byte[bytesAvailable];
                mmInputStream.read(packetBytes);
                for (int i = 0; i < bytesAvailable; i++) {
                  byte b = packetBytes[i];
                  if (b == delimiter) {
                    byte[] encodedBytes = new byte[readBufferPosition];
                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                    final String data = new String(encodedBytes, "US-ASCII");
                    readBufferPosition = 0;
                    handler.post(new Runnable() {
                      public void run() {
                        myLabel.setText(data);
                      }
                    });
                  } else {
                    readBuffer[readBufferPosition++] = b;
                  }
                }
              }
            } catch (IOException ex) {
              stopWorker = true;
            }
          }
        }
      });
      workerThread.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      switch (requestCode) {
        case SOLICITA_ATIVACAO:
          if (resultCode == Activity.RESULT_OK) {
            Toast.makeText(getApplicationContext(), "O Bluetooth foi ativado", Toast.LENGTH_LONG).show();
          } else {
            Toast.makeText(getApplicationContext(), "O bluetooth nao foi ativado, App será encerrada", Toast.LENGTH_LONG).show();
            finish();
          }
          break;
        case SOLICITA_CONEXAO: // pede resultado da solicitaçao, se nao obter o resultado exibe toast
          if (resultCode == Activity.RESULT_OK) {
            MAC = data.getExtras().getString(ListaDispositivos.ENDERECO_MAC);//vai buscar info à lista, ao ENDERECO_MAC
            meuDevice = meuBluetoothAdapter.getRemoteDevice(MAC); // obtem dispositivo remoto atraves do MAC
            try { // tenta a conexao
              meuSocket = meuDevice.createRfcommSocketToServiceRecord(MEU_UUID); // cria um canal de comunicaça0 Rfcomm
              meuSocket.connect(); // tenta conexao  exibre
              try {
                outputStream = meuSocket.getOutputStream();
              } catch (IOException e) {
                e.printStackTrace();
              }
              try {
                mmInputStream = meuSocket.getInputStream();
              } catch (IOException e) {
                beginListenForData();
                e.printStackTrace();
              }
              conexao = true; // apos conectado, passa a true
              btnConexao.setText("Desconectar");
              Toast.makeText(getApplicationContext(), "Você foi conectado com" + MAC, Toast.LENGTH_SHORT).show();
            } catch (IOException erro) { // se falhar conexao exibe
              conexao = false;
              Toast.makeText(getApplicationContext(), "Ocorreu um erro:" + erro, Toast.LENGTH_SHORT).show();
              //retirar o "+erro" se for publicada a app
            }
          } else {
            Toast.makeText(getApplicationContext(), "Falha ao obter o mac", Toast.LENGTH_SHORT).show();
          }
      }
    }
}

This is the code I added in order to receive data:
  void beginListenForData () {
  final Handler handler = new Handler();
  final byte delimiter = 10; //This is the ASCII code for a newline character
  stopWorker = false;
  readBufferPosition = 0;
  readBuffer = new byte[1024];
  workerThread = new Thread(new Runnable() {
    public void run() {
      while (!Thread.currentThread().isInterrupted() && !stopWorker) {
        try {
          int bytesAvailable = mmInputStream.available();
          if (bytesAvailable > 0) {
            byte[] packetBytes = new byte[bytesAvailable];
            mmInputStream.read(packetBytes);
            for (int i = 0; i < bytesAvailable; i++) {
              byte b = packetBytes[i];
              if (b == delimiter) {
                byte[] encodedBytes = new byte[readBufferPosition];
                System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                final String data = new String(encodedBytes, "US-ASCII");
                readBufferPosition = 0;
                handler.post(new Runnable() {
                  public void run() {
                    myLabel.setText(data);
                  }
                });
              } else {
                readBuffer[readBufferPosition++] = b;
              }
            }
          }
        } catch (IOException ex) {
          stopWorker = true;
        }
      }
    }
  });
  workerThread.start();
}

Can you receive data through bluetooth using a standard terminal emulator program?

I used the "Bluetooth terminal " to check if the arduino is sending data , and it is working well but i can't receive it in my app .

So it sounds like it's something Android specific then - you may be better off asking on an Android site where they have more Android knowledge.

You were right , the problem was it the arduino code , thank you for your time.

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


text:
I have a diagram of my Arduino circuit. How do get it ready for PCB manufacture?
For my engineering class, I am building a digital scale. My team has assembled the prototype out of:

Arduino Uno
Hx711 amplifier module
1 kg load cell
2 push buttons
A 4 digit 7-segment display module we found online, but we don't know its specific name
HC-05 Bluetooth module, no specific manufacturer
Lilypad switch CR2032 battery module
DC-DC step up to 5V boost converter module

Our prototype works. Well, sort of (we're still trying to work out the boost converter and c2032 to work). We have diagrammed how each module connects to each other on a piece of paper. However, we want to properly diagram this in a way so we can create a PCB for it.
I have tried the Eagle and Fritzing programs. I am very inexperienced with them. I am not able to find the HC-05 and LED display .sch or .fzz files online for this, so I have came to a halt. I am not sure how each of these modules are actually wired together either.
What can I do next?

I'm a bit unclear what your question is. If your prototype works, can you not look at it to find how it's wired together?  There are many good tutorials on Eagle.  Don't bother with Fritzing - it seems easy at first, but you'll hit its limitations very quickly.

Thank you.  I'm lost as to what to do next, as no one in my school knows about PCB manufacture.

As I wrote there ^^, I don't understand what you're asking for help with. Could you clarify please?  Removing all information from your question which is not directly relevant to the question would be a good way to start.

You're enrolled in engineering at a school where nobody (not even the teachers?) know about PCB design? I found Fritzing to be very useful for new users, you should check out some youtube tutorials on how to import components you find off the web. Also, probably running the whole thing of a CR2032 won't last long with the 4 digit 7 segment display, afaik. Have you calculated the power usage? Engineering isn't just flicking some parts together ;D

You can just place a pin header on your diagram, where you'll want to solder (or mount) the HC-05 module. Or check the internet for existing HC-05 fritzing files. For the 4digit7segment I think you'd be able to find a genereic one. Mind the difference between common anode/cathode and you'll be fine.

You can try to implement the circuit without an Arduino board on a breadboard. So you can get more information about what works and what not. From there after making necessary changes (if there is any), you can draw the schematics and create a PCB layout using Orcad, Eagle etc.There are a lot of tutorials out there about PCB designing.

You can find the parts on fritzing.org. Anyway. You can get rid of some parts and save money if you pick the right ones. Instead of an Arduino Uno take an Arduino Pro Mini with 3.3V and HC-05 without a breakout for 5V Arduinos.
Doing that everything will smaller and running on 3.3V thus getting rid of the DC-DC converter.

Sorry, I am very inexperienced.  Would I be able to run everything at 3.3 volts with a CR2032 coin cell battery?  That is why I have the DC-DC converter.
I am not able to use AAs as I am trying to use as minimal space as possible

Possibly. But you have to take tight control over everything. I assume your Scale will be off most of the time. If you turn everything off and put the Arduino Pro Mini into sleep you can get as low as 1µA. A coin cell battery like CR2032 has something about 200mAh capacity. So it can stay in sleep mode for 200'000 hours or 22 years. Of course the battery will self-discharge much faster. While active your components will draw much more power. You need to examine how much power all your components draw and if you can turn them off. This can be a long path of trial and error.

I am trying to use as minimal space as possible - there are quite a few Arduinos that are much smaller than the Uno, for example an Arduino Micro.


text:
Coding multiple servos in Arduino
I'm a first year persuing Mechatronic engineering, and I'm having trouble with this code that I am using to control a biped robot for my project.
#include <servo.h>
Servo myservoa;
           myservob;
           myservoc;
           myservod;
int     myservoa=10;
          myservob=55;
          myservoc=25;
          myservod=125;

void setup() {
    myservoa.attach(2)
    myservob.attach(3)
    myservoc.attach(4)
    myservod.attach(5)
}

void loop() {
    for pos=10;pos<=75;pos+=1;
    {
        myservoa.write(pos);
        delay(1000);
    }
    for pos=55;pos<=100;pos+=1;
    {
        myservob.write(pos)
        delay (1800)
    }
    for pos=25;pos<=165;pos+=1;
    {
        myservoc.write(pos)
        delay (1000)
    }
    for pos=125;pos<=170;pos+=1;
    {
        myservod.write(pos)
        delay (1800)
    }
}

Could there be an error in the code?

Yeah, some syntax errors. For now I formatted your code correctly and changed the Void and Int to lower case. But you really have to describe, what your actual problem is. You should get error messages during compilation. It is mandatory to add those to your question (click at "edit" under your question do directly editing it)

@chrisl ... "some" syntax errors...? I think it's easier to list the bits that aren't a syntax error.

@user47756 You really need to go back to basics with your C++ syntax knowledge.  Learn the basic syntax before you try writing code.

Chrisl,what syntax errors did you get?

@user47756, are you not getting syntax errors?

what does this question mean? ...Could there be an error in the code?

I think in total there are maybe 5 lines there that don't have syntax errors (not counting brackets)...

Could there be an error in the code?

You could say that, yes.  Let's list all the syntax errors to start with:
#include <servo.h>
Servo myservoa;
           myservob; // This has no type. It's just a word by itself.
           myservoc; // This has no type. It's just a word by itself.
           myservod; // This has no type. It's just a word by itself.

int     myservoa=10; // You already defined myservoa as a Servo type.
          myservob=55; // This has no type. It's just a word by itself.
          myservoc=25; // This has no type. It's just a word by itself.
          myservod=125; // This has no type. It's just a word by itself.

void setup()
{
    myservoa.attach(2) // Semicolons must terminate all statements.
    myservob.attach(3) // Semicolons must terminate all statements.
    myservoc.attach(4) // Semicolons must terminate all statements.
    myservod.attach(5) // Semicolons must terminate all statements.
}

void loop()
{
    for pos=10;pos<=75;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservoa.write(pos);
        delay(1000);
    }
    for pos=55;pos<=100;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservob.write(pos)  // Semicolons must terminate all statements.
        delay (1800) // Semicolons must terminate all statements.
    }
    for pos=25;pos<=165;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservoc.write(pos) // Semicolons must terminate all statements.
        delay (1000) // Semicolons must terminate all statements.
    }
    for pos=125;pos<=170;pos+=1; // Braces are missing, pos is not defined, and extra ;
    {
        myservod.write(pos) // Semicolons must terminate all statements.
        delay (1800) // Semicolons must terminate all statements.
    }
}

You really need to get to grips with the syntax of a language before you start programming in that language. I count just 6 lines (not including { and }) of valid C code there, and two of them are handed to you by the IDE.

I just pasted the code from a friend only that she used two servos. Majenko,could you kindly format my code and send it to me afresh?May be am getting trouble with many servos.

@user47756 This is no free coding service. Majenko pointed out the syntax errors in your code. Look at a basic C/C++ tutorial, learn and then rewrite the code yourself. You should not just copy from other people, because if you don't really understand the code, you will not be able to change it correctly to reach your goal. Show a bit effort here.

Ohh!I got it.My code is now OK and its running successfully upon uploading.Thanks guys.@majenko,@chrisl


text:
How to map 6 bytes of raw data to long long type?
I'm trying to solve some problems for a contest, and I have a problem with it. I have to implement a function that has 3 arguments like this:
void foo(unsigned char* A, unsigned char* B, unsigned char* C);

And what comes in, is 6 bytes of data. I have to convert these 6 bytes of data to integer data (maybe long long). The problem is, I don't know how to map the bytes in the right order.
I'm using an Arduino Uno board.
Please help me with it.

What is the right order of the six bytes? And how are they contained in the char arrays from the functions parameters?

@chrisl 0x123412341234 to {0x12,0x34,0x12,0x34,0x12,0x34}

I'm not quite sure, what exactly you want to do. As I understand you get 3 char arrays with each 2 bytes in the correct order as parameters into your function, and then you want to declare a long long and fill the bytes from the arrays into this variable. Is this correct?

@chrisl nope. each of the parameters inputs 6 byte of data. and I want to convert it like what I said/

The trick is to use a union data type and get full control of the mapping. The issue of data representation and endian is now under your control:
uint64_t foo(uint8_t* A, uint8_t* B, uint8_t* C)
{
  union {
    uint64_t X;
    struct {
      uint8_t A[2];
      uint8_t B[2];
      uint8_t C[2];
      uint8_t D[2];
    };
  } map;
#if defined(MSB_ORDER)
  for (int i = 0, j = 1; i < 2; i++, j--) {
    map.A[i] = 0;
    map.B[i] = C[j];
    map.C[i] = B[j];
    map.D[i] = A[j];
  }
#else
  for (int i = 0; i < 2; i++) {
    map.A[i] = A[i];
    map.B[i] = B[i];
    map.C[i] = C[i];
    map.D[i] = 0;
  }
#endif
  return map.X;
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  uint8_t a[] = { 0x12, 0x34 };
  uint8_t b[] = { 0x56, 0x78 };
  uint8_t c[] = { 0x9a, 0xbc };
  uint64_t res = foo(a, b, c);
  Serial.print((uint32_t) (res >> 32), HEX);
  Serial.print((uint32_t) res, HEX);
}

void loop()
{
}

Cheers!

uint64_t foo(uint8_t* A, uint8_t* B, uint8_t* C)
{
    uint64_t aux = 0;
    aux = A[0];
    aux <<= 8;
    aux |= A[1];
    aux <<= 8;
    aux |= B[0];
    aux <<= 8;
    aux |= B[1];
    aux <<= 8;
    aux |= C[0];
    aux <<= 8;
    aux |= C[1];
    return aux;
}

following sample code:
  uint8_t a[] = { 0x12, 0x34 };
  uint8_t b[] = { 0x56, 0x78 };
  uint8_t c[] = { 0x9a, 0xbc };

  uint64_t result = foo(a, b, c);

  std::cout << std::hex << result;

returns 123456789abc, try the code here, excluding the std::out part, the same code will run on arduino without any problem

When passing data to functions you do this...
foo(a,b,c);

You then extract the variables or data passed to the function like..
void foo(unsigned char* A, unsigned char* B, unsigned char* C) {
    A = whatever;
    B = whatever;
    C = whatever;
}

wow. I'm not that noob ;;
I wanna map the raw 6 byte data to "long long" type variable.
memcpy won't work as I want, cause of the endian rules..

Well your function was written wrong. So is each VAR or CHAR 2 bytes then?


text:
When I turn on the servo it spins on its own before going to the right position and start the sketch
I can't get my head around this: when I turn the servo on it just spins on its own as if it's setting up, it goes to an angle superior to the one I want it to go. (Don't mind if it has to set up but it can't spin more than 20 degrees which is currently doing).
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

int degrees_of_motion = 20;
int servo_speed = 88;

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  myservo.write(0);
}

void loop() {
  for (pos = 0; pos <= degrees_of_motion; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos); // tell servo to go to position in variable 'pos'
    delay(servo_speed); // waits 15ms for the servo to reach the position
  }
  for (pos = degrees_of_motion; pos >= 0; pos -= 1) {
    // goes from 180 degrees to 0 degrees
    myservo.write(pos); // tell servo to go to position in variable 'pos'
    delay(servo_speed);// waits 15ms for the servo to reach the position
  }
}

Humm, all the methods in object myservo are available after you instantiate it.  So try initializing before you attach the servo (swap lines in your setup() method).  Also be careful not to write a negative number to the servo.  I don't think you are doing it.  But just keep it in mind as the driver might interpret it as a really large number.

st2000 Do you mean swapping  myservo.attach(3);
myservo.write(0). It doesn't make a difference also tried to put int after void setup. Was this what you meant?

If you remove the positioning code in the loop() function so that the setup() does an attach followed by positioning the servo to 0 degrees, what happens? Also what if instead of the for loops in the loop() function you instead have a global variable for position which you set to zero degrees in setup() function and then have the logic in the loop() function just increment or decrement by 1 each time loop() is called?

If I remove the loop() function so that the setup() does an attach followed by positioning the servo to 0 degrees: Every time I turn it on it will spin to an unidentified angle really fast and come back to 0 and stop. Also global variable I am really new to Arduino not really sure what you mean. Thank you very much

the question title implies that the motor moves before you run the sketch. it that what happens?

Start simple.  Just power up the servo without connecting the control line to anything.  Most if not all normal servos should do nothing.  Maybe this servo is broken or behaves in unexpected ways. Perhaps the processor has been damaged. You might try a different Arduino Uno or at least a different PWM port on the same Arduino Uno.  Also, you might try a different servo library or write your own.

jsotola If I upload an empty sketch on the servo and power it nothing will happen.

Also tried a new arduino

Noise on the control line could cause random movement, try putting a pulldown on the control line; If this doesn't happen with an empty sketch that is very strange.

What happens if you have a sketch such as the following? This uses the loop() function of the Arduino sketch to do one movement each time the loop() function is triggered.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos = 0;   // variable to store the servo position
int direc = 1; // direction and amount of position iteration, + to increment, - to decrement

int degrees_of_motion = 20;
int servo_speed = 88;

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  pos = 0;            // start off with zero degrees.
  direc = 1;          // start off incrementing the angle by 1
}

void loop() {
  if (direc > 0 && pos > degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = degrees_of_motion;
  }
  if (direc < 0 && pos < - degrees_of_motion) {
    direc *= -1;       // change the direction of iteration, keep amount
    pos = - degrees_of_motion;
  }

  myservo.write(pos);    // tell servo to go to position in variable 'pos'
  pos += direc;          // increment/decrement the position
  delay(servo_speed);    // waits 15ms for the servo to reach the position
}

Thank you but there is no difference with this sketch


text:
Removing and using programmed Atmega 328 of Arduino UNO on customised PCB
I am a newbie. I would like to kno whether the original Atmega328 on Arduino Uno, programmed with my own sketch, can be removed from an Arduino Uno board and used  on my customised PCB?

Do you have the PDIP throughhole or a SMD package version? Sure it's possible, you're just moving the chip around. If you have the support circuitry (clock-gen, power, reset lines,..), there's no reason why this shoudln't work. See https://www.youtube.com/watch?v=8i-2xKcDCzM

Yes, it can. Your board will need to provide +5v and ground, a reset signal, and a crystal for the chip's programmed clock frequency (unless you reprogrammed it to use its internal clock). The power and clock signals will need filter capacitors. You can even re-program it on the board with an FTDI (USB-TTL Serial) cable.
There are lots do-it-yourself instructions to build an Arduino board, which is a good place to start, even if what you eventually want is a larger system board with an Arduino integrated into it. This is one I can vouch for; I built Mr. Alves' Version-1 as my only Uno-like board and have been using it for several years.

Yes. Just need a few components:
10K reset pullup resistor.
0.1uF or 100nF ceramic caps:
1 to bring in DTR signal  from an FTDI Basic if you plan to reprogram the '328P, or to have a serial interface for debugging
1 on the Aref pin for analog voltage reference decoupling
1 on the VCC pin
1 on the Avcc pin. Avcc also connect to Vcc.
Crystal and two 22pF caps as noted already, or a 3-pin resonator, at 16 MHz.
Alternately, you can use the internal 8 MHz circuit for the clock, but the clock source fuses will need to be re-Programmed (using a Programmer).
If you will using a Reset switch, then a diode across the 10K pullup resistor (cathode to the 5V supply, anode to the Reset pin) can also prevent any high voltage glitches on the Reset signal from looking like a High Voltage programming pulse and making the chip look hung up as it waits for the programming sequence to begin.

Yes  I did it. Making the board was not so difficut but took quite some time to solder all the components the others mentioned (chrystals,capacitors, resistors and connectors. However,I found the Nick Gammon site very useful, particularly for the programming
part.http://www.gammon.com.au/forum/bbshowpost.php?bbtopic_id=123


text:
How to solve the white blocks on LCD keypad display?
I have just bought my first Arduino (a Mega 2560 R3 clone by ELEGOO), and I got a cheap LCD display to go with it. I cannot for the life of me get it to display anything other than a row of white blocks (although I uploaded a different sketch that I change the numbers of one of the ports and now it shows the top 3 blocks of the second row as white as well).
When I read the notes on the example LCD sketch "Display" it says the following:
The circuit:

LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
LCD R/W pin to ground
LCD VSS pin to ground
LCD VCC pin to 5V
10K resistor:
ends to +5V and ground
wiper to LCD VO pin (pin 3)

However, when I plug my display into the Arduino the pins don't seem to go into the same ports and there is no other way of fitting it in. For reference my pins go:
LCD - Mega2560

 VSS - AREF,
 VDD - GND,
 V0 - 13,
 RS - 12,
 RW - 11,
 E - 10,
 D0 - 9,
 D1 - 8,
 D2 - 7,
 D3 - 6,
 D4 - 5,
 D6 - 4,
 D7 - 3,
 D8 - 2,
 A - 1-TX,
 K - 0-RX,

 RST - RESET,
 5V - 5V,
 VIN - VIN,
 A0 - A0,
 A1 - A1,
 A2 - A2,
 A3 - A3,
 A4 - A4,
 A5 - A5,

I am not sure what to do any assistance you can provide would be greatly appreciated.
Liam

the pins don't seem to go into the same ports - can you elaborate on that? What do you mean by "same"?

Sorry im new to all this, what i mean is that the pins on the LCD dont seem to match up where the instructions in the code say they should go, (or at least where i think they should go)

OK, what sketch? Link please.

Are you just jamming a vanilla LCD module directly into the side of an Arduino rather than wiring it in properly? An LCD screen is not a shield.

I think you are assuming the pins of the LCD screen match up 1:1 with the pins of the shield. That is wrong. Very wrong. You should start with a tutorial for similar shields (they're all the same, for certain values of "same"), such as this one.

I followed a clip on youtube, but I basically have no idea what I am doing. The display that I have does seem to be designed to plug into an Arduino, it has pins on both sides that line up with the socket on the Arduino (the reset, a0-a5 etc).

this is the sort of thing I tried, the display is very similar to mine. Arduino LCD / Keypad Shield

This seems to be the exact same display as mine - Module Review #1 - LCD Keypad Shield for Arduino

I finally solved the issue, it turns out there was nothing wrong with the LCD shield or the sketch, the problem was the MEGA 2560 (by ELEGOO). The solder joint at port 'Digital 5' was missing, the pin was through the board but there was no joint. All I did to fix it was to properly solder the joint like the others are and it started to work.
Just in case anyone has a similar sort of problem as I did or wants to check the ports are working this is the sketch that I was using when I discovered the missing joint, its a simply scrolling LED sketch:
 /*
  For Loop Iteration

 Demonstrates the use of a for() loop.
 Lights multiple LEDs in sequence, then in reverse.

 The circuit:
 * LEDs from pins 2 through 7 to ground

 created 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Tom Igoe

This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/ForLoop
 */

int timer = 100;           // The higher the number, the slower the timing.

void setup() {
  // use a for loop to initialize each pin as an output:
  for (int thisPin = ***2***; thisPin < ***13***; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  // loop from the lowest pin to the highest:
  for (int thisPin = ***2***; thisPin < ***13***; thisPin++) {
    // turn the pin on:
    digitalWrite(thisPin, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(thisPin, LOW);
  }

  // loop from the highest pin to the lowest:
  for (int thisPin = ***7***; thisPin >= ***13***; thisPin--) {
    // turn the pin on:
    digitalWrite(thisPin, HIGH);
    delay(timer);
    // turn the pin off:
    digitalWrite(thisPin, LOW);
  }
}

you can modify the numbers that are in asterisks in order to check whichever pins you need.
To use it you build the following circuit:

Then simply change which port you connect the wire from the anode of the LED to and wait for the LED to flash on.
Thank you to everyone who posted a message to try and help me fix it, youve helped me learn a lot.
Liam

The words you use to describe the parts of the display and which sketch you are using need to be more precise.
Regarding the part you linked to in your question, the dark blue part is the LCD (Liquid Crystal Display).  Not many buy just this part.  It is too hard to use.
Under it is a green board with the commonly found Hitachi LCD Controller.  This is what most people buy and call the LCD. Many Arduino sketches are written for the Hitachi LCD Controller. While you could connect this type of board directly to an Arduno, you would have to make a special cable which must follow the pin assignments in the particular sketch you are using!
Finally, the darker board beneath the green board appears to be an Arduino shield.  Normally Arduino shields adapt what ever circuit happens to be upon the shield to the Arduino Uno pins and form-factor.  However, again, you mush use a sketch which which follow the pin assignments for the particular shield!
Armed with this knowledge, you should be using/looking-for a sketch specific to your Arduino shield. I suspect you are using the wrong sketch and this is resulting in "white blocks" on your LCD display.
Other considerations:

It is possible your contrast in incorrectly set.  Identify if this control is available on the shield you are using and consider adjusting it.
Is the shield plugged in correctly?  Check to make sure all the pins are connected to the Arduino.  Most shields are designed specifically for the Arduino Uno form factor.
If you are still having problems, consider buying everything (the Arduino Uno and the LCD shield) from one specific well known vendor which can supply support through direct contact or forums.  Usually a good vendor will provide support especially if they provide all parts of a project.

Other approaches:
You should find a sketch which works with your LCD & Buttons Arduino shield.  However, as you have figured out the paths between the Arduino and the Hitachi like LCD Module you might try using the LiquidCrystal Library.  When this library is instantiated, the pins of the Arduino which are to control the Hitachi like LCD module are passed as arguments.  Using the information in the question, it is likely the instantiation should look similar to this:
LiquidCrystal(12, 10, 5, d5, 4, 3)

...Note, you are missing "d5" in your question.  So the above is likely not correct.  Also, from your description, the Arduino appears to control contrast ("V0" pin) for this shield.  As the LiquidCrystal library does not appear to support this, you may need to create additional code to control contrast.

Thank you very much for such a detailed answer, I have used my multimeter and it turns out the pins on the green controller board under the display don't line in the same order as the pins on the LCD keypad shield.

I thought you bought those two (the green LED board (which likely has an Hitachi like interface) and the darker Arduino shield board) together from the same vendor!  Why would they not line up?

it came assembled as one unit. When I used my multimeter to check which pins on the green board were connected to which pins on the black board they seemed to come out different to what everyone else has

Ah! I see.  Well, there are differences between the Uno and Mega 2560.  See this discussion for more.  However I doubt this is the problem.  Note that many Hitachi LCD type board can work in 8 bit mode, 4 bit mode and even serial (uses only 1 bit) mode.  It looks like the sketch you are using is setting up the pins for 4 bit mode.  As what is written in the sketch does not match the wiring of the black board I still say you are using the wrong sketch.  Humm, are you using "LiquidCrystal lcd"? Let me add something to my answer.

Hum, this contrast issue is troublesome.  I see a big multi turn pot right next to the LCD's V0 pin.  I'm betting that controls the contrast and not the Arduino's pin 13 as you have in your question.


text:
Printing transmission data from nRF24L01+
I have a beginner's problem. I have 2 nRF24L01+ devices. They are communicating with each other great, and I can talk with the nRF via SPI.
The problem is I want to display, on the serial monitor, the number of retransmitted packets (ARC_CNT) and the number of lost packets (PLOS_CNT), which are both in the "observe_tx" register on the nRF.
I am using the "Getting Started" example from RF24 1.3.1, with Arduino 1.84, with a few more bits added, and it all works great apart from getting it to show PLOS_CNT & ARC_CNT! I have tried:
printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"));

But this does not give the correct result.
As you have probably guessed, I know nothing about C or C++. There must be a simple way of showing the 2 numbers?
The code I am using is:
#include <SPI.h>
#include "RF24.h"
#include <printf.h> // Required for "radio.printDetails();"

/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 0;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7, 8);
/**********************************************************/

byte addresses[][6] = {"1Node", "2Node"};

// Used to control whether this node is sending or receiving
bool role = 0;

void setup() {
  //pinMode(53,OUTPUT); //may not be required after all
  Serial.begin(115200);
  printf_begin(); //required for "radio.printDetails();" to work
  Serial.println(F("RF24/examples/GettingStarted"));
  Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));
  radio.begin();
  // Set the PA Level low to prevent power supply related issues since this is a
  // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
  radio.setPALevel(RF24_PA_LOW); // _MIN, _LOW, _HIGH, _MAX
  radio.setDataRate(RF24_250KBPS); //250KBPS, _1MBPS, _2MBPS  Lowest rate gives longest range.
  radio.setChannel(108); // 0 - 124 (2.4GHz - 2.524GHz) Usually above 100 best. USA 70 - 80 best.
  radio.setRetries(15, 15); // set retry delay and no of retries. delay between retries, 0=250uS, 15 = 4000uS
  radio.setCRCLength(RF24_CRC_16);  // 8 or 16 bit crc
  radio.printDetails();
  Serial.print(radio.getChannel());
  radio.setAutoAck(1);
  // Open a writing and reading pipe on each radio, with opposite addresses
  if (radioNumber) {
    radio.openWritingPipe(addresses[1]);
    radio.openReadingPipe(1, addresses[0]);
  } else {
    radio.openWritingPipe(addresses[0]);
    radio.openReadingPipe(1, addresses[1]);
  }
  // Start the radio listening for data
  radio.startListening();
}

void loop() {
  /****************** Ping Out Role ***************************/
  if (role == 1)  {
    radio.stopListening(); // First, stop listening so we can talk.
    Serial.println(F("Now sending"));
    unsigned long start_time = micros();
    // Take the time, and send it.  This will block until complete
    if (!radio.write( &start_time, sizeof(unsigned long) )) {
      Serial.println(F("failed"));
    }
    radio.startListening(); // Now, continue listening
    unsigned long started_waiting_at = micros(); // Set up a timeout period, get the current microseconds
    boolean timeout = false; // Set up a variable to indicate if a response was received or not
    while (!radio.available()) {
      // While nothing is received
      if (micros() - started_waiting_at > 200000 ) {
        // If waited longer than 200ms, indicate timeout and exit while loop
        timeout = true;
        break;
      }
    }

    if (timeout) {
      // Describe the results
      Serial.println(F("Failed, response timed out."));
      printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"));
    } else {
      unsigned long got_time;
      // Grab the response, compare, and send to debugging spew
      radio.read( &got_time, sizeof(unsigned long) );
      unsigned long end_time = micros();
      // Spew it
      Serial.print(F("Sent "));
      Serial.print(start_time);
      Serial.print(F(", Got response "));
      Serial.print(got_time);
      Serial.print(F(", Round-trip delay "));
      Serial.print(end_time - start_time);
      Serial.println(F(" microseconds"));
    }
    // Try again 1s later
    delay(1000);
  }

  /****************** Pong Back Role ***************************/
  if (role == 0) {
    unsigned long got_time;
    if (radio.available()) {
      // Variable for the received timestamp
      while (radio.available()) {
        // While there is data ready
        radio.read(&got_time, sizeof(unsigned long));
        // Get the payload
      }
      radio.stopListening();
      // First, stop listening so we can talk
      radio.write(&got_time, sizeof(unsigned long));
      // Send the final one back.
      radio.startListening();
      // Now, resume listening so we catch the next packets.
      Serial.print(F("Sent response "));
      Serial.println(got_time);
    }
  }

  /****************** Change Roles via Serial Commands ***************************/

  if (Serial.available()) {
    char c = toupper(Serial.read());
    if (c == 'T' && role == 0) {
      Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
      role = 1; // Become the primary transmitter (ping out)
    } else if (c == 'R' && role == 1) {
      Serial.println(F("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK"));
      role = 0; // Become the primary receiver (pong back)
      radio.startListening();
    }
  }
} // Loop

printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"));

This should be
printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"),
 OBSERVE_TX, PLOS_CNT, ARC_CNT);

Where the two variables contain the values.

first OBSERVE_TX= means the text that is literally printed
%02X is the format of the variable which is printed
OBSERVE_TX is the variable name

The variable names should be in the same order as the formatting (%'s).
However, in your case the above will not result in the values you want. The items above (OBSERVE_PLOS_CNT and ARC_CNT) are offsets from an addres. What you want is to print the content of that address. Since I don't have an Arduino IDE nearby, you should find yourself the address, and use *(address + OBSERVE_PLOS_CNT). This will use the address, adds OBSERVE_PLOS_CNT, and * means it will show the content of that new address.
Btw, I'm not sure about the exact use of printf_P and PSTR.

When i try that, it gives me "observe_tx was not declared in this scope" and the same error for "plos_cnt", and does not compile. So if i declare a variable called "observe_tx", and substitute "4" for "plos_cnt" ("#define PLOS_CNT 4", in nRF24l01.h), then it prints in the serial monitor : "OBSERVE_TX=401: PLOS_CNT=0 ARC_CNT=7304, with ARC jumping 7304, 1ec4, ca88, 7650, 2218, cddc, 79a8.... each time the loop executes.
I expect PLOS, ARC to initially both be 0, and for ARC to increment  Thanks for your explanation of the additional details - good for my understanding.

The "observe_tx" register is address 0x08. "PLOS_CNT" is defined as 0x04, and ARC_CNT as 0x00. Bits 0-3 of 0x08 register are counting retries, bits 4-7 of 0x08 are counting packet loss. So, if i substitiute address 0x08, and the other numbers:       printf_P(PSTR("OBSERVE_TX=%02x: PLOS_CNT=%x ARC_CNT=%x\r\n"),
*(0x08), 0x04, 0x00);     it prints OBSERVE_TX=8: PLOS_CNT=4 ARC_CNT=0. These are the numbers, rather than the any value of an address. Have i understood it right ?

True, if you put * in front of it, it shows the content, HOWEVER, I'm sure OBSERVE_TX is not the address itself, it is an offset from a base address, but to be honest, I don't know which one. There must be another #define that contains the base address, so you should use *(base_address + OBSERVE_TX), and similar for others.

many thanks for your help. I have it working now.


text:
Will I destroy my Arduino Uno if I connect a 600-mA DC motor to the +5V pin?
I know that if I connect an electronic component that consumes more than 20 mA, my Arduino Uno will be destroyed. I don't know if that refers only to digital pins or refers to +5V pins too.

If you connect a motor to the +5V pin, it will always be on. Is that what you want?
The +5V pin on the Arduino Uno gets power from the on-board 5V linear voltage regulator OR from the USB jack, and thus the host computer. This allows the board to have a fixed 5V source even when applying 9 or 12 V to the barrel jack or the RAW pin, and to be powered by a USB host.
When you draw 600mA for your motor (ignoring what the other devices on the Arduino draw), you are drawing 600mA from the regulator's output. You are also drawing 600mA from the regulator's input, which supplies a higher voltage. Excess power is dissipated as heat. 5V * 600mA is 3W. If you power the board from 9V, you are discarding [(9V-5V)=4V] * 600mA = 2.4W of power. 2.4 Watts is probably too much for the little regulator to handle. It will get too hot and burn up.
If you do this, you will probably be able to still operate it powered by the USB port, as only the 5V regulator is damaged.
However, if you try to draw 600mA and power the board from a USB device like a computer, you may burn up the computer's USB chip and make it useless forever.
For high-power devices like motors, always power them from a sufficient external supply of the appropriate voltage. Be sure to connect the ground of the external power supply to the GND pin of the Arduino. Don't send high current through the Arduino board. The Arduino should handle signals, not power.
Use the signals to activate switching devices like MOSFETs, which are designed to control higher currents by low-power signals.

No, it shouldn't destroy it.  Although you are getting close to the current limit.
The on-board regulator (depending on the board version) can supply up to about 800mA to 1A.
However, the actual maximum current is dependent on the voltage you are supplying the board with - the higher the voltage the hotter the regulator gets and the lower the current that it can supply without shutting down (or burning out).
As long as you run the board from the lower end of the input voltage (7V, say) it should be fine.
It would be better, though, to use an external power supply for the motor anyway, just to reduce the amount of heat the regulator will pump out.
Powering from the USB won't be possible, however: the USB port has a 500mA fuse in the supply circuit.

Upvoted and removed my answer since it was wrong. I edited your answer to also remove the mention about my answer.


text:
Program doesn't read memory well
My program does not read the contents of the memory card, in this case the file "objects.txt". What I wanted to do was: the program reads the objects contained in the text file and allocates the table, then organizes the table alphabetically.
Something is escaping me. Another thing, how do I put a function recognizing if the user pressed a button and if pressed, the program continues?
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

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

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
int x = 0;
String files, memo, memo1;
int sizef = 0;
int sizef1 = 0;
int sizef2 = 0;
int y = 0;
int z = 0;

struct objeto_celeste_s {
  char nome[20];
  float ar;
  float dec;
};
typedef struct objeto_celeste_s objeto_celeste;

char * tab1 [6];
int myCompareFunction (const void * arg1, const void * arg2) {
  return strcmp (*(char **) arg1, *(char **) arg2);
}

File root;
File file;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

char * list[] = {"1.Modo Normal    ", "2.Modo Teste    ", "3.Modo GoTo     ", "4.Modo Manual  "};

// read the buttons
int read_LCD_buttons() {
  adc_key_in = analogRead(0);
  if (adc_key_in > 1000) return btnNONE;
  if (adc_key_in < 50)   return btnRIGHT;
  if (adc_key_in < 250)  return btnUP;
  if (adc_key_in < 400)  return btnDOWN;
  if (adc_key_in < 450)  return btnLEFT;
  if (adc_key_in < 650)  return btnSELECT;
  return btnNONE; // when all others fail, return this...
}

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println ("Welcome!");
  Serial.println ("Selecione um modo no lcd.");
  lcd.begin (16, 2);
  lcd.setCursor (0, 0);
  lcd.print ("  Selecione um");
  lcd.setCursor (0, 1);
  lcd.print ("      modo    ");
  delay (1000);
  lcd.clear ();
  lcd.setCursor(0, 0);
  lcd.print(">");
  lcd.println(list[0]);
  lcd.setCursor(0, 1);
  lcd.print (" ");
  lcd.println(list[1]);
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
}

void loop() {
  lcd_key = read_LCD_buttons();  // read the buttons
  switch (lcd_key) {
    // depending on which button was pushed, we perform an action
    case btnRIGHT:
      break;
    case btnLEFT:
      break;
    case btnUP:
      if (x == 1) {
        x--;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[0]);
        lcd.setCursor(0, 1);
        lcd.print (" ");
        lcd.println(list[1]);
      }
      break;
      if (x == 3) {
        x--;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[2]);
        lcd.setCursor(0, 1);
        lcd.print (" ");
        lcd.println(list[3]);
      }
      break;
    case btnDOWN:
      if (x == 0) {
        x++;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[1]);
        lcd.setCursor(0, 1);
        lcd.println("                ");
      }
      break;
      if (x == 2) {
        x++;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[3]);
        lcd.setCursor(0, 1);
        lcd.println("                ");
      }
      break;
    case btnSELECT:
      if (x == 0) {
        lcd.clear ();
        lcd.print ("Modo Normal");
        Serial.println ("Selecionou o modo normal!");
        delay (1000);
        if (SD.exists("objectos.txt")) {
          Serial.println("O ficheiro 'objetos' foi encontrado!");
          lcd.clear ();
          lcd.setCursor (0, 0);
          lcd.print ("Modo Normal");
          delay (1000);
          file = SD.open("objectos.txt", FILE_READ);
          if (file) {
            while (file.available()) {
              String line = file.readStringUntil('\n');
              sizef++;
            }
          } else {
            //se houver erro a abrir o ficheiro
            Serial.println("Erro a abrir o ficheiro 'objectos.txt'.");
          }
          objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
          Serial.print ("Contados ");
          Serial.print (sizef);
          Serial.println (" objetos no ficheiro objectos.txt.");
          if (tab == NULL) {
            lcd.clear ();
            lcd.print ("Erro a alocar memoria");
            Serial.println ("Erro a alocar memória");
            while (1) { };
          } else {
            Serial.print ("Memória alocada para ");
            Serial.print (sizef);
            Serial.println (" objectos.");
            lcd.setCursor (0, 1);
            lcd.print ("Alocados ");
            lcd.print (sizef);
            lcd.print (" obj");
          }
          file.close();
          char * line1 = (char*) malloc(15);
          file = SD.open("objectos.txt", FILE_READ);
          if (file) {
            Serial.println ("Carregando informação para a memória:");
            while (file.available()) {
              if (file.read() == '\n') {
                char * justafun = strtok (line1, " "); //divide em tokens
                while (justafun != NULL) {
                  if (y == 0) {
                    strcpy (tab[sizef2].nome, justafun);
                    Serial.print ("[");
                    Serial.print (sizef2);
                    Serial.print ("] ");
                    Serial.print(tab[sizef2].nome);
                    Serial.print (" ");
                    y++;
                  }
                  if (y == 1) {
                    tab[sizef2].ar = atof (justafun);
                    Serial.print (tab[sizef2].ar);
                    Serial.print (" ");
                    y++;
                  }
                  if (y == 2) {
                    tab[sizef2].dec = atof (justafun);
                    Serial.println (tab[sizef2].dec);
                    sizef2++;
                    y = 0;
                  }
                  justafun = strtok (NULL, " ");
                }
              }
            }
          }
          file.close ();
          delay (1500);
          lcd.clear ();
          Serial.println ("Proceda ao alinhamento manual do telescópio.");
          lcd.setCursor (0, 0);
          lcd.print ("Proceda ao ");
          lcd.setCursor (0, 1);
          lcd.print ("Alinhamento man.");
          Serial.println ("Depois de o alinhamento estar concluido, pressione o botão Select para prosseguir o programa.");
          //colocar aqui função para reconhecer quando pressiona select
          if (Serial1.available()) {
            int inByte = "V"; //Se o alinhamento está concluido, 0 para não e 1 para sim
            Serial1.write (inByte);
          }
          while (!Serial1) {
            if (Serial1.available()) {
              int inByte = "V";
              Serial1.write (inByte);
              int inByte1 = "e";
              Serial1.write (inByte1);
            }
          }
          delay (1000);
          Serial.println ("Tabela ordenada alfabeticamente:");
          qsort (tab->nome, sizef, sizeof (char *), myCompareFunction);
          for (int i = 0; i < sizef; i++)
            Serial.println (tab[i].nome);
          delay (1000);
          lcd.clear ();
          lcd.print ("Carregue Select");
          lcd.setCursor (0, 1);
          lcd.print ("Para modo manual");
          Serial.println ("Carregue em Select para ir para o modo manual e assim continuar com o programa.");
        } else {
          Serial.println ("O ficheiro 'objetos' não existe.");
          lcd.clear ();
          lcd.print ("Erro nao encontrado");
          delay (2000);
          while (1) { };
        }
      }
      if (x == 1) {
        lcd.clear ();
        lcd.print ("Modo Teste");
        Serial.println ("Selecionou o modo teste!");
        delay (2000);
        if (SD.exists("teste.txt")) {
          Serial.println("O ficheiro 'teste.txt' foi encontrado!");
          lcd.clear ();
          lcd.setCursor (0, 0);
          lcd.print ("Modo Teste");
          lcd.setCursor (0, 1);
          lcd.print ("Ficheiro encontrado");
          delay (2000);
          file = SD.open("teste.txt", FILE_READ);
          if (file) {
            while (file.available()) {//ler o ficheiro
              String line = file.readStringUntil('\n');
              sizef++;
            }
            files = "Contados " + String (sizef) + " objetos no ficheiro teste.txt.";
            Serial.println (files);
            objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
            memo = "Alocados " + String (sizef) + " obj  ";
            memo1 = "Memória alocada para " + String (sizef) + " objetos.";
            if (tab == NULL) {
              lcd.clear ();
              lcd.print ("Erro alocar memoria");
              Serial.println ("Erro a alocar memória");
              while (1) { };
            } else {
              Serial.println (memo1);
              lcd.setCursor (0, 1);
              lcd.print (memo);
            }
            file.close();
          } else {
            //se houver erro a abrir o ficheiro
            Serial.println("Erro a abrir o ficheiro 'teste.txt'.");
          }
        } else {
          Serial.println ("O ficheiro 'teste.txt' não foi encontrado.");
          lcd.clear ();
          lcd.print ("Erro nao encontrado");
          delay (2000);
          while (1) { };
        }
      }
      break;
    case btnNONE:
      break;
  }
  delay (200);
}

You are never using anything of the content oft objects.txt. in the first read you only count the lines in the file and in the second read loop you only do something, when a newline is read, nothing else

Thank you, so in the second read i should do what?

How about actually reading the lines you counted previously and then extracting the data you need from them.

How i do that? :/

Read bytes into a buffer with the read() function and then use the data. Since you havent described what kind of data you have in the file, we cannot help you doing this

How come that you have this big program with two loops for reading from a file but don't know how to read a file? Is this really your code?

Yes, it's my code. My data is "name  ar coordenates dec coordenates" ex: Alnitak 05h40m45.5s -01°56'34"

My english is not good enough, chrisl. But yes, i know how to read a file, ofc!

In first loop i want to know how many lines of text i have, so i do a loop and a container o increase loop for loop, in second loop i want to divide date lines in tokens and save that token in the respective tab.

@1manonearth, your code is very poorly indented. ... most of it is just a blob of text ... it is difficult to follow the program flow because of the way it is. ... it requires reformatting before it can be looked at .... most people do not have the time to format your code so that it can be debugged .... you may get a good answer if you spend some time and clean up your code

here is an example of properly formatted code ... https://arduino.stackexchange.com/questions/51944/sending-data-from-webserver-to-arduino

I would say you can't add a button that restarts/continues the program. Because of all the delay(...) in your code. The arduino chip cant read your input and your button, while it is in a delay mode and hence no reading from the button. Read more about non-blocking delay
You need to keep the main loop method ongoing so the microcontroller-cpu can do it's work. Instead of waiting in a delay loop, doing nothing.
So don't use any delay, they are good for beginner to jump start into Arduino.


text:
Reduce current consumption on ATtiny85
I am trying to reduce current consumption on my project. Right now it is using ~1.28mAh, it should be possible to get it much lower (I am using AA batteries as the power source).
The ATtiny85 has its fuses set to run at 1MHZ, with BOD disabled.
I am using this board to mount the CPU. I desoldered the power LED and the regulator, feeding power directly from the batteries to the 5V input.
Nothing was connected to any other pins while measuring, just 5V and GND. The code was running in debug mode, so every 8 seconds it flashed a debug LED. I don't know for how much this could account.
Full code:
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>

#define DEBUG (true)
#define INT_PIN (0)
#define OUT_PIN (2)
#define LED_PIN (1)

/***************************************************
 *  Name:        ISR(WDT_vect)
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Watchdog Interrupt Service. This
 *               is executed when watchdog timed out.
 *
 ***************************************************/
EMPTY_INTERRUPT(WDT_vect);
EMPTY_INTERRUPT(PCINT0_vect);

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Enters the arduino into sleep mode.
 *
 ***************************************************/
void enterSleep() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_cpu();
  sleep_disable(); /* First thing to do is disable sleep. */

  #if DEBUG
    digitalWrite(LED_PIN, HIGH);
    for (uint16_t dbg = 0; dbg < 65535; dbg++);
    digitalWrite(LED_PIN, LOW);
  #endif
}

/***************************************************
 *  Name:        setup
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Setup for the serial comms and the
 *                Watch dog timeout.
 *
 ***************************************************/
void setup() {
  pinMode(INT_PIN,INPUT);
  pinMode(OUT_PIN,OUTPUT);
  pinMode(LED_PIN,OUTPUT);
  ADCSRA &= ~_BV(ADEN); // ADC off
  power_all_disable();
}

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Main application loop.
 *
 ***************************************************/
void loop() {
  digitalWrite(OUT_PIN, LOW);
  digitalWrite(LED_PIN, LOW);
  /*** Setup the WDT ***/
  wdt_reset();
  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   * WDTCR on ATTINY85 / WDTCSR on ATMEGA
   */
  WDTCR |= (1<<WDCE) | (1<<WDE);
  /* set new watchdog timeout prescaler value */
  WDTCR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
  /* Enable the WD interrupt (note no reset). */
  WDTCR |= _BV(WDIE);
  // sleep for 8 seconds x 43200 = 96 hours = 4 days
  for (uint16_t i = 0; i < 43200; i++)
    enterSleep();
  wdt_reset();
  wdt_disable();
  GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT0); // Use PB0 as interrupt pin
  enterSleep();

  #if DEBUG
    digitalWrite(LED_PIN, HIGH);
  #else
    digitalWrite(OUT_PIN, HIGH);
  #endif
  enterSleep();
  PCMSK &= ~_BV(PCINT0); // Turn off PB0 as interrupt pin
}

I forgot something important: when measuring I wasn't using batteries as the power source, but an FTDI serial USB cable like this link, routing 5V to a breadboard where I put my multimeter. Was I measuring the consumption of the FTDI adapter too?

A sleeping ATTINY uses only microamps, so something else is pulling your power. You might want to enable the pull-up on the INT_PIN - floating pins can waste some power when they drift between high and low voltages. You also want to do power measurements carefully with nothing attached to circuit (like you ftdi). Power can easily flow both into and out of any pin on the chip and mess up your measurements.

@bigjosh as far as I know floating pins doesn't matter in powerdown sleepmode.

I'd remove the attiny from that board, and place it directly into a breadboard. Try and simplify thing, and disabling the watchdog timer for now. 1.28mAh; I assume that h at the end is just a typo. Are you sure your multimeter is accurate in this low range?

Why is it waking every 8 seconds when (according to the comments) you expect the the loop() function's for() loop to renew sleeps for 4 days before continuing?

@JRobert: AFAIK that's how the watchdog timer works, you can only sleep for up to 8 seconds. So if I want to sleep for more than 8 seconds I have to use this for loop.

@Gerben: I also suspected that board, thanks for your suggestions, I'll try them out. Also, good call on my multimeter, it's likely not very accurate as it was very cheap (the model is DT-830D). mAh should be mA ofcourse :)

@JRobert If an input pin has pin change interrupt enabled, the is the input buffers are not disabled during sleep. 10.2.5 Digital Input Enable and Sleep Modes As shown in Figure 10-2, the digital input signal can be clamped to ground at the input of the schmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-down mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VCC/2. SLEEP is overridden for port pins enabled as external interrupt pins.

@j'ordos: Yes, that is correct. My point is that the comments indicate your total for() loop should take 4 days, yet you're seeing activity every 8 seconds (once per WDT interrupt). If, as the comments indicate, every 8 sec is not what you expected to happen, that is the place I would be looking for a bug or a disconnect in my understanding. :)

Today I measured again without the development board. Just the CPU, same setup otherwise (original code, using the FTDI cable as power source) and I got a reading of about 6-8µA. I guess that answers it! Thanks everyone for your help!

Since you have answered your own question in a positive way, you should accept your own answer. :)


text:
What's the point of a USB to Serial converter in Arduino Uno?
I am trying to understand how an Arduino Uno communicates with a PC and why it does so.
As far as I understand, an Arduino can be programmed to communicate with a PC only via a COM interface. At the same time, an Arduino Uno uses a physical USB interface to connect to a PC and it has a USB-serial converter onboard. So data sent from the board is converted from COM to USB to be transferred to the PC where USB data is converted to COM by a device driver to be read by a COM-port listener.
Why does this COM-related stuff is needed if the Arduino already uses the USB stack for connection? And is the Arduino able to emulate a keyboard and mouse if it has to use interrupts for this, so it has to act like USB device without using COM?

You seem to have multiple Arduino products jumbled up together in your mind.

@IgnacioVazquez-Abrams can you please provide detailed answer and point me where i am wrong?

The problem with your understanding is with what "COM" is.
"COMx" is not a physical serial port - it is merely a concept. It is a "serial device" in Windows.
That Serial Device is implemented as a CDC/ACM protocol on USB. It's not "converted" - "COMx" is just the visible interface to the PC's end of the CDC/ACM connection.
The ATMega328P chip (and the ATMega2560) can't talk USB directly. They talk UART. So UART data is sent to another chip that can talk both USB and UART to bridge the two technologies.
So from the PC perspective the chain is:
CDC/ACM Driver ("COMx") => USB => ATMega16U2 => UART => ATMega328P

Boards with an ATMega32U4 chip on them, like the Leonardo, can talk USB directly - so the sequence is much shorter:
CDC/ACM Driver ("COMx") => USB -> ATMega32U4

Again there is no conversion from "COMx" to "USB" since "COM" is just the name given to the exposed end of the CDC/ACM driver.
It can be said that CDC/ACM emulates a serial port over USB. It forms a channel between the CDC/ACM driver ("COMx") and a pair of bulk endpoints in the chip at the other end of the connection.

Is using ATMega16U2 a real need or just workaround for ATMega328P talking USB? I wonder why Uno has more complex and costly (in my opinion) two chips solution instead of 1 chip like Leonardo.

Because it does. That is what the designers designed it to be. If you don't want to use it then don't use it. There is this little thing called "choice". The great thing with the Uno is you can remove the MCU from the board and embed it in your own circuit and still communicate with it (UART is simple, USB is complex). You can't do that with a Leonardo.

Of course you can make your own board with the Leonardo's ATmege32u4 or any of the many other USB-enabled MCUs.  But they're generally only available in 20-year old surface mount packages, not 40-year old DIPs, so you have to be willing to use moderately modern fabrication methods.


text:
Using Arduino GSM with WiFi
I have a project that requires  data to be sent online from a moving bus. I am using ESP8266F modules to send the data.
I am wondering what Arduino modules to buy that will act as an access point with wifi and will connect to the internet through GSM.
In this configuration, the ESP8266 will connect to the access point and will upload the data online.
I want to connect a DF robot "SIM808 GPS/GPRS/GSM Shield For Arduino" to an Arduino Yun and use them as a wifi access point to connect to the internet through GSM connection.
The ESP8266 (5 of them) will connect to the Arduino Yun and will then send variables to the internet through the internet connection provided by the GSM.

Please explain better. How many nodes are sending data? You need a GSM module that can act as an access point as well?

Why not just use a cheap Android phone?

GSM modules tend to use large amounts of current when transmitting so you might find that the ESP modules reset.  Why by an Arduino, stick to an ESP8226 and use that as you access point.

All the ESP (5) are connected individually with their own power supply and they all record certain analog value to be sent to GOOGLE spreadsheet using pushingbox. And my instructor already rejected the idea of using a cheap Android phone.

ESP is a full stack WiFi module. If you are intended to collect some data from several ESPs you can configure one more as an access point and collect those data from other ESPs as stations. At access pint you can make a small web server as well. To send aggregated data through GSM then you can use a GSM module wire-connected to this ESP. To avoid RF interference while GSM sends data, you should use different power sources and shielded twisted pair for connection. It may happan, that you will need to place GSM module at some distance from ESP access point to avoid overload of the receiver. Even better to use external antennae outside the bus for GSM and shield it inside the bus to minimise the interference. I do not see how Arduino can help here.

Maxim, that a good idea but I have to upload the data (analog data) from the different ESPs to GOOGLE spreadsheet using pushingbox. Is it possible to send the data through the web server of the access point ESP connected to the GSM. And is it possible to connect ESP to GSM?


text:
Solution for two software serials
I've been working a while on a project using 3 Arduino Nanos, linked together using this tutorial Nick Gammon.
As I am not experienced with Arduino programming, I was making it step by step.
First I get all devices in one network, then managed to get the correct data sent from the correct device to one receiver. I added a Nextion display to visualize the received data. Then I have some physical buttons and some relays as well.
So far everything went fine until today. I wanted to send a command from the Nextion to the Arduino. Only then I realized that when using multiple software serial ports, only one can receive data at a time.
In my case I have an RS485 on SoftwareSerial and the Nextion.
I'm  feeling a bit upset now, as I soldered everything on a prototyping board as nice as I can. I tried to move the Nextion on to hardware serial, as that was quite easy to access, but the result was inconsistent.
Please, can someone suggest me how to change my project's hardware and what I need to program (Software Serial or Hardware Serial) to make it to work? Basically I am looking for the right direction now,  when I will get that I can figure out the rest by myself.

Please post your code and preferably your wiring. Hardware serial uses interrupts and should work OK with SoftwareSerial unless you are using a low baud rate. SoftwareSerial turns interrupts off and at low baud rates this might be long enough for hardware serial data to be missed.

If you have two different baud rates already try swapping the serial devices around. Put the faster one onto SoftwareSerial.

Thank you for your reply. At the moment i have both devices on 9600. How fast can i go with RS485? I will post code bit later, it is on my laptop at work. Also i want to say huge thank you to You, Nick Gammon for your website. For me being dumb beginner, finding lots of good stuff on it.

RS485 is really an electrical protocol. I don't see why it shouldn't work somewhat faster like 57600 baud.

Ok, now i broke everything, have to start from beginning. Will come back to this, when problems fixed. Thank you anyway. At least i know witch way to dig.

Cool bananas! All working now!

I turned my comments into an answer, which you can please accept if it helps you. That way, a future person with this problem will find an accepted answer, rather than an "unanswered question". Thanks!

Hardware serial, on the face of it, should be the more reliable because it uses hardware that can run simultaneously with other code. It uses interrupts to transfer a received byte from its internal register into program RAM.
Software serial, on the other hand, is somewhat more timing-dependent because it uses timing loops to detect each bit at the correct time. In order to do this, it turns off hardware interrupts in order to ensure that each timing loop runs at the expected speed.
If you use Software serial at the same time as hardware serial, the fact that Software serial turns off interrupts may mean that the processor doesn't get a chance to transfer the most recent byte from the serial hardware to RAM.
A work-around, if possible, is to use Software serial at the fastest possible baud rate. That means that interrupts are turned off for a shorter time. When they are turned back on the processor can recover the most recent hardware serial byte.
Thus, if you have two devices using serial, put the faster one onto Software serial, to reduce the time that interrupts are off.
RS485 does not, per se, specify a transfer rate. It is a balanced electrical protocol, which is designed to minimize the impact of noise over long cable runs.


text:
analogRead() inside a loop always returns 0
I wrote Arduino code to receive analog input from different voltage dividers connected to four pins (A0 to A4) and analog input from a temperature sensor (LM35) to A5. analogRead inside the for loop always returns zero whereas analogRead outside the for loop returns correct values.
What has to be changed to get correct values?
int time=0,y=0;
float volt;
String str;
int countParallel=0;
float voltage[]={0,0,0,0};
float temperature=0;
int sensors_pin[]={A1,A2,A3,A4,A5};
String x="";

// the setup rouontine runs once when you press reset;
void setup() {
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(50);
}

// the loop routine runs over and over again forever;
void loop() {
  Serial.println(analogRead(A5)*500/1023);
  delay(1000);
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      x += (char)inChar;
    }
  }
  // Parallel Disharging
  //  Serial.println(x);
  if(x.toInt()==1) {
    digitalWrite(13,HIGH);
    if(countParallel<1) {
      digitalWrite(6, HIGH);
      digitalWrite(7, HIGH);
      countParallel++;
    }
   for(int i=1,x=14;i<=5;i++,x++) {
    if(i<4) {
      Serial.println(analogRead(x)*(5/1023));
      delay(100);
    } else if(i==5) {
      Serial.println(analogRead(x) * p(500/1023));
      delay(100);
    }
    if(volt<2.8){
     digitalWrite(i+1,HIGH);
   } else if(temperature>40) {
     digitalWrite(2,HIGH);
     digitalWrite(3,HIGH);
     digitalWrite(4,HIGH);
     digitalWrite(5,HIGH);
    }
  }
}

// Series Discharge
if(x.toInt()==2){
    for(int i=A0;i<=A4;i++){
      if(i<A4) {
        voltage[i] = analogRead(sensors_pin[i]) * (5/1023);
        Serial.println(10);
        delay(100);
      } else if(i==A4) {
        temperature = analogRead(sensors_pin[i])*(500/1023);
        Serial.println(9);
        delay(100);
      }
      if(volt<2.8) {
        digitalWrite(i, HIGH);
        delay(100);
      } else if(temperature>40) {
        digitalWrite(2,HIGH);
        digitalWrite(3,HIGH);
        digitalWrite(4,HIGH);
        digitalWrite(5,HIGH);
      }
     }
  }
}

voltage[i]=analogRead(sensors_pin[i])*(5/1023)

Is equivalent to
voltage[i]= analogRead(sensors_pin[i])*0
          = 0;

You are using an integer division, not a floating point divsion. 5 / 1023 evaluates to 0, 5.0f / 1023 evalues to 0.00488... You have repeated this error throughout your lower loop code, which is why you're only getting 0.
In your outer loop you printed it as
Serial.println(analogRead(A5)*500/1023);

Which will first multiply by 500, then divide by 1023, which works. But since you put the above expression in parenthesis, it was first evaluated.

As a side note, it's 1024 rather than 1023.


text:
Using SD card shield on Arduino Due
I have a Seeed Studio SD card shield (V3) that I am trying to use on my Arduino Due. I am having trouble using the SD examples that come with the Arduino IDE.
They worked fine on my Arduino Uno by setting chipSelect to SS. Below is the code I used for the Arduino Uno. It is the same as the CardInfo.ino in the examples section under SD (except for the chipSelect).
CardInfo.ino

    /*
      SD card test
 This example shows how use the utility libraries on which the'
 SD library is based in order to get info about your SD card.
 Very useful for testing a card when you're not sure whether its working or not.

 The circuit:
  * SD card attached to SPI bus as follows:
 ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
 ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
 ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
 ** CS - depends on your SD card shield or module.
        Pin 4 used here for consistency with other Arduino examples

 created  28 Mar 2011
 by Limor Fried
 modified 9 Apr 2012
 by Tom Igoe
*/

// include the SD library:
#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = SS; //CHANGE HERE!!!!!!!!

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("\nInitializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
  pinMode(10, OUTPUT);     // change this to 53 on a mega

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card is inserted?");
    Serial.println("* Is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop(void) {

}

Here is a picture of my setup:

tl;dr
How do I make this shield work on my Due?

One of the main differences between UNO and DUE is the voltage level: UNO uses 5V for all its pins and DUE supports only 3.3V; Is your shield able to work with 3.3V supply AND 3.3V logical signal levels?

I think I know what's happening. This shield is built for Uno, MEGA, and some other older boards, and it communicates via SPI. I think that I will have to use a break out board instead of a shield because the SPI pins on the DUE does not match up with the shield....Unless I can figure out some way to write to it using Serial.

Did you manage to solve your problem? If so, would you like to post the answer and accept it? If you could do so, then that it would remove this question from the unanswered list of questions.

Looking at the pin configuration, the SPI pins are not in the same location as the UNO. Remove the Shield from Due and use cables to connect to the SPI pins


text:
Is there a preprocessor constant for memory size
I would like my compiles to exclude some code depending upon the flash/program space available. To be used in the demo code of a library I support. Whereas my current solution is to use a #ifdef of processor type. But I would like to be more general and not have to specify all the various chips. Rather it would be nice if there was a pre-processor constant that stated the available size.
Where I am not fluent enough in gcc and or avr-gcc I might expect to find some constants similar those that define the beginning and end of the heap.
On case example. Is that both the UNO and Leo have 32K of Flash. But the Leo's core library uses 4K for USB support, resulting in only 28K available. My Library's demo is near max'ed out on the UNO and I would like to automatically trim out based on available program space.

I've seen programs that do this, but I can't find any

Find the io__.h file for your microcontroller, on Linux it is located in /usr/lib/avr/include/avr, on Windows it will be in a somewhat similar location.
Scroll down to the part that says /* Constants */. There are couple interesting macros defined there, FLASHEND being the one you should be interested in. You can use it for example as follows:
#if FLASHEND > 0x8000
/* Include some extra code when sufficient flash is available. */

#endif