text:
Why doesn't millis() use 1 µsec or 1 msec interrupt?
Arduino millis() does not make use of one millisecond interrupt. Instead they make use of 1,024 µsec interrupts and manipulate. Any specific reason why this was implemented this way?
In one case, we can go for timer0 without prescaler and use 1 µsec interrupts. In such case, we have to use CTC mode with OCR0A=15. Inside ISR, we could update the microsecond counter and if it reaches 1,000, we could update the msec timer count. Otherwise we could go for directly 1 msec interrupt (maybe using timer0).
I wrote this code to get micros() and millis(). But there is some issue and I'm not able to get it working correctly.
#include <avr/io.h>
#include <avr/interrupt.h>

#ifndef F_CPU
#define F_CPU 16000000UL
#endif

volatile uint32_t oneMilliCounter;
volatile uint32_t oneMicroCounter;
extern void initializeTimer0CTC_Mode (void);

extern uint32_t millis(void);
extern uint32_t micros(void);

volatile uint32_t oneMilliCounter = 0;
volatile uint32_t oneMicroCounter = 0;

uint32_t millis(void) {
  uint32_t value;
  uint8_t sregCopy = SREG;
  cli();
  value = oneMilliCounter;
  SREG = sregCopy;
  sei();
  return (value);
}

uint32_t micros (void) {
  uint32_t value;
  uint8_t sregCopy = SREG;
  cli();
  value = oneMicroCounter;
  SREG = sregCopy;
  sei();
  return (value);
}

void initializeTimer0CTC_Mode (void) {
  OCR0A = 15; // Set for 1 usec.
  TCCR0A |= 1 << WGM01;  // CTC Mode
  TIMSK0 |= 1 << OCIE0A;
  TCCR0B |= (1 << CS00); // prescaler=1
}

ISR(TIMER0_COMPA_vect) {
  static uint32_t prevMicro;
  oneMicroCounter++;
  if (oneMicroCounter - prevMicro >= 1000)   {
    prevMicro = oneMicroCounter;
    oneMilliCounter++;
  }
}

int main(void) {
  DDRD |= 1 << PD3;
  initializeTimer0CTC_Mode();
  sei();
  uint32_t prevTime = micros();
  while (1) {
    uint32_t currentTime = micros();
    if (currentTime - prevTime >= 1000) {
      PORTD ^= (1 << PD3);
      prevTime = currentTime;
    }
  }
  return (0);
}

What issues? What results are you getting? What do you expect?

One microsecond is only 16 CPU cycles.
The CPU needs 4 cycles to prepare itself for servicing the interrupt
(save the program counter, load the interrupt vector and clear the I bit
in SREG). The interrupt vector itself is a jmp instruction that takes
2 cycles. When the ISR is done, it executes the reti instruction
(return from interrupt) that takes 4 cycles. This means you have only 6
CPU cycles left for:

saving the context, i.e. pushing to the stack any register your ISR
may modify (2 cycles per push)
doing the actual ISR work
restoring the context (2 cycles per pop)
doing also some useful work in the main program.

There is no way you can do half of this in only 6 cycles.

Edit: I did a couple of experiments to gain more insight on the cost
of running an interrupt too often.
In the first experiment, I used your initializeTimer0CTC_Mode()
function to interrupt every microsecond the following program:
// This ISR consists of a sigle `reti' instruction.
EMPTY_INTERRUPT(TIMER0_COMPA_vect);

#include <util/delay.h>

int main(void)
{
    initializeTimer0CTC_Mode();
    DDRD |= _BV(PD2);       // PD2 = digital 2 as output
    sei();
    for (;;) {
        PIND |= _BV(PD2);   // toggle PD2
        _delay_us(499.75);  // 0.5 ms - 4 cycles
    }
}

The program is meant to generate a 1 kHz signal on pin 2, and
that's exactly what it does if the sei(); statement is commented out.
With the sei(); statement, the frequency drops to 375 Hz. This
shows that processing an empty interrupt (an ISR consisting solely of
the reti instruction) costs 62.5% of the CPU power, leaving 37.5% to
the main program. 62.5% is exactly 10 out of every 16 CPU cycles,
which confirms the cycle count of the first part of this answer.
The second experiment was to compile and disassemble your ISR. Here is
what I got:
__vector_14:
    push r1
    push r0
    in   r0, 0x3f  ; 1 cycle
    push r0
    eor  r1, r1    ; 1 cycle
    push r18
    push r20
    push r21
    push r22
    push r23
    push r24
    push r25
    push r26
    push r27
; static uint32_t prevMicro;
; oneMicroCounter++;
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    adiw r24, 0x01
    adc  r26, r1    ; 1 cycle
    adc  r27, r1    ; 1 cycle
    sts  0x0104, r24
    sts  0x0105, r25
    sts  0x0106, r26
    sts  0x0107, r27
; if (oneMicroCounter - prevMicro >= 1000)   {
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    lds  r20, 0x0100
    lds  r21, 0x0101
    lds  r22, 0x0102
    lds  r23, 0x0103
    sub  r24, r20   ; 1 cycle
    sbc  r25, r21   ; 1 cycle
    sbc  r26, r22   ; 1 cycle
    sbc  r27, r23   ; 1 cycle
    cpi  r24, 0xE8  ; 1 cycle
    sbci r25, 0x03  ; 1 cycle
    cpc  r26, r1    ; 1 cycle
    cpc  r27, r1    ; 1 cycle
    brcs 0f  ; 1 cycle if the if() condition is true, 2 otherwise
;   prevMicro = oneMicroCounter;
    lds  r24, 0x0104
    lds  r25, 0x0105
    lds  r26, 0x0106
    lds  r27, 0x0107
    sts  0x0100, r24
    sts  0x0101, r25
    sts  0x0102, r26
    sts  0x0103, r27
;   oneMilliCounter++;
    lds  r24, 0x0108
    lds  r25, 0x0109
    lds  r26, 0x010A
    lds  r27, 0x010B
    adiw r24, 0x01
    adc  r26, r1    ; 1 cycle
    adc  r27, r1    ; 1 cycle
    sts  0x0108, r24
    sts  0x0109, r25
    sts  0x010A, r26
    sts  0x010B, r27
; } }
0:
    pop  r27
    pop  r26
    pop  r25
    pop  r24
    pop  r23
    pop  r22
    pop  r21
    pop  r20
    pop  r18
    pop  r0
    out  0x3f, r0  ; 1 cycle
    pop  r0
    pop  r1
    reti           ; 4 cycles

Unless otherwise noted in comments, every instruction of this listing
takes 2 cycles to execute. Note the large number of CPU registers saved
(push) and restored (pop), and the large number of SRAM accesses
(lds and sts): three 4-byte variables read and written back.
Counting the total number of cycles taken by this ISR is left as an
“exercise to the reader”.

... And even if you could, imagine the performance hit on your sketch. It'd be starved of CPU cycles and never be able to do anything useful...

Using CTC mode would mean you can't use pin 9 as a PWM pin anymore.
Also, setting OCR0A to 15, would mean PWM on pin 10 could only have 15 different PWM values.
So, in essence, pins 9 and 10 can't be used for PWM.

Got it. So in addition to timer, we could get 1Hz (approximate) PWM with duty cycle decided by OCR0A/OCR0B on OC0A/OC0B

Not on OC0A, since you can't change OCR0A without changing the frequency.

You could instead try and use the more capable timer1. You can then use ICR1 to set the TOP. That you can still use OCR1A and OCR1B to set the duty cycle. Though you'd have to change the analogWrite function, to map the 0..255 value to the 0..ICR1 value. (and not use any of the libraries that use timer1, like the servo library)

I think you meant 1kHz, not 1Hz.

Yes, I meant 1KHz. Thanks for correcting. But I just checked ans saw that duty cycle can be changed (Not the frequency) on OC0A. Below is the code outline. First line is inside setup() function:
TCCR0A|=(1<<COM0A1)|(1<<COM0A0);
void loop() {
unsigned int cnt;
for(cnt=0;cnt<255;cnt+=50)
{
OCR0A=cnt;
_delay_ms(1000);
}
    }

Then what was OCR0A=15; supposed to do in your original code?

No, ignore original code. To conclude based on your answer: If we use OCR0A for timer delay, using PWM tied to OCR0A will be difficult (But we can get 50% duty cycle). Otherwise we can control duty cycle though we cannot change frequency.

Even if you could do what you are proposing, which you can't (see Edgar Bonet's excellent answer), imagine the performance hit running an interrupt every single microsecond would have on your code.
Every interrupt takes time away from your code.
Let's crunch some more numbers. If you wanted the millis/micros interrupt to take no more than 1% of the processing time, so it has no noticeable impact on your running code it would have to execute for only 10ns.  That's 1% of 1000ns, or 0.000001 x 0.01.
Now assume it takes 50 clock cycles for a highly optimised version of your function to operate. That's a conservative estimate. That includes the time taken to prepare for, call and return from the interrupt.
For both those to hold true you would have to be able to execute 100 x 50 instructions in a microsecond. (To fill your 1uS you should be able to run your 1% interrupt 100 times, yes?) That's 5,000 x (1/0.000001) instructions per second, or 5,000,000,000 instructions per second.
Assuming a single clock cycle for each instruction, that means your chip would have to be running at 5GHz...!
Can you see the problem?
So we scale it back to something more realistic. Maybe a 10% performance hit instead of 1%. How would that be? Well, it's simple enough to say that it would require a chip running at 10% of the speed. 500 x (1/0.000001). So 500MHz.
Still a long long way away from the 16MHz that the Arduino's ATMega runs at.
So you can see the issue.
So we choose close to 1mS instead. That gives a much lower overhead and it's something that the 16MHz Arduino can cope with.
Why 1024 and not 1000? That's simple: 1000 is base 10. We, as humans, with two hands (usually) of (normally) 5 digits on each, love base 10. We thrive in base 10.  However, computers with their 1s and 0s hate base 10. They much prefer working in base 2. It makes arithmetic really easy for them. And in interrupts we want the arithmetic to be easy.
Let's take a quick look at the maths involved and expand out the macros in the code.
Every tick the millis value is increased by MILLIS_INC, and any extra is added to a "fractional" count.  What's MILLIS_INC? It's:
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)

So let's expand that out - what's MICROSECONDS_PER_TIMER0_OVERFLOW?
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

And what's clockCyclesToMicroseconds?
#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )

What's clockCyclesPerMicrosecond()?
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

And, of course, F_CPU is (typically) 16,000,000.
So now we can put it all together.
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
becomes:

#define MILLIS_INC ((clockCyclesToMicroseconds(64 * 256)) / 1000)
which becomes:

#define MILLIS_INC (((64 * 256)/clocksPerMicrosecond()) / 1000)

Which in turn becomes:
#define MILLIS_INC (((64 * 256)/(F_CPU/1000000L)) / 1000)

Which finally turns into:
#define MILLIS_INC (((64 * 256)/(16000000/1000000L)) / 1000)

So reduce those down a little:
#define MILLIS_INC ((16384 / 16) / 1000)

And finally:
#define MILLIS_INC (1.024)

And since we're talking integers here that is automatically truncated (by the compiler, not at runtime, so it's essentially "free") to 1.
But what about the 0.024ms...? That's simple. The "Fractional" amount is added to another counter - but not as 0.024 - instead as a FRACT_INC amount, which is calculated as ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3). That's 1024 % 100, or just 24, but then that's right shifted 3 times.  That becomes 3. And when that count hits another limit it loops round and adds one to the millis count.  That limit is FRACT_MAX, which is 1000 >> 3 or 125.
All nice and simple and straight forward. Variables, like the fractional count, are kept to just 8 bits (which is what you want on an 8 bit CPU...) and the majority of calculations are done by the compiler, not at runtime by the CPU.  Everything else is simple addition / subtraction and comparisons. Very light. And it runs often enough to be good enough for the majority of uses. And given that, because it's just a timer interrupt and is subject to collision with other interrupts, and can't run when interrupts are disabled, it's only a rough figure anyway. Even the act of reading millis() can slow down the counting of milliseconds, since it disables interrupts while the value of the count is retreived (a so called "critical section").
And yes, it could be tweaked to run at precisely 1000uS intervals and do away with the fractional component - but why bother when it's never going to be that accurate anyway? Also the added complexity of calculating what 1000uS is for a timer configuration when you consider the vast array of speeds that Arduinos could potentially run at (16MHz for an Uno, 8MHz for the 3.3V boards, 1MHz for the default internal oscillator...) it's far simpler to say "This is what it ticks at, and this is the number of milliseconds per tick, with this bit left over" which is calculated at compile time, instead of having to work out prescalers and overflow counts, etc.


text:
MPU6050 accelerometer giving output as -1 -1. Can anyone tell the issue in the code?
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

void setup() {
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}

Serial Monitor output:
AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
AcX = -1 | AcY = -1 | AcZ = -1 | Tmp = 36.53 | GyX = -1 | GyY = -1 | GyZ = -1
[…]

You need to initialize the device and take it out of sleep mode first.

A return value of -1 means that the Wire.read is reading an empty buffer. In other words: you are not connected to the mpu6050. Try a i2c scanner first: https://playground.arduino.cc/Main/I2cScanner

Thanks Jot..! you point out the problem. My MPU was not connected to the arduino. Actually in arduino's MCU i2c module was not working well.

I found that there was a communication problem between MPU and Arduino which I found using code given in this link http://playground.arduino.cc/Main/I2cScanner .
Then I found thought problem Must be in MPU or arduino and problem was in Arduino MCU.
So after changing the Arduino MCU it worked

Acept your own answer to close the question

source: Stack Exchange

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

sort: votes


text:
Function, struct or class?
I am trying to learn more about arduino programming, and recently i've written functions for randomizing and then modifying a single array. Now i'd like to do the same for four individual arrays. This is where i'm getting stuck. My questions:
Am i right to assume that it's not possible calling a function for multiple individual arrays?
Perhaps a separate question, but if a class or struct would be more suitable for multiple instances, what are the major differences worth considering to choose the right approach?

Use arrays. You can pass arrays to functions. On what is more suitable, it depends on what you want to do. In real life, arrays rarely exists by themselves. You can use a struct to group an array and its related data, and a class if you want to tie array, related data and functions in one package.

Thanks for your clarification! Just to make sure we're on the same page: by individual arrays i mean that the four arrays all have different elements (If i'm not mistaken this implies individually declared arrays, no?). I've tried to read up on this, but i can't seem to come up with a solution where the same function returns four separately declared arrays, each with different elements. I'd be happy for a suggestion that points me in the right direction!

Are you trying to use the same function for different arrays at different times, or are you trying to use a function that handles four different arrays at the same time?
If the former, you'd write something like
void myfunc( T *arr, size_t size ) // where T is the type of the array
{
  for ( size_t i = 0; i < size; i++ )
    arr[i] = some_new_value();
}

then call it for each array:
T arr1[N];  // where T is int, float, double, whatever
T arr2[M];
T arr3[O];
T arr4[P];

myFunc( arr1, N );
myFunc( arr2, M );
myFunc( arr3, O );
myFunc( arr4, P );

This assumes all the arrays have the same base type (e.g., they're all arrays of int).
If you want a function to work on four arrays simultaneously, you'd write it as
void myFunc( T *a1, size_t a1_size,
             T *a2, size_t a2_size,
             T *a3, size_t a3_size,
             T *a4, size_t a4_size )
{
  // code for handling each array
}

While I wrote it such that all the arrays have the same type, it doesn't have to be this way.  Each array can be a different type (a1 can be int, a2 can be double, etc.).

Am i right to assume that it's not possible calling a function for multiple individual arrays?

What would give you that impression?  An array is just a pointer to a block of memory - as such it's just a variable. You can pass as many as you like to a function.
Just remember that a function can't know how big the array is that you pass it, since it only gets the pointer to the start of the array, so you need to pass the size of the array with it. You can't rely on the sizeof operator, since that is a compile-time directive that gives the size of a variable, which inside the function will be the size of a pointer (2 bytes on an 8 bit system). It can only give the size of an array (and then only the memory size in bytes, not the count of elements) if its run in the same (or a subordinate) scope as the declaration of the array.

Perhaps a separate question, but if a class or struct would be more suitable for multiple instances, what are the major differences worth considering to choose the right approach?

A struct is just a way of grouping variables into compound types. Think of them as database records. Great for if you want to keep related, but different, information together in one block.  Classes are the same thing but add functions as well.*

* That's a very simplistic description. In actuality you can have functions in structs and not have functions in classes. The real difference between them is how access controls (private/protected/public) are implemented (there is none in structs, and they are all there in classes) and how inheritance / polymorphism works.

Regarding your first question: I can't figure out a way to pass four individually declared arrays to the same function, and figured i'd ask beforehand instead of trying something that in fact is impossible. If it's doable, please elaborate. Also, thanks for describing things in the latter part of your answer.

@Erik I can't unless you show us what it actually is you are trying to do.

"An array is just a pointer to a block of memory" - if we're talking about C or C++, this isn't correct.  Array expressions will be converted ("decay") to pointer expressions in most contexts, but array objects are not pointers.  An array is simply a contiguous sequence of elements - no storage is set aside for a pointer to the first element.

@JohnBode What on earth is an array object?

@Majenko: The memory set aside for the array elements.

@JohnBode That is just memory. There's nothing object-y about it. If it's local to a function it's just a change in the stack pointer. If it's global or static it's a chunk of memory in the BSS or .data section. All you get is a pointer to that block of memory. The array knows nothing about it. The size of an array is only ever known at compile time by the compiler.

@Majenko - I'm using the term "object" the same way that the C language definition uses "object" - a region of storage in the execution environment that may store values.  An array is not a pointer to a block of memory - an array is that block of memory.

@JohnBode The abstract concept of an array may be the memory, but the actual variable that you have in your program is a pointer. Can you add an integer to an array? No. Can you add an integer to a pointer? Yes.

@Majenko: No, the actual variable is not a pointer.  That's the point I'm trying to make.  The actual variable is an array.  No pointer value is stored in the memory referenced by the array name.

@JohnBode So... if you add 1 to an "array" variable, what do you get? I think the difference you are trying to get across is that an array is the address of a block of memory, but a pointer is a variable that contains the address of a block of memory. Either way both are variables that point to a block of memory. The compiler knows more about what the "array" style is pointing to (since it can see that in the source code) but when compiled both pure pointers (char *) and "arrays" (char[...]) are the same thing.

@Majenko: An array is not an address.  An array is a sequence of elements.  An array expression gets converted to a pointer expression as necessary, but that's not the same thing.

@JohnBode So - if you print an array, what do you get? Do you get the array, or do you get an address? Me, I get an address. There is no variable type in C that can store more than a simple number. Everything else is an address (a simple number) to a block of memory over which the compiler overlays an abstract concept. You're confusing abstract concepts and data storage.

@JohnBode This is why you can never pass a copy of an array to a function, and you can never return an array from a function. The array doesn't exist. Only the address.

@Majenko: Except when it is the operand of the sizeof or unary & operators, or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.  When you pass an array expression as an argument to a function (such as to printf), what the function receives is a pointer.  But the array itself is not a pointer.

@Majenko - This is why the expressions arr and &arr yield the same value (the address of an array is the same as the address of the first element of the array), but why the types are different (T * vs. T (*)[N]).

@Majenko: And this is why sizeof behaves differently for expressions of array type vs. expressions of pointer type.

@JohnBode You're still talking abstract concepts overlaid by the compiler. All those things you mention are compile-time constants. Things it can reference in the source code. As soon as it's compiled all those things vanish and are reduced to mere numbers. All you ever have, even if you call a block of memory an "array" and overlay some concept over it, is an address, and maybe a size if specified in the source code and the scope is suitable. No matter what you call an array, it's still a block of memory at an address, and, as you yourself said:

"the expressions arr and &arr yield the same value (the address of an array is the same as the address of the first element of the array)" - the "array" is just an address in memory.

“As soon as it's compiled” you are right. But if you write your code in C, rather than assembly, understanding the difference between an array and a pointer – and the related concept of pointer decay – doesn't hurt.

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


text:
ESP8266 send number in IP address
I want to easily send a number from a phone to my esp8266.
I have an app that sends the number in the format IP/number.
How can I modify the code to give my the number behind the IP address as an integer?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

MDNSResponder mdns;

// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

ESP8266WebServer server(80);

String webPage = "";

void setup(void){

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  if (mdns.begin("esp8266", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }

  server.on("/", [](){
    Serial.println("device connected");
  });
  server.begin();
  Serial.println("HTTP server started");
}

void loop(void){
  server.handleClient();
}

So it would do something like this for and should be looking through every i between 0 and 200. :
server.on("/"+String(i), [](){
    Serial.println("i");
  });

First of all use the event function server.on with a path that corresponds to your function and use a url like this:
192.0.2.2/recordnumber?num=100

With a url parmeter for your number. Your code might look like this:
At the top:
int nums_size = 0;
const int nums_max = 128;
int nums[nums_max];

In setup:
server.on("/recordnumber", [](){
    int num;
    if(server.hasArg("num")) {
      String num_str = server.arg("num");
      if(num_str.charAt(0) == '0') {
        num = 0;
      } else {
        num = num_str.toInt();
        if(num == 0) {
          server.send(400, "text/plain", "not a number");
          return;
        }
      }
      if(nums_size < nums_max) {
        nums[nums_size++] = num;
        server.send(200, "text/plain", "saved");
      } else {
        server.send(500, "text/plain", "full");
      }
    } else {
      server.send(400, "text/plain", "bad params");
    }
});

First you need to extract the string that contains the number (after the /). Since it is already stored in consecutive memory you can pass the pointer to the character after the / symbol to the C function atoi to convert it to an integer.
I assume the pointer is already \0 terminated.
You can use the C function strchr to search for the / symbol.
Tip: use a C compiler on a desktop/PC to check how these functions work. Once you know how to use them, copy them in your Arduino code. This is much faster than uploading/debugging sketches probably.

My phone accesses the ESP via it's IP address for instance: 192.168.2.2/100 or 192.168.2.2/200. The ESP should than store these values 100 and 200 into integers but these numbers could be any number

I adapted the answer, use strchr to search for the / symbol, than use atoi

But in order to extract the right part of the string how do you store the whole  incoming IP address in a string?

WiFi.localIP() is already pointing to a string, you can use this as input for strchr to search for the /  symbol, than you can use atoi.


text:
Using a 12V DC adapter to power Arduino nano, 12v Solenoid and an Hygrometer
First of all I am very novice in electronics so bare with me.
I am trying to make a self watering system using arduino nano, first I tried the fly fish hygrometer module with the 5V power of the Arduino, and that worked.
Then I wanted to add the 12V solenoid, so I changed to a 12V external power through the Vin.
My goal is to use only one power source.
This is what I have done so far:

And Schematics
My question is:
Can I power the hygrometer module using for the positive the 5V outlet of the Arduino nano and the ground from the 12V power source as shown in the figures?
Or will this burn the module or screw the readings?

yes the 5v out can run the module (hygrometers use next to nothing), although 12v is a little high for the nano, might get warm. but no worries, she'll be alright mate.

Thanks @dandavis, but my question is that if you see the schematics, the + of the hygro goes to the 5v and the ground goes to the 12V is that ok?

you mean 0v? that's fine, all grounds are typically commoned (connected together so they have continuity)


text:
"Stand-alone" serial monitor
I usually use Platformio as IDE for my Arduino projects. I like it as an editor, but I don't like its serial monitor feature. So I often open the Arduino IDE in background to use its serial monitor, but this has some drawbacks (including a significant increase in my computer's CPU usage and battery consumption).
Is there an Arduino-compatible serial monitor application that just works as a serial monitor (and not also as an IDE)? I'm most interested in a MacOS application, but if you know a Windows one please tell me as well.

putty ... http://www.putty.org/ ...

I regularly use GNU screen. For example screen /dev/ttyUSB0 115200 where /dev/ttyUSB0 is the serial port of the Arduino, and 115200 is the baud rate.
What's wrong with the PlatformIO serial monitor, by the way?

you can use any serial terminal, search for them. putty is pretty good. aside: do you get constant CPU usage from the arduino program as well? (thought it was just me...)

You can use almost anything; but the catch with using something not integrated is that it may not automatically get out of the way when you try to upload code.

@tttapa thanks. Is there also some kind of gnu serial port scanner? — the biggest issue (for me) is the fact that I can’t copy the output (I don’t know if it’s an issue of PlatformIO, Atom or something on my computer... but as I select one serial monitor word all the text in the window get selected); a secondary problem is that putting data in is quite tricky (compared to the Arduino ide serial monitor)

@dandavis sorry, what do you mean by “do you get constant CPU usage from the arduino program as well?”

Note also that terminal emulators (putty, GNU screen, ...) are way more capable than the Arduino serial monitor, as they let you use ANSI escape sequences to control the cursor, set colors, etc. C.f. the bar display at the top left of this screenshot.

sometimes the IDE pegs my CPU at 25% even idle (the OS blames java), was wondering if that same nastyness was what caused the battery consumption you mentioned...

@noearchimede of course you can copy from the terminal. It just uses a different short cut. On Linux, this is CTRL+SHIFT+C instead of CTRL+C (CTRL+C sends a break), not sure what the Mac equivalent is.

@dandavis yes, that happens quite often and it probably is the most important battery consumption cause

@dandavis do you get constant CPU usage from the arduino program as well? - I found a while ago that under certain circumstances (failed upload was one I think) that the IDE went to using 100% CPU. The only reason it took a while to notice was that I have a 4-core CPU and the other CPUs kept running. I think it wasn't the IDE per se, but a process running avrdude that was looping. After 4 failed uploads my PC got a bit sluggish. :)

@NickGammon: yup, that's it. if i have several sketches open, sometimes I can close 1+ of them (not all) and the 100% usage goes away.

I use CoolTerm, which is available for Mac, Windows and Linux. It is a great serial app, and you can have several windows open at the same, for each serial pipe you may be using (Bluetooth, Arduino Serial, etc).

Consider building your own monitor in Python. This gives you flexibility since Python is cross platform and you can tailor the monitor to your needs.

Install Python.
Install pySerial (pip install pyserial).
Write a Python script to read and/or write to the Arduino across the serial port. There are some great examples out there such as this example and other Stack Overflow answers.

On macOS, you can use the built-in screen command, e.g.:
screen /dev/cu.usbmodem14201 9600

To exit, control-A followed by control-\

There's a list of serial port sniffers here, if you want to view raw data
 softwarerecs.stackexchange serial-port-logging
And a list here of programs which plot graphs from serial data:
softwarerecs.stackexchange serial-data-plotting-programs

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


text:
Unable to read data with 16 serial clock cycles
I am trying to read data from an AD7314 Temperature Sensor that is connected to an Arduino Uno and output that value onto 6 LEDs also connected to the Arduino Uno board. From the image below, the sensor is showing only an output of 0011111111111111 during the streams of 16 clock cycles even after the chip enable goes from low to high before conversion to initiate a new one (it seems that the conversion is stuck). The datasheet says:

A leading zero and 10 bits of data are transferred during a read operation. Read operations occur during streams of 16 clock pulses. Output data is updated on the rising edge of SCLK. The serial data is accessed in a number of bytes if 10 bits of data are being read. At the end of the read operation, the SDO line remains in the state of the last bit of data clocked out of the AD7314 until CE returns low

I am not sure where exactly I am going wrong during the read operation:
Note: for the Waveform image (Top to bottom):

waveform 1: Chip Enable
waveform 2: Serial Clock
waveform 3: MISO Line
waveform 4: MOSI Line

My code is below:
#include <SPI.h>

const int MOSI_PIN = 11;
const int MISO_PIN = 12;
const int SCK_PIN = 13;
const int Slave_PIN = A0;

// module data
uint16_t myValFromTempSensor = 0;

void setup () {
  SPI.begin ();
  SPI.beginTransaction(SPISettings(125000, MSBFIRST, SPI_MODE0));
  pinMode(5, OUTPUT); //LED 3
  pinMode(6, OUTPUT); //LED 4
  pinMode(7, OUTPUT); //LED 5
  pinMode(8, OUTPUT); //LED 6
  pinMode(9, OUTPUT); //LED 7
  pinMode(10, OUTPUT);//LED 8
  pinMode(MOSI_PIN, OUTPUT); // MOSI to SDI
  pinMode(MISO_PIN, INPUT); //MISO to SDO
  pinMode(SCK_PIN, OUTPUT); //CLOCK PIN to SCK
  pinMode(Slave_PIN,OUTPUT); //Slave pin

  digitalWrite(Slave_PIN, LOW);//Set slave low before communication
  for (int i = 5; i < 11; i++) {
    digitalWrite(i, LOW);
  }
  delay(100);
} // end of setup

void loop () {
  digitalWrite(Slave_PIN, HIGH);  //Set slave high to read data
  myValFromTempSensor = SPI.transfer(0x00); // Read Data from the device
  myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;// Bitshift to read next 8 bits
  digitalWrite(Slave_PIN, LOW);
  if(( myValFromTempSensor>=0) && ( myValFromTempSensor<=196)) {
    //Range 0C to 60C is  0 to 196
    digitalWrite(5, bitRead(myValFromTempSensor,0));
    digitalWrite(6, bitRead(myValFromTempSensor,1));
    digitalWrite(7, bitRead(myValFromTempSensor,2));
    digitalWrite(8, bitRead( myValFromTempSensor,3));
    digitalWrite(9, bitRead( myValFromTempSensor,4));
    digitalWrite(10, bitRead( myValFromTempSensor,5));
  } else {
    digitalWrite(5, 0);
    digitalWrite(6, 0);
    digitalWrite(7, 0);
    digitalWrite(8, 0);
    digitalWrite(9, 0);
    digitalWrite(10, 0);
  }
}

from the waveforms, it looks to me like the sensor is outputting 0b0011111111111111 = 0x3fff.

The first 0 is a leading zero according to the datasheet which does not add to the sensor reading

I know, I did read the datasheet. I am just saying that I disagree with your statement: “the sensor is showing only an output of 01000000000”.

I apologize, i corrected it.

I see several issues here.
Sensor output
According to the waveforms shown by your logical analyzer, the sensor is
outputting 0b0011111111111111. We have to discard the first (a padding
zero) and the last five bits (copies of DB0). We then end up with the
actual data bits being 0111111111. This has to be interpreted as a
signed fixed-point number in s.7.2 format, which gives 127.75 °C:
the maximum possible value the sensor can output, and well above its
maximum operating temperature.
I cannot tell what is going wrong here. It looks like the sensor is
either burning alive, or trying to tell you it's extremely unhappy.
SPI mode
You wrote:

SPISettings(125000, MSBFIRST, SPI_MODE0)

SPI mode 0 seems to be pretty common. In this mode, the data lines are
updated on the falling edge of the clock, and they are read on the
rising edge. However, according to your sensor's datasheet, it appears
this sensor works the other way around: it uses SPI mode 1. Your
setting should reflect this.
Decoding the data
You wrote:

myValFromTempSensor = SPI.transfer(0x00);
myValFromTempSensor |= (uint8_t)SPI.transfer(0x00) << 8;

Here you are assuming the least significant byte is transmitted first.
This is not the case: you get a stream of 16 bits with the most
significant first. Thus, in terms of bytes, it's also MSB first.
Then, 6 of these 16 bits have to be discarded in order to get the actual
10 data bits. Since the Arduino has no 10-bit data type, and the
number is signed, it has to be sign-extended to 16-bits. All this can be
done in C/C++ by:

left-shifting one bit to the left (discarding the zero padding bit)
casting to a signed 16-bit integer
right-shifting (which gcc implements using sign
extension) six bits to the right

Or, in code:
digitalWrite(Slave_PIN, HIGH);
uint16_t raw_data = SPI.transfer16(0);
digitalWrite(Slave_PIN, LOW);
int temperature_reading = (int16_t)(raw_data << 1) >> 6;

Edit: Here are more details about the data representation, and about
the conversion to 16-bits done by the expression
(int16_t)(raw_data << 1) >> 6.
According to the datasheet, the sensor gives the temperature as a 10-bit
signed number in two's complement notation. If you fail to acknowledge
the fact that the result is signed, and you interpret the 10 bits
as an unsigned number, then a temperature of −1 °C will be
interpreted as +255 °C, which is obviously very wrong.
Since it's a signed number, increasing the bit width of the temperature
to 16 bits has to be done using sign extension, i.e. the
missing bit positions have to be filled with copies of the leftmost bit
(the “sign bit”).
The datasheet also shows that the sensor sends a stream of 16-bits as
follows:
0 db9 db8 db7 db6 db5 db4 db3 db2 db1 db0 db0 db0 db0 db0 db0

where the first bit is a padding zero, then come the ten data bits
db9 – db0, and then five extra copies of the last data bit.
These extra copies can  be seen in figure 3 (serial interface
digram), and can also be inferred from the sentence “the SDO line
remains in the state of the last bit of data clocked out of the AD7314”.
The line
uint16_t raw_data = SPI.transfer16(0);

puts this bit pattern into the variable raw_data, which is a 16-bit
unsigned integer. Then, the operation raw_data << 1 shifts this
pattern one bit position to the left, discarding the leftmost zero and
padding with another zero on the right, which gives:
db9 db8 db7 db6 db5 db4 db3 db2 db1 db0 db0 db0 db0 db0 db0 0

This is then cast to a signed number, which doesn't change the bit
pattern, but only the interpretation of the leftmost bit, which is now a
sign bit. Then, the number is shifted by 6 bit positions to the
right. Since this is an arithmetic shift, which does sign extension,
the leftmost bit (the “sign bit”) is replicated during the shift, which
yields:
db9 db9 db9 db9 db9 db9 db9 db8 db7 db6 db5 db4 db3 db2 db1 db0

And this is the expected result: the same numeric value that was
originally stored in the “temperature value register” of the sensor,
only represented as a 16-bit number.

I am not sure where you are getting 16 bits from rather than 11 bits (including leading zero) if i understood correctly. The datasheet mentions 11 bits being transferred during streams of 16 clock cycles.

@user7187418: At the hardware level, the SPI port can only handle multiples of 8 bits, and it reads an input bit on every clock cycle. At the library level, the transfer16() method sends 16 clocks pulses and returns an unsigned 16-bit number.

So at the line of code : int temperature_reading = (int16_t)(raw_data << 1) >> 6;  Does this mean i receive the 10 bit signed data, if so , i have 2 questions: 1) If i understood correctly, the transfer16() returns an unsigned 16 bit number does this mean that the 10 bit temperature data in the code mentioned above is an unsigned 10 bit reading ? (i need to read between 0 C and 60 C )  2) Should i output the temperature data on to the 6 leds by reading the only the first 6 bits by using the bitRead() function as i am currently doing or is there another way that i am currently unaware of ?

You seem confused bout binary number representations. See my extended answer. 2) Only you can know how you want to display the temperature to the end user. I would output through the serial port, at least during the debugging stage.

This is not an answer to your question but I cannot add it as a remark since it involves code.
You can greatly reduce your code by using for loops, e.g.:
   pinMode(5, OUTPUT); //LED 3
   pinMode(6, OUTPUT); //LED 4
   pinMode(7, OUTPUT); //LED 5
   pinMode(8, OUTPUT); //LED 6
   pinMode(9, OUTPUT); //LED 7
   pinMode(10, OUTPUT);//LED 8

to
   int n;
   for (n = 5; n < 11; n++)
   {
      pinMode(n, OUTPUT);
   }

And
digitalWrite(5,bitRead( myValFromTempSensor,0));
digitalWrite(6,bitRead( myValFromTempSensor,1));
digitalWrite(7,bitRead( myValFromTempSensor,2));
digitalWrite(8,bitRead( myValFromTempSensor,3));
digitalWrite(9,bitRead( myValFromTempSensor,4));
digitalWrite(10,bitRead( myValFromTempSensor,5));

to
int n = 0;
for (n = 0; n < 6; n++)
{
    digitalWrite(n + 5,bitRead( myValFromTempSensor, n));
}

And
  digitalWrite(5,0);
  digitalWrite(6,0);
  digitalWrite(7,0);
  digitalWrite(8,0);
  digitalWrite(9,0);
  digitalWrite(10,0);

to
int n;
for (n = 5; n < 11; n++)
{
    digitalWrite(n, 0);
}

Instead of hardcoded values 5 and 11 you can use defines, e.g.
#define LED_MIN 5
#define LED_MAX 11

and change
for (n = 5; n < 11; n++)

to
for (n = LED_MIN; n < LED_MAX; n++)

If anyone stumbled on this thread later like I did, it may be helpful to understand that the binary response is a decimal number, specifically with 0.25c resolution. Meaning that the integer value that Edgar Bonet's (excellent) response will give you needs to be multiplied by 0.25 to get the actual temperature in Celsius.
I suggest multiplying by 0.25 because it will give the same result as dividing by 4 but without the risk of a divide by zero error. Also division is extremely slow on Arduino since the underlying instruction set does not have a divide instruction.
I  hope this helpful to someone at some point; if not sorry for the annoyance.

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


text:
Unable to upload the data on thingspeak using uno and esp8266
I am able to connect to thingspeak but now able to upload the data. here are my set of commands:
AT+CIPMUX=0
OK

AT+CIPSTART="TCP","184.106.153.149", 80
OK
Linked

AT+CIPSTATUS
STATUS:3
+CIPSTATUS:0,"TCP","184.106.153.149",80,0
OK

AT+CIPSEND=45
> GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60

busy s...

SEND OK

OK

and after some time unlink
I am giving these commands using arudino serial monitor.
Please help, I have searched a many blogs, youtube videos.

I got it working. Yo!
#include <SoftwareSerial.h>
#include <stdlib.h>

// LED
int ledPin = 13;
// LM35 analog input
int lm35Pin = 0;
float my_value = 22;
// replace with your channel's thingspeak API key
String apiKey = "9PJEF1EP8ZMVY5JA";

// connect 10 to TX of Serial USB
// connect 11 to RX of serial USB
SoftwareSerial ser(10, 11); // RX, TX

// this runs once
void setup() {
  // initialize the digital pin as an output.
  pinMode(ledPin, OUTPUT);

  // enable debug serial
  Serial.begin(9600);
  // enable software serial
  ser.begin(9600);

  // reset ESP8266
  ser.println("AT+RST");
}

// the loop
void loop() {

  // blink LED on board
  digitalWrite(ledPin, HIGH);
  delay(200);
  digitalWrite(ledPin, LOW);

  // read the value from LM35.
  // read 10 values for averaging.

  // convert to temp:
  // temp value is in 0-1023 range
  // LM35 outputs 10mV/degree C. ie, 1 Volt => 100 degrees C
  // So Temp = (avg_val/1023)*5 Volts * 100 degrees/Volt
  my_value++;
  float temp = my_value;

  // convert to string
  char buf[16];
  String strTemp = dtostrf(temp, 4, 1, buf);

  Serial.println(strTemp);

  // TCP connection
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "184.106.153.149"; // api.thingspeak.com
  cmd += "\",80";
  ser.println(cmd);

  if(ser.find("Error")){
    Serial.println("AT+CIPSTART error");
    return;
  }

  // prepare GET string
  String getStr = "GET /update?api_key=";
  getStr += apiKey;
  getStr +="&field1=";
  getStr += String(strTemp);
  getStr +="&field2=";
  getStr += String(strTemp);
  getStr += "\r\n\r\n";

  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  ser.println(cmd);
  Serial.println(cmd);

  if(ser.find(">")){
    ser.print(getStr);
    Serial.println(getStr);
  }
  else{
    ser.println("AT+CIPCLOSE");
    // alert user
    Serial.println("AT+CIPCLOSE");
  }

  // thingspeak needs 15 sec delay between updates
  ser.println("AT+RST");
  delay(30000);
}

You have a malformed HTTP request. You only have half of the first line.
A valid HTTP request would look more like this:
GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60 HTTP/1.1
Host: api.thingspeak.com
Content-length: 0
Connection: close
<blank line>

Just sending "GET : ain't gonna work. For a start, the server won't know what protocol you're speaking (HTTP/1.1), nor what website it's supposed to direct the request to (Host: api.thingspeak.com). Also, the final extra blank line is required to finish the request.

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


text:
Arduino Uno "if" statement is ignored in code and halts execution when using Serial.ReadString()
I'm having a weird issue with my Uno trying to power on a PWM fan using a MOSFET.
I'm setting a simple power on/off code using commands sent over the Serial Monitor, and although this code worked before, after I tried to add some code to control the speed of the PWM fan, my if statements do not work anymore, even with the simple power on/off code:
    String command;           //Define the string variable "command"

void setup() {
  // put your setup code here, to run once:

  pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
  pinMode(13, OUTPUT);    //Set pin 13 to use onboard LED as a waiting for command status LED
  digitalWrite(5, LOW);   //Start with MOSFET off
  digitalWrite(13, LOW);  //Star with status LED off
  Serial.begin(9600);     //Start Serial comm for sending commands

}

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

  Serial.println("What's your command?"); //Ask for a command in the Serial Monitor

  while (Serial.available()==0) {        //Wait for user input stopping the code
    digitalWrite(13, HIGH);               //Blink the onboard LED indicating that the code is waiting for user input
    delay(100);
    digitalWrite(13, LOW);
    delay(100);
  }

  command=Serial.readString();          //Save the Serial Monitor String command to the "command" variable as a String
  Serial.println("data read");          //Confirm Serial Monitor input
  Serial.println(command);              //Print the command sent over the Serial Monitor to confirm the data received

  if (command=="On") {                  //Turn the MOSFET on
    digitalWrite(5, HIGH);
  } else if (command=="Off") {                  //Turn the MOSFET off
    digitalWrite(5, LOW);
  }
  else {                                 //Provide feedback for a wrong command
    Serial.println("Wrong command!");
  }
}

This is my Serial Monitor output after sending "On":
What's your command?
data read
On

Wrong command!
What's your command?

To check if the pin works, I tested a simple code that worked fine:
void setup() {
  // put your setup code here, to run once:

  pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
  digitalWrite(5, LOW);   //Start with MOSFET off
  Serial.begin(9600);     //Start Serial comm for sending commands

}

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

    digitalWrite(5, HIGH);
    delay(2000);
    digitalWrite(5, LOW);
    delay(2000);

}

Does anyone have any idea why the if statements are not working anymore?
Thank you in advance!
AC
EDIT: After trying to use the "else" statement as recommended by per1234, the issue continues to happen, but changing the variable type to an integer works, although the Serial output is rather messy:
int command;           //Define the int variable "command"

void setup() {
  // put your setup code here, to run once:

  pinMode(5, OUTPUT);     //Set pin 5 as MOSFET Gate signal pin
  pinMode(13, OUTPUT);    //Set pin 13 to use onboard LED as a waiting for command status LED
  digitalWrite(5, LOW);   //Start with MOSFET off
  digitalWrite(13, LOW);  //Star with status LED off
  Serial.begin(9600);     //Start Serial comm for sending commands

}

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

  Serial.println("What's your command?"); //Ask for a command in the Serial Monitor

  while (Serial.available()==0) {        //Wait for user input stopping the code
    digitalWrite(13, HIGH);               //Blink the onboard LED indicating that the code is waiting for user input
    delay(100);
    digitalWrite(13, LOW);
    delay(100);
  }

  command=Serial.parseInt();          //Save the Serial Monitor imput command to the "command" variable as an int

  Serial.println("data read");          //Confirm Serial Monitor input
  Serial.println(command);              //Print the command sent over the Serial Monitor to confirm the data received

  if (command==1) {                  //Turn the MOSFET on
    digitalWrite(5, HIGH);
  }
  if (command==2) {                  //Turn the MOSFET off
    digitalWrite(5, LOW);
  }
  else {                                 //Provide feedback for a wrong command
    Serial.println("Wrong command!");
  }
}

And the Serial Monitor output:
What's your command?
data read
1
What's your command?
data read
0
Wrong command!
What's your command?
data read
2
What's your command?
data read
0
Wrong command!
What's your command?

Does anyone experience this issue? I even tried rolling back my IDE to 1.8.3, which I used to write the code the first time, then after a library update, and also getting version 1.8.5, it stopped working.
Also, anyone knows how to avoid the multiple Serial Monitor outputs?
I tested this with "String" variables to be able to get this fixed.
Also, a side question regarding the post size, should I remove the original code when editing, or should I move it to another answer?
Thank you.

The problem with the original code is evidenced in the following:
What's your command?
data read
On

Wrong command!

See that blank line?  Nowhere in your sketch do you specifically print a blank line, rather it is being printed because the command string contains a carriage return and/or newline character captured with the input, which is causing a comparison of exact equality to fail.
To fix this, you could either trim these non-printing characters off the end, or use a different comparison, for example command.startsWith("On").  But if you do use a start-of-string comparison, beware if you have any command verbs that extend other shorter ones.
You also have a bug in your block if-else statements, in that instead of
if ...
if ...
else ...

you should have
if ...
else if ...
else ....

So that the "none of the above" clause only runs when none of the conditions are satisfied, rather than running whenever the penultimate condition is not satisfied.
In terms of the numeric version producing an un-entered value of 0, this is the documented return value of the parseInt() methods if they time out without finding a valid integer.
It would be more traditional to use an end-of-line condition rather than a timeout to detect the end of user input.  Many traditional "until end of line" read mechanisms trim the line ending characters off the resulting string for you, eliminate the comparison problem, too.

Thank you Chris, the if-else statements have changed on my second revision of the code, since the serial output doesn't have the blank line anymore. Do you think deleting everything from my Arduino folder under the Windows user folder would help? The newline or carriage return can be causing the 0 character to show up automatically on the serial output on my integer code.

No, don't wipe your install, rather see the documentation for parseInt and what it says it does if input times out with no number entered.

Let's look at what this code does when you send "On":
  if (command=="On") {                  //Turn the MOSFET on
    digitalWrite(5, HIGH);
  }

This will evaluate true so pin 5 is set to HIGH.
  if (command=="Off") {                  //Turn the MOSFET off
    digitalWrite(5, LOW);
  }

This will evaluate false so the else clause is executed:
  else {                                 //Provide feedback for a wrong command
    Serial.println("Wrong command!");
  }

So the output you are seeing is correct for your code. The problem is that your code doesn't match your intent. For that you need to change this line:
  if (command=="Off") {                  //Turn the MOSFET off

to:
  else if (command=="Off") {                  //Turn the MOSFET off

Then the else clause will only run if the command doesn't match "On" or "Off".
For more information see:
https://www.arduino.cc/reference/en/language/structure/control-structure/else/

Thank you per1234. I'll test this and provide feedback later in the day.

Hi per1234. Unfortunately, this did not fix my issue, but changing the variable type did. Can you please check the code in my edit?

Thank you for your help.
I have been able to find the root cause of my original problem.
After reading this post on https://forum.arduino.cc/index.php?topic=73372.0, more specifically an answer regarding filtering for \n and \r characters and the Arduino IDE Serial Monitor line ending option.
My problem was caused by having the "Newline" option selected in the Serial Monitor. After selecting "No line ending", my original code runs as expected, and I know now how to use String variable and Serial.readString() in a more efficient way, and the if-else statements.
Also, the blank line mentioned by Chris Stratton is gone, and my search to fix that led me to the solution of the main problem, and the code also works 100% with the formatting help provided by per1234.
Thank you both again for the help.

You probably do not want to disable the line ending transmission; rather you likely want to read until a line ending (and then exclude it) rather than until a timeout.  The Arduino serial monitor is a bit odd as a client in encouraging you to tap an on-screen button to send, more typically it's pressing return than triggers transmission, or else if characters are sent as typed, makes the recipient act on them.

Thank you for that info Chris. I will look into that. For now, I'm going to use the serial monitor to simulate the input and effects on my code, since my final goal is to setup the Arduino to read external analog signals, but since I'm quite new to this type of programming, I'm trying to understand what I can or can't do. I've been using Arduino for some years, but mostly with pre-assembled sensor boards and copy pasting code.


text:
Is there a way to put multiple integers in a method?
I'm working on a project that has 3 RGB LEDs. I want to make a simple method that I can call to control the LEDs for example:
showColor(left, 255, 0, 50);

Which would light up the left LED at 100% red, 0% green, and 20% blue. The code I have running for the method is:
 void showColor(int ledPosition, int redIntensity, int blueIntensity, int greenIntensity)
    {
      if (ledPosition == left)
      {
        analogWrite (redPin1, redIntesity);
        analogWrite (greenPin1, greenIntesity);
        analogWrite (bluePin1, blueIntesity);
      }
      else if (ledPosition == middle)
      {
        analogWrite (redPin2, redIntesity);
        analogWrite (greenPin2, greenIntesity);
        analogWrite (bluePin2, blueIntesity);
      }
      else if (ledPosition == right)
      {
        analogWrite (redPin3, redIntesity);
        analogWrite (greenPin3, greenIntesity);
        analogWrite (bluePin3, blueIntesity);
      }
      else if (ledPosition == all)
      {
        for (int index=0, index < 3 ; index++)
        {
          analogWrite (redPins[index], redIntensity);
          analogWrite (greenPins[index], greenIntensity);
          analogWrite (bluePins[index], blueIntensity);
        }
      }
    }

I'm getting tons of errors, like that all of the Intensity variables are not declared and that left, right, all, and middle are not declared. I don't know if this is possible, or what I'm doing wrong. I think I've seen something like this before somewhere else, and I don't want to just use 1 variable to control everything. An answer would be greatly appreciated!

The answer is yes. Beyond that it will be impossible for us to help you with your problem unless you provide a minimal, complete, and verifiable example and the full error messages.

the compiler is telling you to declare variables, so instead of declaring those variables, you post a question here?  ... why?

it is a function, not a method. Classes have methods.

Check your spelling Intensity instead of Intesity.
Consider using switch instead of if-then-else.
Define left, right and middle as [integer] constants somewhere (and probably something more descriptive like rightLED, leftLED and middleLED) because your code is looking for an int, instead you give it something undefined like left, right and middle (and all). I would consider using bitwise operators for identifying the LEDS, instead of a simple integer flag as this gives future flexibility in lighting up combinations without changing your code (the current function would be rewritten to accommodate this).

There are two errors in your code:

The word “Intensity” should always be spelled like this, rather than
“Intesity” (missing “n”)
In for (int index=0; index < 3; index++), the separators should be
semicolons, not commas.

Other than that, and provided proper declarations, your function
compiles just fine.

This answer is slightly off track, but after reading the title my first though was this.
You can have a function that takes multiple integer parameters and there is nothing wrong with that, but there comes a point in your code where you should be looking at better data management.  In this case you have three intensity values that are always going to be related so you could look at a class or struct to hold the data as a single object.
struct Colour
{
    int Red;
    int Green;
    int Blue;
    Colour (const int& r = 0, const int& g = 0, const int& b = 0)
        : Red(r)
        , Green(g)
        , Blue(b)
    {}
}

This would allow you to define an object (called LEDLeft) that held the value for that LED, i.e.
Colour LEDLeft(0xFF, 0xFF, 0x00);    // Define a yellow left LED.

Extending this further you could define a second structure that defined the pins to control the LED, and a third that paired the current colour with the LED.
struct LED
{
    LEDPinout Pins;
    Colour    Colour;
   // Constructor ...
}

Its about this point that using a class rather than a struct would be a better (more conventional*) idea.  i.e.
// THIS IS NOT COMPLETE CODE - IT HAS NOT BEEN TESTED.
class LED
{
    LED (const int& pinRed, const int& pinGreen, const int& pinBlue);
    LED (const LED& other);  // Copy constructor

    void SetColour(const Colour& colour);
    Colour GetColour(void)const;
}

static const Colour RED(0xFF, 0x00, 0x00);
static const Colour BLUE(0x00, 0x00, 0xFF);
enum Positions {Left = 0, Middle, Right, All};
LED TheLeds[] = {LED(2, 3, 4), LED(5, 6, 7), LED(8, 9, 10)};
TheLeds[Left].SetColour (RED);
TheLeds[Right].SetColour (RED);
TheLeds[Middle].SetColour (RED);
delay(1000);
for (int loop = 0; loop < All; ++loop)
    TheLeds[loop].SetColour(BLUE);
delay(1000);


text:
detachInterrupt(0) in arduino not working ? after giving continuous ground to INT0 wakeupnow function should execute once not again and again
#include <avr/sleep.h>

int wakePin = 2;                 // pin used for waking up
int led=13;
int flag=0;

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

void setup()
{
  Serial.begin(9600);
  pinMode(wakePin, INPUT_PULLUP);  // wakePin is pin no. 2
  pinMode(led, OUTPUT);          //   led is pin no. 13
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow()
{
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();                        // enables the sleep bit in the mcucr register
                      delay(500);
                      Serial.println("Rajat");
                      delay(500);
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                      delay(500);
                      Serial.println("Rajat");
                      delay(500);
    sleep_mode();     // here the device is actually put to sleep...!!
      // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                      delay(500);
                      Serial.println("Rajat2");
                      delay(500);
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
    sleep_disable();         // first thing after waking from sleep: disable sleep...
                      delay(500);
                      Serial.println("Rajat3");
                      delay(500);
       detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.

}

void loop()
{
      digitalWrite(led, HIGH);
      delay(1000);
      digitalWrite(led, LOW);
      delay(1000);
    /* delay(500);
      Serial.println("jam");
      delay(500);  */
      if (flag==0)
      {
      sleepNow();     // sleep function called here
      flag=1;
      }
}

After Last Rajat I give ground to INT0.
Output in serial monitor :
Rajat
Rajat
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
1
0
9
8
7
6
5
4
3
2
& so on..!

function should execute once ... are you sure?

after 2 nd rajat is printed, I give ground continously to INT0.
now seeing stepwise..! 1) wakeupnow function will be executed than 2) We detach the interrupt to stop it from continuously firing while the interrupt pin is low using detachinterrupt(0) so now after getting ground wakeupnow should not be exexuted as interrupt is detached from pin 2 even though pin 2 is getting ground

this is not the first thing, is it? sleep_disable();         // first thing after waking from sleep: disable sleep...

Yeah sorry forgot to edit comments, It is written wrong over there..! after getting interrupt 1st thing is wakeupnow  function starts to execute..! but what's wrong in my previous comment..!

but what's wrong in my previous comment ... everything ... you are making an incorrect assumption  about INT0 .... read the documentation ... also look at my first comment ... it is a big red flag

Thanks..! for pointing out mistake will come back after reading document and analysing it again..!

Also; using delay and serial.print inside the interrupt service routine is asking for trouble, as both of them also require interrupts themselves. I'm surprised it even did show you that output.

You're detaching in completely the wrong place. After sleep_mode() returns from sleep and before the interrupt is detached you have an entire second of time where your interrupt can still fire. And it will fire, since a LOW interrupt will keep firing while the input is LOW.
sleep_mode();     // here the device is actually put to sleep...!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
                  delay(500);
                  Serial.println("Rajat2");
                  delay(500);
detachInterrupt(0);

Instead you should detach the interrupt within the interrupt routine itself:
void wakeUpNow()
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up

    detachInterrupt(0);

  int count=10;
  while(count!=0)
  {
    delay(1000);
    count--;
    Serial.println(count);
    delay(1000);
  }
}

Also, all those delays and Serial prints in an interrupt are seriously problematic. An interrupt should never delay() and should never Serial.println().

I agree with Majenko. Since interrupts are off inside an ISR, delays won't work. Thus your code will hang indefinitely. Don't do delays inside an ISR. (Nor serial prints).


text:
How to generate hardware interrupt in mpu6050 to wakeup arduino from SLEEP_MODE_PWR_DOWN mode?
I am using Arduino UNO and has kept in SLEEP_MODE_PWR_DOWN mode & want it to wakeup using MPU6050 hardware INT pin (which should send a signal when MPU is in motion). I have used the article https://lukelectro.wordpress.com/2016/08/11/how-to-enable-motion-detection-interrupt-on-mpu6050/
    #include <Wire.h>
    //Analog port 4 (A4) = SDA (serial data)
    //Analog port 5 (A5) = SCL (serial clock)
    #define SIGNAL_PATH_RESET  0x68
    #define I2C_SLV0_ADDR      0x37
    #define ACCEL_CONFIG       0x1C
    #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
    #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
    #define MOT_DETECT_CTRL    0x69
    #define INT_ENABLE         0x38
    #define WHO_AM_I_MPU6050   0x75 // Should return 0x68
    #define INT_STATUS 0x3A
    //when nothing connected to AD0 than address is 0x68
    #define ADO 0
    #if ADO
    #define MPU6050_ADDRESS 0x69  // Device address when ADO = 1
    #else
    #define MPU6050_ADDRESS 0x68  // Device address when ADO = 0
    #endif

    /*    Example for using write byte
          Configure the accelerometer for self-test
          writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0xF0); // Enable self test on all three axes and set accelerometer range to +/- 8 g */
    void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
    {
      Wire.begin();
      Wire.beginTransmission(address);  // Initialize the Tx buffer
      Wire.write(subAddress);           // Put slave register address in Tx buffer
      Wire.write(data);                 // Put data in Tx buffer
      Wire.endTransmission();           // Send the Tx buffer
    //  Serial.println("mnnj");

    }

    //example showing using readbytev   ----    readByte(MPU6050_ADDRESS, GYRO_CONFIG);
    uint8

_t readByte(uint8_t address, uint8_t subAddress)
{
  uint8_t data;                            // `data` will store the register data
  Wire.beginTransmission(address);         // Initialize the Tx buffer
  Wire.write(subAddress);                  // Put slave register address in Tx buffer
  Wire.endTransmission(false);             // Send the Tx buffer, but send a restart to keep connection alive
  Wire.requestFrom(address, (uint8_t) 1);  // Read one byte from slave register address
  data = Wire.read();                      // Fill Rx buffer with result
  return data;                             // Return data read from slave register
}

void setup()
{
   /*
    * #define SIGNAL_PATH_RESET  0x68
      #define I2C_SLV0_ADDR      0x37
      #define ACCEL_CONFIG       0x1C
      #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
      #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
      #define MOT_DETECT_CTRL    0x69
      #define INT_ENABLE         0x38
      #define WHO_AM_I_MPU6050 0x75 // Should return 0x68
      #define INT_STATUS 0x3A*/
    Serial.begin(9600);
    writeByte( MPU6050_ADDRESS, SIGNAL_PATH_RESET, 0x07);//Reset all internal signal paths in the MPU-6050 by writing 0x07 to register 0x68;
    writeByte( MPU6050_ADDRESS, I2C_SLV0_ADDR, 0x20);//write register 0x37 to select how to use the interrupt pin. For an active high, push-pull signal that stays until register (decimal) 58 is read, write 0x20.
    writeByte( MPU6050_ADDRESS, ACCEL_CONFIG, 0x01);//Write register 28 (==0x1C) to set the Digital High Pass Filter, bits 3:0. For example set it to 0x01 for 5Hz. (These 3 bits are grey in the data sheet, but they are used! Leaving them 0 means the filter always outputs 0.)
    writeByte( MPU6050_ADDRESS, MOT_THR, 0x14);  //Write the desired Motion threshold to register 0x1F (For example, write decimal 20).
    writeByte( MPU6050_ADDRESS, MOT_DUR, 0x01 );  //Set motion detect duration to 1  ms; LSB is 1 ms @ 1 kHz rate
    writeByte( MPU6050_ADDRESS, MOT_DETECT_CTRL, 0x15); //to register 0x69, write the motion detection decrement and a few other settings (for example write 0x15 to set both free-fall and motion decrements to 1 and accelerometer start-up delay to 5ms total by adding 1ms. )
    writeByte( MPU6050_ADDRESS, INT_ENABLE, 0x40 ); //write register 0x38, bit 6 (0x40), to enable motion detection interrupt.     */

    pinMode(13, OUTPUT);      // sets the digital LED pin 13 as output
    pinMode(7, INPUT);        // sets the digital pin 7 as input

}
    uint16_t readdata;
void loop()
{
      Serial.println("scdf");

      if(digitalRead(7)==1)
      {
        while(1)
        {
          digitalWrite(13, 1);
          delay(100);
        }
      }

  //    readdata = readByte(MPU6050_ADDRESS,WHO_AM_I_MPU6050);
  //    Serial.println(readdata);
}

Are you using a library to configure the MPU6050 or interfacing with it manually with the Wire library?

Hi @Majenko..! I had edited the question and add the code..! in this I am simply using the wire library but in this mpu's INT pin is not generating trigger on motion which it should according to the article.

Well, this code worked. In this code, MPU's INT PIN is Active Low so generates Ground on motion which is than connected to INT0 or arduino UNO pin 2 which generates interrupt and wakes UP the MCU
#include <avr/sleep.h>

#include <Wire.h>
 //Analog port 4 (A4) = SDA (serial data)
//Analog port 5 (A5) = SCL (serial clock)
#define SIGNAL_PATH_RESET 0x68
#define I2C_SLV0_ADDR 0x37
#define ACCEL_CONFIG 0x1C
#define MOT_THR 0x1F // Motion detection threshold bits [7:0]
#define MOT_DUR 0x20 // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
#define MOT_DETECT_CTRL 0x69
#define INT_ENABLE 0x38
#define WHO_AM_I_MPU6050 0x75 // Should return 0x68
#define INT_STATUS 0x3A
//when nothing connected to AD0 than address is 0x68
#define ADO 0
#if ADO
#define MPU6050_ADDRESS 0x69 // Device address when ADO = 1
#else
#define MPU6050_ADDRESS 0x68 // Device address when ADO = 0
#endif

int wakePin = 2; // pin used for waking up
int led = 13;
int flag = 0;

void wakeUpNow() { // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP    (i.e. after getting interrupt)
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up

  delay(500);
  Serial.println("WOKEN UP !!!!!!!!!!");
  delay(500);
  int count = 10;
  while (count != 0) {
    delay(1000);
    count--;
    Serial.println(count);
    delay(1000);
  }
  // precautionary while we do other stuff
  detachInterrupt(0);

}

/*    Example for using write byte
      Configure the accelerometer for self-test
      writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0xF0); // Enable self test on all three axes and set accelerometer range to +/- 8 g */
void writeByte(uint8_t address, uint8_t subAddress, uint8_t data) {
  Wire.begin();
  Wire.beginTransmission(address); // Initialize the Tx buffer
  Wire.write(subAddress); // Put slave register address in Tx buffer
  Wire.write(data); // Put data in Tx buffer
  Wire.endTransmission(); // Send the Tx buffer
  //  Serial.println("mnnj");

}

//example showing using readbytev   ----    readByte(MPU6050_ADDRESS, GYRO_CONFIG);
uint8_t readByte(uint8_t address, uint8_t subAddress) {
  uint8_t data; // `data` will store the register data
  Wire.beginTransmission(address); // Initialize the Tx buffer
  Wire.write(subAddress); // Put slave register address in Tx buffer
  Wire.endTransmission(false); // Send the Tx buffer, but send a restart to keep connection alive
  Wire.requestFrom(address, (uint8_t) 1); // Read one byte from slave register address
  data = Wire.read(); // Fill Rx buffer with result
  return data; // Return data read from slave register
}

void setup() {

  /*
   * #define SIGNAL_PATH_RESET  0x68
     #define I2C_SLV0_ADDR      0x37
     #define ACCEL_CONFIG       0x1C
     #define MOT_THR            0x1F  // Motion detection threshold bits [7:0]
     #define MOT_DUR            0x20  // Duration counter threshold for motion interrupt generation, 1 kHz rate, LSB = 1 ms
     #define MOT_DETECT_CTRL    0x69
     #define INT_ENABLE         0x38
     #define WHO_AM_I_MPU6050 0x75 // Should return 0x68
     #define INT_STATUS 0x3A*/
  Serial.begin(9600);
  writeByte(MPU6050_ADDRESS, 0x6B, 0x00);
  writeByte(MPU6050_ADDRESS, SIGNAL_PATH_RESET, 0x07); //Reset all internal signal paths in the MPU-6050 by writing 0x07 to register 0x68;
  writeByte(MPU6050_ADDRESS, I2C_SLV0_ADDR, 0x20); //write register 0x37 to select how to use the interrupt pin. For an active high, push-pull signal that stays until register (decimal) 58 is read, write 0x20.
  writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0x01); //Write register 28 (==0x1C) to set the Digital High Pass Filter, bits 3:0. For example set it to 0x01 for 5Hz. (These 3 bits are grey in the data sheet, but they are used! Leaving them 0 means the filter always outputs 0.)
  writeByte(MPU6050_ADDRESS, MOT_THR, 10); //Write the desired Motion threshold to register 0x1F (For example, write decimal 20).
  writeByte(MPU6050_ADDRESS, MOT_DUR, 40); //Set motion detect duration to 1  ms; LSB is 1 ms @ 1 kHz rate
  writeByte(MPU6050_ADDRESS, MOT_DETECT_CTRL, 0x15); //to register 0x69, write the motion detection decrement and a few other settings (for example write 0x15 to set both free-fall and motion decrements to 1 and accelerometer start-up delay to 5ms total by adding 1ms. )
  writeByte(MPU6050_ADDRESS, INT_ENABLE, 0x40); //write register 0x38, bit 6 (0x40), to enable motion detection interrupt.
  writeByte(MPU6050_ADDRESS, 0x37, 160); // now INT pin is active low

  pinMode(2, INPUT); // sets the digital pin 7 as input

  pinMode(wakePin, INPUT_PULLUP); // wakePin is pin no. 2
  pinMode(led, OUTPUT); //   led is pin no. 13
  // attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW

}

void sleepNow() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable(); // enables the sleep bit in the mcucr register
  delay(500);
  Serial.println("About to sleep");
  delay(500);
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
  delay(500);
  Serial.println("Interupt attached");
  delay(500);
  sleep_mode(); // here the device is actually put to sleep...!!

  // THE PROGRAM CONTINUES FROM HERE AFTER INTERRUPT IS CLOSED
  delay(500);
  Serial.println("Continuing main program after interupt");
  delay(500);

  sleep_disable(); // first thing after waking from sleep: disable sl¯eep...
  delay(500);
  Serial.println("Sleep disabled");
  delay(500);
}
uint16_t readdata;
void loop() {
  if (digitalRead(2) == 0) {
    {

      digitalWrite(13, 1);
      delay(100);
      digitalWrite(13, 0);
      delay(100);
    }
  }
  sleepNow(); // sleep function called here
  readdata = readByte(MPU6050_ADDRESS, 0x3A);
  Serial.print(readdata);
  Serial.print(",");
  readdata = readByte(MPU6050_ADDRESS, 0x37);
  Serial.println(readdata);

}

Glad to see you got it working. Thank you for sharing your solution.

I needed to put detachInterrupt() in the wakeUpNow() function.  Otherwise works great.

+1 Worked great for me.  Love how no external libraries were needed.

Did not work for me until finding out, that the MPU (additionally to the MCU) must get the interrupt cleared by reading: readByte(MPU6050_ADDRESS, 0x3A); And this didn't work in the ISR itself, so I set a boolean "interrupted" and outside the ISR reacted on this an called the readByte. Also do it after MPU init.


text:
How to get the firmware (hex) file from a .ino file containing the code
I currently have a .ino firmware file that I use in the Arduino IDE to program an ATmega328 micro-controller. I would like to get the file that the Arduino IDE uses to program the micro-controller.
Probably the IDE uses a hexadecimal (hex) file or something and sends it to the micro-controller through the serial.
How can I get this file being the only file that the IDE generates is the .ino?

These questions have been answered here before.

@ChrisStratton I removed my question (was not aware of what you wrote) ... if the question has already been answered, it should be marked as duplicate question (s).

I am getting .BIN file while using the above method in Arduino IDE.

I guess this isn't allowing to add another answer.  One approach is to use the "Export compiled binary" listed in the answers.  You can also have the build go to a more predictable (non-temp) folder/directory.   Edit your preferences.txt file and add the line build.path=<folder for build output>, specifying an existing folder to send the build artifacts to.  Your hex files will be in there the next check/build you run.

In the Preferences of the Arduino IDE; after Show verbose output during: check the box next to compilation.
Then when you compile you should get something like this at the bottom of the window:
...
...
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.elf" "/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.hex"
Sketch uses 928 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

At the end of the third line from the bottom you get the .hex filename. In this case (on OSX) that would be /var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.hex

Perfect, this I needed. Now if I send through the serial this .hex file to the microcontroller it will work as the UPLOAD of the IDE?

Click the checkbox next to it to get verbose output on upload. You can the see the command the IDE uses to upload. Just a hint. It uses the avrdude command line program for that.

You are asking how to locate the compiled hex file. It's easy! Follow these steps:

In the Arduino IDE select Sketch > Export Compiled Binary. This performs a compile. Once complete, this command places a copy of the compiled .hex file into the directory of your sketch.

Then either browse to the sketch folder or in the IDE select Sketch > Show Sketch Folder.

This generates two hex files for the target micro-controller; one with the bootloader and one without the bootloader. These hex files can be uploaded to the micro-controller using a programmer such as the Atmel Ice or AVRISPmkII.

It only places .bin files in the sketch folder.

The easiest way to get the file is:

Sketch > Export Compiled Binary
Wait for the compilation process to finish
Sketch > Show Sketch Folder

You will find an extra file in the sketch folder, which in this case will have a .hex extension. This is the compiled file which would normally be uploaded to the Arduino board via Sketch > Upload.
Note that the "Export Compiled Binary" feature is only available from Arduino IDE 1.6.5 and newer.


text:
Ultrasonic sensor not getting reading while connecting to ESP8266
it's been week that i am having issue,that i can’t get ultrasonic readings
when i connect with my esp8266 wifi module ,everytime it gives 0 cm reading.My
both hardwares work perfectly if i connect them individually.
i also divided a code of ultrasonic and esp8266 for the debugging steps,both are working. but when i combine both code together i get no response. In my database server i get 0 distance.
Note: using external power of 5v for ultrasonic sensor.
Is there any logical problem? please help Sir thanks.
Here is a code
#include<ESP8266WiFi.h>
#include<ESP8266HTTPClient.h>
#define trigger 12
# define echo 13
float timex = 0;
float distance = 0;
float max_height = 0;
float extra_space = 4.00;

int TANK_SPECIAL_ID = 1;

void setup() {
    pinMode(trigger, OUTPUT);
    pinMode(echo, INPUT);
    Serial.begin(115200);
    delay(5000);
    WiFi.begin("AndroidAP", "lovely12");

    Serial.println("Setup Initiated\ n");

    while (WiFi.status() != 3) {
        delay(500);
        Serial.println("Waiting for connection");
        Serial.print("WiFi Status: ");
        Serial.println(String(WiFi.status()));
    }
    Serial.println(String(WiFi.status()));
}

void loop() {
        HTTPClient http;
        int Percentage = 0;
        digitalWrite(trigger, LOW);
        delayMicroseconds(2);
        digitalWrite(trigger, HIGH);
        delayMicroseconds(10);
        digitalWrite(trigger, LOW);
        delayMicroseconds(2);
        timex = pulseIn(echo, HIGH);
        distance = timex * 340 / 20000;

        if (max_height == 0) {
            Serial.println("Setting max_height");
            max_height = distance;
            Serial.println("max_height configured..5 seconds delay");
            delay(5000);
            Percentage = -1;
            Serial.print("MAX HEIGHT: ");
            Serial.println(max_height);
        } else {
            int revVal = int(distance / max_height * 100);
            Percentage = revVal– 100;
            Serial.print("Current Ratings: ");
            Serial.print(distance);
            Serial.print(" cm");
            Serial.print(" | Percentage: ");
            Serial.print(Percentage);
            Serial.println(" %");

        }
        if (distance > -1) {
            String Data = "x=" + String(Percentage) + "&y=" + String(max_height) + "&z=" + String(TANK_SPECIAL_ID);
            http.begin("http://zaptraff.atwebpages.com/IOT/IOTCON.php");
            http.addHeader("application/x-www-form-urlencoded");

            int sent = http.POST(Data);
            Serial.print("Request val: ");
            Serial.println(sent);
            //String httpPayload = http.getString();
            //Serial.println(httpPayload);
            if (sent > 0) {
                Serial.println("Data has been sent");
            } else {
                Serial.println("unable to send data");
            }
        }
        delay(1000);
    }
}

hello?????????????

Tell us what happens (exactly) and what doesn't happen, and perhaps you'll get more interest.

i put my all interest to sort out that problem, the exact problem is that my sensor is not giving the  distance reading.. when i try to upload that values to my server with ESP8266

i put my all interest to sort out that problem, the exact problem is that my sensor is not giving the  distance reading.. when i try to upload that values to my server with ESP8266

seems like nobody is intrested to solve my problem although i explained each and everything in post :/

Could you create a minimal, complete, verifiable example of your code please? Take out everything which isn't necessary to show the problem. For example i presume you don't need the http stuff.

if i takeout everything which isn't necessary to run only ultrasonic code, by discarding the esp8266code, than ultrasonic is working perfectly on switching the board to ARDUIO uno from tool bar. but the main problem is that when i add the http code for my esp8266 and change the board to generic esp than the sensor gives 0 value. Reason i added the http code is to send the sensor data to server.

i think i am wasting my time by posting problems here. worst website i ever seen

You may find that being grumpy and unfriendly is not the best way to attract help. We're not paid to be here - you need to make people want to help you. So, you had it working and then changed TWO things (added HTTP code and changed the board) and now it's not working. Does it still work if you only change one thing? If you find that out, you halve the problem space. Which change caused it to break?

As the MIME type implies application/x-www-form-urlencoded is URL encoded. Non-alphanumeric characters must be percent encoded.
It looks like this line:
if (distance > -1) {

Should be:
if (Percentage > -1) {

Further:
Percentage = revVal– 100;

Is sometimes negative. So String(Percentage) is producing - which is likely tripping up your web server because this is an illegal character when parsing x-www-form-urlencoded.


text:
Controlling an LED using SIM900A and Arduino
How can I turn the LED on and off using a received text message?
The sim card is able to receive the message but I can't change the pin status. I also can't see anything in the serial monitor upon reception of the message.
Below is my code.
#include <SoftwareSerial.h>
SoftwareSerial gsm(2,3);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }
  if (gsm.available()>0)
  Serial.write(gsm.read());

  if ( msg == "ON")
  {
    digitalWrite(LED, HIGH);
    delay(1000);
  }
  if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 if (gsm.available()>0)
 {
  msg=gsm.read();
  Serial.print(msg);
 }
}

gsm.read() returns a single character not a string.

Try this code.
#include <SoftwareSerial.h>
SoftwareSerial gsm(2,3);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }

  while(gsm.available() > 0)
  {
    Serial.write(gsm.read());
  }

  if ( msg == "ON")
  {
    digitalWrite(LED, HIGH);
    delay(1000);
  } else if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
  if(msg != "") msg = "";
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 msg = "";
 while(gsm.available() > 0)
 {
  msg += gsm.read();
 }
 Serial.println(msg);
}

This code works like charm.


text:
Arduino status of bit
Is the a way to check the status of a bit in an arduino Uno?
Like how in Atmel AVR, there is bit_is_clear or bit_is_set

If it's an AVR-based Arduino, you can use bit_is_clear() and bit_is_set().

you can do it in a single line:
bool isSet = (var & (1 << bitNumber)) != 0;

1 << bitNumber is a bit shift in this case it means that the 1 will be multiplied with the power of 2
& is the bitwise AND operator. The each bit of the result is 1 if and only if both the corresponding bits in the inputs is 1.

Let's say there is a register called r1, and you want to do something if its 6th bit is set to 1.
Here are two equivalent if statements, both doing the same thing:
if(r1&64){Do something;}
if(r1&(1<<6)){Do something;}

Tiny extra code information:
Let's say you want to do something if r1 = 01XX10XX00 where X means you don't care.
Here are three if statements, all doing the same thing:
if((r1&0b11001100)==(0b01001000)){Do something;}
if((r1&0b11001100)==((1<<6) | (1<<3))){Do something;}
if((r1|0b00110011)==(0b01111011)){Do something;}

If you & (logic and) a 0 somewhere, then you are setting that bit to 0
If you | (logic or) a 1 somewhere, then you are setting that bit to 1

Best of luck on your future ventures.

Arduino defines the function bit(), which makes it easy to do an if:
if (val & bit(5)) { // Is bit 5 set?
    // Do something
} // if

Note that you need to use the bit-and (&) operator, not the Boolean-and (&&) operator.
If you want to check if the bit is clear, you can use the not (!) operator - but then you need parentheses:
if (!(val & bit(5))) { // Is bit 5 not-set (clear)?
    // Do something
} // if


text:
Typing into ESP8266 with a USB keyboard
I need to be able to connect a USB keyboard, like a tiny Xbox keyboard, or a nice wireless one, into an ESP8266-based thing to type passwords into the MCU. Adapting the PS2 lib for AVRs (PS2==USB pinouts for KBs) proved unreliable, so I tried a fake Pro Mini.
It worked much better, perfect with PS2, but only with a subset of my USB keyboards, namely a 104 Das Keyboard and an old-school Dell one. My 2002-era Mac keyboard doesn't work, none of my 5 wireless keyboards work, and neither do Xbox or foldable keyboards. Nothing that presents as a composite device works (like a keyboard with USB slots), only dead-simple (no fancy keys/knobs) keyboards seem to work.

Would a USB host module (like the Uno shield, but not a shield) let me read from more than just basic PS2-emulating USB keyboards?
Is the code to read basic alphanumeric keys consistent among different keyboards, or will each model need special instructions? (much like a driver would provide an actual OS)
If it's anything but "plug and play", what would be a simple way (no soldering) to securely input passwords into an MCU?

EDIT:
Early USB keyboards and PS2 keyboards have the same pinout and behavior, so you can use a Pro Mini and the Arduino ps2keyboard demo to read such USB keyboards, either with a passive USB keyboard to PS2 male adapter for less than $1 USD, or via a female USB wired the same. Fancier keyboards don't work as such, at all, hence the possible need for a USB host module.

it is unclear what you are describing .... you say that you want to use a USB keyboard, but you talk about PS2 keyboard ... please update your question to make it clear

look at this https://arduino.stackexchange.com/questions/48447/how-to-detect-host-computer-when-boot-power-on-just-use-usb-without-any-sens    ......  use arduino nano

@jsotola: i want to type into the ESP w/ a USB keyboard, hopefully wireless, no PC in sight...

some, maybe most, usb keyboards have a "boot keyboard mode" ( or something like that), that is used to allow keyboard functionality when navigating bios menus. .... arduino usb host module should work for you.  ... the problem is figuring out the software

My 2002-era Mac keyboard doesn't work,

That doesn't surprise me - modern Macs have never needed PS/2 support.

none of my 5 wireless keyboards work,

That's because they're not keyboards, they're wireless transceivers that provide USB HID interfaces.

and neither do Xbox or foldable keyboards.

Too modern, and of course XBox has never needed PS/2 support.

Nothing that presents as a composite device works (like a keyboard with USB slots), only dead-simple (no fancy keys/knobs) keyboards seem to work.

Of course, they aren't PS/2 keyboards, they're USB devices.
Older keyboards provided dual operation - USB and PS/2. This is a function provided by the keyboard, not the USB standard. Mac keyboards, since the Apple computers never had PS/2 ports (since PS/2 is an IBM standard from the PS/2 computers back in the 80s & 90s). Modern keyboards that provide more than just a simple keyboard functionality cannot really provide PS/2 as well since that can't provide the other features of the keyboard. The same goes for composite devices, or wireless devices - they facilities they provide are in excess of what PS/2 can provide, so it would be illogical trying to provide PS/2 support - especially as PS/2 ports are getting rarer on computers now.

Would a USB host module (like the Uno shield, but not a shield) let me read from more than just basic PS2-emulating USB keyboards?

Sure, if you can get the libraries working on the ESP8266, which may well be a huge challenge in- and of itself.

Is the code to read basic alphanumeric keys consistent among different keyboards, or will each model need special instructions? (much like a driver would provide an actual OS)

All USB keyboards are class-compliant HID devices. They send HID reports in a standard format, maybe with custom additions. The basics are always the same though.

If it's anything but "plug and play", what would be a simple way (no soldering) to securely input passwords into an MCU?

It'd be far from "plug and play" getting a USB host interface working with the ESP8266.  Consider other more simple routes, such as using serial, or configuring the ESP8266 as an access point and using a web browser to configure it.

i feel slightly battered, but much more informed; thanks for your time. i guess i'll have to have it "learn" a cheap IR kb...

The USB Host Shield Library 2.0 has supported the ESP8266 for about a year. Support for the ESP32 was added more recently.
The following is a link to the project README listing the supported boards and microcontrollers.
https://github.com/felis/USB_Host_Shield_2.0#boards