text:
how fast does loop() run in Arduino
Hi I am using Arduino Nano to gamify my experience on Unity3D. I know that Update() in Unity3D runs every frame per second but I because I'm not an electronics guy I don't know how loop() function runs on Arduino.
Does it depends on number of CPU cycles(or micro processor chip in case of Arduino) or what? Please explain. I facing some lags in my game. I can fix them only if know how is loop() function running on Arduino
There ain't a lot of information about loop() in arduino documentation

"runs every frame per second" not sure you completely understand frames, or maybe just a typo. but in Unity3D each frame runs as fast as possible, they don't purposefully but a delay in the frame

put a delay in the frame (can't edit it? thought i could)

Looks like the short answer is "as fast as possible".

Loop runs as long as loop needs to run.
Instructions in a CPU run sequentially. The more instructions there are the longer it takes to run.
The more code you put in loop the longer loop will run.
There are two ways to know how long each iteration of loop will take:

Profiling: Actively time each iteration of loop, though be warned, the act of timing will affect the amount of time taken.
Cycle counting. Compile the source into assembly and total up the number of clock cycles needed for all the instructions (including calls to functions). Arduous for small loops, a gargantuan task for anything else.

Also note that many external factors can affect how long loop() takes to run - such as serial communication speed, etc.

Don't forget interruptions for example updating the millis value every 16000 clock cycles (for 16Mhz oscilator). They stop execution of program in regular intervals and prevent the arduino from being a good PWM source. (yes you can turn them off)

@FilipFranik: 1. The interrupt that updates the millis() value runs every 1024 µs, or 16384 CPU cycles at 16 MHz. 2. Interrupts affect the quality of software PWM output (e.g., the Servo library). They have no effect on hardware-generated PWM (e.g., with analogWrite()).

the instructions between the end of loop() and the next run of it are a ret, jmp and a call.
You can consider the main function to be effectively:
void main(){

    init();
    while(1) loop();

}

Though in reality there is some setup done before init() to make millis() and such work.

Also you have serial event code after loop.

@Majenko isn't that done with interrupts?

No, it's not. It's just called at the end of loop. It's very crude and many people don't understand just how pointless it really is.

I think the loop() is optimized by the compiler, so no actual jmp or ret occur. The code translates to: while (1) yourLoopCode; without function call. But I saw horrible dumb things with GCC...

The more I look at the standard runtime of an arduino the more I am dissapointed...

@next-hack: Newer versions of the Arduino IDE call gcc with the -flto option, which enables link-time optimization and may result in loop() being inlined. Older versions do not use this option, so loop() gets compiled into a real function, which is repeatedly called by main().

A look at main.cpp (for avr code in my installation) in file:
C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\main.cpp

shows that the Arduino runs loop() alternately with serialEventRun() in an infinite loop:
int main(void)
{
    init();
    initVariant();
 #if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

Inspection of HardwareSerial.cpp shows that serialEventRun() simply calls serialEvent(), if you have defined it in your sketch.
This means that you can write your own infinite loop within loop() perfectly safely, unless you have written serialEvent() code and are expecting it to run regularly.
This begs the question: if serialEvent() is called sequentially with loop(), will serialEvent() be called if loop() never returns? In other words, is serialEvent() interrupt-driven as well as being called when loop() returns?  A quick test -see below- shows that it is not interrupt-driven, so the previous paragraph is true.
/*
  Serial Event Checker

  A sketch to see if serialEvent() is interrupt-driven.
  Will serialEvent() be called if loop() never returns?

  This code is based on Tom Igoe's SerialEvent example.

  On (at least) Arduino Uno we find that serialEvent() simply runs
  sequentially with loop().  When loop() never returns serialEvent()
  is never called.

  NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
  other ATmega32U4 based boards.

  R Symonds-Tayler 2018-02-01

  This example code is in the public domain.

*/

String inputString = "";         // a String to hold incoming data

void setup() {
  // initialize serial:
  Serial.begin(115200);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

// comment out this definition to allow loop() to return
#define INFINITE_LOOP

void loop() {
#ifdef INFINITE_LOOP
    while(1);
#endif

}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      Serial.print("Got: '");
      Serial.print(inputString);
      Serial.println("'");
      // clear the string:
      inputString = "";
    }
  }
}

This means that serialEvent() code might just as well go into your main loop() within a:
if(serial.available()){
   // your code here...
}

block.

It depends on what's in the loop. From a few clock cycles to infinite hang.

try looking up arduino functions
micros()
and
delayMicroseconds()
If you might need your loop to wait longer than 16000 microseconds then also look up the other delay() function which does milliseconds.
By the way, the internal clock is very slightly off and varies with room temperature, so don't rely on it staying synchronised to your other device without a handshake.

micros() and delayMicroseconds() use 32-bit integers (unsigned long) and can manage durations up to 2³² µs, or about 1.19 hours.

In this article bri_huang made a nice experiment using an oscilloscope and simple write functions.
He calculated the speed of the loop to be 117 kHz even though the microcontroller has a 16 MHz clock.
https://learn.sparkfun.com/blog/1687

That link does not really say a lot about how “fast” loop() is (which I.M.O. Is meaningless), but only how fast the Arduino implementation of digitalWrite() is (which is not exactly the fastest way to toggle a pin on the Arduino).

So no satisfactory answer yet? Or can we assume it runs at the speed of the crystal oscillator?

@Alejandro Camus It has a billion factors all the way from temperature of your room to how much load is the microprocessor is handling, we cannot even say that it runs at the speed of the oscillator as commands take time to do

That is a good test of how fast digitalWrite() works; not a good test of how fast loop() loops. In that test, they're benchmarking digitalWrite(), with no reasonable expectation that it's a single clock cycle or a single instruction.

Yep, points taken


text:
Arduino Mega and other modules power consumption
I have an Arduino Mega 2560 to which I have connected:

Arduino GSM Shield 2
Waveshare 10 DOF IMU sensor
Waveshare NEO-7M-C (B) GPS module
HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.
My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.

Current is what matters, not input voltage.

This question has been already answered by 3 pp in the arduino.stackexchange. Not only the recommended voltage is 7-12V, but also you should not increase the voltage, as the Arduino Mega 2560 has a linear voltage regulator. The larger the voltage, the larger the power dissipation, with 0 benefits. Beware that the headers on the arduino board cannot handle a very large current (maybe 500mA?).

You can't fix it with more voltage. The board you are using (schematic here) uses a linear voltage regulator. All increasing the voltage does is make the regulator run hotter.
You could try running from around 7V, this will minimize the heat dissipation in the regulator and may allow you to pull more current through it but I suspect you've simply hit the design limits of the power supply circuits.
Instead of using the Arduino's built in power supply to convert from 12V to 5V you could try using an external 5V supply with a greater current capability connected directly to the Arduino 5V rail.

You should not try to power your arduino with more than 12 V.  The barrel jack connector can take between 7 and 12 V and from there steps it down to the proper voltage for the Arduino (5V).  Anything being powered by the arduino is limited to how much current it can output, so if you have too many modules, you may need to have a separate power supply for those.  If you do this, there several things you need to consider:

What voltage does each module need? (This is probably 5V, but you should check the datasheets or any documentation you have)
How much power does it consume? You might find this in documentation, but you can also calculate it yourself: P = I*V  Once you know how much power each module/sensor consumes, you know how much your power supply needs to supply.

If you use a separate power supply for any of your modules/sensors,  make sure the ground pin is also tied to Arduino's ground.

Power applied to the VIN pin is regulated down to 5V by the on-board regulator on the Mega. The minimum voltage is about 6.2V because of the regulator dropout (that is, the regulator needs at least 1.2V above it's 5V output in order to operate.) 9-12V is recommended.
Applying a higher and higher voltage will not provide any more power to the Mega and it's peripherals/shields. Instead, the excess power is dissipated in the regulator as heat.
If you experience low-power situations, the solution is to power the peripheral devices from a separate regulator than the one built-in to the Mega, which is really intended to power the Mega board/processor and maybe 1 shield.
You could obtain a high-current (3A or more) 5V supply, and connect the peripherals' power inputs to it, as well as power the Arduino in via the 5V pin (leaving VIN disconnected!). Be sure to tie the grounds of all peripherals and the arduino and power supply together.
Be sure also to pay attention to the voltages required by the peripheral modules, as it's common now to find modules that are rated for 3.3V and would be damaged by 5V. This is probably not the case for you, since your system is working sometimes.

The Arduino GSM shield 2 demands 700mA-1000mA current. It is recommended to power the board with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current when the modem is in heavy use.
The modem can pull up to 2A of current at peak usage, which can occur during data transmission.
The GPS module takes only 35mA, so the fault is in the GSM shield.

arduino nano(5v usb)(3.3v).
arduino uno(12v dc jack)(5v).

what is this "answer"?

source: Stack Exchange

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

sort: votes


text:
NRF24L01 receiving even if no data sent
I am using nRF24L01 to communicate between two micro controllers. Both are Arduino Uno.
The question i have here is , even if i do not send any data from sender to receiver , the receiver device is constantly checking for the data, and the blank data is being received per second. And also no data is received by receiver which is sent by sender.
I am sharing the code for both sender and receiver.
Please suggest me what wrong i am doing.
Receiver Code :
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String response;
boolean done = false;

void setup() {

 delay(500);
 Serial.begin(9600);

 radio.begin();
 radio.setPALevel(RF24_PA_MIN);
 radio.openReadingPipe(0, 0xF0F0F0F0AA);
 radio.startListening();

}

void loop() {

   if (radio.available()) {

   radio.read(&response, sizeof(response));
   done = true;

}

if (done) {
  Serial.println(response);
}

done = false;
delay(1000);

}

Sender Code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
String request;

void setup() {

delay(500);
Serial.begin(9600);

radio.begin();
radio.openWritingPipe(0xF0F0F0F0AA);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();

}

void loop() {

   while ( Serial.available() > 0 )  {

   request = Serial.readString();

   Serial.println(request);
   radio.write(&request, sizeof(request));

   delay(1000);

 }
}

Comments are not for extended discussion; this conversation has been moved to chat.

I've written a code for NRF24L01+ based on the datasheet.run them on your arduino and test them.CE pin is PIN7 in arduino and CSN is PIN8 in arduino.
NRF_monitorRegisters() shows all Registers of NRF.It's nice to test your NRF
maybe it helps:
for transmitter:
#include <SPI.h>

int sending = 1;
int data = 7;

void IRQ() {
  Serial.println("STATUS register from IRQ ISR :  ");
  digitalWrite(8, 0);
  SPI.transfer(0x07);
  delay(10);
  Serial.println(SPI.transfer(0xff), BIN);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x08);
  delay(10);
  Serial.println(SPI.transfer(0xff), BIN);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);
}

void NRF_transmitterBegin() {

  //reading
  /*digitalWrite(8, 0);
    SPI.transfer(0x00);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  pinMode(7, OUTPUT);  //CE
  pinMode(8, OUTPUT);  //CSN
  delay(100);
  digitalWrite(8, 1);
  digitalWrite(7, 0);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.begin();
  delay(1000);

  digitalWrite(8, 0);   //flush TX_FIFO
  SPI.transfer(0xe1);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x00 + 0x20);
  delay(10);
  SPI.transfer(0x0e);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  /*digitalWrite(8, 0);
    SPI.transfer(0x11 + 0x20);
    delay(10);
    SPI.transfer(0x3f);
    delay(10);
    digitalWrite(8, 1);*/

  //Down for DYNPL
  digitalWrite(8, 0);
  SPI.transfer(0x1c + 0x20);
  delay(10);
  SPI.transfer(0x01);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x1d + 0x20);
  delay(10);
  SPI.transfer(0x04);
  delay(10);
  digitalWrite(8, 1);
  //Up for DYNPL

  digitalWrite(8, 0);
  SPI.transfer(0x01 + 0x20);
  delay(10);
  SPI.transfer(0x3f);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x02 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x03 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x04 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x05 + 0x20);
  delay(10);
  SPI.transfer(0x4c);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x06 + 0x20);
  delay(10);
  SPI.transfer(0x06);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x0a + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x10 + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);
  delay(10);

}

void NRF_transmit(int whatIsData , float data , float hum) {    //hum is used just for temp&humidity
  /*
     byte 0 says what is our data:  1 -> data and humidity    2 -> movement   3 -> gas

     1(float) :   byte 1 -> integer part of temp  byte 2 -> fractional part of temp   byte 3 -> integer part of humidity    byte 4 -> fractional part of humidity    byte 5 -> %battery
     2(binary) :  byte 1 -> %battery
     3(float) :   byte 1 -> integer part of gas   byte 2 -> fractional part of gas    byte 3 -> %battery

     %battery feature is in progress ...
  */

  int byte0 = 0 , byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
  float buf = 0;

  byte0 = whatIsData;

  switch (whatIsData) {
    case 1: {

        byte1 = data;
        buf = data - byte1;
        byte2 = buf * 10;

        byte3 = hum;
        buf = hum - byte3;
        byte4 = buf * 10;

        break;
      }
    case 2: {

        break;
      }
    case 3: {

        byte1 = data;
        buf = data - byte1;
        byte2 = buf * 10;

        break;
      }
    default: {
        break;
      }
  }

  digitalWrite(8, 0);
  SPI.transfer(0xe1);   //flush TX_FIFO empty
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0xa0);   //write on TX_FIFO
  delay(10);
  SPI.transfer(byte0);
  delay(10);
  SPI.transfer(byte1);
  delay(10);
  SPI.transfer(byte2);
  delay(10);
  SPI.transfer(byte3);
  delay(10);
  SPI.transfer(byte4);
  delay(10);
  SPI.transfer(byte5);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(7, 1);   //CE High
  delay(1);
  digitalWrite(7, 0);   //CE Low

}

void NRF_monitorRegisters() {

  for (int i = 0; i < 30; i++) {
    digitalWrite(8, 0);
    SPI.transfer(i);
    delay(10);
    Serial.print(i , HEX);
    Serial.print(" -> ");
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);
  }
  Serial.println("");

}

void setup() {

  Serial.begin(115200);

  NRF_transmitterBegin();
  NRF_monitorRegisters();

}

void loop() {

  NRF_transmit(3 , 15.1 , 0);

  delay(1000);
}

for receiver :
#include <SPI.h>

long int lastTime = 0;

void IRQ() {

  int whatIsData = 0;
  int byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
  float data = 0 , hum = 0 , buf = 0;

  /*Serial.println("STATUS register from IRQ ISR :  ");
    digitalWrite(8, 0);
    SPI.transfer(0x07);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  digitalWrite(8, 0);
  SPI.transfer(0x61);
  delay(10);
  whatIsData = SPI.transfer(0xff);
  delay(10);
  byte1 = SPI.transfer(0xff);
  delay(10);
  byte2 = SPI.transfer(0xff);
  delay(10);
  byte3 = SPI.transfer(0xff);
  delay(10);
  byte4 = SPI.transfer(0xff);
  delay(10);
  byte5 = SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  switch (whatIsData) {
    case 1: {

        buf = byte2;
        data = byte1 + buf / 10;
        buf = byte4;
        hum = byte3 + buf / 10;

        Serial.print("Received data from DHT22 -> temp:");
        Serial.print(data);
        Serial.print("  humidity:");
        Serial.println(hum);

        break;
      }
    case 2: {

        Serial.println("Received data from PIR -> Move detected");

        break;
      }
    case 3: {

        buf = byte2;
        data = byte1 + buf / 10;

        Serial.print("Received data from gas sensor -> %gas:");
        Serial.println(data);

        break;
      }
    default: {

        Serial.println("a problem accured");

        break;
      }
  }

}

void NRF_receiverBegin() {

  //reading
  /*digitalWrite(8, 0);
    SPI.transfer(0x00);
    delay(10);
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);*/

  pinMode(7, OUTPUT);  //CE
  pinMode(8, OUTPUT);  //CSN
  delay(100);
  digitalWrite(8, 1);
  digitalWrite(7, 0);

  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.begin();
  delay(100);

  digitalWrite(8, 0);   //flush TX_FIFO
  SPI.transfer(0xe1);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);   //flush RX_FIFO
  SPI.transfer(0xe2);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x07 + 0x20);
  delay(10);
  SPI.transfer(0xf0);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  digitalWrite(8, 0);
  SPI.transfer(0x00 + 0x20);
  delay(10);
  SPI.transfer(0x0f);
  delay(10);
  digitalWrite(8, 1);
  delay(10);

  /*digitalWrite(8, 0);
    SPI.transfer(0x11 + 0x20);
    delay(10);
    SPI.transfer(0x01);
    delay(10);
    digitalWrite(8, 1);*/

  //Down for DYNPL
  digitalWrite(8, 0);
  SPI.transfer(0x1c + 0x20);
  delay(10);
  SPI.transfer(0x01);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x1d + 0x20);
  delay(10);
  SPI.transfer(0x04);
  delay(10);
  digitalWrite(8, 1);
  //Up for DYNPL

  digitalWrite(8, 0);
  SPI.transfer(0x01 + 0x20);
  delay(10);
  SPI.transfer(0x3f);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x02 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x03 + 0x20);
  delay(10);
  SPI.transfer(0x03);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x04 + 0x20);
  delay(10);
  SPI.transfer(0xff);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x05 + 0x20);
  delay(10);
  SPI.transfer(0x4c);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x06 + 0x20);
  delay(10);
  SPI.transfer(0x06);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x0a + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

  digitalWrite(8, 0);
  SPI.transfer(0x10 + 0x20);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  SPI.transfer(0xaa);
  delay(10);
  digitalWrite(8, 1);

}

void NRF_startListening() {

  attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);

  digitalWrite(7, 1);   //CE High
  Serial.println("Listening started");

}

void NRF_monitorRegisters() {

  for (int i = 0; i < 30; i++) {
    digitalWrite(8, 0);
    SPI.transfer(i);
    delay(10);
    Serial.print(i , HEX);
    Serial.print(" -> ");
    Serial.println(SPI.transfer(0xff), BIN);
    delay(10);
    digitalWrite(8, 1);
  }
  Serial.println("");

}

void setup() {

  Serial.begin(115200);

  NRF_receiverBegin();
  NRF_startListening();
  NRF_monitorRegisters();

}

void loop() {

  /*if (millis() - lastTime > 20000) {
    NRF_monitorRegisters();
    lastTime = millis();
  }*/

}

Please, explain the how's and why's of your answer.

OK.if u read Datasheet u'll found that NRF communicates with MCU by SPI.
and u can control the NRF by it's registers.
in page 48 of NORDIC Datasheet u can see all commands of NRF (for example u can write on a register with 001A AAAA witch AAAAA is address of register and in next step u'll write the registers value.)
and in page 54 u can see the registers address.

You answer may be correct, but I learnt nothing from it. I only got two sketches, one that works; the other, no. Why one and not the other? I don't know; no explanation given.

You may have reversed the wire:
RF24 radio(7, 8); //  CE,CNS

This could be a valid comment towards an answer, but it needs more explanation.  Perhaps your theory is that by not properly enabling the chip, the idle state of MISO is being read and misinterpreted as the status register showing data available.  But if that is your theory, you need to actually state it, not just leave a cryptic mention of wiring.

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


text:
Default sketch working but arduino is not recognizing
I have an arduino UNO and when I connected the device through the USB to the PC (with windows 7 64 bit),
The default blinking sketch, which comes shipped with it, is working,
but the device recognition sound is not playing.
and the device driver installation dialog never appeared and no arduino entry in the device manager.
And when I tried to upload a successfully compiled sketch from the ide 1.8.4 ,
It just says, 'problem uploading to board'
More verbosely, ' avrdude: can't open device""\.\COM1": the system cannot find the file specified'
The device is getting power and running the sketch,
But device is not recognized, maybe it is connected charge only, can I install the drivers manually?
Thanks in advance for any help.

Is it real or a copy?

What do you mean?

Is it a genuine Arduino or a cheap clone from eBay or Amazon?

I got it from a local electronic parts store so it is a copy.

Then you need to identify what usb interface chip it uses and install the right drivers for it, and make sure that your cable is working right.

Thanks for the quick help but how to identify it?  I'm new to arduino

By reading the text on it.

Let us continue this discussion in chat.

Sorry, can't chat now. Just read the text on the USB interface chip. That's the one closest to the usb socket, obviously.

Chip says: MEGA16U2

Then you have a (potentially) genuine Arduino Uno R3. Installing the IDE should install the drivers for you - otherwise the drivers are included in the ZIP version of the IDE for you to manually install. So next is to try a different  USB cable. Some cables only have power wires in them and no data, which may be what you have there.

Welcome to Arduino Stack Exchange.  Please take the tour at https://arduino.stackexchange.com/Tour to get the most out of this site.  Generally the IDE will only offer ports that will work.

I tried a new cable but it's still the same issue.

Hahaha! I figured it out! The USB connector on the board's side was loose connected! It didn't felt like more pressable & when I pressed it enough, it firmly fitted.
When it loose connected, the board connects power only.
The drivers were installed automatically & it showed under COM6. I've got sketches running in no time.
I' ve tried a lot of knight rider patterns with a bunch of RGB LEDs then ;-)
Thank you @Majenko and the arduino stack exchage for your kind replies.


text:
Issue with If statement and boolean logic
I'm trying to control motor based on rain sensor and my own build anemometer. It should only controlling motor clockwise/CW for open the roof if there are no rain (indicated by value above 900) AND the wind speed below 4 km/h. If there are raining (analog value below 650) and/or wind speed above 4 km/h the motor should spin counterclockwise/CCW. I succeed to rotate the motor CCW if rain and/or high wind speed happen, but when the motor hit the limit switch for stopping the motor, motor only stop for maybe 2 seconds and then back rotating CW (open the roof), even the wind still above 4 km/h. The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h. Here is my If Statement logic program:
if ((analogRead(rain) < 650 || (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind < 2)){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind > 4){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind < 2){
  motor_open();
}

Did I make mistake when using && boolean operator? Or its something else?

Why do you call analogRead() multiple times? Do you expect the result to change that quickly?

Only the first and last options will be possible there.

Use analogRead() once and reuse the variable, also what about nesting if statements instead? I think that would improve readability as you can first check if it's raining and then check if it's windy, follows human pattern of thought a bit more than two comparisons at once. Another thing I would avoid is separating else statements from the if statement with a newline, harder to read.

I don't expect for fast result change, only want that the motor respond accordingly. I'm thought it would work with multiple if statements and raining and windy comparisons.

You only need two tests: "is it too windy or too wet?" Yes, close it. Otherwise, "is it not windy enough and not rainy enough?" Yes, open it.

The first paragraph of your question says no rain and wind speed below 4 km/h, roof open. The last paragraph of your question says "The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h". If the wind is 3 km/h, should the roof be open or closed?

Sorry the first was typo, it should be 2 km/h.

Could you update your question please.

i want to control motor movement (open and closed) based on rain and wind condition. If rain below 650 or wind above 4 km/h then motor closing the roof. And if rain above 900 (which indicates the rain has stop or no rain at all) and wind below 2 km/h then motor open the roof. And I had an issue with motor movement (spin direction), when the limit switch for stopping the motor (when it closing the roof) is pressed, only about 1-2 seconds after the motor stopped, it suddenly activating the motor for opening the roof, even in high wind speed (above 4 km/h).

I ran a test with your original code, with rain and wind varying over all the range:
(rain, wind) -> action
------------------------
(600, 1) -> motor_closed
(600, 2) -> motor_closed
(600, 3) -> motor_closed
(600, 4) -> motor_closed
(600, 5) -> motor_closed
(650, 1) ->
(650, 2) ->
(650, 3) ->
(650, 4) ->
(650, 5) -> motor_closed
(700, 1) ->
(700, 2) ->
(700, 3) ->
(700, 4) ->
(700, 5) -> motor_closed
(750, 1) ->
(750, 2) ->
(750, 3) ->
(750, 4) ->
(750, 5) -> motor_closed
(800, 1) ->
(800, 2) ->
(800, 3) ->
(800, 4) ->
(800, 5) -> motor_closed
(850, 1) ->
(850, 2) ->
(850, 3) ->
(850, 4) ->
(850, 5) -> motor_closed
(900, 1) ->
(900, 2) ->
(900, 3) ->
(900, 4) ->
(900, 5) -> motor_closed
(950, 1) -> motor_open
(950, 2) ->
(950, 3) ->
(950, 4) ->
(950, 5) -> motor_closed

So your logical expression reduces to this:
if (analogRead(rain) < 650 || Wind > 4) {motor_close();}
else if (analogRead(rain) > 900 and Wind == 1) {motor_open();}

It's that what you want?
What's that "limiting switch"? May be it's a physical problem (like installing sensor under de roof)

you can improve your code by declaring a temporary variable, e.g. ar in this way ar = analogRead(rain); and then perform your code checking ar instead of analogRead(rain).

The concept is when its raining or strong wind the motor will closing the roof, and when no rain and no strong wind then the motor will open the roof. For controlling motor I use 2 limit switches for stopping the motor when it reach the edge of the roof, 1 for stopping from closing, 1 for stopping from opening. There no issue with limit switches, everything looks good.

@rofimu. Look at test I ran. What is missing or superfluous in that?

actually, my first code before I use with multiple If statements is similar like this. But I don't know why every limit switch active (pressed), the motor stop (roof closed), but maybe 1-2 seconds later it turn the opposite way and open the roof although in strong wind condition, but able to stop completely after pressing the second limit switch.
I still prefer with else if (analogRead(rain) > 900 and Wind < 2) {motor_open();}. Is it and or && for the operators?

In C it is && and || for logical "and" and "or" operations.

Personally I like to force precedence in my if statements to ensure that things always work precisely as I intend.  Group your logical predicates with brackets:
if ((analogRead(rain) < 650) || (Wind > 4)) {
    motor_close();
} else if ((analogRead(rain) > 900) and (Wind < 2)) {
    motor_open();
}

Using intermediate variables would make it more readable:
bool tooWindy = (Wind > 4);
bool notWindy = (Wind < 2);
bool tooRainy = (analogRead(rain) < 650);
bool notRainy = (analogRead(rain) > 900);

if (tooWindy || tooRainy) {
    motor_close();
} else if (notWindy && notRainy) {
    motor_open();
}

Giving names to the logical conditions makes it far more obvious what is going on:

If it is too window or it is too rainy then close the roof.
Otherwise, if it's not too windy and it's not too rainy then you can open the roof.

And of course you have the time when it's between too rainy and not too rainy, or between too windy and not too windy, in which case nothing should happen. This is called hysteresis and is good to have since it stops the roof from opening and then immediately wanting to close.
You could also improve the logic of the system even more and implement a small Finite State Machine:
enum {
    CLOSED, OPENING, OPEN, CLOSING
};

int state = CLOSED;

switch (state) {
    case CLOSED:
        if ((analogRead(rain) > 900) && (Wind < 2)) {
            motor_open();
            state = OPENING;
        }
        break;

    case OPENING:
        if (digitalRead(limit_open) == HIGH) {
            motor_stop();
            state = OPEN;
        }
        break;

    case OPEN:
        if ((analogRead(rain) < 650) || (Wind > 4)) {
            motor_closed();
            state = CLOSING;
        }
        break;

    case CLOSING:
        if (digitalRead(limit_close) == HIGH) {
            motor_stop();
            state = CLOSED;
        }
        break;
}

In that you only attempt to open the roof (and even check to see if you should open the roof) if the roof is actually closed. Similarly for checking for and closing the roof - it only happens when the roof is actually open.  Nothing happens in the way of checks while the roof is in the process of opening or closing, so it has to complete its open or close operation first before any more decisions are made as to whether the roof should be open or closed.

Did I make mistake when using && boolean operator? Or its something else?

use brackets liberally.
rather than
if (x > 65 && y < 10)

instead,
if ((x > 65) && (y < 10))


text:
Arduino Mega and other modules power consumption
I have an Arduino Mega 2560 to which I have connected:

Arduino GSM Shield 2
Waveshare 10 DOF IMU sensor
Waveshare NEO-7M-C (B) GPS module
HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.
My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.


text:
I2C FRAM read/write is very slow. Taking over 500 microseconds per read, almost 500 per write
I've used the example code for the Adafruit I2C FRAM breakout board, but I've made it even simpler by just writing the same thing to each byte location and then reading them all off, doing nothing with the data.
I can tell it works because I can read off any byte and get the expected value, but the problem is that it works way too slowly. writing and reading 512 bytes takes almost a full half a second. This just won't work for my application, but I suspect there's something fundamentally wrong with what I'm doing.
I tried calling Wire.setClock(400000);, which supposedly is the maximum speed my Nano can drive an I2c slave at, but no matter what argument I input, the operation takes the same amount of time (498616 microseconds, within about +/- 20 microseconds).
I also tried calling Wire.begin(); TWBR = 10;, because I read that somewhere. But again, I get no difference. Here's my whole code- It's pretty simple
#include <Wire.h>
#include "Adafruit_FRAM_I2C.h"

/* Example code for the Adafruit I2C FRAM breakout */

/* Connect SCL    to analog 5
Connect SDA    to analog 4
Connect VDD    to 5.0V DC
Connect GROUND to common ground */

Adafruit_FRAM_I2C fram = Adafruit_FRAM_I2C();
uint16_t          framAddr = 0;

byte p = 55;   //any old value- just write the same thing into all locations

void setup(void) {
    Serial.begin(153600);
    //Wire.begin();
    //TWBR = 10;
    //Wire.setClock(400000);

    if (fram.begin()) {
        Serial.println("Found I2C FRAM");
    }
    else {
        Serial.println("I2C FRAM not identified ... check your connections?\r\n");
    }

}

void loop(void) {

    int i = 0;

    long a = micros();

    for (i ; i < 512; i++){  //write 512 bytes to the FRAM board
        fram.write8(i, p);

    }

    for (i = 0 ; i < 512; i++) {  //read 512 bytes from the FRAM board
        fram.read8(i);

    }

    long b = micros();

    Serial.println(b - a);
    Serial.println("");
}

You are running at 400000 bits per second, or 200000 per half second you say it takes.
You have about 1000 transactions (actually 1024 but for simplicity I will call it 1000)
200000/1000 = 200 bits per transaction.
Wire is blocking and not very efficient. So say it is actually only transmitting 25% of the time.

That's 50 bits per transaction. Now I don't know the protocol that chip uses, but if it's like the SPI chips it would need 5 bytes per transaction - 1 for the I2C address, 3 for the FRAM address, and 1 for the byte. With start, ack, etc call it 10 bits per byte.
That makes 50 bits per transaction.
So yes, half a second to write then read it all is perfectly possible.
The slowness stems from the fact that you are working a byte at a time instead of larger blocks of data in one transaction.

Now I  am at my computer I can take a look at the datasheet and get some more accurate numbers.
A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.
A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.
So for a read and write it's 38+48 = 86 bits.
Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.
At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.
If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.
So not a bad guestimate of 25% transmission in my original surmising.

Jeez, thanks for the breakdown on that. I wonder what the manufacturer had in mind to be able to do this, since the library only includes the single byte read and write functions.

The Adafruit library https://github.com/adafruit/Adafruit_FRAM_I2C has indeed only functions to write and read a single byte. You could add your own functions to write and read 32 bytes. I think that the FRAM is fast enough to keep up with the I2C write or read and I assume that the FRAM itself causes no extra delay.

The manufacturer provides many ways of reading and writing, not just single byte. Adafruit chose to only implement byte reads and writes for simplicity. Read the data sheet and control the chip without the crutch of a library to do more.

400kHz I2C clock, assuming at least 4k7 pullup resistors and very short wires, trying to write and read 32 bytes... that is hard to calculate, but 100ms is possible and perhaps 50ms. The Wire buffer is 32 bytes, that means when writing data already 2 bytes are taken for the register-address and 30 bytes are left for data.

@Jot - If I need two bytes for addressing, does this mean that I won't be able to write a 32 bit float?

You're mixing bits and bytes. You have 32 bytes of buffer space, which is 256 bits.


text:
Establishing an MQTT connection using Arduino Mega and ESP8266
As the title says, I want to send MQTT messages to a server using ESP8266 with an Arduino Mega as controller, but so far, every library that I have found is based on Ethernet. I don't want Ethernet, I want WiFi, so those solutions don't work for me.
I have tried using PubSubClient library, but the problem is that to create an instance (PubSubClient client(?????)), I have to set a client. What should I put in there? Is there another library I must use?

You require an ESP8266 library that implements the Arduino standard Client & Server classes (or at minimum the Client class).
Personally I'd program the ESP8266 directly to make it perform the MQTT request itself (using the libraries bundled with the ESP8266 core). Have the Arduino tell it what to send through some protocol you make yourself over UART.

you have the AT firmware in the esp8266?
use WiFiEsp library
or if you can change the esp8266 firmware, you could try JeeLabs esp-link

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


text:
Connect arduino with C# Desktop application wireless using esp8266
I am using wifi module esp8266 , what is easiest way to communicate arduino with desktop application and make a wireless communication between them. Please refer any useful resources

Are you using the ESP with an Arduino or stand-alone?

I am using esp with Arduino

There are many options. What exactly do you want to do?

Either use TCP or UDP to communicate. With TCP one end will be the server and will open a socket (your choice) and the other end will connect to it (much like communicating with a web server). With UDP both ends will open a socket and send discrete packets backwards and forwards.
How you would do either of those in C# is outside the scope of this website.
The ESP8266 has AT commands that perform the task for you - chiefly AT+CIPSTART.
The simplest to understand is probably TCP communication where you can just follow any of the myriad of website based examples. However instead of communicating with a website using HTTP you will be communicating with your own server software written in C# using your own custom designed protocol.
A simpler option may be to use a real web server as a "man in the middle" to which both the ESP8266 and your C# program communicate. That website could become a database back-end for your program.
Of course, what you decide to do depends entirely on how complex your program is and what data it is you want to transfer.

I just want to send a simple string from esp8266 to my C# application. I do not want to go for a web server. Can we do this like we do with serial port and arduino. Can you send me some useful links

Learn what TCP sockets are.

you can use a serial port, but a web server would be much simpler to deploy as it would not require client drivers.


text:
Waking Arduino from sleep by holding button for more than 3 seconds
I am working on a battery powered Arduino project, where I need to put a standalone Arduino in sleep mode (to save some battery).
My aim is to put Arduino in sleep mode by holding a button for 3 seconds or more on pin 2 (hardware interrupt) and wake it up by holding the same button by 3 seconds or more.
I can put the Arduino to sleep by holding button more than 3 seconds, but I can't wake it from it by holding the button for 3 seconds.
Below is my code:
#include <avr/sleep.h>
const int led1 = 44;
const int led2 = 45;
const int led3 = 46;
const int usbState = 12;
float pressLength = 0;
const int button = 2;
int optionOne = 100;
int optionTwo = 3000;

void setup() {
  pinMode(button, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(usbState, INPUT);
  Serial.begin(9600);
}

void loop() {
  while (digitalRead(button) == LOW) {
    delay(100);
    pressLength = pressLength + 100;
    Serial.print("ms-");
    Serial.println(pressLength);
  }
  if (pressLength >= optionTwo) {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    sleepNow();     // sleep function called here
  } else if (pressLength >= optionOne) {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, HIGH);
    while (1) {} //Keeps LEDS HIGH
  }
}

void sleepNow() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable(); // enables the sleep bit in the mcucr register
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
  sleep_mode(); // here the device is actually put to sleep!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
  while (digitalRead(button) == LOW) {
    delay(100);
    pressLength = pressLength + 100;
    Serial.print("ms-");
    Serial.println(pressLength);
  }
  if (pressLength >= optionTwo) {
    SleepNow(); //Back to sleep fucntion
  } else if (pressLength >= optionOne) {
    sleep_disable();
    // first thing after waking from sleep: disable sleep...
    resetFunc();//Resetting
  }
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}
void(* resetFunc)(void) = 0;

Please help. Thanks.

with 2 resistors and a capacitor you can do that without code.

^How, where to attach cap and resistors and what values.?

You won't manage it without external circuitry.
The problem is the Arduino has to be awake to know you held the button for 3 seconds. You can only wake immediately you press the button. However you could then sleep again if the button is released within 3 seconds.
For external circuitry, you would need to arrange to charge (or discharge) a capacitor slowly through the button so that it reaches a threshold after 3 seconds and that threshold triggers the input to the Arduino. A HIGH input on the Arduino is 0.6×Vcc, so 3.3V for a 5V Arduino. If you arrange it that the capacitor reaches 3.3V after being charged for 3 seconds the input will see it at the right time.

simulate this circuit – Schematic created using CircuitLab
In this circuit, R1 and C1 form an RC network that charges the capacitor through the switch. C1 and R1+R2 form an RC network that discharges the capacitor all the time, so it is discharged when you release the button.
Discharge time will be slightly longer than charge time owing to the addition of R1 + R2.
To calculate the charge time, you can use T=RC which is how long (in seconds) it takes to charge the capacitor up to 63.2% of the supply voltage. That's fractionally over the 60% that the HIGH threshold is, so that's fine.
If you want T=RC to equal 3 seconds, you can rearrange the formula to suit your components. For instance if you have a 1000µF capacitor available you can rearrange to R=3/0.001 = 3kΩ. So a common 3.3kΩ resistor and 1000µF capacitor would give you (3300 × 0.001) 3.3 seconds.
R2 wants to be small enough that it doesn't slow down discharge too much, yet high enough that it doesn't draw too much current. Using about 10% of R1 is reasonable (330Ω), so with a 3.3 second charge time that resistor would increase the discharge time by 0.33 seconds.
This method is basically a very extreme form of debouncing.

There is no need at all for electronics here: you can perform all in software.
When you press the button, check it after 3 seconds. If it's still pressed => set the wakeup interrupt and then sleep.
Similarly. When you press the switch during sleep, you will wake up. Before doing anywhing, check after 3 seconds if the button is still pressed. Still pressed? => wake up (i.e. enable peripherals, etc), otherwise go to sleep.
Using electronics when you have already a MCU is wasteful.

@next-hack Read paragraph 2 of the answer. Anyway, waking the MCU for a few seconds may not be what is wanted since it will increase power consumption while the decision is being made - and this is only a couple of passives anyway, with zero idle current.

@next-hack Anyway, you're second guessing the OPs requirements. Yes, as in many things, there are multiple ways of performing the same or similar task. However the OP asked specifically about waking the MCU after 3 seconds of button press, not waking the MCU immediately then 3 seconds later deciding whether or not to stay awake. Personally I wouldn't do either, but would use an external small XLP MCU (such as a PIC10LF320) as a power management controller.

my fault, I missed the "However you could then sleep again if the button is released within 3 seconds.".
About second guessing, you're right too, still, sometimes, suggestions can be useful, e.g. to make someone realize that 3 seconds in which the MCU is active (possibly in a lower power-state, using a lower clock frequency, with everything disabled), will not have any noticeable impact in most cases.


text:
RFID-RC522 not working, red led is on
I am working with RFID-RC522 and Arduino UNO. I have check pin configurations again and again tried different libraries. It is not reading card and red led on RC522 is consistently on.

Here's a picture of the card reader I have. If yours looks identical, then this library should work: https://github.com/ljos/MFRC522

The auth_read_write.ino sketch worked for me. Before you install the library, I recommend removing any other MFRC522 libraries from your arduino/library folder.
The only thing I did differently was used a 74HC4050 running at 3.3V between the Arduino and card reader. Some people claim you can connect the reader directly to the Arduino. I didn't want to take a chance of burning out the card reader so I used the 74HC4050.
Here's how I connected it:
Component markings and connections

|-------------------------------------------|
|   SPI    |  UNO  | 74HC4050  | RFID-RC522 |
|----------|-------|-----------|------------|
| SDA (SS) |  10   |     7     |            |
| SDA (SS) |       |     6     |    SDA     |
| SCK      |  13   |     5     |            |
| SCK      |       |     4     |    SCK     |
| MOSI     |  11   |     3     |            |
| MOSI     |       |     2     |    MOSI    |
| MISO     |  12   |           |    MISO    |
| IRQ      |  N/C  |    N/C    |    N/C     |
| GND      |  GND  | 8,9,11,14 |    GND     |
| RST      |   5   |           |    RST     |
| 3.3V     |       |     1     |    3.3V    |
|-------------------------------------------|


text:
POST to server using ESP8266 module- Arduino Uno- AT+ commands
I'm trying to send a set of data in Json format to a server I have set up which has a specific URL and an access token. The server requires a POST command. So my final URL is: http://myurl.com/myaccesstoken
The idea is that the Arduino UNO acquires some data from a sensor it then uses the ESP8266 to connect to wifi and send the acquired data to my server.
I do not understand why my server does not receive data
Thank you a lot in advance for your help.
I have used the following code:

#include "Arduino.h"
#include "ESP8266.h"
#include "SoftwareSerial.h"
#include "ArduinoJson.h"

#define ssid "mySSID"
#define pw "myPW"
#define IP "xxx.xxx.xxx.xxx"
#define URL "http://myurl.com/myaccesstoken"

int incomingByte;

void setup() {//I connect to wifi
  Serial.begin(115200);
  Serial.println("AT");
  delay(5000);
  analogReference(INTERNAL);
  if(Serial.find("OK")){
    Serial.println("AT+CWMODE=3");
    delay(1000);
    String WF=String("AT+CWJAP=\"")+ssid+"\",\""+pw+"\"";
    Serial.println(WF);
    delay(5000);}
}

void loop() {
  //JSON data creation
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["flow"] = 2.54;
root["measured"] = "2017-08-14T06:16:03.418Z";
root.printTo(Serial);
delay(5000);
 // I start communication with server
 Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
 delay(5000);
 Serial.println("AT+CPSTATUS");
 // I use HTTP protocol to POST the data
    Serial.println("AT+HTTPINIT");
    delay(2000);
    Serial.println("AT+HTTPPARA=\"CID\",\"1");
    delay(2000);
    Serial.println("AT+HTTPPARA=\"URL\",\"http://myurl.com/myaccesstoken\"");
    delay(2000);
    Serial.println(String("AT+HTTPPARA=\"CONTENT\",\"application/json"));
    delay(2000);
    Serial.println("AT+HTTPDATA=\" + 81 + \",1000"); //81 is the computed length of my JSON
    delay(2000);
    Serial.println("AT+HTTPACTION=1");
    delay(2000);
    Serial.println("AT+HTTPREAD");
    delay(2000);
    if(Serial.available() > 0)
        {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte);
    }
    Serial.println();
    Serial.println("AT+HTTPTERM");

    delay(5000);
  }

Your code doesn't work because you start by sending ESP-specific AT commands to open a socket, then you suddenly switch to SIM800-specific AT commands, and the ESP goes "WTF dude?!"
I suggest you read some tutorials on accessing web sites with the ESP8266 not with the SIM800.

Ok. Can you suggest tutorials? Because I used a similar code (at least in the first part) to send data on thingspeak without problem and I did not find any useful tutorials on web.

@Wolf Do you have sample thingspeak code im having trouble with ESP8622

@jason Yes.Anyway you can start from the code above, removing all the "http+xxxx". The example is too long for this chat...where I can share with you it?

I suggest you use computer based tools to start communication with ESP8266 module and test out sending and receiving data before you connect the module with Arduino.
If you are looking for tutorials for the same then I suggest you visit this link maybe it will solve your problem or give you a direction to work on


text:
Power consumption in Arithmetic Operation in Arduino UNO
I would like to know how much current is consumed by multiplication operation in Arduino (ATMega328P) microcontroller. As per ATMega328p datasheet, multiplication operation takes 2 cycles. I have to now convert it to current.
Please let me know how to calculate it. Attached is ATMega328p datasheet for frequency versus current graph.

Did you try dividing?

I very much doubt it will be measurable compare to everything else going on in the chip.

Arduino is 8-bit microcontroller run by 8 MHZ clock frequency. So, to determine the period of the microcontroller clock, use equation as below:
Period (T) = 1/f = 1/ (8*10^6) = 0.125µs
Execution time (t) = C * T = 2 cycle * 0.125µs                                                                 Energy (E) = V * I * t = 5.5 6mA(from above fiigure) * 20.125µs                                                                                Please help me to correct if that above concept is correct or not

I think you'll find the Uno runs at 16MHz, not 8Mz, and 5V, not 5.5V.

Okay...if I change that ...everthing else is ok ?

Well, it doesn't tell you how much power the multiply operation uses, only how much power is used by the entire chip during the time it takes to execute a multiply operation.

I think that should be fine.Basically, I need to calculate the energy consumption for my encoder which has few multiplication operation and addition operation. Similarly I can calculate for addition too.

Did you read about what the "P" stands for in ATmega328p? PicoPower. The chip energy consumption depends on frequency and voltage (as in the diagram above). As most hardware design consumes energy on transitions it is not realistic to try to isolate the energy requirements for the instruction set (the processor core) as there are so many other activities (transitions) going on, e.g. clocks, timers, bus, etc.

The power consumed by the chip won't change much by multiplying (compared to, say, adding). The chip is always fetching and executing instructions, unless you have put it into one of its sleep modes.
The only power consumption change would be if the instruction had a side-effect on a peripheral. For example, turning on the ADC unit (for analog reading), or by setting an output pin high or low.
Having said that, I set up a couple of tests and measured the power consumption. I didn't use a Uno because the power used by the "power on" LED and the voltage regulator tend to swamp the power consumption of the chip itself. However it was tested on an Atmega328P.

Addition
Test sketch
volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo += 42;
  }

Generated code
  a6:   80 91 00 01     lds r24, 0x0100
  aa:   90 91 01 01     lds r25, 0x0101
  ae:   8a 96           adiw    r24, 0x2a   ; 42
  b0:   90 93 01 01     sts 0x0101, r25
  b4:   80 93 00 01     sts 0x0100, r24
  b8:   f6 cf           rjmp    .-20        ; 0xa6 <main+0x10>

Measured consumption
I measured an average of 7.00 mA.

Multiplication
Test sketch
volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo *= 42;
  }

Generated code
  a6:   4a e2           ldi r20, 0x2A   ; 42
  a8:   20 91 00 01     lds r18, 0x0100
  ac:   30 91 01 01     lds r19, 0x0101
  b0:   42 9f           mul r20, r18
  b2:   c0 01           movw    r24, r0
  b4:   43 9f           mul r20, r19
  b6:   90 0d           add r25, r0
  b8:   11 24           eor r1, r1
  ba:   90 93 01 01     sts 0x0101, r25
  be:   80 93 00 01     sts 0x0100, r24
  c2:   f2 cf           rjmp    .-28        ; 0xa8 <main+0x12>

Measured consumption
I measured an average of 6.32 mA.

Conclusion
I found this rather surprising, that it used less power doing a multiplication compared to an addition. Setting all ports to output and low was intended to remove any side-effects from spurious inputs on the input ports.
Still, as you can see from the generated code, most of the instructions are "helper" instructions (like loading from registers, storing to registers, looping etc.).
I'm still not sure I believe the results, perhaps someone else would like to try to reproduce them?
Update
As Edgar Bonet pointed out, the multiplication test became zero after 14 iterations and thus it gave the processor the simpler task of multiplying by zero. I changed the multiplier to 41 which does not become zero. This time the average consumption was 7.34 mA which was higher than the addition test.

It is worth noting that, after 14 iterations, foo is zero in your multiplication test. Also, this test spends 47% of its time doing memory access, v.s. 67% for the addition test. I would expect memory accesses to cost more energy than arithmetics, as you are loaded by the stray capacitance of the whole data bus. But then, if you only read and write zeros, you never charge that stray cap.

@EdgarBonet Good catch! See amended answer.

Why not just measure the current drawn by the board and an empty loop vs. a loop that does some multiplication? (other than 1,2,4,8..)

Is there any simpler way to measure current? I have digital USB multi-meter   purchased from http://www.ebay.ca/itm/like/172750787230?chn=ps&dispItem=1. I am powering from the USB port of this usb multimeter adapter but current is always same in all cases. Please let me know.

That device can only measure current in 10mA increments. You probably need something that can measure uA or better. A decent VOM or a bench top multi meter for example.

Okay. What will be the probe pins in Arduino Micro-controller in case we have to use multi meter othan USB multi-meter?

Use the 5V supply pin and connect the meter is series.

you mean 5V pin of arduino to multimeter's +ve terminal and GND of Arduino to multimeter's GND right?

Like this Better yet, google 'how to measure current' before you break something.

Hey! For current measurements you have to move your red probe to hole marked with A, uA and/or mA, or you will shorcut something

SO, if I measure current at 5V pin of arduino using multimeter (in range of micro amper), then I can compute the power consumption as below. Is this understanding correct? Arduino Uno R3 run by 16 MHZ clock frequency. So, to determine the period of the microcontroller clock, use equation as below: Period (T) = 1/f = 1/ (1610^6) = 0.0625µs Execution time (t) = C * T = 2 cycle * 0.0625µs Energy (E) = V * I * t = 5(measure current at 5V) * (2*0.0625)µs

I could NOT read micro ampere current at 5V power point. While measuring current via digital multi-meter, the mills-ampere current is showing reading as "1." So, in the equation E=V * I t (E = V * I * t = 510mA * (2*0.0625)µs, if I put I as 10mA, does that mean current taken by entire chip not Arithmetic operations, right?

Is there any way to determined the current or energy consumed while performing instruction sets (e.g. addition, multiplication, subtraction etc) in ATMega328P?


text:
Grounding for arduino, measuring phase controllled 240V
I would like to measure a phase controlled 240Vac waveform as a digital PWM input for an arduino. The signal would look something like this:

My intent was to use a zener clipping circuit to limit the positive portion of the waveform to 5V, and measure that signal. However, I want to make sure I'm properly grounding these items. This is what my proposed circuit looks like, with all components inside a metal chassis.

I feel like ideally I would isolate this waveform from the system controller/light with a 1:1 transformer, but I'm unsure if that is feasible given its irregularity. Can I safely connect the arduino ground to the system's neutral, or am I barking up the wrong tree?
Thanks!

The more I think about it, the more I think that I should tie Arduino ground to chassis ground and rely on N and G being within a few volts of each other.

How can you get current flowing around the circuit without that ground connection? However, you really want to invest in some form of galvanic isolation to keep the mains away from the Arduino.

You shouldn't really connect the mains direct to the Arduino like that - even with a zener. The potential for disaster is somewhat large.
Instead you should galvanically isolate the mains from the Arduino. I would use something as simple as an opto-isolator:

simulate this circuit – Schematic created using CircuitLab
Make sure that R1 is rated for at least 339V and can dissipate enough power (1W). The resistance of R1 needs to be small enough that the opto-isolator triggers properly, yet large enough that you don't need a great honking heater of a resistor to cope with the power. 150K seems a reasonable compromise.
D2 is needed to prevent the LED In the opto-isolator from being reverse biased with 339V in the reverse-swing portion of the waveform.
You can incorporate your zener as well if you want to "push down" the waveform to get a lower cross section of it (clip off the upper portion) instead of just reducing its amplitude:

simulate this circuit
In this R1 is the same as the resistor you were planning to use before. The added R3 resistor is to limit the current through the LED (drop the 5V to the LED forward voltage at a suitable current for the LED).

Thanks for the response, it does seem more reasonable to isolate the arduino from the mains voltage, and I didn't think about an optocoupler. Am I correct that your second circuit would effectively provide the inverted signal of my original plan? (5V until the positive portion of the waveform, when it would be 0V) Also, your recommendation is to pin the arduino to the chassis ground at the input? Thanks!

Yes the output will be active low. No need to ground the Arduino, no.

your circuit will work, and can be simplified a little bit further. But it will work.
it is safer to use isolation, however. there are multiple ways to go about doing it.
the key here is to detect zero crossing, and start counting from there.


text:
How can I swap a servo with a stepper motor?
I'm looking for a way to swap servo 1 with a stepper motor to achieve a single direction circular motion with stops and delay. Instead, now I have the servo going back and forth to repeat the action.

This is the code I'm currently using to drive the servo:
void loop() {
  topServo.write(115);
  delay(500);

  for(int i = 115; i > 65; i--) {
    topServo.write(i);
    delay(2);
}

This is a schematic of my project:

simulate this circuit – Schematic created using CircuitLab
Can anyone help me to configure this? or point me into the right direction.
Any help would be greatly appreciated!

When you got the 28-BYJ48 stepper motor, did you also get a ULN2003  Motor driver board?

@sempaiscuba Yes, I do have a ULN2003 Motor driver board

Firstly, I'm going to assume that you got a ULN2003 Motor driver board something like this along with your 28-BYJ48 stepper motor.
Secondly, I would always recommend using a separate power supply for your stepper motors. Even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).

I've used the following code to test a setup using a 28-BYJ48 stepper motor and an Arduino. The connections to the driver board (IN1 - IN4) are mapped to pins 8-11 on the Arduino in this case. The code will cause the stepper to rotate 1 full revolution in one direction, pause for 1 second and then rotate one full revolution in the other direction.
(I've often found this simple piece of code really handy for troubleshooting!)
#include <Stepper.h>

const int stepsPerRev = 2048

// initialise the stepper library on pins 8, 9, 10 & 11
Stepper myStepper(stepsPerRev, 8,10,9,11);

void setup() {
  // set the speed
  myStepper.setSpeed(4);

}

void loop() {
  // step one revolution in one direction:
  myStepper.step(stepsPerRev);
  delay(1000);

  // step one revolution in the other direction:
  myStepper.step(-stepsPerRev);
  delay(1000);

}

thank you for your answer! I will give this a try. Is it mandatory to use a separate power supply for the stepper motor? I don't think it's drawing that much current. Or do you recommend this for other reasons? I don't have an extra power adapter laying around to test this at the moment. Could I use a battery instead?

A suitable battery will work fine, but even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).


text:
Can not receive data from UART with stepper motor
I am using an Arduino Mega2560
While my motor is moving I can not receive anything from the UARTs. When the motor ends movement, I receive data from UART.
How can I make my motor move without stopping the reception of data from UART?

Why should we take the time to help you if you won't make a little effort with your question? Edit your post to have proper spelling and punctuation. Format your code (hint: Tools > Auto Format if using the standard Arduino IDE).

If you look at AccelStepper.cpp code of the library you're using, you'll notice that runToNewPosition() is:
void AccelStepper::runToNewPosition(long position)
{
    moveTo(position);
    runToPosition();
}

which, in turns calls:
// Blocks until the target position is reached
void AccelStepper::runToPosition()
{
    while (run())
    ;
}

In turn, run() returns false only when the position is reached, as shown here:
boolean AccelStepper::run()
{
    if (_targetPos == _currentPos)
    return false;

    if (runSpeed())
    computeNewSpeed();
    return true;
}

As you can see, your program is blocked until the position is not reached.
Data can be still received by the serial port (until buffer is exceed), but you won't be able to read it until that while ends.
To make the motor running without blocking the program, you should implement the AccelStepper functions in the loop function, in a non-blocking way.
In particular, (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications), in rotate_motor() call only:
stepper1.moveTo(1100);

Then in the loop, write somewhere:
stepper1.run();

EDIT:
Hint for having the motor moving forward and then backward as in your original code:
Add a state variable (say you call it "m"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling stepper1.run(), check if you actually must move (if (m != 0)). When you call the stepper1.run() method, check if it returns false. In this case it means it reached the position, then you must change the value of m accordingly.

when I write stepper1.moveTo(1100); stepper1.run(); the motor do not make any movement . it is static. what problem??

Because, as you can see in the code, that method only sets the target position and compute the speed. (https://github.com/adafruit/AccelStepper/blob/master/AccelStepper.cpp). You must also write in the loop stepper.run(). That method is responsible for the actual movement, and it must be continuously called (in the loop function), as written in the cpp source.

ok . but I need to bring it to zero position when it finish rotate. in other words . go to 90 degree then go back to zero . that will be continuous

I wrote in the answer (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications).  :)
Hint: add a state variable (say you call it "m"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling run, check if you actually must move (if (m != 0)). When you call the run() method, check if it returns false. In this case it means it reached the position, then you must change the value of m accordingly.
I added this on the answer.


text:
How do I connect an Adafruit headphone jack to an Arduino 101?
I just purchased Adafruit headphone jack and I want to know how to connect it to an Arduino 101. I'm trying to use a breadboard to play a sample tone melody from the Arduino libraries, which I want to hear with my iPhone headphones.
I have been looking online for instructions on how to do this, but found nothing. Please advise.
Thank you!

You mean this thing? https://www.adafruit.com/product/1699

Yes that thing! :)

First you need to confirm that the socket will actually work with your headphones. Make sure that the ground connection of the headphones (either the sleeve or the ring right next to the sleeve, depending on the type of headphones) is serviced by a connection.
Second you need to wire one or both of the tip and the first ring to the Arduino's output that you are using to generate audio. This should be done through a capacitor to block the DC voltage and only pass the AC waveform.

simulate this circuit – Schematic created using CircuitLab
Ideally, though, you should first pass the signal through a small headphone amplifier otherwise you risk drawing too much current out of the Arduino's GPIO pin.


text:
Troubleshooting an Arduino Computer Program
I am trying to make a serial monitor print something based on when a button is pushed.
When the button is not pushed, the variable storing it equals 1.
When the button is pushed, the variable equals 0.
When I have an if statement like this, why does it print what I want when I have one where the zero is, but not when it is like that and the button IS pressed.
Thanks
int led = 2;
const int buzzer = 3;

int upButton = 5;
int downButton = 7;
int enterButton = 6;

int up = 1;
int down = 1;
int enter = 1;

bool homeActivated = true;
bool appsActivated = false;

int homeLocation = 1;
int appsLocation = 1;

bool homePrinted = false;
bool appsPrinted = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode (upButton, INPUT);
  pinMode (enterButton, INPUT);
  pinMode (downButton, INPUT);
  Serial.println("Initializing");
  delay(2000);
}

void loop() {
  up = digitalRead (upButton);
  enter = digitalRead (enterButton);
  down = digitalRead (downButton);

  //move up and down
  if (up = 0)
  {
    if (homeActivated = true)
    {
      homeLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      homePrinted = false;
    }
    else if (appsActivated = true)
    {
      appsLocation + 1;
      Serial.println("Scrolled Down 1");
      delay(1500);
      appsPrinted = false;
    }
  }

You need to learn basic C syntax.
= is assignment, not comparison.
For comparison you use ==

https://www.tutorialspoint.com/cprogramming/c_operators.htm

That explains a lot. Thank you so much. Thank you again, I wouldn't have figured that out. I am new to Arduino programming.


text:
Arduino Editor: Monitor menu show "Serial port unavailable"
Ubuntu 16.04LTS 64bit, Arduino Pro Mini board (ATmega 328P, 3.3V 8Mhz)
I have problem with WEB editor: I selected Arduino Pro mini and ticked "8Mhz ATmega 328P". I tried to upload "blink" test program from Examples, but Web editor show "Error uploading, check if selected board is currently available." And Monitor menu show "Serial port unavalable".
$ dmesg | grep tty
[    0.000000] console [tty0] enabled

I tried to reboot, not help. The green LED on Arduiono is "on" and red LED is blinking. I tried to verify the built-in COM port, in terminal run command    dmesg | grep FTDI, but no any output returned.
$ ls -l /dev/ttyUSB*
ls: cannot access '/dev/ttyUSB*': No such file or directory

It looks that FTDI USB to Serial port converter not recognized on Ubuntu?

I've had this in Windows before now. There, I was able to resolve it by reinstalling the driver from device manager. I don't have an Ubuntu box with me so can't test the steps for Ubuntu yet. I'll try later, but let me know if this works in the meantime.

This guide was for Ubuntu 13.04. I'm working from a mobile phone screen, so I couldn't find a more current guide.

What are you uploading through? The Pro Mini has no USB interface of its own.

Mini Pro connected via FTDI USB to Serial converter Breakout (FT232RL).

I believe, the FTDI drivers already have been built in Ubuntu, not?

Have you tried a different cable?

Tried another cable, FTDI adapter now recognized, $ ls -l /dev/ttyUSB* return
crw-rw---- 1 root dialout 188, 0 Aug 26 19:45 /dev/ttyUSB0. But Serial port is still grayed out.

And have you added yourself to the dialout group as per the Linux Arudino instructions?

I missed that, after adding user to the group 'dialout', the serial port is now enabled. sudo usermod -a -G dialout username. Thanks a lot!

type "tail -f /var/log/kern.log" into a terminal window. This will show you the messages that the kernel produces. Hit enter a few times so you can easily see when something new is added.
Now remove (hmm. easier if you do that before typing the command above).  and insert the arduino. Now your kernel should produce a few messages stating it found a new device. Linux has drivers for all popular USB chips so no driver issues expected.
With a bit of luck you'll see something like:
   Aug 27 18:53:23 kernel: usbcore: registered new interface driver ch341
   Aug 27 18:53:23 kernel: usb 3-3: ch341-uart converter now attached to ttyUSB0
What comes after "now attached to" is what you need to use for the serial port....

Do a ls -l /dev/tty* in a console screen and then search for the tty* port that your arduino is connected to (mine is ttyACM0), you will see which group (my group is dialout for Ubuntu 17.10) you need to add yourself to in order to be able to access your arduino via the Serial Monitor.


text:
Angular velocity of a dc motor controlled by a potentiometer
I created a setup in which a potentiometer controls a dc motor, with current flow through the dc motor controlled by an H-bridge.
The principle is as follows:
With the potentiometer dial set to the mid-point, the motor is off. Rotating the potentiometer clockwise would cause the motor to rotate in one direction, with speed dictated by the displacement of the potentiometer from the mid-point: the greater the displacement from mid-point, the greater the speed of rotation of the motor. If the potentiometer is rotated anti-clockwise, away from mid-point, the motor would rotate in the opposite direction from before; again, with speed dictated by the extent of displacement of the potentiometer from mid-point.
The loop has three functions, where HB_12EN is to enable the drivers, HB_1A is the first driver input, and HB_2A is the second driver input (H-Bridge pins 1, 2 and 7, respectively) as per this datasheet:
http://www.ti.com/lit/ds/symlink/sn754410.pdf
To summarise their functions: HB_12EN allows voltage to be applied to the the device controlled by the H-Bridge (in this case a motor), and is pulse-wave-modulated. HB_1A and HB_2A control the flow of current through the motor, setting its angular velocity. HB_1A set HIGH and HB_2A set LOW directs current one way through the motor, and HB1A set LOW and HB_2A set HIGH directs current the other way through the motor.
The loop is:
//OUTPUTS
int const HB_12EN = 9; //pwm pin
int const HB_1A = 2;
int const HB_2A = 3;

//INPUTS
int const POT_MOT = 0; //A0, analog 0

//GLOBAL VARIABLES
unsigned int pot_val = 0; //ADC value from potentiometer
unsigned int grp_num = 1;

pot_val = analogRead(POT_MOT);
grp_num = setMotSwitch(HB_12EN, HB_1A, HB_2A, pot_val, grp_num);
setMotSpeed(HB_12EN, pot_val, grp_num);

The two (non-library) functions are:
unsigned int setMotSwitch(int const motor_reg, int const first_motor, int const sec_motor, unsigned int pot_value, unsigned int group_num) //grp 0: 0-383; grp 1: 384-639; grp 2: 640-1023
{
  if (pot_value >= 0 && pot_value < 384)
  {
    if (group_num != 0)
    {
       digitalWrite(motor_reg, LOW);
       digitalWrite(first_motor, HIGH);
       digitalWrite(sec_motor, LOW);
       group_num = 0;
    }
  }
  else if (pot_value > 383 && pot_value < 640)
  {
    if (group_num != 1)
    {
      digitalWrite(motor_reg, LOW);
      digitalWrite(first_motor, LOW);
      digitalWrite(sec_motor, LOW);
      group_num = 1;
    }
  }
  else if (pot_value > 639 && pot_value <= 1023)
  {
    if (group_num != 2)
    {
      digitalWrite(motor_reg, LOW);
      digitalWrite(first_motor, LOW);
      digitalWrite(sec_motor, HIGH);
      group_num = 2;
    }
  }
  else
  {
      digitalWrite(motor_reg, LOW);
      digitalWrite(first_motor, LOW);
      digitalWrite(sec_motor, LOW);
      group_num = 0;
  }
  return group_num;
}

void setMotSpeed(int const motor_reg, unsigned int pot_value, unsigned int group_num)
{
  unsigned int mot_speed = 0;
  if (group_num == 0)
  {
    mot_speed = map(pot_value, 0, 383, 255, 0);
    mot_speed = constrain(mot_speed, 0, 255);
    analogWrite(motor_reg, mot_speed);
  }
  else if (group_num == 1)
  {
    if (pot_value > 500 && pot_value < 523)
    {
      digitalWrite(motor_reg, HIGH); //braking
    }
    else
    {
      digitalWrite(motor_reg, LOW);
    }
  }
  else if (group_num == 2)
  {
    mot_speed = map(pot_value, 640, 1023, 0, 255);
    mot_speed = constrain(mot_speed, 0, 255);
    analogWrite(motor_reg, mot_speed);
  }
}

I tried to proceed as follows:
As the potentiometer would produce an ADC input with 1024 states, I divided those 1024 states in to 8 groups, the first three groups, covering the first 384 states (0-383) correspond to a dc motor direction (let's say anticlockwise), representing different speeds of rotation (ignoring issues of many-to-one mapping). The middle 2 groups, 256 states (384-639), correspond to a stationary motor. The last three groups, 384 states (640-1023), correspond to motor rotation in the other direction (in this example, clockwise). The ADC inputs have to be translated in to analog outputs with 256 possible states (0-255), so I map each range as appropriate; for 0-383, the mapping has to be reversed, so an input of 383 corresponds to an input of 0. The middle range (384-639) is stationary, but I tried to make a small "sub"-range in the middle a "braking range", I believed this is achieved by setting both H-bridge inputs to LOW. The 640-1023 range mapping is 640 to 0 and 1023 to 255.
Hopefully that makes sense. It seems to work, the issue I am having is that the motor seems to achieve a greater speed in one direction compared to the other: the maximum rotation speed produced in the motor is greater when the potentiometer is at its maximum in one direction compared to the other. I am pretty sure the code above gives an "even" mapping from the potentiometer to the motor for both directions. Is this, then, something to do with hardware?, and is it something to be anticipated in these kinds of setups?
Any help would be appreciated. If anyone has any advice on the best way to combine a potentiometer -or similar- input with a motor output let me know. The "braking" functionality is also a little confusing.

I appreciate all the feedback so far. I would like to add that the code itself is a product of a number of factors. It is partly constrained by a textbook: I am trying to limit the code to what has been covered in a textbook I am working through. The other factors include: I) I wanted to use a number of functions, and II) I wanted to write a programme that would bypass setting the H-Bridge pins through every iteration. My main motivation for posting is that I would like to know if the issue I am having with motor speed is a coding issue or possibly a hardware issue.

Personally I wouldn't bother with "groups". Just do simple maths:
int velocity = analogRead(POT_MOT) - 512;

velocity now gives you a value from -512 to +511.
bool dir = (velocity >= 0);

dir is now true for a positive value (0 is considered positive) or false for negative.
velocity = abs(velocity);

velocity is now made positive if it is negative.
So you now have two variables: dir which sets the direction, and velocity which sets the speed.
Now you can "offset" it:
velocity = map(velocity, 0, 512, -128, 255);

velocity is now changed to fit into the range -128 to 255. Anything above 0 is a valid speed, anything below is the "dead zone" and stops the motor.
if (velocity <= 0) {
    // If it's negative or zero stop
    digitalWrite(motor_reg, LOW);
    digitalWrite(first_motor, LOW);
    digitalWrite(sec_motor, LOW);
} else {
    if (dir) { // Pot was positive
        analogWrite(motor_reg, velocity);
        digitalWrite(first_motor, LOW);
        digitalWrite(sec_motor, HIGH);
    } else { // Pot was negative
        analogWrite(motor_reg, velocity);
        digitalWrite(first_motor, HIGH);
        digitalWrite(sec_motor, LOW);
    }
}

Adjust the negative value in the map to change the size of the "dead zone".

i would break out this into three or at least two parts:
1) a call to change the speed of the motor;
2) a call to read the potential meter setting;
3) a call to convert the potential meter setting into motor speed, optional.
the code would look like this:
  pot_setting = potsetting_read(); //read pot setting
  speed_setting = pot2spd(pot_setting); //convert pot setting to motor speed
  motor_setspeed(speed_setting); //set motor speed

it is not difficult to figure out each of the three functions.
the  more challenging of the three, to a newbie, is the one that sets the motor speed. there are many ways to do it, and I personally prefer to use timer interrupts.
the basic construct is to sequentially go through a set of pin states, where the duration of each state transition is controlled by a timer interrupt. by changing how fast that timer interrupt takes place, you change the speed in which the pins transition their states, thus motor speed.


text:
Problem receiving full serial event+SMS
I wrote code in Arduino to read SMS. I have a problem with receiving it from serial.
String str;

void setup() {
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  delay(1000);
}

void loop() {
  Serial.println("AT+CMGF=1");
  delay(2000);
  Serial.println("AT+CMGR=1");
  delay(5000);
  while (Serial.available()>0) {
    str = char(Serial.read());
    Serial.print(str);
  }
  Serial.println();
}

I have an A6 GSM modem. When I read the serial I just get:
+CMGR: "REC READ

Nothing more!
I should get something like this:
+CMGL: 1,"REC READ","+989207201219",,"2017/08/26,21:54:56+05"
test 20

I changed my code to:
int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;
  if (readch > 0) {
    switch (readch) {
      case '\n': // Ignore new-lines
        break;
      case '\r': // Return on CR
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len-1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  // No end of line has been found, so return -1.
  return -1;
}

void setup() {
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
}

void loop() {
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CMGR=1");
  static char buffer[80];
  if (readline(Serial.read(), buffer, 80) > 0) {
    Serial.print("You entered: >");
    Serial.print(buffer);
    Serial.println("<");
  }
  delay(3000);
}

But I get nothing.

I didnt get the answer there

Did you read that you shouldn't delay?

I remove the delays, But didint get anything at all

I need a clean code to understand :(

I seem to post this same link about 10 times every day. I do wish people would learn the basics... https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Have you not noticed that you are doing two things with just one thing? I.e., you are using Serial for two purposes? Which do you want to use it for - communication with your modem, or communication with the PC? Make your mind up.

@Majenko I want to communicate with the modem, read the sms and do something based on what sms contain

I changed the code. so It works fine
String inputString = "";         // a String to hold incoming data
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("AT+CMGF=1");
  Serial.println("AT+CPMS=\"SM\",\"SM\",\"SM\"");
}

void loop() {

  Serial.println("AT+CMGR=1");

}

void serialEvent() {
    inputString = Serial.readString();
    Serial.println(inputString);
    delay(5000);
  }

The arduino is a "small memory" device. So it probably does not have a big serial buffer. On say "linux on a PC" you get a 4096 byte buffer, but on an arduino, probably only say 16. Now as luck will have it "+CMGR: "REC READ" is precisely 16 characters....
From the code that I see, you seem to be sending commands to the modem and then reading/echoing them. I would have liked to use two different serial ports or something like that.
In any case, if it sort of works for those first 16 characters, remove all the delays and put one of them near the end of the loop() function. Remove the initial print to the modem in the setup function.

I get more characters too. sometimes more than 30 characters.


text:
Super-fast USB communication; how is it possible?
On Arduino forums, there's a post where someone improved the USB communication and made it super-fast. I don't understand how he did this, and I'm trying to recreate this, but failing.
My test code
I made a simple program on Python for testing; here it's:
import serial
import sys
import datetime

ser = serial.Serial(
   port = 'COM9',
   baudrate = 26*115200, #biggest number acceptable by python
   parity = serial.PARITY_NONE,
   stopbits = serial.STOPBITS_ONE,
   bytesize = serial.EIGHTBITS
)

if ser.isOpen() == False :
   ser.open()
   if ser.isOpen() == False :
      print("Can't open serial port")
      sys.exit(1)

start = datetime.datetime.now()
s = b'abc'*10000
ser.write(s)
total_len = len(s)
end = datetime.datetime.now()
speed = total_len/(end - start).total_seconds()/1e6
print("Speed: " + str(speed) + " MB/s")

And I made a simple Arduino program to read:
char buf[500];

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

void loop() {
  if (Serial.available() > 0) {
     Serial.readBytes(buf, 500);
  }
}

With this, my best result was 0.2 MB/s with my Arduino mega. However, on that post, they reached 12 Mbit/s = 1.5 MB/s!!!!! This is insane!
Atemmpting to achieve their result:
Apparently Arduino libraries are different than before, so just taking their code and putting it in my arduino\avr\cores\arduino directory doesn't work. So I started trying to edit the code myself. I'm a C++ dev, so supposedly this should be doable... but...
The problem I faced
So eventually, the problem I faced was that there are two Serial communication modes (apparently) UART and CDC. The code from the forum uses CDC, while my Arduino IDE uses UART. I tried enabling CDC using:
#define USBCON

but this lead to the error:
error: #error "Targets with both UART0 and CDC serial not supported"

At this point I don't know how to continue, as I'm not a hardware expert. But I'd like your opinion on this whole thing:

Is it possible to get these speeds? How?
If it's, why is it not in the default Arduino library?
In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Is it possible to get these speeds? How?

Not without a 32-bit Arduino with a USB interface.

If it's, why is it not in the default Arduino library?

Because you can't use it on an 8-bit Arduino without a USB interface.

In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Yes, get a 32-bit Arduino with a USB interface such as the Arduino Due that the poster of that thread used.

Oh, I see. So the only problem is that I'm using mega? So Due or Teensy 3.6 should be fast? Thanks for explaining! I ordered these and they're on their way :)

You can't use that code on the Teensy, it's a completely different system. The Teensy already has very optimized USB anyway.

Hello again. May I ask, what's the best speed I should expect from Teensy 3.6? I got 1.15 MB/s. I was hoping of getting to the full 480 mbps = 60 MB/s. Is that possible?

You'd be better off asking that kind of thing on the teensy forums. I'd say 1.15MBps on a HS USB connection is fine for a bulk endpoint.


text:
Simplest/best way to control a set of 8-10 PWM signals from a smartphone
As part of a larger project, I would like to be able to control a set of 8-10 PWM signals remotely, from a smartphone at a distance of 10 meters or more.  I will probably convert the PWM signals to analog voltages, and reduce their voltage swings to more like 0-1v, using a resistor divider and RC filter; they will drive high impedance loads in the remainder of the project.  I’d write an app for the smartphone allowing user control over the duty-cycle of each PWM signal (and thus the analog signal levels).
It seems to me that the way to go is Arduino, interfaced to the phone with Bluetooth.  I'd need one of the higher end Arduinos to get enough PWM signals (the basic ones like Uno only have 6 PWM outputs).  Software-generated PWMs are probably not high-frequency enough, as I’d like the filtered analog signals to be as ripple-free as possible. There seem to be several ways to interface Bluetooth to Arduino, such as the HC-05.
If people here concur with this approach, I shall move this question to the Arduino forum.
`

Do you need a PWM output or just the analog value?   Might be easier to get a DAC with 8 or more outputs than to fool around generating 8 PWM signals then filtering and scaling them to get what you need.

From phone to Arduino via bluetooth, then drive something like the AD5669.  That has 8 channels, and you can connect a couple of them to the Arduino.

Interesting idea.  I think though that there's no reason to introduce another piece of hardware.   Since each signal will be driving a small subcircuit anyhow, adding a couple resistors (and a cap, though I'd probably want that anyhow) isn't really much of a burden.

might consider "splurging" for an ESP32, which has wifi and btle support.

Looks to me like ESP32 is the ticket.  Gives me Bluetooth, with optional wifi.    Gives me 16 outputs, at high frequencies (to facilitate filtering to analog).   A nice development board for $20 ... https://www.sparkfun.com/products/13907

I strongly recomend MQTT, which run over TCP/IP. That solve the distance problem. And you don't need to write a client app. And it's not bluetooth!

Never heard of MQTT.   Can you tell me more ?

HC-05 is rated to about 9m so it wouldn't necessarily meet your requirement. The ESP8266 (example of one implementation called the Node MCU) can output PWM on any of the 0-16 pins. It can easily implement a web server which would let you control your outputs via 8026.11 (wifi). It also means you don't need to build anything for the phone/ tablet/ PC just use a web browser. The duty cycle could be set through the web server on the ESP. The ESPs are around the same price as an Arduino.
I've used the HC-05 with an arduino. It works very well, though not very far. For the Android side I used app inventor which is extremely easily to use for bluetooth.

Using wifi instead of Bluetooth had occurred to me and maybe that'd be better.  I'm a little confused though: the part# you cite looks like it's just a wifi adapter for Arduino.  But you seem to be saying it's an alternative to Arduino and can provide the PWM outputs by itself.

It does look like that at first glance but is in fact an complete MCU, no Audrino required. It can be programmed using the Arduino IDE and you can use the GPIO pins.

I can live with 9 meters. This thing is more likely to be controlled by a phone (than a computer), through a GUI probably not much more complicated than 8-10 sliders (one for the duty-cycle of each PWM output).  Maybe the question I should be asking is whether that'd be easier to implement in Android or in HTML.  I'm not really familiar with doing either.

If it's < 9m and you want to choose between HTML and android for the phone side; then check out app inventor. If you go with the HC-05, then the Android side can be done entirely in app inventor which is very easy to use - no coding, just blocks.

If you're going to go with the esp32 you can't use the Arduino development environment for the Bluetooth functions and other functions are not yet implemented.

Yeah, they say you have to use the Espressif IDF instead; since I'm not familiar with the Arduino IDE anyhow, that shouldn't be a hardship for me.   This wouldn't prevent me from using App Inventor for the Android side though, would it ?

It would not prevent you from using App Inventor.


text:
Open Parent Class as Child Class (SD Fat Library)
I'm currently using the SDFat library and am passing a global FatFile

I if have a function that requires an SdFile type and I know that a given instance of FatFile is a valid SdFile what is the best way to reopen FatFile F as SdFile J?
Right now I'm doing:
SdFile ActiveFile;  //Global Active File
...
void SDRun (FatFile &RunFat)
{
  SdFile RunRoot;
  RunRoot.open("/", O_READ);
  ActiveFile.close();
  ActiveFile.open(&RunRoot,RunFat.dirIndex(),O_READ);
  ....

However, this only works when RunFat is in the root directory.

If RunFat is an instance of SdFile you can just cast it:
SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat);

RunRoot and RunFat are now the exact same file in the exact same state (no need to open it or anything) but seen as an SdFile not a FatFile.

Ok, doing SdFile& RunRoot = dynamic_cast<SdFile&>(RunFat); I get an error cannot dynamic_cast 'RunFat' (of type 'class FatFile') to type 'class SdFile&' (source type is not polymorphic)

Did you make sure you got all the & in the right places?

I have, I've also tried a few variants, but the dynamic cast continues to give me a source type is not polymorphic error.

Maybe it's not a proper child->parent relationship then. Or it's not really a class, or something?


text:
Inkjet Printer Robot Wheels
I'm newbie about Arduino.
Can i build arduino robot wheels using Canon/Epson Cartridge inkjet printer?
The idea is like Drawing Robot

but i want to use cartridge printer instead of using a pen.
so after searching, and it look like ZUtAPocketPrinter

The Drawing Robot is using Trinket Pro
And ZUtAPocketPrinter is using Arduino (don't know using Uno/Nano/etc)
Can I use Trinket Pro or what types of arduino that i can use (Uno, Nano)?
And what hardware, sensor that require to scan/measure size of the paper?
And if there is tutorial, please share the link.

Now I understand your predicament.

Usually a robot uses 2 identical motors for drive in order to change directions or go straight.  Usually a printer will only have 1 motor to drive the paper and 1 motor to drive the print head.  And usually they are not identical.  Making it difficult to build a useful robot.  Also, printers usually use stepping motors.  Most people building their first (small) robot usually use continuous servo motors.  This makes for an easy to build first (small) robot as seen in this picture:

You have to check your answer against the revised OP's question. He really wants to make a real logo turtle -like that use printer ink cartridges instead of pens.

But the OP already marked the answer as correct.  Also, it has become more apparent that the OP is looking for an opinion.  Many people will not like that as it solicits discussions instead a clear question and a concise answer.  Stackexchange works best when the OP builds something, then comes and asks why something does not work.