body:
I'm making a project with an sd card where the user enters a file name over the serial port, and then the aduino does thing to that file. Right now i'm working on getting the serial input to work, but one Serial.print() is somehow changing a variable/output of another Serial.print(), but before it is even called.
Here is my code:
char input, output;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      Serial.println("Ready\nEnter input text");
      while (!Serial.available()); // wait till serial available
      delay(2000);
      byte avail = Serial.available() - 1;//extra newline char at end that we don't want
      char inBuf[avail];
      //Serial.println(avail);
      Serial.readBytes(inBuf, avail);
      Serial.read();
      Serial.print("'");
      Serial.print(inBuf);
      Serial.println("'");
      delay(1000);
      Serial.println(avail);//problematic line
    }

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

    }

When i have the line uncommented, the output is:

    Ready
    Enter input text
    'asd&.'
    4
When all i have typed is 'asd' (no quotes).
With the line commented out, the output is as expected:

    Ready
    Enter input text
    'asd'
I have no clue how it is happening, and should be physically impossible, since it is changing code before it is called.

title: Serial.print changes serial output before it is called

Answers: 1

body: Your string needs to end with a null character `'\0'`.  I think yours does not because of the way that you filled the buffer, so you're getting whatever junk is in memory next to your array printed in addition to the array itself.


body:
My setup is using an Uno r3, and the motor driver is an L289N.

I am going to set it to run at a lower RPM, but when adjusting `enA` or `enB` to set to below 130, it won't spin.

    // connect motor controller pins to Arduino digital pins
    // motor one
    int enA = 2;
    int enB = 7;
    int in3 = 5;
    int in4 = 6;
    int in1 = 3;
    int in2 = 4;

    void setup()
    {
      // set all the motor control pins to outputs
      pinMode(enA, OUTPUT);
      pinMode(enB, OUTPUT);
      pinMode(in3, OUTPUT);
      pinMode(in4, OUTPUT);
    }
    void demoOne()
    {
      analogWrite(enB, 130);
      // turn on motor B
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      delay(500);
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      delay(5000);
      // this function will run the motors in both directions at a fixed speed
      // turn on motor A
      // set speed to 200 out of possible range 0~255
      analogWrite(enA, 130);
      // turn on motor B
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      // set speed to 200 out of possible range 0~255
      delay(100); //this function to set masa untuk rotation
      // now change motor directions
      // now turn off motor
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      delay(5000);
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      delay(200);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      delay(5000);
      digitalWrite(in3, HIGH);
      digitalWrite(in4, LOW);
      delay(200);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      delay(5000);
      digitalWrite(in3, LOW);
      digitalWrite(in4, HIGH);
      delay(100);
      digitalWrite(in3, LOW);
      digitalWrite(in4, LOW);
      delay(5000);

      analogWrite(enB, 130);
      // turn on motor B
      digitalWrite(in1, HIGH);
      digitalWrite(in2, LOW);
      delay(400);
      digitalWrite(in1, LOW);
      digitalWrite(in2, LOW);
      delay(5000);
    }

    void loop()
    {
      demoOne();
      delay(3000);

    }

title: DC motor with L289N driver cannot set RPM lower than 130

Answers: 2

body:
Looks like you are controlling two motor outputs via the H-bridge, where the logic inputs are `in1,in2` and `in3,in4`.  First of all, you need

    pinMode(in1,OUTPUT);
    pinmode(in2,OUTPUT);

One reason why the motors may not spin for analogWrite value less than 130 is that, coincidentally, the voltage output is too low and motor stalls.  Test this two ways: does (1) changing the motor supply voltage or (2) changing the argument of `analogWrite` actually change the speed?

If no, it may be that `pinMode(enA,OUTPUT);` sets the output as digital and should be removed.  In that case a number less than 128 gets interpreted as a logic 0 and the motor will not spin.

P.S. your code can be neatened up using port syntax and bitwise operators.

    digitalWrite(in1,HIGH);
    digitalWrite(in2,LOW);

can be written on a single line with

    PORTD |= _BV(in1);

Also

    digitalWrite(in1,LOW);
    digitalWrite(in2,LOW);

becomes

    PORTD &= ~(_BV(in1) | _BV(in2));

body:
On an Uno, `D2` and `D7` (`enA` and `enB`) do not have true PWM (analogWrite) capabilities- they will be 100% on at values of 128 or higher, and off at 127 and lower.

You will need to use 3, 5, 6, 9, 10 or 11 for PWM (i.e. your `enA` and `enB`) on the Uno.

See [Arduino Reference - analogWrite()][1] for more info on PWM pin availability on Arduino boards.

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


body:
Note :

This question is completely different from the questions that I have asked before although the code snippets might be the same, So please do not waive it as a duplicate right when you see it.

In my setup I have connected two arduino's Serially. An Arduino Mega is the one that is sending the string and a Arduino Uno is the one that's receiving it.

- Arduino Mega : TX1(19),RX1(18) - Serial1
- Arduino Uno : RX(10),TX(11) - using SoftwareSerial
- Gnd is connecetd on both boards

Arduino UNO - code is same for both cases

    #include <SoftwareSerial.h>
    SoftwareSerial s(10, 11);
    void setup()
    {
      delay(200);
      Serial.begin(9600);
      Serial1.begin(9600);
      s.begin(9600);
      while (!Serial) ;  // wait for Arduino Serial Monitor
    }
    void loop()
    {
      if(s.available()>0)
      {
         Serial.print("\nrec\n");
         delay(100);
         String b = s.readStringUntil('\n');
         delay(100);
         Serial.print(b);
         delay(40);
      }
   }

When the code in my arduino mega has only a print statement to send a string an infinite no. of times to the Uno, The Uno is receiving the string properly.

Arduino Mega

    void setup()
    {
      Serial1.begin(9600);
    }
    void loop()
    {
      Serial1.println("e2e4");
      delay(100);
    }

Now when I send the string an infinite no. of times from the Arduino mega but this time the mega has a lot more functions included in the program as well. In this case the Uno does not receive the string sent.

Arduino Mega - code containing a lot of functions and sedning a string to
                  Uno

    int SensorValStore_Prev[8][8] = { {0,0,0,0,0,0,0,0}, \
                                      {0,0,0,0,0,0,0,0}, \
                                      {1,1,1,1,1,1,1,1}, \
                                      {1,1,1,1,1,1,1,1}, \
                                      {1,1,1,1,1,1,1,1}, \
                                      {1,1,1,1,1,1,1,1}, \
                                      {0,0,0,0,0,0,0,0}, \
                                      {0,0,0,0,0,0,0,0} };

    int SensorValStore_Curr[8][8]={ {0,0,0,0,0,0,0,0}, \
                                    {0,0,0,0,0,0,0,0}, \
                                    {1,1,1,1,1,1,1,1}, \
                                    {1,1,1,1,1,1,1,1}, \
                                    {1,1,1,1,1,1,1,1}, \
                                    {1,1,0,1,1,1,1,1}, \
                                    {0,0,0,0,0,0,0,0}, \
                                    {0,1,0,0,0,0,0,0} };
    //int SensorValStore_Curr[8][8];
    int sum1[8],sum2[8],temp[8][8],k,l,i,j,rank,nextRow;
    String file,moveSan,Temp,bestMove;
    char Buffer[20];
    void doAction();
    void ReadSensor();
    void Difference();
    void binToIntCalc();
    void check();
    void getMovePlayed();
    void SendMove();
    void getMove();

    void setup()
    {
      Serial.begin(9600);
      lcd.begin(16,2);
      pinMode(22,INPUT_PULLUP); // Reed switch - Row1
      pinMode(24,INPUT_PULLUP); // Reed switch - Row2
      pinMode(26,INPUT_PULLUP); // Reed switch - Row3
      pinMode(28,INPUT_PULLUP); // Reed switch - Row4
      pinMode(30,INPUT_PULLUP); // Reed switch - Row5
      pinMode(32,INPUT_PULLUP); // Reed switch - Row6
      pinMode(34,INPUT_PULLUP); // Reed switch - Row7
      pinMode(36,INPUT_PULLUP); // Reed switch - Row8
      pinMode(2,INPUT_PULLUP);// Push Button
      pinMode(38,OUTPUT);
      pinMode(40,OUTPUT);
      pinMode(42,OUTPUT);
      pinMode(44,OUTPUT);
      pinMode(46,OUTPUT);
      pinMode(48,OUTPUT);
      pinMode(50,OUTPUT);
      pinMode(52,OUTPUT);
      pinMode(3,OUTPUT);
      digitalWrite(38,HIGH);
      digitalWrite(40,HIGH);
      digitalWrite(42,HIGH);
      digitalWrite(44,HIGH);
      digitalWrite(46,HIGH);
      digitalWrite(48,HIGH);
      digitalWrite(50,HIGH);
      digitalWrite(52,HIGH);
      digitalWrite(3,LOW);
    }

    void loop()
    {

      // doAction();
      delay(40);
      Difference();
      delay(40);
      binToIntCalc();
      delay(40);
      check();
      delay(40);
      getMovePlayed();
      delay(40);
      getMove();
      delay(40);
      //}
    }

    void Print(int matrix[8][8])
    {
      for(i=0;i<8;i++)
      {
        for(j=0;j<8;j++)
        {
          Serial.print(matrix[i][j]);
          Serial.print(" ");
        }
        Serial.println();
      }
    }

    void doAction()
    {
      nextRow = 0;
      for(i=0;i<8;i++)
      {
        digitalWrite(38 + nextRow,LOW);
        delay(40);
        ReadSensor(i);
        digitalWrite(38 + nextRow,HIGH);
        delay(40);
        nextRow +=2;
      }
    }

    void ReadSensor(int iter)
    {
      delay(10);
      for(j=0;j<8;j++)
        SensorValStore_Curr[iter][j] = digitalRead(j+2);
    }

    void Difference()
    {
      for(i=0;i<8;i++)
        for(j=0;j<8;j++)
          temp[i][j] = abs(SensorValStore_Curr[i][j] - SensorValStore_Prev[i[j]);

    }

    void binToIntCalc()
    {
      for(i=0;i<8;i++)
        for(j=0;j<8;j++)
        {
          sum1[i] += pow(2,j)*SensorValStore_Prev[i][j];
          sum2[i] += pow(2,j)*SensorValStore_Curr[i][j];
        }
     }

    void check()
    {
      k=0;
      l=0;
      for(i=0;i<8;i++)
      {
        if(sum2[i]>sum1[i])
          k = i;
        if(sum2[i]<sum1[i])
          l = i;
        delay(40);
      }
    }

    void getMovePlayed()
    {
      for(j=0;j<8;j++)
      {
        if(temp[k][j] == 1)
        {
          rank =k+1;
          file = String(char(97+j));
          delay(40);
          moveSan = file + rank;
          Temp = moveSan;
        }
      }
      for(j=0;j<8;j++)
      {
        if( temp[l][j] == 1)
        {
          rank =l+1;
          file = String(char(97+j));
          delay(40);
          moveSan = file + rank;
          Temp.concat(moveSan);
        }
      }
    }

    void SendMove(String movePlayed)
    {
      Serial.println("start");
      Serial.print(movePlayed);
      Serial.println();
    }

    void getMove() // SENDING STRING TO THE ARDUINO UNO
    {
     while(1){
      Serial1.println("e2e4");
      delay(100);
      }
    }

Note: getMove() is the function that sends the string to the arduino through Serial1

title: Serial communication between 2 arduino's doesn't works when Sending string in a program with a lot of functions

Answers: 1

body:
My answer might not be what you'd expect but I'll try anyway.

Did you troobleshoot your serial communications ? Try doing a simple programm for both cards and try sending data from one to another.

Uno code

    #include <SoftwareSerial.h>

    #define rxPin 10
    #define txPin 11

    SoftwareSerial s(rxPin, txPin);

    String buff = "";

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

    void loop()
    {
        if(Serial.available)
        {
            while(Serial.available())
            {
                buff += char(Serial.read());
            }
            s.print(buff);
            buff="";
        }

        if(s.available)
        {
            while(s.available())
            {
                buff += char(s.read());
            }
            Serial.print(buff);
            buff = "";
        }
    }

Mega code

    String buff = "";

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

    void loop()
    {
        if(Serial.available)
        {
            while(Serial.available())
            {
                buff += char(Serial.read());
            }
            Serial1.print(buff);
            buff="";
        }

        if(Serial1.available)
        {
            while(Serial1.available())
            {
                buff += char(Serial1.read());
            }
            Serial.print(buff);
            buff = "";
        }
    }

Did you double check your connections ? Tx (mega) to rx (uno) and rx (mega) to tx(uno)

In your setup() on your arduino mega

    void setup()
    {
      Serial.begin(9600);
      lcd.begin(16,2);
      pinMode(22,INPUT_PULLUP); // Reed switch - Row1
      pinMode(24,INPUT_PULLUP); // Reed switch - Row2
      pinMode(26,INPUT_PULLUP); // Reed switch - Row3
      pinMode(28,INPUT_PULLUP); // Reed switch - Row4
      pinMode(30,INPUT_PULLUP); // Reed switch - Row5
      pinMode(32,INPUT_PULLUP); // Reed switch - Row6
      pinMode(34,INPUT_PULLUP); // Reed switch - Row7
      pinMode(36,INPUT_PULLUP); // Reed switch - Row8
      pinMode(2,INPUT_PULLUP);// Push Button
      pinMode(38,OUTPUT);
      pinMode(40,OUTPUT);
      pinMode(42,OUTPUT);
      pinMode(44,OUTPUT);
      pinMode(46,OUTPUT);
      pinMode(48,OUTPUT);
      pinMode(50,OUTPUT);
      pinMode(52,OUTPUT);
      pinMode(3,OUTPUT);
      digitalWrite(38,HIGH);
      digitalWrite(40,HIGH);
      digitalWrite(42,HIGH);
      digitalWrite(44,HIGH);
      digitalWrite(46,HIGH);
      digitalWrite(48,HIGH);
      digitalWrite(50,HIGH);
      digitalWrite(52,HIGH);
      digitalWrite(3,LOW);
    }

I don't see the `Serial1.begin(9600)` as said by @chrisl but you mentionned it above.

I hope this helps, sorry if I've not solved your problem.


body:
The point here is to syncronise a DS3231 module (on an Arduino) via serial port with NTP time by computer.

The problem here is that I'd like to know how much time is taken by the serial and I2C transmission, because if the PC sends the time at a time `t1` and transmit it to the Arduino, the Arduino decodes it and sends it to the DS3231, the time `t1` is received at a time `t2` greater than `t1`.

    PC (t1) => Serial(t1+x) => Arduino(t1+x+y) => I2C(t1+x+y+z) => DS3231(t2=t1+x+y+z)

 - `t1` -> NTP time recorded by PC
 - `x`  -> Time taken by serial transmission
 - `y`  -> Time taken by arduino buffering/processing
 - `z`  -> Time taken by I2C transmission at 100kHz
 - `t2` -> Time when message is received by DS3231

Is it negligible for a precision at millisecond?

I found a table on Wikipedia that displays [time per bit per baudrate][1]. I am planning to use a baudrate of 57600.

I tested offset using a simple echo program available [here](https://pastebin.com/ZEhpBkLW) at 300 baud:

    String buff="";

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(300);
    }

    void loop() {
      if(Serial.available())
      {
        while(Serial.available())
        {
          buff += char(Serial.read());
        }
        Serial.print(buff);
        buff = "";
      }
    }

  [1]: https://en.wikipedia.org/wiki/Serial_port#Settings

title: What precision can I expect by syncronising DS3231 with PC serial?

Answers: 2

body:
Transmission time will certainly not be negligible. To estimate it, you could use the roundtrip delay calculation, which is (roughly) how the NTP protocol is [implemented](https://en.wikipedia.org/wiki/Network_Time_Protocol#Clock_synchronization_algorithm) in the first place.

- at PC time T1, PC sends current time T1 to Arduino via UART
- Arduino sets the time T1 in DS3231 via I2C
- Arduino reads the time T2 from DS3231 via I2C
- Arduino sends the time T2 to PC via UART. This happens at time T3 from PC's point of view.

Now the PC can estimate the half-roundtrip delay R as (T3-T2)/2. See the following chart which denotes current time form POW of PC and RTC

            |--UART--|--I2C--|--------|--I2C--|--UART--|
    PC      T1              T1+R     T2+R           T3=T2+2R
    DS3231  -                T1       T2              T2+R

Next, at time T4, the PC sends the value (T4+R) via UART. This will result in  DS3231 to be set to (T4+R), which happens exactly R time after T4, so that both clocks are now set to the same value.

Estimation of R can be repeated several times. In this case you can calculate the standard deviation which tells you how much "jitter" your clocks have.

body:
I second the general idea of Dmitry Grigoryev’s answer: your best option
is to measure a round-trip time and use half of that as an estimate of
the one-way time. Otherwise you will have too many unknowns. For
example, you don't know how long your OS takes to process the outgoing
message and send it through USB to the USB/serial bridge inside the
Arduino. As an optimization, I would send the time information and the
synchronization strobe as two separate messages, with the latter being a
single byte. This way the latency of the synchronization strobe (the
only latency that matters) is minimized.

## Latency of serial communication

I did some research to try to nail this one down. At 57600 bits/s,
the theoretical time per bit is about 17.4 µs, as stated in the
Wikipedia article you linked to. In practice, the actual time can be
rounded more or less depending on the UART capabilities and the clock
speed. You did not specify what Arduino you are using. In the following,
I will assume an AVR-based Arduino clocked at 16 MHz, which is
presumably the most common.

The UART in the AVR constrains the bit time to be a multiple of
8 CPU cycles, i.e. 0.5 µs when running at 16 MHz. The
closest you can get to the ideal timing is therefore 17.5 µs.
However, the Arduino core library has a [hard coded compatibility
exception][baud] which, in this very specific case, sets the bit
duration to 17 µs instead. Since you are presumably configuring the
port at /8N1, which is the default, the time per byte is then
170 µs (1 start bit, 8 data bits and 1 stop bit).

Actually, when transmitting a single byte, the transmission time is
slightly less than that. The UART can report the byte as received as
soon as it is done taking the required three samples of the stop bit,
which happens slightly after the _middle_ of that stop bit. The
theoretical time it takes to transmit a single byte is then about
9.56 times the single-bit duration, or about 162.56 µs at
57600/8N1.

I did a simple loopback test with the TX and the RX of my Uno shorted
together. I used a timer to time the execution of the following code:

<!-- language-all: lang-c++ -->

    Serial.write('.');
    while (!Serial.available()) continue;

The result was 182.38 µs, or about 10.73 bit durations. A
fraction of this time is taken by the execution of `Serial.write()` and
`Serial.available()`. In order to get closer to a bare hardware latency,
I also timed a low-level version of the two lines above:

    UDR0 = '.';
    while (!bit_is_set(UCSR0A, RXC0)) continue;

This has to be run with interrupts disabled. The execution time was now
between 164.19 and 164.81 µs, i.e. 9.66 to 9.69 bits
durations.

## Alternative approach

As a final note, I would recommend you consider buying a GPS module with
a 1PPS output. This 1PPS is a 1 Hz logic signal with the rising
edges tightly aligned to the start of the UTC seconds. You typically get
an accuracy in the tens of _nanoseconds_. Since this is just a logic
signal that you can easily compare with the 1 Hz output of your RTC
module, you get rid of all the latency issues that come with computers
(your NTP client), or data links (USB, serial, I2C).

[baud]: https://github.com/arduino/Arduino/blob/1.8.5/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp#L109-L118


body:
Is there any other function to add strings into buffer and updating values as well.

This is the problem I am coping with while using strcat()

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/nV2SK.png

    char temp[2] = "A";
    char temp_end[2] = "a";
    char buf_adc[20]="alok";
    char buf_hum[20]="lok";
    char buf_temp[20]="vjf";
    char buf[100];
    void setup() {
    Serial.begin(115200);

    }

    void loop() {
      strcat(buf,buf_adc);
    strcat(buf,temp);
    strcat(buf,buf_hum);
    strcat(buf,temp);
    strcat(buf,buf_temp);
    strcat(buf,temp_end);

    Serial.println(buf);

    }

title: How do I clear previous values while using strcat() to add strings?

Answers: 1

body:
`strcat` always concatenates to the end of the string. Instead, for your first `strcat` you should really be using `strcpy`, which copies one string over the top of the other - that is, it places it at the *start* of the string, effectively starting a new string.

However, unless you *really* need the data in a string for some specific reason, you don't need to build a string up - just print each part to serial separately with its own `Serial.print` function.


body:
I have just written a java algorithm to get a chess move when a chess move is inputted in SAN notation the algorithm used : Monte Carlo. Is it possible to integrate this program with an Arduino mega and How?

My mega will be getting inputs from a sensory board and I want to send these inputs to the java program without using any additional board.

<b>Note:
By integrate I mean that the Java program should run in the Arduino mega itself</b>

Can anyone suggest a solution?

title: Integrating Java program with arduino mega is it possible?

Answers: 1

body:
[There is a project called uJ][1] by Dmitry Grinberg that enables you to do that, somehow. It has been tested on AVR devices too, not your particular one however. Knowing AVRs, that shouldn't be a stopper at all.

That said, I don't think it's a very good idea. The overhead of the JVM may only let you handle some 'slow' signals, unless you heavily rely on peripherals and wit to do stuff. Though in your particular application, that shouldn't be that much of an issue.

Instead of having the trouble of running a JVM and such, you may just as well rewrite the code in C/C++ or whatever, even for increased efficiency. There may also be some Java to C transpilers, I haven't looked, wary of the dragons.

However, if you eventually decide against that and instead choose to talk to the microcontroller over serial or something else, there is the <strike>dreadful</strike> excellent RxTx library for Java that works pretty fine after all, or the Firmata library.

  [1]: http://dmitry.gr/?r=05.Projects&proj=12. uJ - a micro JVM


body:
I'm trying to send data from my esp to my arduino using serial using the following codes :

esp :

    server.on("/drive",HTTP_GET, handleDrive);
    void handleDrive()
    {
        server.send(200,"text/html", "Drive!");
        String sendToArduino = "";
        for (int i=0;i<server.args();i++)
        {
       sendToArduino = sendToArduino+server.argName(i)+"="+sendToArduino.arg(i)+"&";
        }
        Serial.println(sendToArduino);
    }

and on arduino :

    Serial.begin(9600);
    esp8266.begin(115200);

    if (esp8266.available())
    {
       String  readString="";
       while (esp8266.available())
       {
         delay(2);
         char c = esp8266.read();
         readString += c;
       }
    }

but when i send data from esp to arduino i get it with "noise"

Ex : "variable1=1234"   i recive it on arduino "varia`b@e=12`"
What can i make to make sure that what i send is same in arduino ?

title: ESP send data to Arduino

Answers: 1

body:
Firstly you need to write a more reliable serial reading routine on the Arduino. As it stands your routine is lucky you even get what you do. You need to write a routine that doesn't care about time, but instead cares about the terminating character of the line you are receiving.

* [Here is an article I wrote all about it.](https://majenko.co.uk/blog/reading-serial-arduino)

Secondly, you cannot communicate reliably using SoftwareSerial at 115200 baud.  While the Arduino is capable of receiving a byte at that baud rate using bit banging, there typically isn't enough time between successive bytes to allow the Arduino to store what it has just received, and so it starts receiving partway through the next byte, corrupting both it and the following byte. That's the cause of the corruption you are seeing.

You should either slow down the baud rate (9600 is a good choice), or send the data one byte at a time and add a delay between each byte (somewhat hacky...).


body:
I used multiple of Serial.read() and Serial.parseInt() to get characters and a number ( like "xy123" ) on an Arduino UNO.
Then I checked the result on Serial monitor.

Unfortunately I couldn't get the character with second Serial.read().

Here's the code:

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

    void loop(){
      if (Serial.available() >0) {

        // I want to reacive the characters like "xy123"
        char input1 = Serial.read();
        char input2 = Serial.read();
        int value = Serial.parseInt();

        Serial.println(input1); // ok
        Serial.println(input2); // * no good * (-1)
        Serial.println(value);  // ok

        // Writing some codes with input1 ,input2 and value ...
      }
    // I don't want to use delay().
    }

How do I get the second character?

Thanks.

title: Why doesn't Serial.read() read multiple character?

Answers: 2

body:
You did not read the second character, because the character did not arrive yet. Wait until it is available. `read` doesn't wait. `parseInt` has the waiting build-in.

You can wait for the second character by reading the two characters with the waiting function `readBytes`. It will wait a second for the next character.

    char buff[2];
    if (Serial.readBytes(buff, 2) == 2) {
      char input1 = buff[0];
      char input2 = buff[1];
    ...

If you send only one character, readBytes will wait one second for the next and the returns that one char was read.

body:
      if (Serial.available() >0) {

This is like saying "I won't go into that room until there is at least one dog in there".  Someone tells you there is a dog there. You go into the room and say "Hey, why aren't there **two** dogs there?".

If you want to read two bytes one approach is to wait until they are available:

      if (Serial.available() >= 2) {


body:
I'm trying to print an int on both an LCD and the Serial Monitor, but its only being displayed on the LCD. The Serial Monitor is printing question marks.

Here is my Arduino code:

<!-- language: lang-cpp -->

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
    int x = 10;

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

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

title: Print output on 16x2 LCD and Serial Monitor

Answers: 1

body:
If you are using clasical UNO, then pins `0` and `1` are Serial. Declaring `lcd(1,...` make LCD use the pin `1` too, so Serial is confused and garbled.

Use other pins for `lcd` and adjuct the wires acordingly.


body:
I'm having an error in buffers that handle strings and I can not figure out what the problem is. The example below shows what is happening. Can someone help me?

    void setup() {
       char* ss1 = "";
       char* ss2 = "";
       String txt = "";

       Serial.begin(115200);

       txt = "1234560001a";
       txt.toCharArray(ss1, txt.length());

       Serial.printf("\n\n");
       Serial.printf("ss1 = %s\n", ss1); // It prints "1234560001" whithout last char "a"

       // Force incorrectly "ss1" to be equal to "ss2" and still removes the last character.
       txt = "abcdef";
       txt.toCharArray(ss2, txt.length());

       Serial.printf("ss1 = %s\n", ss1); // It prints "abcde" whithout last char "f"
       Serial.printf("ss2 = %s\n", ss2); // It prints "abcde" too
    }

title: Error handling strings and chars

Answers: 2

body:
`toCharArray` is alias for `getBytes`. `getBytes` is documented as "Copies the String’s characters to the **supplied** buffer." You did not allocate the memory for the copied characters.

the right use of 'getBytes' and 'toCharArray' is

    char buffer[BUFF_SIZE];
    str.getBytes(buffer, sizeof[buffer]);

note: `getBytes` functions sets the terminating zero of the c-string in buffer

body:
About the problem with losing the last character:

As already said in the comments, the `toCharArray()` method is only an alias for the `getBytes()` method of string objects. We can see it's implementation in the IDEs folder under `hardware/arduino/avr/cores/arduino/WString.cpp`:

    void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const
    {
        if (!bufsize || !buf) return;
        if (index >= len) {
            buf[0] = 0;
            return;
        }
        unsigned int n = bufsize - 1;
        if (n > len - index) n = len - index;
        strncpy((char *)buf, buffer + index, n);
        buf[n] = 0;
    }

We give the length as parameter, which is then reduced by 1. The function `strncpy()`, that is used here, will only copy `n = bufsize - 1` bytes. In the end, the `n`th byte will be set to `0` as the terminating null character.

This means, that the length, that we give as parameter, already includes the space for the null character. But the method `String::length()` will not include the null character in length calculation (in most cases this is not wanted). So you can simply add 1 to the length before giving it to `toCharArray()`.

About the overwriting problem:

As stated in [this question's answer][1] and in several other discussions about C/C++ (for example [here][2]), string literals are meant to be immutable. The mentioned sources say, it is different, if you define a string variable as

    char *str = "test";

or

    char str[] = "test";

In the second case a normal mutable array is created. In the first case the string will be placed in read only memory. From your problem I read, that on Arduino this is placed in RAM, thus technically mutable. But the compiler thinks of it as immutable. A common optimization, when dealing with immutable strings, is to let every used string literal with the same content be saved at the same memory address.

In your code you are initializing 2 strings with only the terminating null character in them. The compiler thinks "Oh, wait, these two string literals are immutable and equal, so I can save memory by only saving it once and let both pointers point to this memory address". When writing to the strings in Arduino the behavior doesn't seem to be defined. As the Arduino cannot throw an exception it will most likely do the write. Since both pointers are pointing to the same memory address, they show both the same content. Also, when writing a string longer than the initialized value, memory space outside from the original string will be written. If other variables are saved there, they will get overwritten. This is the reason, by you should always explicitely allocate the memory (static or dynamic) for a string, until another function does it for you. When using a dynamic allocation of memory, you should also consider heap fragmentation, which can easily lead to strange behavior.

If you turn on verbose output for compilation, the compiler also warns you, that you try to convert a constant string literal to a non-constant char pointer:

    sketch_jul09a.ino:3:15: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

To conclude, you should not declare string variables like this. If you have a variable string buffer with initialized values, you should use

    char str[]="test";

If you want to define a constant string, use the keyword `const`:

    const char *str = "test";

Then writing to it will result in a compiler error, so that you sense, if you are doing this.

  [1]: https://stackoverflow.com/questions/8795576/initializing-a-char-pointer-in-c-why-considered-dangerous#8795589
  [2]: http://www.cplusplus.com/forum/beginner/30156/


body:
I am trying to interface this sensor, https://www.robotous.com/forcetorquesensor (RTF60-HA01-C), with the Arduino Mega. The sensor has an input voltage of 5Vs and communicates using CAN/RS232/RS422. I am using the RS232 and have connected wires properly and have tried to establish Serial Communication using the below code.

    #include<String.h>
    # define BuffSize 32

    byte buff[BuffSize];
    unsigned char data_field[16];
    byte comm[11]  = {0x55, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA};
    // SOP == 0x55, EOP == 0xAA, Checksum == summation of each data in data_field
    void setup() {

      // put your setup code here, to run once:
      Serial.begin(115200);
      Serial2.begin(115200);
      for (int i = 0; i < BuffSize; i++) {
        buff[i] = 13; //Number to initialise buffer
      }

    }

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

         Serial2.write(comm, 11);
        //Serial.println(Serial2.available());
        if (Serial2.available() > 0) {
          //int read = Serial2.readBytes(buff, BuffSize);
            String output = "";
            for(int i=0;i<BuffSize;i++){
            buff[i]=Serial2.read();
            output = output + buff[i] + "|";
         }
      //Serial.println(read);
        Serial.flush();

        Serial.println(output);
        Serial.println();

        }
      }

The output I receive is just 0s and the occasional 10. Like below

    0|0|0|0|0|0|0|0|10|0|0|0|0|0|0|0|0|10|0|0|0|0|0|0|0|0|10|255|255|255|255|255|

I am new to this and hope this is not a stupid question.
Let

title: Trying to connect FT sensor to Arduino Mega using RX TX

Answers: 2

body:
You obviously haven't understood the way this device communicates over serial. You don't just throw an "11" at it to get it going - you have to craft a proper command packet and send that, and the device then starts responding with response packets that you must parse properly.

A command packet starts with 0x55, then has the command and data (8 bytes in total), then a checksum and EOP byte (0xAA).

For example:

    0x55, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B, 0xAA

When reading you do *not* look for "at least one byte" then try and read 32 bytes. That's just never going to work.  You need to wait for 0x55 to arrive, then wait for each of the 16 following command+data bytes to arrive, one at a time (they do NOT arrive all at once!), and store them - then calculate the checksum for those command and data bytes, and read the next byte and make sure it matches the checksum. Finally, confirm you have a proper packet by reading the EOP byte of 0xAA.

Ideally, you want to implement a sliding window algorithm whereby you have an array of 19 bytes and incoming bytes filter down from one end of the array to the other. When the first byte is 0x55 and the last byte is 0xAA, and the penultimate byte equals the (truncated) total of bytes 2 to 17 inclusive, do you have an actual packet and can act on the data.

body:
The Serial RX and TX pins of an Arduino are not RS-232 compatible without using some type of circuit to give you the proper voltage levels.

    **RS-232 logic and voltage levels**
    0 (space)  Asserted  +3 to +15 V
    1 (mark)  Deasserted  −15 to −3 V

Connecting the RX/TX pins of an Arduino directly to an RS-232 device may fry your Arduino in addition to just not working for communication.  This circuit given below is an example what you'll need.  There are pre-made adapter boards available for a few dollars.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/DZNdw.jpg


body:
I'm struggling a bit with Arduino language + its IDE not being 100% real C++. I wrote my own I2C library for a sensor but can't get the IDE's compiler to recognise it. I'm using Ubuntu 18.04.

I get `no such file or directory` for all of these things I've tried:

 - Include the `.h` file by absolute and relative path in the `.ino` code
 - Put `.cpp` +  `.h` files in ~/Arduino/libraries
 - Put `.cpp` +  `.h` files in ~/sketchbook/libraries
 - Put `.cpp` +  `.h` files in ~/sketchbook/libraries/mylibrary
 - Put `.cpp` +  `.h` files in ~/sketchbook/libraries/mylibrary and try to "install" the library in the IDE (Sketch -> Include library -> Manage libraries; it's not listed)

I'm following the [official guide here][1]. Any ideas on how to get the compiler to recognise my library?

  [1]: https://www.arduino.cc/en/Hacking/Libraries

title: How to install your own library with Arduino IDE 1.8.5?

Answers: 1

body:
You need to:

1. Create the folder ~/Arduino/libraries/MyLibrary
2. Place the library files in there named as:
   * ~/Arduino/libraries/MyLibrary/MyLibrary.h
   * ~/Arduino/libraries/MyLibrary/MyLibrary.cpp
3. **Restart the IDE if it is running**
4. Use `#include <MyLibrary.h>` in your sketch

This is assuming your sketchbook is set to ~/Arduino - change that to wherever the sketchbook is set to (check in Preferences for that location).

Note that in Linux capitalisation is *important*. The filesystem is case sensitive, and the name of your folder should have the same name and capitalisation as the name of your header file.


body:
I am having trouble parsing NMEA sentences coming from a GY-NEO6MV2 board (https://www.cytron.io/p-gps-neo6mv2), using the TinyGPS (https://github.com/mikalhart/TinyGPS) library. The GPS board itself is connected to an Arduino Pro Mini 3v3 8MHz (ATmega328)

First of all, to start debugging I want to disable all NMEA sentences other than GGA and RMC (which are the only ones I need for this project)

According to the manual, this can be done by sending PUBX commands through the SoftwareSerial (no need for binary UBX)

I am doing this in the following way

    #include <SoftwareSerial.h>
    #include <TinyGPS.h>

    // GPS SoftwareSerial
    // Shares pins with (MISO 12/ MOSI 11) used for SPI

    #define GPS_RX_PIN 12
    #define GPS_TX_PIN 11

    TinyGPS gps;
    SoftwareSerial GPSSerial(GPS_RX_PIN, GPS_TX_PIN);

    void setup()
    {
      Serial.begin(115200);
      GPSSerial.begin(9600);

          GPSSerial.print("$PUBX,40,GLL,0,0,0,0*5C\r\n");
          GPSSerial.print("$PUBX,40,ZDA,0,0,0,0*44\r\n");
          GPSSerial.print("$PUBX,40,VTG,0,0,0,0*5E\r\n");
          GPSSerial.print("$PUBX,40,GSV,0,0,0,0*59\r\n");
          GPSSerial.print("$PUBX,40,GSA,0,0,0,0*4E\r\n");
    }

    void loop()
    {
    // ...
    }

However, the GPS board will not respond to these commands and keep sending all the NMEA sentences.

FWIW, this is the original code I'm building my project on - https://github.com/billygr/arduino-aprs-tracker/blob/master/arduino-aprs-tracker.ino

Any thoughts would be appreciated...

title: Sending PUBX commands to GPS Board (Ublox NEO-6M) through SoftwareSerial

Answers: 1

body:
I've tried your code sending those PUBX commands to a ublox module and they work successfully for me.

There are a lot of fakes about on the internet using AT6558 chips repackaged as ublox. Check the GPTXT messages that are output when the GPS module is powered up to see if its really a ublox module or a fake one like this:

    $GPTXT,01,01,02,MA=CASIC*27
    $GPTXT,01,01,02,HW=ATGM332D,0080113573899*18
    $GPTXT,01,01,02,IC=AT6558-5N-31-0C500000,J7M911C-B2-008827*50
    $GPTXT,01,01,02,SW=URANUS4,V4.3.0.5*18


body:
So, I was working with a project in which I used a joystick module to control two servos at the same time. The joystick controls the servos in a way that when the joystick is moved along x-axis, both servos move in the same direction but when joystick moves in y-axis, the servos move in different directions. I have this program:

    #include <Servo.h>
    Servo servo1;
    Servo servo2;
    int joyx = 0;
    int joyy = 5;
    int joyval;
    int joyvalx;
    int joyvaly;
    void setup() {
        Serial.begin(9600);
        servo1.attach(3);
        servo2.attach(5);

    }

    void loop() {
        Serial.println(joyvalx + "," + joyvaly);
        int x = analogRead(joyx);
        int y = analogRead(joyy);
        if(x != joyvalx){
            joyval = map(x, 0, 1023, 0, 180);
            servo1.write(joyval);
            servo2.write(joyval);
        }
        if (y != joyvaly){
            joyval = map(y, 0, 1023, 0, 180);
            servo1.write(joyval);
            servo2.write(1023-joyval);
        }
    }
However, the servos don't seem to work properly. One servo works fine but the other just gets stuck. Also, if I use the code for only one direction (x-axis or y-axis) by removing the code for the other, then both servos work good. I can't understand the problem. If anyone does, please help me.

title: Servos not working properly with joystick

Answers: 1

body:
The problem, as jsotola pointed out, is that your code writes totally different values to the servos very fast. You don't combine the two values from the joystick, but just overwrite the previous servo value. So this cannot work.

As I interpret your description, you want the x axis to move both servos the same amount in the same direction (in unity), while the y axis determines the difference of position between them. If you move the y axis to one side, the first servo will go a bit clockwise, while the other goes a bit counter-clockwise. When you then move the x axis, both servos will move to the corresponding direction, while maintaining their position difference.

It is better to first write a formula, how you will calculate each servo position from the given joystick values. The above behavior can be described with these formulas:

    servo_1_value = mapped_x + mapped_y;
    servo_2_value = mapped_x - mapped_y;

Now you have to map the joystick values correspondingly:

    mapped_x = map(x, 0, 1023, 0, 180);
    mapped_y = map(y, 0, 1023, -90, 90);

Note, that you should change the parameters for mapping `y` to the values you need. In the above code they are set to the maximum (meaning that moving the y axis to either end will effectively disable the x axis, since the servo cannot move past 0 or 180 degrees).

You don't really need to check, if the value changed. But if you really want to, you should check the calculated values for each servo separately. Something like this:

    if(servo_1_value != old_servo_1_value){
        servo1.write(servo_1_value);
    }
    if(servo_2_value != old_servo_2_value){
        servo2.write(servo_2_value);
    }

But you don't really need to check for a change here.


body:
My arduino uno with the NRF24L01 combination gives failed messages on writing.

Using the basic example code 'getting started' literally copied from:
http://tmrh20.github.io/RF24/GettingStarted_8ino-example.html, my serial monitor constantly writes 'failed' (See attached screenshot)

The setup is for my Arduino uno as described in the table on
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo#PP (Arduino pin for
TMRh20 RF24 Library)

The code:

    /*
    * Getting Started example sketch for nRF24L01+ radios
    * This is a very basic example of how to send data from one node to another
    * Updated: Dec 2014 by TMRh20
    */
    #include <SPI.h>
    #include "RF24.h"
    #include <printf.h>

    /****************** User Config ***************************/
    /***      Set this radio as radio number 0 or 1         ***/
    bool radioNumber = 1;
    /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
    RF24 radio(7,8);
    /**********************************************************/
    byte addresses[][6] = {"1Node","2Node"};
    // Used to control whether this node is sending or receiving
    bool role = 0;
    void setup() {
      Serial.begin(115200);
      printf_begin();
      Serial.println(F("RF24/examples/GettingStarted"));
      Serial.println(F("*** PRESS 'T' to begin transmitting to the other node"));

      radio.begin();
      // Set the PA Level low to prevent power supply related issues since this is a
     // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default.
      radio.setPALevel(RF24_PA_LOW);

      // Open a writing and reading pipe on each radio, with opposite addresses
      if(radioNumber){
        radio.openWritingPipe(addresses[1]);
        radio.openReadingPipe(1,addresses[0]);
      }else{
        radio.openWritingPipe(addresses[0]);
        radio.openReadingPipe(1,addresses[1]);
      }
      radio.printDetails();
      // Start the radio listening for data
      radio.startListening();
    }
    void loop() {

    /****************** Ping Out Role ***************************/
    if (role == 1)  {

        radio.stopListening();                                    // First, stop listening so we can talk.

        Serial.println(F("Now sending"));
        unsigned long start_time = micros();                             // Take the time, and send it.  This will block until complete
         if (!radio.write( &start_time, sizeof(unsigned long) )){
           Serial.println(F("failed"));
         }

        radio.startListening();                                    // Now, continue listening

        unsigned long started_waiting_at = micros();               // Set up a timeout period, get the current microseconds
        boolean timeout = false;                                   // Set up a variable to indicate if a response was received or not

        while ( ! radio.available() ){                             // While nothing is received
          if (micros() - started_waiting_at > 200000 ){            // If waited longer than 200ms, indicate timeout and exit while loop
              timeout = true;
              break;
          }
        }

        if ( timeout ){                                             // Describe the results
            Serial.println(F("Failed, response timed out."));
        }else{
            unsigned long got_time;                                 // Grab the response, compare, and send to debugging spew
            radio.read( &got_time, sizeof(unsigned long) );
            unsigned long end_time = micros();

            // Spew it
            Serial.print(F("Sent "));
            Serial.print(start_time);
            Serial.print(F(", Got response "));
            Serial.print(got_time);
            Serial.print(F(", Round-trip delay "));
            Serial.print(end_time-start_time);
            Serial.println(F(" microseconds"));
        }
        // Try again 1s later
        delay(1000);
      }
    /****************** Pong Back Role ***************************/
      if ( role == 0 )
      {
        unsigned long got_time;

        if( radio.available()){
                                                                        // Variable for the received timestamp
          while (radio.available()) {                                   // While there is data ready
            radio.read( &got_time, sizeof(unsigned long) );             // Get the payload
          }

          radio.stopListening();                                        // First, stop listening so we can talk
          radio.write( &got_time, sizeof(unsigned long) );              // Send the final one back.
          radio.startListening();                                       // Now, resume listening so we catch the next packets.
          Serial.print(F("Sent response "));
          Serial.println(got_time);
       }
     }
    /****************** Change Roles via Serial Commands ***************************/
      if ( Serial.available() )
      {
        char c = toupper(Serial.read());
        if ( c == 'T' && role == 0 ){
          Serial.println(F("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK"));
          role = 1;                  // Become the primary transmitter (ping out)

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

        }
      }
    } // Loop

While my other arduino has the same setup only radioNumber = 0 on that one.

The monitor output:
[![monitor output][1]][1]

My setup:
[![Arduino setup][2]][2]

  [1]: https://i.stack.imgur.com/Sjjy3.png
  [2]: https://i.stack.imgur.com/MCHco.jpg

EDIT:
Ok so i managed to run printDetails() (thanks for the help on that one)
This came up with:

    STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
    RX_ADDR_P0-1  = 0x65646f4e31 0x65646f4e32
    RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
    TX_ADDR   = 0x65646f4e31
    RX_PW_P0-6  = 0x20 0x20 0x00 0x00 0x00 0x00
    EN_AA   = 0x3f
    EN_RXADDR  = 0x02
    RF_CH   = 0x4c
    RF_SETUP  = 0x03
    CONFIG   = 0x0e
    DYNPD/FEATURE  = 0x00 0x00
    Data Rate  = 1MBPS
    Model   = nRF24L01+
    CRC Length  = 16 bits
    PA Power  = PA_LOW

on arduino one, and with the following on arduino 2 with radionumber = 1

    STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
    RX_ADDR_P0-1  = 0x65646f4e32 0x65646f4e31
    RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
    TX_ADDR   = 0x65646f4e32
    RX_PW_P0-6  = 0x20 0x20 0x00 0x00 0x00 0x00
    EN_AA   = 0x3f
    EN_RXADDR  = 0x02
    RF_CH   = 0x4c
    RF_SETUP  = 0x03
    CONFIG   = 0x0e
    DYNPD/FEATURE  = 0x00 0x00
    Data Rate  = 1MBPS
    Model   = nRF24L01+
    CRC Length  = 16 bits
    PA Power  = PA_LOW

title: NRF24L01 writing fail

Answers: 2

body:
See how/whether Arduino actually communicates with the master nRF, before tackling the problem of the tx/rx.

Use the code given below to print out the tx and rx radio registers (no libraries required except SPI).  You will need to use the right values for CE and CSN pins.  Post the data in your question, there are many several people on stack exchange who will be able to help you find the solution.

    #include <SPI.h>
    #define CE_pin 4
    #define CSN_pin 5
    #define MOSI_pin 11
    #define MISO_pin 12
    #define SCK_pin 13
    byte data_in;

    byte radio1_tx_addr[5] = {0xC5, 0xC5, 0xC5, 0xC5, 0xC5};
    byte radio2_tx_addr[5] = {0x31, 0x31, 0x31, 0x31, 0x31};

    void setup() {
      Serial.begin(115200);
      pinMode(CE_pin, OUTPUT);//chip enable set as output
      pinMode(CSN_pin, OUTPUT);//chip select pin as output
      pinMode(MOSI_pin, OUTPUT);//SPI data out
      pinMode(MISO_pin, INPUT); //SPI data in
      pinMode(SCK_pin, OUTPUT);//SPI clock out
      SPI.setBitOrder(MSBFIRST);//SPI Most Significant Bit First
      SPI.setDataMode(SPI_MODE0);// Mode 0 Rising edge of data, keep clock low
      SPI.setClockDivider(SPI_CLOCK_DIV2);//Run the data in at 16MHz/2 - 8MHz
      digitalWrite(CE_pin, HIGH);//RX mode
      digitalWrite(CSN_pin, HIGH);//SPI idle
      SPI.begin();//start up the SPI library
      delay(100);

      nrf_set_TX_ADDR(radio1_tx_addr); // set TX/RX addresses
      nrf_set_RX_ADDR_P1(radio2_tx_addr);

      Serial.print("CONFIG");
      nrf_read_register(0x00);
      Serial.print("EN_AA");
      nrf_read_register(0x01);
      Serial.print("EN_RXADDR");
      nrf_read_register(0x02);
      Serial.print("SETUP_AW");
      nrf_read_register(0x03);
      Serial.print("SETUP_RETR");
      nrf_read_register(0x04);
      Serial.print("RF_CH");
      nrf_read_register(0x05);
      Serial.print("RF_SETUP");
      nrf_read_register(0x06);
      Serial.print("STATUS");
      nrf_read_register(0x07);
      Serial.print("OBSERVE_TX");
      nrf_read_register(0x08);
      Serial.print("RPD");
      nrf_read_register(0x09);
      Serial.print("RX_ADDR_P0");
      nrf_read_register(0x0A);
      Serial.print("RX_ADDR_P1");
      nrf_read_register(0x0B);
      Serial.print("RX_ADDR_P2");
      nrf_read_register(0x0C);
      Serial.print("RX_ADDR_P3");
      nrf_read_register(0x0D);
      Serial.print("RX_ADDR_P4");
      nrf_read_register(0x0E);
      Serial.print("RX_ADDR_P5");
      nrf_read_register(0x0F);
      Serial.print("TX_ADDR");
      nrf_read_register(0x10);
      Serial.print("RX_PW_P0");
      nrf_read_register(0x11);
      Serial.print("RX_PW_P1");
      nrf_read_register(0x12);
      Serial.print("RX_PW_P2");
      nrf_read_register(0x13);
      Serial.print("RX_PW_P3");
      nrf_read_register(0x14);
      Serial.print("RX_PW_P4");
      nrf_read_register(0x15);
      Serial.print("RX_PW_P5");
      nrf_read_register(0x16);
      Serial.print("FIFO_STATUS");
      nrf_read_register(0x17);
      Serial.print("DYNPD");
      nrf_read_register(0x1C);
      Serial.print("FEATURE");
      nrf_read_register(0x1D);
    }

    void loop() {
    }

    void nrf_read_register(byte reg) {
      digitalWrite(CSN_pin, LOW);
      SPI.transfer(reg);
      data_in = SPI.transfer(0x00);
      digitalWrite(CSN_pin, HIGH);
      Serial.print(": 0x");
      Serial.print(reg,HEX);
      Serial.print(" => 0x");
      Serial.println(data_in,HEX);
      delay(10);
    }

    void nrf_set_TX_ADDR(byte x) {
      digitalWrite(CSN_pin, LOW);
      SPI.transfer(0x30);
      SPI.transfer(x[0]);
      SPI.transfer(x[1]);
      SPI.transfer(x[2]);
      SPI.transfer(x[3]);
      SPI.transfer(x[4]);
      digitalWrite(CSN_pin, HIGH);
      delay(10);
    }

    void nrf_set_RX_ADDR_P1(byte x) {
      digitalWrite(CSN_pin, LOW);
      SPI.transfer(0x2B);
      SPI.transfer(x[0]);
      SPI.transfer(x[1]);
      SPI.transfer(x[2]);
      SPI.transfer(x[3]);
      SPI.transfer(x[4]);
      digitalWrite(CSN_pin, HIGH);
      delay(10);
    }

body:
I'm currently writing a driver (for fun) and noticed that if the clock line is not at the correct idle logic level when the CS pin goes low, the chip freaks out and gives me issues when reading/writing registers. This may or may not help you, but figured it would be worth a shot to mention it.

Edit: The chip expects CPOL 0, so I used a pull down resistor on the clock line. So it will by default idle low.


body:
i wan’t to know if is possible to use  [this raw e-ink display ][1] with arduino. if it’s possible to directly connect cables from this ribbon cable to arduino without any driver pcb and control it with 3 or 4 wire SPI.
[the pinout of the display is on the 6th page][2]

  [1]: https://www.robotics.org.za/image/cache/catalog/waveshare/W12561/W12561-000-500x500.jpg
  [2]: https://www.waveshare.com/w/upload/7/77/1.54inch_e-Paper_Datasheet.pdf

title: 1.54 e-ink without driver

Answers: 1

body:
Kind of yes and kind of no.

It requires external circuitry, but that circuitry isn't a "driver board" in the traditional sense.

An e-Ink display requires high voltages to charge the electrostatic cells. Traditionally that would be provided using an external "driver" circuit - a *boost* voltage converter.

However this display has that boost converter built in - though it doesn't have *all* the components, because they just won't fit.

You need to provide the diodes, switching MOSFET, and inductor, etc as shown on page 18 of the datasheet.  Nothing less will do.


body: I'm working on a project that requires calculating the time for which a pushbutton is kept pressed without being released. Is there a code snippet that i can use for this particular need ?

title: Arduino - Calculating the time for which a Pushbutton is pressed and held without being released

Answers: 1

body:
There is a library called "Debounce", which you can find here: [playground.arduino.cc][1]. Based on that library, here is a simple sketch that displays the amount of time a button is pressed.

    // Connect one end of a N.O. push button switch to GND and the other
    // end to pin 4 of the Arduino.
    // NOTE: If the button is held down for less than the debounce delay
    //       time, the elapsed time will display the debounce delay time.
    #include <Debounce.h>
    const byte SWITCH = 4;
    unsigned long startTime = 0;
    unsigned long endTime = 0;
    unsigned long elapsedTime = 0;
    const byte debounceDelayTime = 50;

    Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

    void setup(){
      Serial.begin(9600);
      pinMode(SWITCH, INPUT_PULLUP);
    }

    void loop(){
      if(debouncer.update()){
        if(debouncer.read() == 0){
          startTime = millis();
          Serial.println("Button Pressed");
        }
        else if(debouncer.read() == 1){
          endTime = millis();
          Serial.println("Button Released");
          elapsedTime = endTime - startTime;
          Serial.print("Button Held Down For ");
          Serial.print(elapsedTime);
          Serial.println(" ms.");
        }
      }
    }

  [1]: https://playground.arduino.cc/uploads/Code/Debounce.zip


body:
The code below is used for controlling a relay with an Arduino. Pressing the touch sensor connects and disconnects the relay.

If the user presses/touches/holds their finger on the touch sensor for longer than two seconds, how do I adjust the program to do something other than connecting or disconnecting the relay?

    #define TouchSensor 9 // Pin for capactitive touch sensor

    int relay = 2;

    boolean currentState = LOW;
    boolean lastState = LOW;
    boolean RelayState = LOW;

    void setup() {
      Serial.begin(9600);
      pinMode(relay, OUTPUT);
      pinMode(TouchSensor, INPUT);
    }

    void loop() {
      currentState = digitalRead(TouchSensor);
        if (currentState == HIGH && lastState == LOW){
        Serial.println("pressed");
        delay(1);

        if (RelayState == HIGH){
          digitalWrite(relay, LOW);
          RelayState = LOW;
        } else {
          digitalWrite(relay, HIGH);
          RelayState = HIGH;
        }
      }
      lastState = currentState;
    }

title: Touch Sensor - Determining Pressing/Hold Length and Modifying Program Flow Accordingly

Answers: 3

body:
You have to determine, how long a the sensor was pressed until released. When it is released you can take the corresponding steps. If the press was shorter than say 1.5s, you can switch the relay. Else you can do something else.

There are many ways to achieve this. You can program it yourself by using the `millis()` function. You would have to set a timestamp, when the state of the sensor changes to high, then wait for it to go low and substract the timestamp from the current value of `millis()`. This would give you the duration of press, which you can use in a corresponding `if`-statement.

Or you can use the `Debounce` library for it, which makes it a bit simpler (not a lot, but you should consider debouncing depending on the type of sensor you use). Look at the answer from VE7JRO to [this question][1]. The `debouncer.update()` function checks, if the state of the button changed. If so and the value was LOW (in your case this would has to be changed to HIGH), a timestamp is set with the value of `millis()`. When an update with LOW occurs, the time difference between the two events is calculated and the corresponding action are taken. I will add the code from the answer for reference here:

    // Connect one end of a N.O. push button switch to GND and the other
    // end to pin 4 of the Arduino.
    // NOTE: If the button is held down for less than the debounce delay
    //       time, the elapsed time will display the debounce delay time.
    #include <Debounce.h>
    const byte SWITCH = 4;
    unsigned long startTime = 0;
    unsigned long endTime = 0;
    unsigned long elapsedTime = 0;
    const byte debounceDelayTime = 50;

    Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

    void setup(){
      Serial.begin(9600);
      pinMode(SWITCH, INPUT_PULLUP);
    }

    void loop(){
      if(debouncer.update()){
        if(debouncer.read() == 0){
          startTime = millis();
          Serial.println("Button Pressed");
        }
        else if(debouncer.read() == 1){
          endTime = millis();
          Serial.println("Button Released");
          elapsedTime = endTime - startTime;
          Serial.print("Button Held Down For ");
          Serial.print(elapsedTime);
          Serial.println(" ms.");
        }
      }
    }

  [1]: https://arduino.stackexchange.com/questions/54268/arduino-calculating-the-time-for-which-a-pushbutton-is-pressed-and-held-withou#54271

body:
This sketch uses a millis() timer to add the concept of time to debouncing a button with the [Bounce2][1] Library, (This library may be included with the current version of the Arduino IDE). This sketch **does not** contain any code to turn a relay on and off.

  [1]: https://github.com/thomasfredericks/Bounce2

    // Connect one end of a N.O. push button switch to GND
    // and the other end to pin 4 of the Arduino.
    #include <Bounce2.h>

    byte buttonState = 0;
    byte lastButtonState = 0;
    const byte buttonPin = 4;
    const byte debouncerInterval = 50;         // Time in ms.
    unsigned long buttonHeldThreshold = 2000;  // Time in ms.
    unsigned long buttonPressTimeStamp;

    Bounce debouncer = Bounce();

    void setup(){
      Serial.begin(9600);
      pinMode(buttonPin, INPUT_PULLUP);
      debouncer.attach(buttonPin);
      debouncer.interval(debouncerInterval);
    }

    void loop(){

      if(debouncer.update()){

        if(debouncer.read() == 0){
          buttonState = 1;
          buttonPressTimeStamp = millis();
          Serial.println("Button Pressed");
        }
        else if(debouncer.read() == 1){
          buttonState = 0;
          Serial.println("Button Released");
        }
      }

      if(buttonState == 1){
        if(millis() - buttonPressTimeStamp >= buttonHeldThreshold){
          buttonState = 2;
          Serial.println("Button Held for 2+ seconds");
        }
      }

      // Print out the contents of the buttonState variable only when it changes.
      if(buttonState != lastButtonState){
        Serial.print("Button state = ");
        Serial.println(buttonState);
        Serial.println();
        lastButtonState = buttonState;
      }
    }

Keep in mind that this library has `debouncer.rose()` and `debouncer.fell()` functions that may be helpful to you. It's always a good idea to look at the *.h and *.cpp files in the libraries you install. There may be several functions that are not demonstrated in the library's examples. Sometimes the author(s) use code comments in the library which can help you to trouble shoot any issues that may arise.

body:
For this kind of scenario "activation" of the button is *never* done when it is pressed. Yes, under "normal" circumstances you press a button, a circuit is made, and something happens.

However, if you need more than just that simple operation you never do anything just when it's pressed.

For example, if you click on a link on a web page, nothing really happens when you press the mouse button. Yes, the link is "selected", but that's all. Nothing active happens until you *release* the mouse button.  It's the act of "press-then-release" that constitutes a "click" - and then only if the release happens within a certain time after the press.

That allows such other options to happen, such as "press-drag-release" for drag and drop, or  "press-wait-release" for selecting without activating, etc.

So for your scenario you have two desired "triggering" options:

* press-release
* press-hold

As long as the "release" of the "press-release" happens in a shorter time than the "hold" time of the "press-hold" you can differentiate between them.

So your methodology would look something like this:

* Button pressed - record the time
* Either:
  * Button released and time elapsed < 2 seconds, or
  * Time elapsed >= 2 seconds

As code that may look something along the lines of:

    static uint32_t ts = 0;
    static uint8_t buttonState = HIGH;

    uint8_t buttonValue = digitalRead(ButtonPin);

    if (buttonValue != buttonState) { // The state has changed.
        buttonState = buttonValue; // Record it
        if (buttonState == LOW) { // Button has been pressed
            ts = millis(); // Record the time
        } else if (ts > 0) { // Released - ts must have been set by a press
            if (millis() - ts < 2000) { // Less than 2 seconds have passed
                // Run your "press" routine
                ts = 0; // Clear our time stamp.
            }
        }
    } else if (ts > 0) { // It hasn't changed state, but was pressed
        if (buttonState == LOW) { // It's held in. Not strictly necessary but can't hurt
            if (millis() - ts >= 2000) { // 2 seconds have passed
                // Run your "hold" routine
                ts = 0; // Clear our time stamp.
            }
        }
    }

The time stamp variable `ts` is both used to record the time the button was pressed and also as a flag to indicate that we are currently in an "unactivated" state.  That is, for the "held" state to indicate whether or not we still need to run our "held" routine or not.  Without that check, after 2 seconds of holding the button the "held" routine would keep running over and over and over again until the button is released. It's kind of like implementing a "forced" release of the button after it has triggered the "held" routine.  After that first triggering of "held" we no longer care what is done with the button. We ignore everything until the next time it is pressed when we set `ts` again.


body:
Here is my schematic:
[![enter image description here][1]][1]

I've removed the resistors from the LEDs to make it smaller.
The 1 and 2 on the left are outputs from the arduino (which supplies the VCC and ground).

These 1 and 2 are HIGH or LOW and I want the leds to turn on according to this table:

    ┌───────┬────────────────────┐
    │ INPUT │ OUTPUT             │
    ├───┬───┼──────┬──────┬──────┤
    │ A │ B │ Led1 │ Led2 │ Led3 │
    ├───┼───┼──────┼──────┼──────┤
    │ 0 │ 0 │ 1    │ 0    │ 0    │
    │ 1 │ 0 │ 0    │ 1    │ 0    │
    │ 0 │ 1 │ 0    │ 0    │ 1    │
    │ 1 │ 1 │ 1    │ 0    │ 0    │
    └───┴───┴──────┴──────┴──────┘

And this is the code I am using with the ATTiny85

    const int pinA = PB3;
    const int pinB = PB4;
    const int pinOut1 = PB2;
    const int pinOut2 = PB1;
    const int pinOut3 = PB0;

    void setup() {
     pinMode(pinA, INPUT);
     pinMode(pinB, INPUT);
     pinMode(pinOut1, OUTPUT);
     pinMode(pinOut2, OUTPUT);
     pinMode(pinOut3, OUTPUT);

     int a = digitalRead(pinA);
     int b = digitalRead(pinB);

     if (a == b) {
      digitalWrite(pinOut3, HIGH);
     }
     else if (a == HIGH) {
      digitalWrite(pinOut1, HIGH);
     }
     else {
      digitalWrite(pinOut2, HIGH);
     }
    }

With this set up, I get this output:

    ┌───────┬────────────────────┐
    │ INPUT │ OUTPUT             │
    ├───┬───┼──────┬──────┬──────┤
    │ A │ B │ Led1 │ Led2 │ Led3 │
    ├───┼───┼──────┼──────┼──────┤
    │ 0 │ 0 │ 1    │ 0    │ 0    │
    │ 1 │ 0 │ 0    │ 1    │ 0    │
    │ 0 │ 1 │ 1    │ 0    │ 0    │ <- See the difference
    │ 1 │ 1 │ 1    │ 0    │ 0    │
    └───┴───┴──────┴──────┴──────┘

I think it has something to do with the fact that the ATTiny gets powered on if you supply 5v to one of the input pins too and not to VCC.

And yes, I keep restarting the board (by pulling out the VCC pin and seeing the led turn off).

I've also tried connecting A and B to VCC and ground both in all possible positions. Here I noticed that connecting A (or B) to 5v (of the arduino) while VCC is not connected, the board will turn on.

I hope this is enough info.

  [1]: https://i.stack.imgur.com/uC8be.png

title: Digital Comparator with ATTiny85 doesn't behave as expected

Answers: 3

body:
You have to assign the status of all output pins in each of your "if statement" conditions. Think of it like 'if that happens, I want x, y, & z to be ON, and a, b, & c to be Off'. Unchanging the HIGH status of one output will remain that output HIGH for all conditions. Output pins never change their statuses untill they have an order "your code" to do this. Also you have to replace your code inside a loop function to repeat your code without the need to manually reset your ATTiny.

Assuming LED1 = pinOut1, LED2 = pinOut2, LED3 = pinOut3.
You have to replace "if conditions" in your code by the following:

    while( 1 ){
        int a = digitalRead(PinA);
        int b = digitalRead(PinB);

        if ( a == b ) {
            digitalwrite (pinOut1 , HIGH);
            digitalwrite(pinOut2,LOW) ;
            digitalwrite (pinOut3, LOW);
        }
        else if ( a == HIGH ) {
            digitalwrite(pinOut2,HIGH) ;
            digitalwrite(pinOut1,LOW) ;
            digitalwrite(pinOut3,LOW);
        }
        else if ( b == HIGH ) {
            digitalwrite(pinOut3,HIGH) ;
            digitalwrite(pinOut1,LOW) ;
        digitalwrite(pinOut2,LOW);
        }
    }

Also according to your application speed requirements, you can add a delay of about 300 ms before reading your digital inputs to allow the user to change the status of these digital inputs.

body:
> I think it has something to do with the fact that the ATTiny gets powered on if you supply 5v to one of the input pins too and not to VCC.
>
> And yes, I keep restarting the board (by pulling out the VCC pin and seeing the led turn off).
>
> Here I noticed that connecting A (or B) to 5v (of the arduino) while VCC is not connected, the board will turn on.

All of the above is roughly translated into "I am frying my chip and don't know why it does not work".

Look at "absolute maximum ratings" in datasheet:

"Voltage on any Pin except RESET with respect to Ground -0.5V to **VCC+0.5V**"

In short, you need to power MCU up **before** applying voltage to input pins. That is why it is so surprising that you do not have a loop in your main().

body:
I see nothing wrong in your code, except a terrible design decision that
forces you to reset the ATtiny every time you want to change its inputs.
I guess, then, that the problem is in the way you _use_ it. For example,
let's say you are testing the lines of the table one by one. Once you
are done with the second line and decide to move to the third, let's say
that you:

1. power-cycle the ATtiny
2. set its A input to `LOW`
3. set its B input to `HIGH`.

The ATtiny could very well be reading its inputs right between the steps
2 and 3 above. It would then see both inputs `LOW` and do what it is
supposed to do in that case. This is called a _race condition_, and
usually leads to bugs that are very hard to find.

The right way to use _this particular program_ is to never remove the
power and:

1. set the new inputs
2. pulse the RESET pin of the ATtiny `LOW` for a few microseconds.

Of course, it would be way better to have a sensible design that doesn't
force you to reset. C.f. Ahmed M.Zahran's answer. For this kind of
trivial problem (just a truth table implementation) I prefer to
implement the solution in plain C:

<!-- language: lang-c -->

    #include <avr/io.h>

    static const uint8_t truth_table[] = {1, 2, 4, 1};

    int main(void)
    {
        DDRB = 0x7;  // PB0..PB2 as outputs
        for (;;) {
            uint8_t input = (PINB >> 3) & 0x3;  // the 2 input bits
            PORTB = truth_table[input];  // send output to the LEDs
        }
    }

If you are worried about power, put the ATtiny to sleep and wake it up
on a pin change interrupt. But be sure to have the simple version
working _first_, before you worry about power saving and sleep modes.


body:
Arduino board type used in this session is Arduino Uno R3 DIP/SMD CH340

Below is the description of wiring and code in Arduino to assemble a Bluetooth RC car using android smartphone:

1. Tested the motor dc result both of wheel works (can spin forward and or backward). power direct from the battery.
2. Tested HC-05 bluetooth moduled. The phone can paired the bluetooth module.
3. Tested out1 out2 out3 and out4 on L298N using direct power from the battery the wheel spinning (forward and or backward).
4. The code for the Bluetooth rc simple car used below as described.

The car failed to move (forward, backward, turn left/right). how to make the motor dc and or the motor stepper works remotely. thank you

[![Wiring Table][1]][1]

[![L298N Motor Stepper / Driver Motor][2]][2]

[![HC-05 Bluetooth module][3]][3]

[![Pin to Arduino][4]][4]

[![Fritzing Skematic][5]][5]
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(12, 13); // RX, TX
    #define m1 3
    #define m2 5
    #define m3 9
    #define m4 10

    int data=0,kec=0;
    boolean forward=true;

    int fast[11]={0,80,100,120,140,160,180,200,220,240,255};

    void setup()
    {
      pinMode(m1,OUTPUT);
      pinMode(m2,OUTPUT);
      pinMode(m3,OUTPUT);
      pinMode(m4,OUTPUT);

      mySerial.begin(9600);
     }

    void motorOut(unsigned char lpwm, unsigned char rpwm, boolean arrow){
       if(arrow==false){
          digitalWrite(m3,HIGH);
          digitalWrite(m1,LOW);
          analogWrite(m4,255-lpwm);
          analogWrite(m2,rpwm);
       }
       else{
         digitalWrite(m3,LOW);
         digitalWrite(m1,HIGH);
         analogWrite(m4,lpwm);
         analogWrite(m2,255-rpwm);
      }
    }

    void loop(){
      if(mySerial.available()>0){
        data=mySerial.read();
        if (data =='0') { kec=0;}
          else if (data =='1') { kec=1;}
            else if (data =='2') { kec=2;}
              else if (data =='3') { kec=3;}
                else if (data =='4') { kec=4;}
                 else if (data =='5') { kec=5;}
                  else if (data =='6') { kec=6;}
                    else if (data =='7') { kec=7;}
                      else if (data =='8') { kec=8;}
                        else if (data =='9') { kec=9;}
                          else if (data =='q') {kec=10;}

      //S= Stop
     if (data == 'S')
     { motorOut(0,0,false); }

    //F=Forward
    if (data=='F')
    { motorOut(fast[kec],fast[kec],true); }

    //I=turn right forward
    if (data=='I')
    { motorOut(fast[kec],((fast[kec])/2),true);}

    //G=turn left forward
    if (data=='G')
    { motorOut(((fast[kec])/2),fast[kec],true); }

    //R=turn right
    if(data=='R')
    { motorOut(fast[kec],0,true); }

    //L=turn left
    if(data=='L')
    { motorOut(0,fast[kec],true); }

    //B=back
    if(data=='B')
    { motorOut(fast[kec],fast[kec],false); }

    //H=turn left back
     if (data=='H')
       { motorOut(((fast[kec])/2),fast[kec],false); }

    //turn right back
       if (data=='J')
        { motorOut(fast[kec],((fast[kec])/2),false); }
      }
    }

  [1]: https://i.stack.imgur.com/H78eG.jpg "Wiring Table"
  [2]: https://i.stack.imgur.com/KSnEL.jpg "L298N Motor Stepper / Driver Motor"
  [3]: https://i.stack.imgur.com/jiF9V.jpg "HC-05 Bluetooth module"
  [4]: https://i.stack.imgur.com/atejj.jpg "Pin to Arduino"
  [5]: https://i.stack.imgur.com/mo3qm.jpg

title: L298N, HC-05 Simple Bluetooth remote car not running in Arduino

Answers: 1

body: sorry for my careless. finaly its works....wrong pin assign the main problem....should be IN1, IN2, IN4 and IN3 not IN1, IN2, IN3 and IN4. thank you for all hands for help before


body:
Say we have an array named `myMeasurements`

    int myMeasurements[9]={3,4,8,12,7,2,1,67,8};

**How can I find the index of the maximum element of this array?**

For example the MATLAB code would be:

    myMeasurements = [3,4,8,12,7,2,1,67,8];
    [maxValue,Index] = max(myMeasurements);

where `maxValue` is returned as 67 whereas the `Index` is returned as 8.

For the record, I am using Teensy 3.2 and I program it with the Arduino IDE using the Teensyduino add-on.

title: How to find the index of the maximum value in an array?

Answers: 4

body:
Arduino forum has discussed finding the index once you know which value's index you want. Solution was arrived at by traversing the array by value you were looking for.

For your requirement, you will have to

(1) find the maxValue first and then

(2) find the position(index) of that maxValue using the code they have discussed here :
[https://forum.arduino.cc/index.php?topic=121116.0][1]

  [1]: https://forum.arduino.cc/index.php?topic=121116.0

body:
The code given by Jakub Krnáč gets a slight change which will give the index of the max value. Here is the changed code:

    int myMeasurements[9]={3,4,8,12,7,2,1,67,8};
    int max,current, maxI;
    for(int i = 0;i < 9;i++){
        current = myMeasurements[i];
        if(current > max){
            max = current;
            maxI = i;
        }
    }

body:
    int myMeasurements[9] = {3,4,8,12,7,2,1,67,8};
    int maxI = 0;
    for(int i = 1;i < 9;i++)
        if(myMeasurements[i] > myMeasurements[maxI])
           maxI = i;

body:
First of all, do you really need int values for the measurements or not? If not, and you have numbers between 0 and 255, switch the values to byte, your microcontroller will thank you.

Then, there is a problem with the other answers, which is... The variables cannot be left uninitialized!!! You can use this code to get the info you need:

(I also put the size of myMeasurements in a const variable.. You can thank me later for this)

    const byte maxMeasurements = 9;
    int myMeasurements[maxMeasurements ]={3,4,8,12,7,2,1,67,8};

    byte maxIndex = 0;
    int maxValue = myMeasurements[maxIndex];

    for(byte i = 1; i < maxMeasurements; i++)
    {
        if(myMeasurements[i] > maxValue) {
            maxValue = myMeasurements[i];
            maxIndex = i;
        }
    }


body:
Here is my code to find the frequency of an input rectangular wave at pin 8 of the Arduino Uno board.

    const uint16_t freqPin = PB0;
    const uint16_t load = 0;
    unsigned long int count=0;
    unsigned int value=0;

    void setup()
    {
    Serial.begin(9600);
    DDRB = 0x00;
    TCCR1A = 0;
    TCCR1B = TCCR1B & B11111000 | B00000111;
    TCNT1 = load;
    TIMSK1 |= (1<<ICIE1);
    TIMSK1 |= (1<<TOIE1);
    sei();
    }

    void loop()
    {
    }

    ISR(TIMER1_OVF_vect){

      count++;
    }
    ISR(TIMER1_CAPT_vect){
      value = TCNT1;
      TCNT1 = load;
      Serial.println(count);
      Serial.println(value);
    }

The output is

    0
    0
    0
    0
    0

 Why the output is showing zeroes only. why is this happening ? Can someone explain?
Thanks in advance.

title: Error in finding frequency of an input signal

Answers: 1

body:
There are a few ways to measure the frequency of the incoming signal.  Here are ideas based on the assumption that's all you want, rather than to use specific pins of the Arduino:

 - Use timer interrupts and `digitalRead(8);` (or faster `(PINB & _BV(0))`) to sample when the signal is high or low.  Transfer the data off Arduino, e.g. to a PC, then do a Fourier transform (Matlab, Mathematica, Excel, whatever you like).  Alternatively, calculate the frequency on-board.  This way it is possible to measure frequencies up to several tens of kHz, with a precision of few Hz.
 - Use `attachInterrupt()` on either digital pins 2 or 3.  Count the number of rising edges of the square wave within a given time period.  You can use the timer if you need accuracy, but the method will not be as good as Fourier transform.


body:
i'd like to have a esp-01 powered on and controlled with a push button only.
so imagine the device is off, the user press the momentary push button. in the setup the esp8266 turn on a mosfet or something similar to give himself power using another line. the user release the button and the device is on. i want to be able to understand long button press and double press and similar stuff too. even when device is already powered on. so i need to have a pin attached to the button somehow
this is what i have till now, thanks to a very skillfull friend of mine

the vcc is 5 v and pin tollerance is only 3v

it must be completely off when not pressed for long battery duration

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/h37qR.png

title: Power management circuit

Answers: 1

body:
You need to isolate your button from the logic output using a diode. For example:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/IhE5U.png)

<!-- End schematic -->

In this method M1's gate is normally pulled up by R2. It can either be pulled down by M2 (switched by the "HOLD" signal) or by the switch via D1.

The BTN input is pulled up by R1, and can be pulled down by the switch. M2 can't pull it down because the diode is reverse biased and blocks current trying to flow from BTN via M2 to ground.

R3 is just a pull-down on the gate of M2 to keep it off when HOLD is floating (the power is off).

If you need to interface the 5V "BTN" signal with a lower voltage-tolerant input pin just use a couple of resistors as a voltage divider to reduce the voltage to within the proper levels for the pin.


body:
I am using Arduino in an IOT application where I have to read impulses coming from a sensor and send a mean value of these impulses without missing any impulse while sending the value so is it possible to achieve such operation knowing that Arduino is a single core chip.

I read about `Protothreading ` libraries but it may miss an impulse during the check phase so I want to know if there is another solution

title: Reading and sending with Arduino?

Answers: 1

body:
Although the Arduino only has one CPU core and can only execute one program instruction at a time, it's not limited to only doing one *thing* at a time.

An MCU is a complex device with lots and lots of *peripheral* devices built into it. The CPU is only one small block of the overall device.

Much of a program is merely instructions telling the peripherals how to perform.

For instance, when sending data through Serial the CPU doesn't say "Send this bit. Now wait. Now send this bit. Now wait again" - instead it just says "Here's this byte to send. Now go and send it and tell me when you're done". The UART peripheral then sends the byte by itself with no further input from the CPU leaving the CPU free to do other things.

Then there's the Timer peripherals.  The CPU sets them up to count from a clock source, and do different things depending on different events, like a specific number is reached in the counting, etc. The CPU has no need to go "Count up one. Count up one. Count up one." - it just goes "Count up from 0 using this clock source and tell me when you reach 100" (for example).

Similarly, there are "External Interrupts". The CPU doesn't need to sit watching an IO pin all the time, going "Have you changed yet? Have you changed yet? Have you changed yet?" - it just goes "Tell me when you have changed" and the CPU goes off to do other things.

Of course, all these things have caveats. The biggest is that if the CPU is doing something very timing critical, such as "bit banging" serial data manually through a GPIO pin (for example with SoftwareSerial) it can be set to ignore all these interrupt signals from the peripherals. That means, if you're using an "External Interrupt" to count pulses, and you have to use SoftwareSerial to communicate, it's possible that SoftwareSerial's sending or receiving routines could cause the detection of a pulse to be either delayed (not really a problem) or to be missed completely.

So you don't want to use SoftwareSerial if it can be avoided if you want to use External Interrupts for this kind of operation.

The other option is to use a timer. I mentioned that they just count up from 0 (or they can count down, too) using a configurable clock source. That counting happens completely independently of the CPU, and carries on regardless of whether interrupts are enabled or disabled. And the great new is that most timers can be configured (depending on which Arduino you use) to use an external signal as the clock source for the counting.

That means you can configure a timer to count your pulses for you regardless of what the CPU is doing. All you have to do is every so often (how often depends on how frequently your pulses arrive - the timer has a limit on how many it can count before it overflows) ask the timer for what it has counted up to and reset its count to 0. That could be done as part of your "sending" routine. Get the count, reset it to 0, and send the results.


body:
I am having an issue with my Nextion display. I have uploaded the following code via Arduino IDE to my Arduino MEGA 2560.

My Nextion Editor shows the button as `ID:9` on `page0` named `floor`. I am not entirely sure if the code below is correct. I had one issue where the upload from the laptop to the Mega wouldn't finish, but I managed to bypass that issue by disconnecting the Nextion and swapping RX and TX cables from Nextion while the upload was in progress. Not sure how else I would fix that issue? (If anyone has any ideas haha)

All that is meant to happen is when the dual button state is changed, the onboard `LED_BUILTIN` is set to `HIGH` and if in its second state, is set to `LOW`.

# CODE

    #include "Nextion.h"

    NexDSButton bt0 = NexDSButton(0, 9, "floor");

    int ledPin = LED_BUILTIN;

    char buffer[100] = {0};

    NexTouch *nex_listen_list[] =
    {
        &bt0,
        NULL
    };

    void bt0PopCallback(void *ptr)
    {
        uint32_t dual_state;
        NexDSButton *btn = (NexDSButton *)ptr;
        dbSerialPrintln("b0PopCallback");
        dbSerialPrint("ptr=");
        dbSerialPrintln((uint32_t)ptr);
        memset(buffer, 0, sizeof(buffer));

        if(dual_state)
        {
            digitalWrite(ledPin, HIGH);
        }
        else
        {
            digitalWrite(ledPin, LOW);
        }
    }

    void setup(void)
    {
        nexInit();

        bt0.attachPop(bt0PopCallback, &bt0);

        dbSerialPrintln("setup done");
        pinMode(ledPin, OUTPUT);
    }

    void loop(void)
    {
        nexLoop(nex_listen_list);
    }

My issue is that the MEGA is identifying the touch event (as the TX LED on the MEGA flashes) however it is not turning on the MEGA's onboard built-in LED.

Any help would be greatly appreciated!

title: Nextion Dual State Button

Answers: 2

body:
This is part of the code I have been using for an extraction fan, The button text is tested and if the button matches the command the fan is turned on or off and the button text is changed accordingly. Hope this helps.

    void b19PopCallback(void *ptr) //Extraction Fan
    {
      NexButton *btn = (NexButton *)ptr;
      memset(buffer, 0, sizeof(buffer));
      btn->getText(buffer, sizeof(buffer));

      if (strcmp(buffer, "ON"))
      {
        //COMES BACK AS A FALSE (0) IF BOTH STRINGS MATCH
        digitalWrite(b_motor, LOW);
        strcpy(buffer, "ON");
        btn->setText(buffer);
      }

      else
      {
        digitalWrite(b_motor, HIGH);
        strcpy(buffer, "OFF");
        btn->setText(buffer);
      }

    }

body:
You can try int ledPin=13 instead of led_builtin . Led builtin connected 13 pin. Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO it is attached to digital pin 13 .  Try  this one.

    #include "Nextion.h"
    int ledPin = 13;
    NexDSButton bt0 = NexDSButton(0, 1, "bt0");
    uint32_t dual_state=0;

    void setup(){
    nexInit();
    pinMode(ledPin, OUTPUT);
    }
    void loop(){
    bt0.getValue(&dual_state);
    delay(200);

    if(dual_state==1) //When pressed dual state button dual_state =1
      {
        digitalWrite(ledPin, HIGH);
      }
      else if(dual_state==0)
      {
        digitalWrite(ledPin,LOW );
      }

    }


body:
When i connect my arduino nano to windows 10; the arduino nano is powered on (the "POW" led is on and not blinking; none of the others are on) but it doesn't show up on my computer. It used to but I think I may have shorted it.

Oddly, I get a measurement of 5V coming from digital pins 2,3,4 if connected through USB or 12V if I connect external power source to V_in. These are the pins that were on before what I believe was a short. Can someone tell me what is the component that is damage and whether it is possible to fix. Thanks!

title: Arduino Fried? Power is being delivered to Arduino but COM not found

Answers: 1

body:
If you were powering from 12V and shorted the 5V to GND then yes, it is all dead. The regulator will have stopped regulating. 12V will have then been sent to every component on the board. The USB chip, the main MCU, the 5V regulator - all will be toast.

You *could* repair it by replacing almost every component on the board, but when they're so cheap, why would you bother?


body:
I'm new to schematics, trying to figure out where to put a resistor (no  instructions other than the schematic)

I'm told I need:
10K variable Resistor x 1, 4.7K Resistor x 1, 100 Resistor x 1

But I only see where to put the 10k resistor (I added a blue circle around the 10k). Can someone show me (describe, illustrate) where to put the others?

And where there's the triangles for +5V or AGND, do I put something there (purple circles)??

Thanks!

Here is a link from the project I'm trying to build
https://bestengineeringprojects.com/arduino-weighing-machine-using-hx711/

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/H0jAr.png

title: Schematic interpretation, where to put resister?

Answers: 2

body:
Neither are shown in that schematic, as described in the text.

> ***Calibration Circuit:*** The weight calibration circuit is shown in figure 2. [...]
>
> [A schematic that includes a 4.7kohm resistor]

...

> Note: Cathode and Anode pin of LCD (pin 15 and pin 16) is not shown in circuit diagram. Connect +5 volt to pin 15 with current limiting resistor (generally 100-ohm) and pin 16 of LCD to ground.

body:
The 4.7kOhm resistor is shown in the second image (They simply didn't want to scramble the big image). It shows, that the pin between the resistor and the button has to be connected to pin D10 of the Arduino:

[![enter image description here][1]][1]

The 100 Ohm resistor isn't shown in the image, too. But in the text it says:

> Note: Cathode and Anode pin of LCD (pin 15 and pin 16) is not shown in
> circuit diagram. Connect +5 volt to pin 15 with current limiting
> resistor (generally 100-ohm) and pin 16 of LCD to ground.

Pins 15 and 16 are not shown in the diagram, but the text gives all necessary information. Connect pin 15 of LCD to the 100 Ohm resistor and this resistor to 5V power source. And then connect pin 16 of LCD to ground.

---

The two other symbols, that you circled, are used as indicator of the power source. Normally all pins, which are marked with +5V (triangle) are connected together to the 5V power source. The triangle consisting of 3 horizontal lines marks ground. Normally all grounds are connected together to the ground pin of the power source.

So these symbols are used, so that you don't have to draw all the lines for connecting the power lines together.

  [1]: https://i.stack.imgur.com/yW34y.png


body:
I'm building a puzzle for an escape room. I want to give the user 6 wires and 6 terminals, then confirm that they've connected the correct wires to the correct terminals (one-to-one).

My first (successful) attempt to implement this puzzle was to connect the wires to 6 PWM analog outputs set to different levels, and connect the terminals to 6 analog input pins. By time-averaging the readings on the input pins, I was able to determine which wire(s) are connected to which terminals, if any.

I currently have no resistors in the circuits.

As the puzzle is currently designed, it's possible for the user to do weird things like:

* Connect multiple wires to the same terminal.
* Connect multiple wires together, without connecting them to any terminal.
* Touch multiple exposed wires and/or terminals.

My questions boil down to two:

* Is my current approach dangerous, either for the Arduino or my users, and are there recommended precautions I should take?
* Is there a better (safer or simpler or more robust) way to implement the puzzle?

I'm a software engineer, but a complete noob when it comes to _real_ electronics and Arduino, so please feel free to assume I know nothing.

title: How can I differentiate between multiple circuits?

Answers: 2

body:
I would also connect the terminals to the 6 analog input pins and have 6 unique voltages, one per wire. The Arduino will only provide the output when the 6 wires are placed on the correct terminals. In other words, that is when the Arduino sees the correct analog voltage on the respective pins.

I personally would add a [RC Low pass filter][1] to the output of the PWMs. [More information here.][2] Your PWM output would go into the Vin and the then the Vout would go to your wire (ie the analog input). One filter per channel.

[![Basic RC filter][3]][3]

The RC filter will protect the Arduino from shorts to +ve, Gnd and the other pins as well as providing a bit of protection from static. It will also simplify your code.

At the moment you are having to implement fancy code to average out the voltage on those analog pins. The RC filter would essentially make that code not needed.

To calculate the value of the resistor and capacitor you need:
There is a very good article over at [All About Circuits that goes into this subject in detail][4].

To calculate the value we need to know the frequency:

> The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. [- Arduino Analog Write][5]

I used http://sim.okawa-denshi.jp/en/PWMtool.php to calculate the values of R & C needed with a very low ripple ( < 60mV ) using common values. I based my calculations around the 490Hz as the lower frequencies perform worst with low pass filters.

I suggest you use values of `R = 10k` and `C = 4.7uF`. You can play with these values until you get the output you desire.

One last thing I would consider is to put some protection on the terminals that connect to the analog pins. This could be a small resistance in series, or a 5.1V zener in parallel (the pin may already have this?) or some capacitance in parallel.

----------

**EDIT:**
I have just had a brainwave - You don't need to use the PWM's to output the different analog values - you could use a voltage divider circuit instead. No RC filter needed. For example:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/SJhtb.png)

<!-- End schematic -->

----------

**Edit #2:**
> Jonathan Wrote:
The only minor downside I'm noticing is that if the user has two wires connected to the same terminal, it affects all the voltages read across the other terminals, **making it hard to give the user incremental feedback** on how many wires are correctly connected.

This can easily be solved by providing 6 individual voltage divider networks, as shown below. Notice how each voltage divider has a different ratio.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/M6viA.png)

<!-- End schematic -->

  [1]: https://en.wikipedia.org/wiki/Low-pass_filter
  [2]: https://www.electronics-tutorials.ws/filter/filter_2.html
  [3]: https://i.stack.imgur.com/Eeiko.png
  [4]: https://www.allaboutcircuits.com/technical-articles/low-pass-filter-a-pwm-signal-into-an-analog-voltage/
  [5]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

body:
First, let's consider the logic of your program. You have two groups of
pins: 6 pins connected to the wires and 6 pins connected to
the terminals. The first thing I would do is forget that these are two
different groups. Consider you just have 12 pins that the user has
to connect in a specific fashion. This way most “weird things” the user
could do, like connecting wires together, are not a special case
anymore. They are just another invalid combination. Now what you have to
do is, for every pair of pins among those 12, determine whether or
not they are connected together. If any pair is connected that shouldn't
be, you have an invalid combination. If any pair is not connected while
it should be, it's again an invalid combination. If every pair is the
expected state (either connected or not connected), then the user did
solve the puzzle.

Now, for the hardware side. A simple way to know whether two pins are
connected together is to set one of them to `INPUT_PULLUP` and the other
one to `OUTPUT` `LOW`. This second pin should be the _only_ one
accessible to the user that outputs a `LOW`. All other exposed pins
should be set as either `INPUT` or `INPUT_PULLUP`. Now, if the first pin
reads `LOW`, you know have a connection. If it reads `HIGH` the two pins
are not connected together.

Here is an example program demonstrating that principle. It loops over
the 66 possible pairs to check whether they are connected or not.
You just have to replace the inner `if` with your code that validates
the combination.

<!-- language: lang-c++ -->

    const int PIN_COUNT = 12;
    const uint8_t pins[PIN_COUNT] = {...};

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

        // Set all pins to INPUT_PULLUP.
        for (int i = 0; i < PIN_COUNT; i++)
            pinMode(pins[i], INPUT_PULLUP);
    }

    void loop() {
        // Loop over all pin pairs (pins[i], pins[j]).
        // Set pins[i] to OUTPUT LOW, then read pins[j].
        for (int i = 0; i < PIN_COUNT - 1; i++) {
            pinMode(pins[i], OUTPUT);
            digitalWrite(pins[i], LOW);
            for (int j = i+1; j < PIN_COUNT; j++) {
                if (digitalRead(pins[j]) == LOW) {
                    Serial.print("pins ");
                    Serial.print(pins[i]);
                    Serial.print(" and ");
                    Serial.print(pins[j]);
                    Serial.println(" are connected together.");
                }
            }
            pinMode(pins[i], INPUT_PULLUP);
        }
    }

As for the safety, you should be fine as long as the users do not have
access to any low-impedance ground or voltage source. In particular, the
GND and 5V pins should not be user-accessible. For extra protection, you
could put a 1 kΩ resistor in series with each pin, but then all the
pins that are not actively being tested should be set to `INPUT` rather
than `INPUT_PULLUP`, otherwise multiple pullups in parallel may start to
compete with the series resistor.