text:
Servos not working properly with joystick
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.

You don't initialize joyvalx and joyvaly. 2. You never assign anything to joyvalx or joyvaly.

+1 for nicely formatted code

your answer is here 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   ........ you have two pieces of code that are like two dogs fighting over a bone

1023-joyval, which is 0 to 180? ...

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.

I like this answer; I'd just add one very important thing: you should not call the functions at max speed, but rather call it let's say once every 10 ms. The responsiveness is still high, but 1) the other parts of the program run better and 2) you on't try to give mechanical components commands which are too fast

Yes, you can do this, but I don't think, that writing at max speed really would do something bad. The servo is controlled via PWM and it will go to the specified position as fast as it can, you cannot control it's speed. When writing slower (with a delay or a millis() construction), then there only will be lesser positions in between, but the overall value change would be the same; at maximum an instant jump from 0° to 180°. On the other side it would prevent jitter, if you measure a bigger number of analog values and only write the average to the servo.

in fact point 2 should not be applicable for servo motors (I checked the library and it updates the value once per timer overflow, so it automatically neglects all the other commands). Nevertheless having a human interface in constant acquisition is not something very advisable in my opinion; it drains resources (even if in this case no other "tasks" have to be performed) and floods with useless information the receiver (for instance, the PC at the other end of the serial link). This, again, apart from the mechanical problems which in this case are not present due to the library design

You are right, for a bigger program this is important. I didn't include it for simplicity, but it's definitely a good point for a remark.

Thanks @chrisl, your answer did do the work. Now both servos are working great. Thanks a lot.


text:
NRF24L01 writing fail
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:

My setup:

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

Do you have the same setup for the receiver? How far is the receiver from your transmitter? The NRFs have some trouble if they are to close to one another.

Same setup, about 2 / 3 meters away. However, this more likely seems like a problem of transmitting rather than receiving because this says that transmitting is not even working right?

Sorry, you're correct. The timeout message threw me off. It seems like the Arduino is unable to communicate with the NRF. Try wiggling all the connections, to make sure they make good contact. Try calling the printDetails function.

hmm the connections seem fine... especially because both devices give the same error. (same setup). I have a small issue implementing the printDetails. when I add the line radio.printDetails(); anywhere, I don't see any response in my monitor?

@Mart You have to initialize printf first for printDetails to work.

Thanks @Avamander I updated my initial question with the printDetails output. I have no clue what can be wrong

Looking at the pictures, I'm sure this issue is caused by too weak power supply. Try soldering a large decoupling capacitor to the module's VCC and GND pins directly, if that doesn't improve the situation use an external 3.3V regulator.

Cross posted to: https://github.com/nRF24/RF24/issues/445

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.

Rewrite your answer as an actual solution, if it is one.  Presently, it appears more of a comment.

Thanks, i'll try asap and post the result. Did you place a resistor between sck pin and ground? (assuming this layout: https://tmrh20.github.io/RF24/ )

I didn't need to physically place a resistor due to my MCU having them internally, but that should work fine. Maybe 10k?

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);
}

CONFIG: 0x0 => 0xF
EN_AA: 0x1 => 0x3F
EN_RXADDR: 0x2 => 0x2
SETUP_AW: 0x3 => 0x3
SETUP_RETR: 0x4 => 0x5F
RF_CH: 0x5 => 0x4C
RF_SETUP: 0x6 => 0x3
STATUS: 0x7 => 0xE
OBSERVE_TX: 0x8 => 0x0
RPD: 0x9 => 0x0
RX_ADDR_P0: 0xA => 0x31
RX_ADDR_P1: 0xB => 0x32
RX_ADDR_P2: 0xC => 0xC3
RX_ADDR_P3: 0xD => 0xC4
RX_ADDR_P4: 0xE => 0xC5
RX_ADDR_P5: 0xF => 0xC6
TX_ADDR: 0x10 => 0x31
RX_PW_P0: 0x11 => 0x20
RX_PW_P1: 0x12 => 0x20
RX_PW_P2: 0x13 => 0x0
RX_PW_P3: 0x14 => 0x0
RX_PW_P4: 0x15 => 0x0
RX_PW_P5: 0x16 => 0x0
FIFO_STATUS: 0x17 => 0x11
DYNPD: 0x1C => 0x0
FEATURE: 0x1D => 0x0

You are at least talking to the radio.  All settings are default except CONFIG: 0x0 => 0xF (PRX mode, powered up, crc=2 enabled) SETUP_RETR: 0x4 => 0x5F (up to 15 retransmit attempts) RF_CH: 0x5 => 0x4C (channel 2476 MHz) RX_PW_P0: 0x11 => 0x20 (32-byte payload) RX_PW_P1: 0x12 => 0x20 (32-byte payload).  See section 9 of the nRF data sheet for index of the register values.

One of the radios needs to be PTX (primary transmitter), the data you posted above show the radio is set to PRX (primary receiver).  Make sure receiver and transmitters have common pipe addresses and use the same radio frequency. Upvote answer, please, if it is helpful to you.

Okay, thanks! so if I'm able to talk to the radio, why will the writing result in a fail? Are these settings incorrect? I just took them out of the box like this and started working with them like described above without editing settings.

For each Arduino controlling the TX/RX radios, put my code into your program at the end of setup section and copy here what the output is.  There are many things which can be wrong.  Also check one of the radios has bool radioNumber = 0; and the other bool radioNumber = 1;

CONFIG: 0x0 => 0xF
EN_AA: 0x1 => 0x0
EN_RXADDR: 0x2 => 0x2
SETUP_AW: 0x3 => 0x3
SETUP_RETR: 0x4 => 0x5F
RF_CH: 0x5 => 0x4C
RF_SETUP: 0x6 => 0x3
STATUS: 0x7 => 0xE
OBSERVE_TX: 0x8 => 0x0
RPD: 0x9 => 0x0
RX_ADDR_P0: 0xA => 0x24
RX_ADDR_P1: 0xB => 0x15
RX_ADDR_P2: 0xC => 0xC3
RX_ADDR_P3: 0xD => 0xC4
RX_ADDR_P4: 0xE => 0xC5
RX_ADDR_P5: 0xF => 0xC6
TX_ADDR: 0x10 => 0x24
RX_PW_P0: 0x11 => 0x20
RX_PW_P1: 0x12 => 0x20
RX_PW_P2: 0x13 => 0x0
RX_PW_P3: 0x14 => 0x0
RX_PW_P4: 0x15 => 0x0
RX_PW_P5: 0x16 => 0x0
FIFO_STATUS: 0x17 => 0x11
DYNPD: 0x1C => 0x0
FEATURE: 0x1D => 0x0

radionumber is 1 on the first arduino, 2 on the second

TX and RX addresses are not opposite, they are same on each Arduino. See this by comparing RX_ADDR_P0 with TX_ADDR: 0x24 on one Arduino, 0x31 on the other.  Try swapping radio.openReadingPipe(1,addresses[0]); for radio.openReadingPipe(1,addresses[1]); and vice versa

All fine and stuff, but shouldn't the nrf24 library from tmrh20 fix this? Your last suggestion didn't work.. (and upvoting is something i can't do yet)

I don't know about that library, but from the information you gave, it appeared the problem was that the addresses set incorrectly.  TX address of radio 1 should equal RX address (of relevant data pipe) for radio 2, and vice versa.  I will add to my answer code that will let you set the addresses manually.

Let us continue this discussion in chat.

source: Stack Exchange

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

sort: votes


text:
1.54 e-ink without driver
i wan’t to know if is possible to use  this raw e-ink display  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

Please add more info, not just a  link to a picture!

i’ve just posted the datasheet

DONT CROSS POST!

See figure 7-5 in the datasheet you linked. There it shows you how to connect the board.

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.

thanks. i was thinking that i just solder few wires to a ribbon cable but i understood that there must be a lot of other components

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


text:
Arduino - Calculating the time for which a Pushbutton is pressed and held without being released
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 ?

Constrain your question.  Are you talking Minutes? Seconds?  Milliseconds?  If milliseconds, how do you plan on contending with switch bounce?

Milliseconds only. I haven't figured out the solution for the bounce problem yet.

Was not asking how you were going to solve it.  Wanted to know how you were going to interpret it. Guessing, I would say you want to start counting in millisecond increments on first contact.  Then I am going to assume you want to stop counting at last contact.  But the tricky bit: You will not know about last contact until after (depending on the quality of your switch) 10s of milliseconds goes by with out additional contacts.  So, what ever solution you choose, you will need to consider these issues and guess at the timing, try them then adjust them until you get the desired results.

Yeah that is exactly how I'am interpreting this question. Okay let me try and get back here. Thanks buddy.

There is a library called "Debounce", which you can find here: playground.arduino.cc. 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.");
    }
  }
}

The millis() overflow shouldn't be an issue, since the substraction endTime - startTime will also overflow, since elapsedTime is also an unsigned long.

Hi VE7JRO, I get this error, is there something wrong with importing the library ? :Arduino: 1.8.5 (Windows 7), Board: "Arduino/Genuino Uno"
C:\Users\user\Desktop\buttonpresstrial3\buttonpresstrial3.ino:1:22: fatal error: debounce.h: No such file or directory
#include <debounce.h>
                  ^

compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Sorry @VishwaV, you can find it here: https://playground.arduino.cc/uploads/Code/Debounce.zip. I'll update my answer. I'm using version 1.0.6.2 of the IDE, and I'm guessing the newer versions use the updated Bounce2 libraries.

Hi @VE7JRO, Even after importing it to my libraries folder in arduino, I'm getting this error : D:\arduino-1.8.5\libraries\Debounce\Debounce.cpp:2:22: fatal error: WProgram.h: No such file or directory .  What should i do ?

On line 2 of Debounce.cpp, remove this: #include "WProgram.h" and replace it with this: #include "Arduino.h".

I replaced it with the help of notepad and the error still persists @VE7JRO

Try adding a couple of blank lines to the top of Debounce.cpp. The error was on line 22 (Debounce.cpp:2:22) the first time. Adding blank lines should change the line number of the error. We need to verify you are editing the right file.

Hi @VE7JRO i added a couple of blank lines to the top of debounce.cpp file and the error still stays on line 22. Am i editing the wrong file then ?

Yes, you are editing the wrong file.

Oops , okay wait this is what I did, I saw the Debounce.cpp file. Converted it into wordpad format and changed the line as you said. After doing this, i saved it back in the word format. Should i change it back to cpp format or anything like that ?

And the error has an additional line now :
Multiple libraries were found for "Debounce.h"
Used: C:\Users\user\Documents\Arduino\libraries\Debounce
Not used: D:\arduino-1.8.5\libraries\Debounce

It looks like the IDE can't decide whether to use the library on C drive or D drive. I would remove one of the duplicate libraries. File name should be: Debounce.cpp. I'm not familiar with wordpad. Do you have a simple text editor?

Hii @VE7JRO , you were right i removed one of those duplicate libraries and got it right. Your code is working absolutely fine now, Thanks.


text:
Touch Sensor - Determining Pressing/Hold Length and Modifying Program Flow Accordingly
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;
}

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. 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.");
    }
  }
}

This sketch uses a millis() timer to add the concept of time to debouncing a button with the Bounce2 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.
// 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.

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.


text:
Digital Comparator with ATTiny85 doesn't behave as expected
Here is my schematic:

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.

The outputs are simple logic with 10k series in R’s to avoid latchup.  L1=XNor<A,B, L2=A&!B , L3 =!A&B

"I've removed the resistors from the LEDs to make it smaller." - Your comment refers to the schematic, not to the circuit as built, is that right?

Yes, just the schematic, I noticed the bad phrasing but didn't bother to edit it.

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.

That doesn't fix the issue. Resetting the ATTiny is equal to looping and turning the rest off.

Would you have to reset the ATTiny each time you change the input?

Well I would use it only for a short time period.

Have added the delay ?

Yes manually by disconnecting and connecting

This has the core of the answer, but you need to explain what is wrong, not just provide a dump of alternate code without explanation.

@Chris Stratton You are right, I have edited my post

@AhmedM.Zahran These changes only necessary if the code runs in a loop, in which case suggestion to add a delay does not apply. Likewise, adding a delay makes these changes unnecessary.

@Maple I mean, delay can be added inside the loop to give some time availability to change the statuses of the digital inputs, rather they are going to act immediately after a single input change. I'm talking about 300ms which means the LED indicators will be changed about 3times in a second.

@AhmedM.Zahran In that case you answer is incorrect. Adding delay in a loop does not guarantee you that both inputs already changed, no matter where in a loop you put it. And what is wrong with reacting immediately? It is ATTiny with nothing else to do anyway.

These inputs are digital outputs of aurduino that means a 300ms delay is a very sufficient time to decide that these are the desired outputs or not.

You have 3 sequential IFs in your code. The change in a single input can happen between them, resulting in wrong output. The delay will only make this wrong output stay longer.

Input statuses are stored in a and b and these are never changed during execution of IF statements. So a 300ms delay will be dependent upon the application. Don't judge the presented solution until your requirments don't match with it. You said it it's just an ATTiny!

My apologies. The correct statement would be "The inputs can change  between reading a and b pins, resulting in wrong output". Introducing a delay does not improve the function of the code in any way. It only reduces reaction time. Why on earth would you do that? Besides, I do not see any mention of a loop in text.

By default you are using a microcontroller to repeat the implemented functions. not to manually reset its power to repeat the code. So why he is using a microcontroller? If you intend to sell this device, Are you going to tell the user to reset the power of the device to get a different output? What happens if the user powered up the device before assigning the inputs? He will get no result, because he was slowly enough to catch the code.

You asking all the right questions. But all of them have nothing to do with providing correct answer. Your proposed code changes are correct and required, but only if you specifically mention surrounding the code with the loop. Your proposed addition of a delay is required only in one-shot implementation, in which case other code changes are not necessary.

I'm going to edit my post to add a loop but I don't believe that one-shot code is a good implementation in that application until there is an automatic reset function implemented in Arduino.

I agree that loop is better implementation because it does not depend on power scheme. From OP comments it seems the power will be off most of the time, in which case a one-line change to add delay and making sure that Arduino does not set outputs before power is applied can be sufficient for simple experiments.

reading pins should be in the loop as well

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:

power-cycle the ATtiny
set its A input to LOW
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:

set the new inputs
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:
#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.

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().

Hm thank you, I'll improve it with a loop or by using interrupts on changed voltages.

do not start thinking about interrupts until you can write basic code

While not entirely false, this does not address the glaring issue of the code, but only the tangential failure to achieve a clean power on reset when inputs are powering the chip.  If the code were correct, this theoretical issue would not be seen in practice.

Why is the code not correct? I don't see a problem with it.

@ChrisStratton "not entirely false" implies "partially false". Please, point out a single false part of the answer, otherwise it is just ugly insinuation.

@Tvde1 Your code is correct if it only runs once and the inputs already set, for example if you add delay in the beginning. But if you add loop then setting some pins to 1 is not enough, you also need to clear other pins to 0, as in Ahmed's answer.

Yes but I was going for low power usage, because I wouldn't need it to run often, I figured I moght as well only turn it on when I need it to output.

As I explained above, you have to keep Arduino outputs at tri-state before you apply power to ATTiny and before you remove it. Then you need either delay to give Arduino time to set both outputs, or you need a loop. In case of a loop setting some pins to 1 is not enough, you also have to clear already set pins back to 0.

Let's say your inputs supposed to be 1:1. If you set A first you have 1:0, and your code activates Led2. Then you set B and you have 1:1. This time your code activates Led1, but Led2 remains active too.


text:
L298N, HC-05 Simple Bluetooth remote car not running in Arduino
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:

Tested the motor dc result both of wheel works (can spin forward and or backward). power direct from the battery.
Tested HC-05 bluetooth moduled. The phone can paired the bluetooth module.
Tested out1 out2 out3 and out4 on L298N using direct power from the battery the wheel spinning (forward and or backward).
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

    #include
    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); }
  }
}

you forgot to ask a question

what tests have you done?

Instead of writing many if-else if statements, use a simple switch(data){ case '0':

What data gets send to mySerial? Can you confirm, that the correct data is actually received? Maybe echo it back to the source. If this doesn't work, your serial connection doesn't work (maybe because the HC-05 isn't really connected). If it works, try to drive the motor through the driver, by connecting the corresponding pins to 5V. If this doesn't work, your driver connection is not correct. You should provide a schematic instead of photos.

nothing displayed data from serial monitor.
HC-05, icon indicator green in android phone (success conecting to the car).
L298N, the motor run after i give direct power to PIN 5 and Ground.
the battery 4 x 1.2 alkaline or 9v

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


text:
How to find the index of the maximum value in an array?
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.

Arduino libraries have no special function to find the element in array

Duplicate of https://stackoverflow.com/a/2953498/5296568

I have an Average library that does all this kind of thing for you. Here is how it finds the maximum value's index: https://github.com/MajenkoLibraries/Average/blob/master/Average.h#L194

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;
    }
}

The content of the myMeasurements array is coming from the ADC (analogRead) and hence it is 10 bits (0-1023). Unless the map function is used, they cannot be declared as a byte. I refrained from doing this because the map function reduces the resolution and it is likely that the values stored in the myMeasurements array are close to each other, i.e. the resolution plays an important role when finding the maximum element. I can define it as unsigned int Instead of int.

As a matter of fact, I am going to use the analogReadResolution(16) command to increase the ADC precision to 16-bits, which is also supported by the unsigned int data type.

@canberk_gurel you don't need a map (which is slow), you can just do something like (uint8_t)(readAnalog(channel) >> 4) (I don't remember the function, so forgive if readAnalog is not correct). In any case yes, if you need more than 8-bit measurement you need a more-than-8-bit variable, and so uint16_t is perfect

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;

Put >= for last found max

Beaten by a few seconds... Even if a little of explanation why this is better than the previous answers would not have hurt...

You don't use variable for current number, you don't use  variable for max value, only for max index. You can assign 0 to maxI before for loop and so skip 1 iteration so it's faster a little bit and takes less ram

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

So two passes in the array to get the max index? Uhm...

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;
    }
}

Oh, those wonderful uninitialized variables....


text:
Error in finding frequency of an input signal
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.

You should add something to differentiate which ISR is printing which "0". That may give some clues.

I have edited the OVF ISR where the Serial.print command was written mistakenly.

As I remember, Serial doesn't work inside of an ISR. Am I wrong?

What frequency range are you hoping to measure?

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.


text:
Power management circuit
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

Q2 looks upside down to me...

yeah probably yes

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

simulate this circuit – Schematic created using CircuitLab
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.

this is a good solution. the problem is that I'll use 3v as in, and the btn should work  the opposite: high when button pressed and low all the rest of the time

3v for control (HOLD) is fine as long as M2's threshold is suitable. 3V for sensing (BTN) can just go through a simple voltage divider. Why do you need the button reversing? It needlessly complicates things.


text:
Reading and sending with Arduino?
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

One word: Interrupts. Google them.

Post some more details of what you are trying to achieve.  You want to count pulses?  Interrupts as Majenko said.

yes i need to count pulses so i dont want that at the moment when i send a value, i miss a pulse

I have googled for polthread and pollthread, and can't find anything. Can't you provide a link. Regardless, count each impulse in a ISR (one statement should do it) and in the loop() you can calculate and output the mean using 'millis()`

sorry ,its protothreading here is a link https://www.hackster.io/reanimationxp/how-to-multithread-an-arduino-protothreading-tutorial-dd2c37

@Majenko if i use interrups every time i get an impulse wont it disturb the sending function ? knowing that i have to send a value every period of time

Unless the sending function relies on timing critical bit banging, no, you won't "disturb" it. What is this mythical "sending function"? What are you using to communicate? How are you controlling it?

i am sending my mean value over Lora network to a gateway

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.

what if the frequency that i am counting is variable? can the timer solution still work

Yes. It just cares about edges. As long as the number of pulses you need to count is less than the maximum the timer can count (or you "expand" it using the overflow interrupt) within the period at which you read-and-reset the count it doesn't care what the frequency is (as long as it's below 1/2 the system clock frequency).

i get ur solution however if i use the timer as a counter how would i know the time during witch i counted my pulses to get a mean value ?

There is more than one timer. Timer0 drives millis().


text:
Nextion Dual State Button
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!

Did you select a hardware serial port for nexSerial? Do you see the text "setup done"? Do you see the text "b0PopCallback"? Did you enable the event in the nextion editor? Please update your initial question with more information.

I have done no coding in the Nextion editor as I thought Arduino IDE handles all the coding. How would I go about enabling the event in Nextion?

I will admit that I did load this code from a sample sketch provided by Nextion, however I ONLY used the code and never looked into the .HMI file. I might browse over that and try and understand what you mean by enabling the event in Nextion :)

In the callback, where does it assign a value to dual_state?

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);
  }

}

strcmp doesn't return true or false so your comment about it returning FALSE if both strings match is a bit misleading. See strcmp - strcmp is designed to return a number < 0 if string1 is less than string2, 0 if they are the same, and > 0 if string1 is greater than string2 (in the collating sequence).

Regardless of the failure in describing the return type of strcmp, I believe that is indeed what the OP is missing.  The code in OP never checks the string and assign any value to dual_state.

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 );
  }

}


text:
Arduino Fried? Power is being delivered to Arduino but COM not found
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!

If you observe 12V on an MCU pin, the MCU is certainly dead.

Sometimes this happens when there is a short circuit, but does not necessarily fry the board. Is the nano touching any other conductive material? Finally, I would like to suggest that you try and restarting windows since windows at times just fails to pick up the Arduino.

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?


text:
Schematic interpretation, where to put resister?
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/

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:

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.

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.


text:
How can I differentiate between multiple circuits?
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.

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.
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.

This is exactly the method I use for testing development boards I make. A shield is attached which links 50% of the pins to the other 50% through 100r resistors. Scanning the pins with one set low checks for both proper continuity as well as shorts to other pins.

Beautiful. This is the paradigm I was missing. It totally hadn't occurred to me that I could actually measure under different configurations in rapid succession. My options for building things just exploded. I'll try it out.

This worked wonderfully. I much prefer it over my analog approach, as I don't need to worry about defining expected voltage ranges for each input. And of course, I didn't need to check all 1211/2 combinations, since I really just need to know which wires are connected to each terminal (66 checks) - if two terminals or two wires were connected, it would necessarily result in the wrong combination of wires connected to a given terminal. It is however important to check for more than the expected 6 connections, to handle the case where the user somehow bridges all the terminals. Thanks!

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 to the output of the PWMs. More information here. 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.

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.
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

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:

simulate this circuit – Schematic created using CircuitLab

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.

simulate this circuit

@sa-leinad Cool idea on the voltage divider circuit.

Cool. So the expectation is that with your second idea, I should be able to see actual different (stable) voltages on the different wires, which eliminates the need for the time averaging, right? I'll try it out.

I tried it out, and this (second idea with the voltage divider circuit) seems to work fine. 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. Thanks again!

Ahhh, I was not aware of the need to provide incremental feedback. In that case you will need 6 different voltage divider networks. I will edit my answer to include this.


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

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

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

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

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

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

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

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

void loop()
{
}

Cheers!

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

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

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

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

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

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

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

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

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


text:
Prevent Arduino IDE from rebuilding the core library after every restart
I have an Arduino IDE 1.8.5 setup (installed from the ZIP file) which I use to work exclusively with a single board. Every time the IDE is restarted, the first compilation takes much longer than subsequent ones. Apparently, the reason is that Arduino IDE rebuilds the core library:

Archiving built core (caching) in: C:\Users\User\AppData\Local\Temp\arduino_cache_976772\core\core_arduino_avr_mega_cpu_atmega2560_82177ffe36573ad451e992f583fff1d1.a

Is there a way to prevent that and make the IDE keep the cached core library across restarts? I have the "Aggressively cache compiled core" option checked, but it doesn't seem to help.

Use uecide instead. The caching works on there.


text:
Arduino code to run 2 thing simultaneously
I am making a project for my college in which I need to measure the rpm of the motor and show the real-time clock on the 128x64 GLCD simultaneously but when I run the project it only shows one thing at a time. is there any method to show both of them simultaneously I am not putting any code because I just compile my hall sensor separately and rtc code separately

You write code that does what you want. You never "do two things simultaneously", but write code that just does what you want. You have to understand what your current "two codes" do and how they work before you can try getting them to work together.

Without code it's hard to suggest improvements. Have a look at the blink without delay example (millis to get rid of blocking code like delay). This is what I used to emulate parallel processing.

Interrupts are your friend. So are the timer/counters.

Arduino Microprocessors are mostly single core devices and thus are unable to do more than one thing at a time.
The trick is to write code efficiently so it looks like several things are happening at the same time but in reality they just happen very quickly.
The LCD only needs to show time every second and displaying RPM every second should be enough so to get both to happen within a second should be possible.


text:
Powering Atmega328P-Pu externally
Please I'm new to Arduino and I need assistance. I'm working on a project which makes use of the ultrasonic sensor to make a certain pin high if a certain distance is attained. When I used the USB port to power it up it worked fine. When I use external power(tried two different 9V microphone battery) it's not giving desired result. Now I want to try using just the Atmega328P on the board externally(separately from the Arduino).
Questions

What could be the cause of the malfunction when I use external 9V battery
what voltage should I connect to the VCC of the Atmega cos I'm scared of damaging it.
Am I going to power the ultrasonic sensor with an entirely different source from the VCC or I can tap from that same VCC source.
Any other information I need to know using the ATmega on its own

1.8 - 5.5V (max)
The datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Summary.pdf) will tell you that input Voltage is: 1.8 - 5.5V
That's max of 5.5V so don't use 9V battery without a voltage divider.
To power the chip all you need is voltage to Pin 7 and GND to PIN 8.
16Mhz Crystal Most Likely Required
However, to get it to work after removing the chip from an Arduino Uno board you will also need a 16Mhz Crystal on pins 9 & 10.  You will also need two 22pF capacitors on pins 9 & 10, each connected to ground.
I've written this all up with pictures at my blog: http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone
Your final circuit will look something like the following (from my blog article):

Without the Crystal you will most likely find that your sketches don't seem to run.
Note: The red LED is connected just as a blink test (more on that in the article).

Thank you very much. I really appreciate your response. Would try everything out.

A voltage divider is not a regulator, don't try to power a chip with a divider!

Okay, good point. But was only attempting to mention that 9V was too much.  So are you saying that if he divided the voltage down to 3.3V for example and applied that voltage (which is in the range that the chip can handle) it would cause some kind of problem?

@raddevus a voltage divider doesn't regulate, as the load changes so will the voltage, a stable voltage is required to run a micro controller.

What you need is a voltage regulator! There are many options to choose from linear regulators to buck (or boost) DC-DC converter. You can buy them from various sources as well.

What could be the cause of the malfunction when I use external 9V battery?

The ATMega can only handle 5V maximum, using 9V will either destroy it or engage protection circuitry that will prevent the chip from operating and being damaged.

What voltage should I connect to the VCC of the Atmega?.

Most of the time an ATMega is powered with 5V, but depending on the clock frequency they can operate at lower voltages, the datasheet will have the details.

Am I going to power the ultrasonic sensor with an entirely different source from the VCC or I can tap from that same VCC source?

With the appropriate choice of powersupply you can power both the AVR chip and your sensor with the same power supply.

Any other information I need to know using the ATmega on its own?

The datasheet will contain all you need to know, but if you want to use the Arduino tool chain you will need to:

Use an external crystal
Burn the Arduino (or AvrDUDE) bootloader

I can't conclude which of the questions you are helping me answer.

@user169847 I edited the answer to be more clear


text:
Arduino SD count files and open last, How to?
I am trying to count files. I have one hidden file from Windows10 so i am doing "-1" but I want to open the last file and can't work out how, any help? Please, Thanks
#include <SD.h>
int entryCount = 0;
File root;
int total = 0;
int Lfile = 0;
void setup()
{
  Serial.begin(9600);
  pinMode(10, OUTPUT);
  SD.begin(4);
  root = SD.open("/");
  printDirectory(root, 0);
  root.close();
  Serial.println();
  Serial.print(total-1);
  Lfile = total-1;

  File dataFile = SD.open(Lfile);
  // if the file is available, write to it:
  if (dataFile) {
    while (dataFile.available()) {
      Serial.write(dataFile.read());
    }
    dataFile.close();
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println();
    Serial.println("error opening last file");
  }
}

void loop()
{
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs)
{
  while (true)
  {
    File entry = dir.openNextFile();
    if (! entry)
    {
      if (numTabs == 0)
      return;
    }
    for (uint8_t i = 0; i < numTabs; i++)
      Serial.print('\t');
    Serial.println(entry.name());
    total = entryCount;

    Serial.print(entryCount++);

    Serial.print('\t');

    entry.close();

  }
}

what does last file mean?

sd card have files log01.txt, log02.txt, etc. Last file is last file which was created

Consider using the exist() method found in the SD.h library you already are including in your program.  Assuming you will create no more than 99 files and the last file created will have the highest 2 digit value as part of its name, test for the existence of the file log99.txt.  If not found, decrement the 2 digit number and test for the existence of file log98.txt.  Repeat this process until you find the newest file created.


text:
Wait for ALL serial data to be received
Is there a way to make the Arduino wait until all the serial data has been received? Say I send a 32 byte long string over serial (the length is actually random), how would I make my Arduino wait till all 32 bytes have been received?
If I execute Serial.readBytes straight away, it only reads one char. At the moment I'm using delay, but I'm worried that it is wasting time on the Arduino, as I would like it to be processed straight away. What I want to happen is I plug in my Arduino, type in the name of an input and output file, and it will start copying the input file into the output file. I don't want to re-upload every time I want to change files, so I would like to select over serial which ones to use. However, sometimes there will be no \r or \n sent at the end, which cuts off some of the file name.
Here is my code:
#include <SoftReset.h>
#include <SPI.h>
#include <SdFat.h>
#define csPin 4

SdFat SD;
File sourceFile;
File outputFile;

int bufSize;
uint32_t lastPos = 0, timeLast, timeNow;
//fix this (error: deprecated conversion from string constant to 'char*')
//char *outputFileName = "output.wav";
#define outputFileName "output.wav"
byte avail;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
  }
  Serial.print(F("Initializing SD card..."));

  // see if the card is present and can be initialized:
  if (!SD.begin(csPin, SPI_FULL_SPEED)) {
    Serial.println(F("Card failed, or not present"));
    soft_restart();
  }
  Serial.println("Card initialized.");
enterInputFileName:
  Serial.println(F("Enter input file name:"));
  while (!Serial.available()); // wait till serial available
  delay(100);
  avail = Serial.available() - 2; // extra '\n' & '\r' that we dont want
  char inbuf[avail];
  Serial.readBytes(inbuf, avail);
  Serial.read(); // remove '\n' from buffer
  Serial.read(); //remove '\r' from buffer
  inbuf[avail] = '\0';

  char inputFileName[avail];
  strcpy(inputFileName, inbuf);
confirmInputFileName:
  Serial.print(F("Select file '"));
  Serial.print(inputFileName);
  Serial.println(F("'? Y/N"));

  while (!Serial.available()); // wait till serial available
  delay(100); //wait for all chars to be recieved
  avail = Serial.available() - 2;
  if (avail > 1) {
    Serial.println(F("Enter 1 character"));
    while (Serial.available()) { //clear serial buffer
      Serial.read();
    }
    goto confirmInputFileName;
  }
  char confirm = Serial.read();
  Serial.read();
  Serial.read();
  switch (confirm) {
    case 'Y': break;
    case 'y': break;
    case 'N': goto enterInputFileName; break;
    case 'n': goto enterInputFileName; break;
    default: Serial.println(F("Enter Y/N")); goto confirmInputFileName; break;
  }
  //up to here works
  Serial.println(SD.exists(inputFileName));

  SD.remove(outputFileName);
  outputFile = SD.open(outputFileName, FILE_WRITE);
  outputFile.close();
  //read source and write to output
  sourceFile = SD.open(inputFileName);
  timeLast = micros();
  if (sourceFile) {
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println(F("Copying"));
    while (sourceFile.available()) {
      //make buffer size 50% of free ram, or amount of bytes left if smaller
      bufSize = min((freeRam() * 0.5 ), sourceFile.available());
      byte data[bufSize];
      sourceFile.readBytes(data, bufSize);
      lastPos = sourceFile.position();
      sourceFile.close();
      outputFile = SD.open(outputFileName, O_APPEND | O_WRITE);
      outputFile.write(data, bufSize);
      printStats();
      outputFile.close();
      sourceFile = SD.open(inputFileName);
      sourceFile.seek(lastPos);
    }
    sourceFile.close();
    outputFile.close();
    Serial.println(F("Finished"));
    unsigned int sec = millis() / 1000;
    unsigned int mins = sec / 60;
    sec -= mins * 60;
    Serial.print(F("Time taken: "));
    Serial.print(mins);
    Serial.print(':');
    Serial.print(sec);
    Serial.print(F("Speed: "));
    Serial.print((sourceFile.size() / 1000) / (millis() / 1000));
    Serial.print(F(" KB/s"));
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.print("error opening files");
    SD.initErrorHalt();
  }
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(200);
  digitalWrite(LED_BUILTIN, LOW);
  delay(200);
}

int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

void printStats() {
  timeNow = micros();
  uint32_t timeTaken = timeNow - timeLast;
  float sent = sourceFile.position() / 1000.0;
  float fileSize = sourceFile.size() / 1000.0;
  float left = fileSize - sent;
  float speed;
  speed = 1000000UL / timeTaken * bufSize;
  speed /= 1000;
  unsigned int sec = millis() / 1000;
  unsigned int mins = sec / 60;
  sec -= mins * 60;
  int estSec = (left / speed);
  int estMin = estSec / 60;
  estSec -= estMin * 60;
  Serial.print(F("\tSent (KB): ")); Serial.print(sent);
  Serial.print(F("\tLeft (KB): ")); Serial.print(left);
  Serial.print(F("\tSize (KB): ")); Serial.print(fileSize);
  Serial.print(F("\tTime: "));      Serial.print(mins); Serial.print(':'); Serial.print(sec);
  Serial.print(F("\tSpeed (KB/sec): "));     Serial.print(speed);
  Serial.print(F("\tFree: "));      Serial.print(freeRam() - bufSize);
  Serial.print(F("\tBuf: "));       Serial.print(bufSize);
  Serial.print(F("\tEST: "));       Serial.print(estMin); Serial.print(':'); Serial.print(estSec);
  //todo fix this line
  //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
  Serial.print('\n');
  timeLast = micros();
}

... Count them.

I did say that the amount would be random

Then you need to be sending the length too, or terminating the data somehow.

https://majenko.co.uk/blog/reading-serial-arduino

Please show the code you tried for reading the incoming data, and describe the data, especially how the Arduino can be able to tell how much data to read / when to stop reading & start processing.

You need to format the message so that the receiver knows where the message ends and a new one begins.
Then on he receiving end you fill a buffer until a full message is received and then handle the message.
A more advanced tactic is to process the bytes as you receive them. This requires that you build a statemachine but means you don't have to store a copy of the entire message.

I decided to use a loop to read into a buffer until it got to a newline or carriage return char, or it has waited longer than it takes to receive a char.

after source code was add to the question:
you use the readBytes function wrong. if you set the size parameter to count of available bytes it will read the count of available bytes.
allocate a buffer and set the second parameter as the buffer size. the readBytes will try to fill the buffer, waiting max one second for the next character, which is enough to read the complete line sent from Serial Monitor.
if (Serial.available()) {
  char buff[50];
  int length = Serial.readBytes(buff, sizeof(buff) - 1);
  buff[length] = 0; // terminating zero of c-string
  Serial.println(buff);
}

note: readBytes will wait one second after the last character received. better is to use readBytesUntil with expected terminator. or you can set smaller timeout on Serial with Serial.setTimeout(200)

I was concerned about the same thing recently when I worked on a project that would read serial data (received on a Bluetooth HC-05).
My loop() does a lot of work for my project (Never Type A Password Again (Arduino-driven Touchscreen Device @ CodeProject.com ) but reading the serial data is a big part of the work to do also.
I implemented the following code and it has been literally running for weeks now with no problems.
if (Serial1.available() > 0) {
    incomingByte = Serial1.read();
    while (incomingByte > 0){
      if (incomingByte == 0x01){
        Keyboard.press(KEY_LEFT_CTRL);
        Keyboard.press(KEY_LEFT_ALT);
        Keyboard.write(KEY_DELETE);
        Keyboard.release(KEY_LEFT_ALT);
        Keyboard.release(KEY_LEFT_CTRL);
      }
      else{
         Keyboard.write(incomingByte);
      }
      incomingByte = Serial1.read();
    }
  }

You can see that it reads bytes while they are available which might lead you to think it might lock up, but it handles it very well.
Quite A Bit Of Work
It does quite a bit of work because it is capturing any bytes that come across Bluetooth (and then it types them on the connected computer -- that's a long story, check out the article for more).
Quite A Few Bytes
It also reads at least 64 bytes (password length + special Control char bytes) but it handles it quite well.

while (Serial1.available > 0), without the while (incomingByte > 0) and second read would do the same. but the concept read byte handle byte is good, but not for this question

@Juraj  I checked and that is a good point.  I will look more closely at that.  thanks. I think the answer still helps the OP get closer to an answer since it was somewhat of a open-ended question.