text:
Convert String to const unsigned char
String abc ="0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

const unsigned char displaydata={reinterpret_cast<const unsigned char*>(abc.c_str())};

display.drawBitmap(displaydata, startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE);

Get error: invalid conversion from 'const unsigned char' to 'unsigned char' [-fpermissive]*
When I write like this
String abc ="0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff";

display.drawBitmap(reinterpret_cast<const unsigned char*>(abc.c_str()), startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE);

No error but black screen no display image
When I write like this
const unsigned char displaydata[]={ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

display.drawBitmap(displaydata, startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE);

It is working
The string data coming from the server is returning to me as stirng, I am trying to reflect it on the screen. I want to convert a string data to const unsigned char with code
So I'm trying to convert

How exactly is the server giving you the binary data? Please include an example string from the servers answer to the request. Is it really in the format of your first string?

With const unsigned char displaydata={reinterpret_cast<const unsigned char*>(... you're assigning a pointer to a single character.  Or more importantly, part of a pointer to a character, which if the memory address (pointer value) was larger than 0xFF would be pretty useless. So, the problems start here with a missing pointer declarator (a *)  There's not much Arduino to the question. Fairly squarely a C++  question, unless I'm missing something.

String is a custom Arduino class, so could be classed as an arduino question (pun intended) on that merit.

Step one: Split the String into chunks using the comma delimiter. Step B: convert each chunk from its textual representation into its numeric value. Step Delta: place that value into the array. Step 0: forget const, that's irrelevant.

@Majenko, I didn't feel strongly enough about it to close-vote it.

That string is literally the characters 0xff ... while the array is the bytes 0xff...
Where the string contains 4 bytes to say 0,x,f,f (followed by comma and space) the array will have 1 byte the 255 (and no need for a comma or space to delimit).
If you are looking to convert the text hex string to bytes, look at a combination of How to convert an hex string to an array of bytes? and looping through the string.


text:
Why is my passive buzzer clicking instead of buzzing when set to HIGH?
everyone. I am working on learning Arduino from scratch and I am on the buzzer lesson. The tutorial I am following consists on writing a code to get an input from the user in the form of an integer number, and, if it is greater than 10 (or whatever threshold you set it to) it will buzz.
I wrote the code exactly as the tutorial said but the buzzer would not buzz, it would do a weird clicking sound instead. I searched for a reason everywhere and could not find an explanation. Most questions in forums were solved by changing the positive wire from the 5V to a regular pin on the board, and those problems were due to the fact that the people asking the questions were not aware that the buzzer was a passive one.
Anyway, I managed to get a buzz by switching from digital to analogWrite and typing a value less than 255. It seemed weird that 255 and HIGH would produce the click, but values less than 255 would buzz, so I tried several analogWrite values:

At 255 the buzzer does the weird clicking.
At 254 the buzzer does a very faint buzz.

The buzzing got louder as I wrote lower numbers until it got stable at around 250, and then got less loud as I decreased the number.
Does anyone know why that is? Is the voltage too much for the buzzer at 255/HIGH? I tried a resistor but still got nothing but clicking with the program set to 255/HIGH.
This is mostly out of curiosity, but I'd still appreciate it if you could answer it.
Here is the code ("Numero" means "number" and "Dame un número" means "Give me a number":
int Numero;

int buzz=10;

int DLY=2000;

String msg="Dame un numero.";

void setup() {

Serial.begin(9600);
pinMode(buzz,OUTPUT);

}

void loop() {

Serial.println(msg);
while (Serial.available()==0){

}

Numero=Serial.parseInt();

if (Numero>25){

  Serial.println(Numero);

  analogWrite(buzz,10);

  delay(DLY);

  digitalWrite(buzz,LOW);

}

}

for passive buzzer use the tone() function. active buzzer makes sound with 5 V only. https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/

those problems were due to the fact that the people asking the questions were not aware that the buzzer was a passive one.

You seem to know, that you have a passive buzzer, but you don't know, what that means for you.
A buzzer consists mostly of a piezo element, which vibrates and thus makes a sound, if you provide it with an alternating voltage. Here we have 2 types of buzzers:

The ones, that generate the alternating voltage themselves, thus only demanding a simple constant voltage from you to operate (these are the active buzzers)
and the ones, that only have the piezo and thus demand to be provided with an alternating voltage by you (these are the passive buzzers).

You have the second type, a passive buzzer. The following is happening:
digitalWrite(pin, HIGH) will only set the pin to HIGH. On the transition from LOW to HIGH, you get a click, because the piezo in the buzzer is reacting to that change. analogWrite() on the other hand generates a PWM signal, which is an alternating voltage (alternating between LOW and HIGH).
When changing the number for analogWrite(), you are not changing the frequency, but only the duty cycle (the ratio of HIGH and LOW times in one period of the signal).

analogWrite(pin, 255) means 100% duty cycle and thus a constant HIGH signal. Actually it is equivalent to digitalWrite(pin, HIGH), because analogWrite() is doing exactly that, if you provide 255 (similarily it uses digitalWrite(pin, LOW), if you provide 0). Thus you again hear the same click.
As the piezo in the buzzer needs to oscillate to make a sound, you need to give him time for getting back to the LOW state. With the analog value 254 the LOW time of the signal is rather small, so that the piezo cannot reach its complete LOW state again. The oscillation amplitude is rather small that way. Thus you only hear a very faint buzz.
With analogWrite(pin, 250) you reached the maximum, because now the piezo has enough time to get to its LOW state again. The amplitude is at its maximum here, thus it is the loudest value.
When going lower than 250 towards zero, you are also reducing the amount of energy, that you give to the buzzer, thus the volume will reduce (though this is certainly not a linear process and depends also on the characteristics of the buzzer).

Just as Juraj already wrote in the comments, a passive buzzer can be interfaced with the tone() function. It will generate the alternating voltage for you and you can even set the frequency to your liking, so that you get tones with different pitches. There are tons of tutorials about the tone() function on the web.

I don't agree with your "When going lower than 250 towards zero, you are also reducing the amount of energy" statement. It reduces the average voltage, but average voltage is not what gets maximum sound out of a piezo emitter. You're going to get the maximum volume out of a piezo element at 50% duty cycle (digitalWrite(pin, 128)).

@DuncanC You mean analogWrite(pin, 128). But as I think closer, you may have a point there. Its difficult to map the duty cycle to the volume. Can you explain more, why at 50% duty cycle you have the highest volume? The piezo is fast enough, so that changes between 5 and 250 would not matter much. When the pin is high, the piezo moves in one direction. When low into the other. In between it stands still. The amplitude is given by the voltage (for the above range), which is equal for all high or low states. Thus I now could say, that in that range the value doesn't matter for the volume.

Or am I thinking wrong here?

Well, to say it will be loudest at 128 is an over-simplification. It will be the closest to a pure tone at 128, and you'll get equal time with the element in the in and out positions. At values other than 128 there will be additional harmonics introduced into the tone. (There's lots of high frequency harmonics in a square wave signal anyway, but at a duty cycle other than 50% there will be even more.)

Hey man, thanks for the explanation. Could not have asked for a better one on passive buzzers. It was clear and concise and solved my burning question. Keep it up.

A passive Piezo buzzer needs excitation to make sound, from your code you have a delay time of 2000 ms.
2000ms means a frequency of 0.5 Hz thats not enough.for my YL-44 Passive buzzer
even the smallest possible number allowed by the arduino delay(ms) function wich is 1 ms isn't enough to hear a clear sound. A frequency of 2000 Khz was good with delayMicroseconds(us).
double outPin = outPin;
double freq_Hz = freq_Hz;
double period_s = 1 / m_freq_Hz;
double period_ms = m_period_s * 1000;
double period_us = m_period_ms * 1000;
void loop() {
 digitalWrite(m_outPin, HIGH);
 delayMicroseconds(period_us / 2);

 digitalWrite(m_outPin, LOW);
 delayMicroseconds(period_us / 2);
}

As chrisl explained, a passive buzzer needs a switched signal of the desired frequency in order to produce a tone of a specific pitch. It's going to produce the best/loudest output with a square wave (50% duty cycle.)
The analogWrite function outputs a PWM (pulse-width modulation) signal. That is a signal of a fixed frequency but varying duty cycle (The ratio of on time to off time.) At 50% (value 128) you should be able to get a decent tone out of it. (It looks like the PWM frequency varies by Arduino model: )
If you want to produce tones of varying frequncies, use the Arudino library's tone() function, documented here: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/
With the tone() function you provide the pin number and the desired frequency, and it does the rest. As mentioned in the docs, the tone function interferes with PWM output on boards other than Mega.
You could also get a tone with code like this:
bool state = HIGH;
int buzz=10;
unsigned long time = 0;

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

void loop() {
   if (millis() > time) {
      state = state == HIGH ? LOW: HIGH;
      time = millis() + 2;
      digitalWrite(buzz, state);
   }
}

If you loop does nothing else, that should give you a tone of roughly middle C. (250 hz, if my math is correct.)

source: Stack Exchange

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

sort: votes


text:
Compilation error when trying to give pointer to a function to another function
I'm trying to write a library for Arduino using the Wire library.
Here's my code:
PiCom.h:
#ifndef PiCom_h
#define PiCom_h

#include "Arduino.h"
#include <Wire.h>
class PiCom
{
public:
    PiCom(int address, int* integers[], double* doubles[]);
    static void onReceiveCallback(int numbytes);
    static void onRequestCallback();
private:
    //Actually arrays of pointers to the data to be sent, has to be declared that way cause the size of the array isn't known at compile time
    int** _integers;
    double** _doubles;

    void onReceive(int numbytes);
    void onRequest();

    static PiCom instance;
};

#endif

PiCom.cpp:
#include "Arduino.h"
#include "PiCom.h"

static void onReceiveCallback(int numbytes)
{

}

PiCom::PiCom(int address, int* integers[], double* doubles[])
{
    _integers = integers;
    _doubles = doubles;

    Wire.begin(address);
    void (*receiveFunction) (int);
    receiveFunction = &PiCom::onReceiveCallback;
    Wire.onReceive(receiveFunction);//Here i get an error
}

I want the  constructor to be created when a new instance is created. A mehtod in this object should be called when data is requested or received. When trying to pass onRequest(int) directly to Wire.onRequest(void (*) (int)) an error is thrown. Same happend when saving it to receiveFunction.
This problem was solved by using a static function (onReceiveCallback(int). I wanted this static function to call onRequest(int) in the object saved into PiCom::instance.
But now i'm getting another error:
PiCom\PiCom.cpp.o: In function `PiCom':
C:\Program Files\Arduino\libraries\PiCom/PiCom.cpp:26: undefined reference to `PiCom::onReceiveCallback(int)'
C:\Program Files\Arduino\libraries\PiCom/PiCom.cpp:26: undefined reference to `PiCom::onReceiveCallback(int)'

Pointer to a member function is a painful corner of C++ until C++11. This is why when you try to pass an instance method pointer to Wire.onReceive (without the static keyword), you will get an error similar to:
error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.  Say '&PiCom::onReceiveCallback'

Well, you can't argue with the C++ ISO standard... changing the function to a static one (with external linkage, as they say) is indeed a workaround, as you have found out.
For this workaround to compile properly you just need to omit the static keyword from your definition (where it is implemented), and leave your declaration (in the header file) as is:
PiCom.h:
...
static void onReceiveCallback(int numbytes);
...

PiCom.cpp:
void PiCom::onReceiveCallback(int numbytes)
{
    ...
}

By doing this you can pass it to Wire.onReceive without any problem, from the PiCom constructor, as follows:
PiCom::PiCom(int address, int* integers[], double* doubles[])
{
    ...
    Wire.onReceive(&PiCom::onReceiveCallback);
    ...
}

Works as it should. I already noticed that i forgot the "PiCom::" and also figured out that i have to use static only in thüe declaration. But anyways, thank you for the detailed answer.

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


text:
Memsic Accelerometer not returning T value
I hooked up a Memsic2125 accelerometer to a Arduino Uno.  X and Y values are returning fine, but the T value is returning -4000 every time.
// these constants won't change:
const int xPin = 2;     // X output of the accelerometer
const int yPin = 3;     // Y output of the accelerometer
const int tPin = 4;     // Y output of the accelerometer

void setup() {
  // initialize serial communications:
  Serial.begin(9600);
  // initialize the pins connected to the accelerometer
  // as inputs:
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
  pinMode(tPin, INPUT);
}

void loop() {
  // variables to read the pulse widths:
  int pulseX, pulseY, pulseT;
  // variables to contain the resulting accelerations
  int accelerationX, accelerationY, accelerationT;

  // read pulse from x- and y-axes:
  pulseX = pulseIn(xPin,HIGH);
  pulseY = pulseIn(yPin,HIGH);
  pulseT = pulseIn(tPin,HIGH);
  // convert the pulse width into acceleration
  // accelerationX and accelerationY are in milli-g's:
  // earth's gravity is 1000 milli-g's, or 1g.
  accelerationX = ((pulseX / 10) - 500) * 8;
  accelerationY = ((pulseY / 10) - 500) * 8;
  accelerationT = ((pulseT / 10) - 500) * 8;

  // print the acceleration
  Serial.print(accelerationX);
  // print a tab character:
  Serial.print("\t");
  Serial.print(accelerationY);
  // print a tab character:
  Serial.print("\t");
  Serial.print(accelerationT);
  Serial.println();

  delay(100);
}

The output looks like this...
-104    -24 -4000
-96 -24 -4000
-96 -24 -4000
-104    -24 -4000
-96 -24 -4000
-104    -24 -4000
40  -216    -4000
120 -184    -4000
72  -200    -4000
-80 -376    -4000
456 672 -4000
-8  -40 -4000
-112    0   -4000
-112    0   -4000
Any ideas on how to get the -4000 fixed?

Maybe I 'm wrong but it seems that only two accelerations (X, Y) are digital. What is T standing for?

According to the datasheet, T is the chip temperature and is an analog value, not a digital pulse like X and Y accelerations, hence you cannot read it and compute it the same way as X and Y!

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


text:
Blink not working
I have written this code to write and receive signals over i2c between two Uno's. I have a master and a slave code, this is working fine. Now I want the led to blink, for this I added the blink without delay example. Unfortunately I can't get it working at all...
// Wire Slave Receiver

#include <Wire.h> //include Library
// define Led Pins
#define LED1 3 //Pin 3
#define LED2 4 //Pin 4
#define LED3 5 //Pin 5

int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 500;           // interval at which to blink (milliseconds)

void setup()
{
  Wire.begin(4);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output

  //set Pin modes
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  //intern pulldown
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, LOW);

}

void loop()
{
  unsigned long currentMillis = millis();
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  while (1 < Wire.available()) // loop through all but the last
  {

    char c = Wire.read(); // receive byte as a character
    Serial.print(c, BIN);     // print the character as Binary

  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x, BIN); // print the integer as Binary

  if (x == 1) { //turn LED1 on
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, LOW);
    digitalWrite(LED1, HIGH);
    Serial.println("LED1 on");
  }
  if (x == 2) { //blink LED1
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED1, ledState);
    }
  }

  if (x == 3) { //turn LED2 on
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, HIGH);
    delay(100);
  }
  if (x == 4) { //blink LED2
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED2, ledState);
    }
  }
  if (x == 5) { //turn LED3 on
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, HIGH);
  }
  if (x == 6) { //blink LED3
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED3, ledState);
    }
  }
  if (x == 7) { //turn LED1 nad 2 on
    digitalWrite(LED3, LOW);
    digitalWrite(LED1, HIGH);
    digitalWrite(LED2, HIGH);
  }
  if (x == 8) { //Blink LED1 and 2
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);
  }
  if (x == 9) { //turn LED2 and 3 on
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);

    digitalWrite(LED2, HIGH);
    digitalWrite(LED3, HIGH);
  }

}

Thanks for your response. I tried to put all the of statements into the loop, but it's still not working. :P I have no idea how to put it into the loop so it works.
// Wire Slave Receiver

#include <Wire.h> //include Library
// define Led Pins
#define LED1 3 //Pin 3
#define LED2 4 //Pin 4
#define LED3 5 //Pin 5

int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 500;           // interval at which to blink (milliseconds)

void setup()
{
  Wire.begin(4);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output

  //set Pin modes
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  //intern pulldown
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, LOW);

}

void loop()
{
    if (x == 1) { //turn LED1 on
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, LOW);
    digitalWrite(LED1, HIGH);
    Serial.println("LED1 on");
  }
  if (x == 2) { //blink LED1
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED1, ledState);
    }
  }

  if (x == 3) { //turn LED2 on
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, HIGH);
    delay(100);
  }
  if (x == 4) { //blink LED2
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED2, ledState);
    }
  }
  if (x == 5) { //turn LED3 on
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, HIGH);
  }
  if (x == 6) { //blink LED3
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED3, ledState);
    }
  }
  if (x == 7) { //turn LED1 nad 2 on
    digitalWrite(LED3, LOW);
    digitalWrite(LED1, HIGH);
    digitalWrite(LED2, HIGH);
  }
  if (x == 8) { //Blink LED1 and 2
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);
  }
  if (x == 9) { //turn LED2 and 3 on
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);

    digitalWrite(LED2, HIGH);
    digitalWrite(LED3, HIGH);
  }
  unsigned long currentMillis = millis();
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  while (1 < Wire.available()) // loop through all but the last
  {

    char c = Wire.read(); // receive byte as a character
    Serial.print(c, BIN);     // print the character as Binary

  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x, BIN); // print the integer as Binary

}

You are misinterpreting how the onReceive callback works. The millis() code like in the BlinkWithoutDelay example relies on the fact, that it is run repeatedly very fast, so that effectively the time is checked regularily very fast.
The onReceive callback is only called once every time, that the Wire library received an I2C message, from an interrupt service routine. It is not called repeatedly. So the millis() code in there, will only be executed once. Since no time has passed (and millis() wouldn't increment inside an ISR either way) nothing happens there and the callback exits. After that the code is not executed further times.
You need to put the millis() code into the loop() function, so that it is executed repeatedly. In fact you can put all the if statements with x into the loop() function.

EDIT:
Your second version of the code should result in compilation errors (which you really should have included into your question). They will say, that x is not declared in this scope. You read the I2C data from the buffer in the onReceive callback and save it into a newly created variable x. Since x is declared inside the function, it will cease to exist right after the end of this function. The loop() function does not know about x. You need to define x globally outside of any function at the start of your sketch.
This results in this code:
// Wire Slave Receiver

#include <Wire.h> //include Library
// define Led Pins
#define LED1 3 //Pin 3
#define LED2 4 //Pin 4
#define LED3 5 //Pin 5

uint8_t x=0;                    // define x at global scope, so that it is available everywhere
int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 500;           // interval at which to blink (milliseconds)

void setup()
{
  Wire.begin(4);                // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output

  //set Pin modes
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  //intern pulldown
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, LOW);
  digitalWrite(LED3, LOW);

}

void loop()
{
    if (x == 1) { //turn LED1 on
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, LOW);
    digitalWrite(LED1, HIGH);
    Serial.println("LED1 on");
  }
  if (x == 2) { //blink LED1
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED1, ledState);
    }
  }

  if (x == 3) { //turn LED2 on
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, HIGH);
    delay(100);
  }
  if (x == 4) { //blink LED2
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED2, ledState);
    }
  }
  if (x == 5) { //turn LED3 on
    digitalWrite(LED2, LOW);
    digitalWrite(LED3, HIGH);
  }
  if (x == 6) { //blink LED3
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      if (ledState == LOW) {
        ledState = HIGH;
      } else {
        ledState = LOW;
      }
      digitalWrite(LED3, ledState);
    }
  }
  if (x == 7) { //turn LED1 nad 2 on
    digitalWrite(LED3, LOW);
    digitalWrite(LED1, HIGH);
    digitalWrite(LED2, HIGH);
  }
  if (x == 8) { //Blink LED1 and 2
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);
  }
  if (x == 9) { //turn LED2 and 3 on
    digitalWrite(LED1, LOW);
    digitalWrite(LED2, LOW);

    digitalWrite(LED2, HIGH);
    digitalWrite(LED3, HIGH);
  }
  unsigned long currentMillis = millis();
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  while (1 < Wire.available()) // loop through all but the last
  {
    char c = Wire.read(); // receive byte as a character
    Serial.print(c, BIN);     // print the character as Binary
  }
  x = Wire.read();    // receive byte as an integer
  Serial.println(x, BIN); // print the integer as Binary
}

Note, that I changed the type of x to uint8_t, an unsigned int of 8 bits. Restricting x to 8 bits prevents problems with writing a variable inside an ISR. The Uno has an 8-bit microcontroller, so it handles 8 bits at a time. int has 16 bits and is thus handled in two steps. An interrupt can occur at any time, so the ISR might write x in the middle of a calculation, which results in a totally garbled value of x. Handling a 1 byte/8 bits variable cannot be interrupted (also called "atomic") and prevents this issue.

Thanks for your response. I tried to put all the of statements into the loop, but it's still not working. :P I have no idea how to put it into the loop so it works.

@Marvinm You can add your new code to your question by editing it. Then I can check it for errors

I'am sorry for beeing so pushy, but I really need this code in about one day. I will give you a little credit as well. If you can solve this problem.

Then add your new code to your question. Then I can help you

I don't understand.

You wrote, that you tried to put all the if statements in the loop, but it was not working. That means, that you actually have tried it and created a new version of your code, where you've put all the if statements into the loop function. You should add this code to your question by editing it

There it is. Hope that helps

@Marvinm I added an extra explanation.

Also I edited your question, so that both the old and the new code can be seen. That way others have the chance to also get help from this Q&A.

Thanks soo much, you are a legend, can u leave you mail for PayPal here. Thanks.

You are welcome :) Nope, I'm not doing this for money. You can upvote my answer, if you like

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


text:
Data transmission rate of accelerometer mpu6050 to arduino uno vs Sampling rate of mpu6050
mpu6050 has sampling frequency of 1kHz (mentioned in datasheet). But when i interface it with arduino uno via I2C communication (400Khz bus speed), i only get 50 raw data (each of x,y,z). There is no delay in the program. why is this happening. Why am I not getting 1000 or at least 800 samples. What is the concept I am missing here. Please explain in detail. I have also attached the code and output for 1 second.
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"
//#include <SoftwareSerial.h>
//SoftwareSerial BTserial(10,11);
MPU6050 accelgyro;
char ch;
int incomingbyte = 0;
int16_t ax, ay, az;
int16_t gx, gy, gz;

void setup() {

  Wire.begin();
  Serial.begin(115200);

  accelgyro.initialize();
  accelgyro.setXAccelOffset(542);
  accelgyro.setYAccelOffset(-835);
  accelgyro.setZAccelOffset(1651);
  accelgyro.setXGyroOffset(6);
  accelgyro.setYGyroOffset(-18);
  accelgyro.setZGyroOffset(23);
}
void loop()
{
  accelgyro.getAcceleration(&ax, &ay, &az);
  accelgyro.getRotation(&gx, &gy, &gz);

  Serial.print(ax); Serial.print("\t");
  Serial.print(ay); Serial.print("\t");
  Serial.println(az);
}

the datasheet indicates that the sample rate is programmable ... looks like register 25 is involved ... this document describes the register functions ... https://invensense.tdk.com/wp-content/uploads/2015/02/MPU-6000-Register-Map1.pdf

HI @jsotola , thanks for the reply. I found out sampling rate divider that is at reg 0x25 , 255 was set. So the sampling rate should be either 31.25Hz DLPF is disabled or 3.9 hz  when DLPF enabled according to the datasheet (pg no 12 in the link you have provided). Still i am getting more than these values around 50 samples. How come? Also sampling rate is different from data transmission rate from mpu6050 to arduino uno right? Can you explain in detail like how many bytes would transmitted through i2c and all those calculation stuffs.  I am not getting that

Set the I2C to 400kHz using Wire.setClock(), I think by default it's set to 100kHz. That would bump up the sampling rate from 50 Hz to 200 Hz. If that's not enough I think you have to disable the digital low pass filter.

Your problem is the Serial.print which slows down the loop. Add a counter in your loop and do a serial.print just once in a while.

i want to know what is the unit of this signal? for example what is the 5608 ?? in first row

The reason is that Serial.print() is mush slower compared to reading a sample from the sensor.
If you comment the print(), then read sensor data for a certain time repeatedly and calculate the output data rate accordingly, you will find that the sampling rate is indeed 1000 Hz.
If what you wanted is merely to store the data and use it afterwards (instead of real-time processing), you can store the sensor readings in a SD card, which is always much faster than serial printing. A useful trick is that do not write data to the sd card whenever you get a new sample, but use a software buffer (i.e., array) to store the samples (the buffer size depends on the RAM of microcontroller) and then write the whole buffer to the sd card when it's full.
However, as long as you want to store the data (either print in serial or write in a file), you'll always have to 'sacrifice' some data rate and cannot get 1kHz as mentioned in datasheet.
Hope this helps.


text:
Serial.parseFloat() reads 0 despite me entering different value
I'm trying to make a robot that asks the user for the longitude and the altitude form the user and then using the data the GPS collects to go to the wanted location, however when I use Serial.parseFloat() to get the location from the user, i get the right value for the latitude and the longitude returns zero for some reason
here's the code i wrote
#include "Adafruit_FONA.h"

// standard pins for the shield, adjust as necessary
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
#define PIN13 13
#define IN1 6      //IN1
#define IN2 7        //IN2
#define ENA 5          //ENA
#define ENB 10        //ENB
#define IN3 8          //IN3
#define IN4 9          //IN4
#define trigger1 A3      //Trigger
#define echo1 A2        //Echo
#define trigger2 A4
#define echo2 A5
#define trigger3 A0
#define echo3 A1

// We default to using software serial. If you want to use hardware serial
// (because softserial isnt supported) comment out the following three lines
// and uncomment the HardwareSerial line
#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
int counter;
char serialData;
int duration;
float distance1, distance2, distance3;
float latitudeDestination, longitudeDestination;

// Hardware serial is also possible!
//  HardwareSerial *fonaSerial = &Serial1;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
// Have a FONA 3G? use this object type instead
//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST);

void getLatitude(){
    Serial.println("Enter the latitude destination :");
    while (Serial.available() == 0){}
    latitudeDestination = Serial.parseFloat();
}

void getLongitude()
{
    Serial.println("Enter the longitude destination :");
    while (Serial.available() == 0){}
    longitudeDestination = Serial.parseFloat();
}

void securityPassed()
{
    Serial.println("You need to pass security first");
    while (Serial.available() ==0){}
    serialData = Serial.read();
    if (serialData == '1')
    {
        Serial.println("Passed") ;
    }
    else {}
}

void setup() {
    pinMode(PIN13, INPUT);
    pinMode(trigger1, OUTPUT);
    pinMode(echo1, INPUT);
    pinMode(trigger2, OUTPUT);
    pinMode(echo2, INPUT);
    pinMode(trigger3, OUTPUT);
    pinMode(echo3, INPUT);
    pinMode(IN1 , OUTPUT);
    pinMode(IN2, OUTPUT);
    pinMode(IN3, OUTPUT);
    pinMode(IN4, OUTPUT);
    pinMode(ENA, OUTPUT);
    pinMode(ENB, OUTPUT);

    digitalWrite(ENA , HIGH);
    digitalWrite(ENB, HIGH);

    Serial.begin(9600);

    getLatitude();
    getLongitude();
    securityPassed();

    Serial.println(F("Adafruit FONA 808 & 3G GPS demo"));
    Serial.println(F("Initializing FONA... (May take a few seconds)"));
    fonaSerial->begin(4800);
    if (! fona.begin(*fonaSerial)) {
        Serial.println(F("Couldn't find FONA"));
        while (1);
    }
    Serial.println(F("FONA is OK"));
    // Try to enable GPRS
    Serial.println(F("Enabling GPS..."));
    fona.enableGPS(true);
}

void loop() {
    delay(2000);

    float latitude, longitude, speed_kph, heading, speed_mph, altitude;
    float latitudeDistance = latitudeDestination - latitude ;
    float longitudeDistance = longitudeDestination - longitude;

    // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix
    boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude);
    if (gps_success) {
      Serial.print("GPS lat:");
      Serial.println(latitude, 6);
      Serial.print("GPS long:");
      Serial.println(longitude, 6);
      Serial.print("GPS speed KPH:");
      Serial.println(speed_kph);
      Serial.print("GPS speed MPH:");
      speed_mph = speed_kph * 0.621371192;
      Serial.println(speed_mph);
      Serial.print("GPS heading:");
      Serial.println(heading);
      Serial.print("GPS altitude:");
      Serial.println(altitude);
      Serial.print("Latitude Distance: ");
      Serial.println(latitudeDistance);
      Serial.print("Longitude Distance: ");
      Serial.println(longitudeDistance);

      if ( latitudeDistance < 0.00001 && latitudeDistance > -0.00001)
      {

        if ( longitudeDistance < 0.00001 && longitudeDistance > -0.00001)
        {
          Serial.print("Arrived");
          stopm();
        }
        else
        {
          if (!counter == 1 && longitudeDistance > 0 )
          {
            moveRight();
            Serial.println("Turning Right");
            counter =1;
          }
          else if ( !counter == 1 && longitudeDistance < 0 )
          {
            moveLeft();
            Serial.println("Turning Left");
            counter=1;

          }
          moveForward();
        }
      }
      else
      {
        moveForward();
        Serial.print("Going To Destination");
      }
    }
    else {
      Serial.println("Waiting for FONA GPS 3D fix...");
    }
}

Can you demonstrate the problem with a simpler program?

Craig, I really wish I could make it simpler but I think the problem is caused by the GPS, so I just want people to take an look at the whole code to figure out where I went wrong

but the problem simply is that the function void getLatitude() works very well while the function void getLongitude() which is very similar to it doesn't work so well, when i enter the longitude destination in the serial monitor it gives the variable longitudeDestination a valure of zero no matter what value i enter

Are you sure you can't make something simpler with the problem? Can you make a simpler version that works to read the lat/long?

unfortunately not as the code is intended to receive the coordinates from the user and receive a signal from the raspberry pi that the user passed the face-recognition system and start navigating to it, all that in one Arduino code

Craig, this method working fine when i used it by its self, but when adding it to this code to work along with GPS it doesn't show the same efficiency, and there are not any easier ways to read lat/long than this one as far as i know

You are setting the lat/long Distance variables before reading the lat/long from the GPS.

What exactly are you sending to it? How does your location string look like?

@gre_gor it looks something like this 31.215486. just a normal float. I just would like to note that the first function getLatitude() works perfectly unlike the other one getLongitude

It is certainly possible that a person typing (or an automated system feeding data in packets over a spotty link) might fail to provide a valid number in the (default 1 second) time before parseFloat() times out.
However, given this is the second value to be read, there's a more complex possibility.
It's likely that the sequence actually sent might be something like
123.45\r\n
In this case 123.45 and the first non-value character \r will be consumed by the first parseFloat().
But that leaves a remaining \n in the serial buffer, so the serialAvailable() check is satisfied immediately and the next parseFloat() begins before the user has even started typing.  Unless they're very quick to respond, it may time out before they even begin.
If the user is supposed to use a terminal program that sends a carriage return and/or newline, you should probably change input processing to either consume until the end of the line before processing.
Or you can make your code flexible by being sure to consume any trailing line end characters (after checking for them with Serial.peek()) before you decide that the user has begun entering a new value and starting your next parseFloat() call.
You could also make your own more sophisticated parseFloat() using a different algorithm.

the two values should be send at once from Serial Monitor, separated by some non-digit character. parseFloat ignores non-digit initial characters.

@Juraj parseFloat ignores and consumes leading non-digit characters and one trailing one.  But if there are two, that second will trip the asker's serial data check, and cause the second parsing timeout to begin immediately.  The values in question are entered in response to distinct prompts so no, they wouldn't be sent "at once" unless someone decided to ignore the prompts and type them in immediate succession, or pipe in data from a script.  Changing the program to request all values on the same line could sort of work, if the terminal is in line mode or the user is careful not to pause.

Chris, exactly what I meant. Session Monitor sends the line at once


text:
String does not name a type
I'm using Arduino IDE for ESP32 WROOM board. I am testing the OTA feature with the ESP32httpUpdate library. I am using the example sketch of the library with the name httpUpdate.ino
However, as soon as I change the update url with a string pointer that I declare globally, it is throwing a compile error that String does not name a type. Any ideas?
/**
 * httpUpdate.ino
 *
 *  Created on: 27.11.2015
 *
 */
String* FIRMWARE_UPDATE_VERSION = "1000";

String* updateURL = "XYZ.php";

#include <Arduino.h>

#include <WiFi.h>

#include <HTTPClient.h>
#include <ESP32httpUpdate.h>

#define USE_SERIAL Serial

void setup() {

    USE_SERIAL.begin(115200);
    // USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    WiFi.begin("SSID", "PASSWORD");

}

void loop() {
    // wait for WiFi connection
    Serial.println("Yolo");
    if((WiFi.status() == WL_CONNECTED)) {

        t_httpUpdate_return ret = ESPhttpUpdate.update(updateURL, FIRMWARE_UPDATE_VERSION);

        switch(ret) {
            case HTTP_UPDATE_FAILED:
                USE_SERIAL.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
                break;

            case HTTP_UPDATE_NO_UPDATES:
                USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
                break;

            case HTTP_UPDATE_OK:
                USE_SERIAL.println("HTTP_UPDATE_OK");
                break;
        }
    }
}

https://docs.google.com/document/d/1G28416DlDBxZEHrLdYylUgBE80ePzbWDJtMKpQ6lJKk/edit?usp=sharing

link to the code

Code, that is this short, should be copied directly into the question and formatted correctly as code by selecting it and pressing the {} button in the editor. I've done this for you now, but please remind it for the next question.

Hey thanks. I did try to add the code in the question itself but it got weird and I couldn't do the formatting clearly so I gave a link.

what is String* updateURL = "XYZ.php";? you assign a pointer to constant char array to a pointer to String object. Where did you see something like this? It should be const char* updateURL = "XYZ.php"; or String updateURL = "XYZ.php";

I initially started with String updateURL = "XYZ.php" but the same error came up. Then I saw in the http library that the httpUpdate function accepts a pointer value so I was trying out with a string pointer

String is included by Arduino.h. Before #include <Arduino.h> String is not defined. Move #include <Arduino.h> to the top of the file or remove it. If you remove it, the Arduino builder adds it.

Thank you. It worked!/


text:
Combining sketches
I have two codes for my to sensors and they work separately. However, I need to combine them in one program please can you help?
The pulse code
 /* PulseSensor Starter Project and Signal Tester
 *  The Best Way to Get Started  With, or See the Raw Signal of, your PulseSensor.com™ & Arduino.
 *
 *  Here is a link to the tutorial
 *  https://pulsesensor.com/pages/code-and-guide
 *
 *  WATCH ME (Tutorial Video):
 *  https://www.youtube.com/watch?v=RbB8NSRa5X4
 *
 *
-------------------------------------------------------------
1) This shows a live human Heartbeat Pulse.
2) Live visualization in Arduino's Cool "Serial Plotter".
3) Blink an LED on each Heartbeat.
4) This is the direct Pulse Sensor's Signal.
5) A great first-step in troubleshooting your circuit and connections.
6) "Human-readable" code that is newbie friendly."

*/

//  Variables
int PulseSensorPurplePin = 0;        // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED13 = 13;   //  The on-board Arduion LED

int Signal;                // holds the incoming raw data. Signal value can range from 0-1024
int Threshold = 550;            // Determine which Signal to "count as a beat", and which to ingore.

// The SetUp Function:
void setup() {
  pinMode(LED13,OUTPUT);         // pin that will blink to your heartbeat!
   Serial.begin(9600);         // Set's up Serial Communication at certain speed.

}

// The Main Loop Function
void loop() {

  Signal = analogRead(PulseSensorPurplePin);  // Read the PulseSensor's value.
                                              // Assign this value to the "Signal" variable.

   Serial.println(Signal);                    // Send the Signal value to Serial Plotter.

   if(Signal > Threshold){                          // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
     digitalWrite(LED13,HIGH);
   } else {
     digitalWrite(LED13,LOW);                //  Else, the sigal must be below "550", so "turn-off" this LED.
   }

delay(10);

}

The gsr code:
void setup()
{
    Serial.begin(9600);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    digitalWrite(2, HIGH);
    delay(500);
    digitalWrite(3, HIGH);
    delay(500);
    digitalWrite(4, HIGH);
    delay(500);
}

void loop()
{
    if (analogRead(A0) > 60)
    {
        digitalWrite(4, HIGH);
    }
    else
    {
        digitalWrite(4, LOW);
    }
    if (analogRead(A0) > 20)
    {
        digitalWrite(2, HIGH);
    }
    else
    {
        digitalWrite(2, LOW);
    }
    if (analogRead(A0) > 45)
    {
        digitalWrite(3, HIGH);
    }
    else
    {
        digitalWrite(3, LOW);
    }

    Serial.println(analogRead(A0));
    delay(20);
}

just combine the codes in setup and loop functions - at a quick glance, there shouldn't be any conflict - have you even tried? if so, what problem did you face?

I faced problem my sensor not reading and i tried to change the analog input  but it wouldn't read

Please provide us with the actual combined code so we can compile and flash it. Also the corresponding output of your three codes could be helpful


text:
How to protect sensors used on atheletes?
I'm working on a project were we are trying to attach accelerometers to soccer players and capture various aspects of movement data.  Breadboarded circuits are coming along nicely and I'm now looking for how to best protect sensors we can mount on players.  (All wire at the moment unfortunately - BT next.)
Although I can find ways to protect the sensor for sensor damaging impact (we are essentially interested in player impacts with the ball or ground) there are other aspects of protection I'm not sure about.  Any recommendations on how to protect from moisture without increasing bulk too much, minimizing cushioning which could affect the data and of course avoid adding anything that could injure the player?  I have come across other examples of movement studies, but they have been by musicians or other situations that do not include outdoor weather and sweaty bodies.

Just make it, so it's easy to repair. Thing will break, no matter what, at those conditions. Just make sure the players aren't electrocuted :-)

The only way this is ever done is with some kind of product casing. You can buy pre-fab cases for electronic projects, but to get something really slick and appropriate for your purpose, you're gonna have to make something yourself. You might look into 3D printing.
Something like this might work: https://www.sparkfun.com/products/8601
For protection from salt-water, this product is worth a look: http://www.corrosionx.com/
There's some different products there, but I've seen a demo of that product, where we ran an entire RC airplane system, servos, motors, and receiver, UNDER WATER.

That looks like the kind of case I was thinking of for the data logger module.  The accelerometers should be smaller and I was thinking of trying a soft setting sealer to coast the sensor.  I think they are low power enough to not have problems with heat dissipation issues.  The 3D printing is an interesting idea - only been reading about that and seeing demos at shows.  Might be the time to try it out.

Or, just don't. The effect of sweat on electronics is often overestimated. Many electronics work underwater just fine. Covering it with shrink-tube or plain old packing tape might be enough. I've done that with sensitive components on RC float planes. You could also try "Corrosion-X" spray.

Good comment.  I have worked with sensors in the field for geophysics and we have had some weather problems from time to time.  I like your experience with simple solutions.  Watch the Red Green Show much? ;-)

No, but you're not the first person to ask that. I have a Youtube channel (jasmine2501) where I try to keep it simple. It's mostly about firearms and RC stuff, but there's a few Arduino vids up there too. I've been an engineer for a long time and seen a lot of waste when searching for "ideal" solutions when it wasn't needed. Good engineers recognize perfection, but great engineers recognize "good enough"


text:
Where are these capacitors on the arduino schematic?
My arduino has these two capacitors

But I can't find any 47uf capacitors on the schematic. Is this not the value but instead a code? Where are these in the schematic?

I don't know why you are concerned, but if you had an up-to-date schematic you would see them. They are exactly where you would expect to see them- around the 5V regulator.

I'm not concerned, I'm learning. I was just wondering if I was missing something or most of the schematics online don't show them for some reason.

What: Looking at the schematic that you provided, it seems likely that they serve as C6 & C7.
Why: These are shown as 100 uF each and act as "filter" capacitors for IC4, the 5V regulator.
Within certain limits, such capacitors are not critical in value, and the manufacturer has probably decided that a factor of in the capacitance is probably acceptable.
They are probably correct :-).
How to check: You can check this yourself with an Ohm-meter set to the lowest Ohm range available - often = 200 Ohms max.
Turn off power to the board and leave it off for say 5 minutes to allow capacitors to discharge.
Locate I4 and find its input and output pins or tracks leading to them. You can often get ohmic connections at vias as the tracks change board layers.
IC4 pin1 will be grounded.
One lead of C6 & C7 are also grounded.
The pad you can see in your photo on the board edge side of the caaps is probably the -ve terminals (about 99%+ likely) (and they match the can markings)
and the "stippled" surface is almost certainly system ground.
If you can confirm that the two caps are connected to ground as and where described above, then:
Apply Ohm meter probes between the non ground lead of a capacitor and each non-ground pin in turn of IC4. One of them will be a low resistance connection if they are C6 & C7. Check the other capacitor - it should connect to the other side of IC4.
Reversing the meter leads in each case may give somewhat different readings for non-hard-connected points but should be low and consistent for hard-connected by a track points.


text:
How can I increase resolution for current sensor?
I purchased a ACS711 Hall effect-based linear current sensor (http://www.pololu.com/product/2197) and when i read the input it's basically always the same. After doing some research I think it's because there is only a 10bit AD converter and since the current is only changing a little bit it's not enough to catch the change. For my situation I'm pulling around 40-90ma idle and when the motor turns on it jumps up so I want this sensor to see that but it only jumps up to about 120ma. Any tips on how to fix this? Maybe a different sensor? Can I use an amplifier to boost the analog signal?

You definitely want a different sensor for this. Your current sensor isn't sensitive enough for the current application.

Are you sensing the right line? Because, a motor using only 30-80mA doesn't sound right?

If you have a transistor, simply amplify the voltage. This allows you set different reference voltages

@Jasmine yeah. I typically have to use 2A adapters for motors. Check that out.

In default configuration, the Arduino's ADC has a range of 0v-Vcc (5v or 3.3v depending on the model). If you are sure your input voltages will always be way lower than Vcc, spreading the ADC's resolution over that range is a waste of accuracy. What you need to do is to properly configure your analog reference voltage.
Basically, this is a way of telling your Arduino "instead of spreading your ADC's bits over a range of 0v to Vcc, just cram all that accuracy between 0v and [refVoltage]."
So:

Measure the highest analog output your sensor will give.
Setup a voltage divider to output a little more than that
Connect the voltage divider's output to the AREF pin
in setup(), declare analogReference(EXTERNAL);

And that's basically it. As noted, in this specific case you'd probably be better off buying another sensor altogether. However, you won't always have that luxury, and knowing how to set the analog voltage reference always comes in handy.

The problem with this is that the sensor produces voltage offsets from Vcc/2, so your ADC has to support voltages of 0 to about Vcc/2 - ie: you can get only about a resolution gain of 2.  To do better you need differential inputs rather than single ended (eg: having the ADC 0-1024 counts span 2.2v - 2.7v if Vcc=5V).  That could be done with op amps, or using a different Arduino.  I guess I'll write up the latter, since it takes a bit more explaining.

First, let's look at where you are now.  The sensor you have reports current changes at 110mV per amp.
That means 40mA => 4.4mv, 90mA => 9.9mv, and 120mA => 13.2mv -- all very small voltages and small changes in voltage.
Let's work backward, tho.  A 5V Arduino in typical ADC mode has a resolution of about 5 mV (5 V / 1024 counts), whilea 3.3V Arduino would have a resolution of about 3.3 mv).  Divide those step sizes by 0.11V/A sensitivity and you'll see that a different of 1 count on the ADC will represent about 45ma (5V Vcc) or 30 ma (3.3V Vcc).  But there is always inaccuracy and noise, so it's going to be hard to reliably distinguish between 90mA and 120 mA (using your figures).
You can improve that somewhat by switching to a sensor with higher sensitivity (and lower maximum range) like https://www.pololu.com/product/1185 which improves the sensitivity to 185 mV per amp.  The step size of the ADC converters would translate to about 26 mA (@5V) or 17.5 mA (@3.3V).  That's still pretty tight.
You might be able to manage with the more sensitive sensor and a 3.3V Arduino - if you use capacitors to filter out the electrical noise on the sensor to ADC input, and you average multiple readings in your code to further smooth the values.  But it would be marginal.
So you need to amplify the sensor.  Yes, you could do that with an external amplifier, like an op Amp.  A transistor is more difficult because you need it to stay fairly linear which gets trickier, and you may need more than one stage - so an op amp is easier.
There's another tricky factor - you need to compare the voltage from the sensor to some reference - Vcc/2 for your sensor, and 2.5V for the more sensitive one.  The current is proportional to the difference between the sensor reading and that reference (the current going one way for sensor output above reference, the other way for sensor output below reference).
I'll mention another option - you could use an Arduino Mega or Leonardo.  These chips offer the option of differential inputs (one pin goes to the signal, and one to the reference), and they have built in selectable amplifiers with up to 200x amplification.  That should give you plenty of resolution, without needing to use external active analog circuitry.
You will still need to filter the sensor output to smooth spikes from the motor (current spikes translated to voltage spikes by the sensor).  You may need to also filter the Arduino Aref input with a cap.
Suppose you were to use an Arduino Mega or Leonard with the sensor you have.  You'd want a Vcc/2 reference, which could simply be two identical resistors (say 10K ohm) between Vcc and Ground as a voltage divider (and maybe a cap to ground for filtering).  You would still probably need to calibrate by finding the ADC value for no current as your reference and subtract that from the reading you get when current is flowing.


text:
Storing data (strings) if ethernet fails to send it
Flow goes something like:
Read sensors
Send data
If send fails store the data in eeprom/flash/sd
If sent check if any previous ones have failed and send those
So my question is what's the best storage option to save the data? Is there an easy way to save strings or am I going to have to write it byte by byte?

Depends on how many data you want to save.
And do you have something like a backup battery?
In my current project, I save some RFIDkeys to EEPROM when it has no internet connection and low battery, otherwise it just waits for internet connection.
Writing byte-by-byte isn't actually that difficult, you can use a struct to pack your bytes and then write the bytes of the struct to your memory.
Put it in a for loop, and it'll save them all.

In my opinion SD would be the best way because it is cheap, small, relatively fast and easily portable on a PC, using FAT (but it uses a lot of resources) or even raw; but then you have to use some more trick to get to the raw data from a OS, its not just "plug n read".
The SD library uses FAT under the hood, and it gives you a nice and easy interface. Just remember that SD works at 3.3V, and connecting them directly to arduino will break them fast, even if often not immediately.

SD would mean a bigger footprint though, right? a 1Mbit SO chip is pretty small but supporting an SD slot takes up a lot of space. I only use 3.3v arduinos now. :-)

well, you can use a microSD, they have the same interface. beat that :P
I normally buy microSD with adapter, and i use to solder directly on the adapter, so i can easily swap the card when needed (please pay attention to remove them when the micro is NOT writing. i use a "unmount button" or a temporized write every seconds, with a led that light up when writing)

Other than SD (see @lesto's answer), you can also store the data locally on your Arduino's EEPROM. You can store a byte at a time. The amount of storage varies from chip to chip, the AtMega328p that powers Arduino UNOs has 1kb. The eeprom is persistent over resets, I suspect not if you're reprogramming it, so think how you're going to get the data off before you start storing valuable info.
At 1kb, size is at a premium, so you probably don't want to use text strings, just the raw data. Remember that, if your chip resets, you will lose any memory variables with info about e.g. where you're up to. I would probably include some sort of checksum of each record, to test if the data is yours or not. I would include a counter or timestamp, so when you are starting up, you can read all memory to find the newest (valid) record; the next record is one greater, and at the next memory address. When you get to the end of the memory, restart at 0. If you store a one-byte counter, a one byte checksum, and 2 bytes of data, you can store 256 records. You could mark records off as you send them, or keep a counter in memory of which ones you have already sent - if your chip is reset, it may resend old records (very rarely), which your server would need then need to handle.
If using eeprom, try to spread your writes - you get a certain number of writes PER MEMORY LOCATION, so if you always write to address 15, then 15 will wear out before the others. I think I saw a reference to "100,000 writes", but am unable to find that now to confirm. 100,000 writes at 1 write per second to the same address will have your eeprom fail after about 27 hours; 4 writes per second spread over 1K will cause a fail after about 10 months.
Test what happens when you write past the end of memory - some possible scenarios include failed write, write to a different location (e.g. trying to write to address 1024+1 will write to address 1024), not writing at all and reading it back will return 0, 255, or another number (consistent or otherwise)
See http://arduino.cc/en/Reference/EEPROM on how to write to eeprom.
To find out how many bytes of memory your EEPROM has, use E2END. Addresses run from 0 to E2END, so E2END might be 1023 (0 to 1023=1024 bytes).

The reference to "100,000 writes" can be found in the ATmega datasheet: “The EEPROM has an endurance of at least 100,000 write/erase cycles.”


text:
Why is the atmega chip reset three times during programming?
I'm trying to understand the auto reset process and why a capacitor hooked up between DTR and Reset works so I ran it through my logic analyzer and I'm seeing the chip reset three times during the programming process. Does anyone know why it's done three times and not just once?
You can see in the picture the top pin is the DTR and the bottom two are attached to reset (digital/analog). When DTR drops low the reset pin does too for between 200-500us but it does it three times in around 1 second.

How are you programming it?

Using the Arduino IDE and and FTDI cable.

It does it to "force" a reset.
Historically, when you open the serial port on an FTDI interface, the DTR will automatically go LOW.  However, recently FTDI decided it'd be a good idea to change their driver so that when you open the port the DTR line doesn't go low - you have to manually tell it to go low.  But this is only on the FTDI official drivers.
If you have a driver that is newer than a certain date (no idea what date) then just running avrdude by itself on an FTDI interface may not work properly since DTR isn't being lowered.
To get around that Arduino have included a forced toggling of the DTR line as part of the programming sequence to make the target board reset.
But of course, if the driver is old enough, or not the "official" FTDI driver (i.e., you're in Linux for instance) then the lowering of the DTR by avrdude works fine.
So what you are seeing there is first a brief toggle of DTR by the IDE to force a reset, then avrdude opening the port and DTR going low, then finally the IDE toggling DTR again one last time to force a final reset.
And to me that says you're either not in Windows, or you have an FTDI driver while does toggle the DTR line automatically.
I also have a feeling that avrdude may also have started including manual control of the DTR line within it - so if avrdude is new enough, even with a new FTDI driver that doesn't automatically, you will still see the repeated action of DTR.
It's what we call belt and braces.  Use every method possible to get the board to reset, so no matter what you hardware and software arrangement the board has a very good chance of being reset into the bootloader.


text:
Store value in EEPROM to perform different actions on reset?
I want the same button to wake up (reset) and put it to sleep but this is hard if the button is tied directly to the rst pin. My thought was to read and store a value in EEPROM so tell the chip what mode we were in so it can perform the counter action. For example, on RST if the value is 0 the chip should wake up and do things. It would then set the value to 1. If the button is pressed again, the chip resets, reads there is a 1 and now just puts the chip into deep sleep after setting the value back to 0. Rinse, repeat.
Does this make sense? Will this work? Is there a better/easier way?

Makes perfect sense to me.

the answers to the three questions .... yes, yes, impossible to answer without a definition of "better" and "easier"

While it looks interesting as idea, IHMO you have keep in mind:

Include some code for button denouncing logic. Actually you will receive couple of “resets” during ~20ms during button press. Without denouncing you may end up with reset signal right at the moment you write to the EPROM. While EPROMs are pretty “solid” nowadays, it many not be good practice. One of potential solutions IMHO is to delay update EPROM with state switch for 20ms after boot, so it be done in stable state.
You may also consider to include electronic circuit to hold reset long enough to reboot the controller (it may also reduce bouncing).
EPROM has finite lifespan in terms of rewrite cycles, if your device turned on and off ~100 timers per day, it may die in a ~year.
Writing the EPROM usually consumes significant amount of energy, so it may reduce battery lifespan (if you use battery).

Probably more classic approach with sleep / wake up by button looks more reasonable, unless you have shortage of pins ;)

Totally agree with Serge.
To cover issues #3 and #4 of Serge's answer I recommend you to have a look at FRAM.
It has more durability with 10 trillions of write cycles.


text:
PID cooler temperature control
Hello Hello I am making a controller of a small cooler (dry ice) PID but Im not sure if I am using the indicated mosfet
Im trying with a NPN 222a
and my second option is IRFZ44
Which would be the best option?

#include <DallasTemperature.h>
#include <OneWire.h>

#define PWM 13   //-------------AquÃ definimos las constantes que se van a utilizar en el programa
const int analogin_potA = A0;

//Definiciones componentes
#define heater1 5   //TIP34c
#define sensor1 A2  //TMP36

// Variables globales
byte man_byte=0;
float Kc=1; //---- Constante proporcional del PID
float Taui=100000; //----- Constante integral del PID
float Taud=0; //----- Constante derivativa del PID
float T=0.5;  //------ Periodo de muestreo de la variable de proceso   // Ts
float Mk=0; //----ManipulaciÃ³n del PID actual
float Mk1=0; //----- ManipulaciÃ³n del PID del tiempo de muestreo anterior

float E=0; //----- Error actual
float E1=0;  //----- Error anterior
float E2=0; //------- Eerror 2 veces atrÃ¡s del tiempo de muestreo actual
float Ref_Temp=5; //-------- Referencia de la temperatura (Â°C)
float Temp=0; //----- Variable de proceso (temperatura)
//---------------- Constantes del PID digital ---------------
float BC1=0;
float BC2=0;
float BC3=0;
//----------------

void setup()   {
%Serial.begin(9600);
%Serial.write(Temp);
pinMode(analogin_potA, INPUT);
BC1=Kc*(1+(T/Taui)+(Taud/T));
BC2=Kc*(-1-(2*Taud/T));
BC3=Kc*Taud/T;
}

void loop() {   // Este es la funciÃ³n que se ejecuta cÃclicamente dentro del Arduino
Temp = analogRead(analogin_potA);
// AquÃ va la calibraciÃ³n del sensor para convertir los volts leidos en Â°C

//
E = Ref_Temp - Temp;

Mk=Mk1+BC1*E+BC2*E1+BC3*E2; // Esta es la ecuaciÃ³n del PID que calcula la manipulaciÃ³n actual (Mk)

// AquÃ estamos limitando el valor mÃ¡ximo y mÃnimo de la manipulaciÃ³n a 0-255
if (Mk > 255){
Mk=255;}
if (Mk < 0){
Mk=0;}
man_byte=Mk;

analogWrite(PWM, man_byte); //AquÃ mandamos la manipulaciÃ³n actual al pin generador de PWM (pin 5 del arduino)

//AquÃ recorremos la manipulaciÃ³n actual a la manipulaciÃ³n anterior, el error actual al error anterior y el error 2 veces anterior al error anterior.
Mk1=Mk;
E2=E1;
E1=E;

//AquÃ irÃa la comunicaci+on serial con la computadora para desplegar el valor de la temperatura y leer el valor de la referencia.
Serial.println("Temperatura_1");
    Serial.print(Temp);
    delay(1000);
//

}

which ever one that works without overheating ... you did not say what best option actually means and your post is not about arduino

Is "NPN 222A  supposed to be a 2N2222A NPN transistor?    If so, the IRFZ44's  60A limit can handle much higher current than the 2N2222's 600mA capability.   How much current do you want to drive through your Peltier?


text:
Need to operate 2 different sensors (MPU 6050 and Admp 401) simultaneously
I need to operate 2 different sensors (MPU 6050 and Admp 401) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.
Here are the sketches:
1.Code used for IMU (MPU-6050)
// CONNECTIONS
//Gyro - Arduino UNO R3
//VCC  -  5V
//GND  -  GND
//SDA  -  A4
//SCL  -  A5
//INT - port-2

#include <Wire.h>
//Declaring some global variables
int gyro_x, gyro_y, gyro_z;
long gyro_x_cal, gyro_y_cal, gyro_z_cal;
boolean set_gyro_angles;

long acc_x, acc_y, acc_z, acc_total_vector;
float angle_roll_acc, angle_pitch_acc;

float angle_pitch, angle_roll;
int angle_pitch_buffer, angle_roll_buffer;
float angle_pitch_output, angle_roll_output;

long loop_timer;
int temp;

void setup() {
  Wire.begin();                                                        //Start I2C as master
  setup_mpu_6050_registers();                                          //Setup the registers of the MPU-6050
  for (int cal_int = 0; cal_int < 1000 ; cal_int ++){                  //Read the raw acc and gyro data from the MPU-6050 for 1000 times
    read_mpu_6050_data();
    gyro_x_cal += gyro_x;                                              //Add the gyro x offset to the gyro_x_cal variable
    gyro_y_cal += gyro_y;                                              //Add the gyro y offset to the gyro_y_cal variable
    gyro_z_cal += gyro_z;                                              //Add the gyro z offset to the gyro_z_cal variable
    delay(3);                                                          //Delay 3us to have 250Hz for-loop
  }

  // divide by 1000 to get avarage offset
  gyro_x_cal /= 1000;
  gyro_y_cal /= 1000;
  gyro_z_cal /= 1000;
  Serial.begin(115200);
  loop_timer = micros();                                               //Reset the loop timer
}

void loop(){

  read_mpu_6050_data();
 //Subtract the offset values from the raw gyro values
  gyro_x -= gyro_x_cal;
  gyro_y -= gyro_y_cal;
  gyro_z -= gyro_z_cal;

  //Gyro angle calculations . Note 0.0000611 = 1 / (250Hz x 65.5)
  angle_pitch += gyro_x * 0.0000611;                                   //Calculate the traveled pitch angle and add this to the angle_pitch variable
  angle_roll += gyro_y * 0.0000611;                                    //Calculate the traveled roll angle and add this to the angle_roll variable
  //0.000001066 = 0.0000611 * (3.142(PI) / 180degr) The Arduino sin function is in radians
  angle_pitch += angle_roll * sin(gyro_z * 0.000001066);               //If the IMU has yawed transfer the roll angle to the pitch angel
  angle_roll -= angle_pitch * sin(gyro_z * 0.000001066);               //If the IMU has yawed transfer the pitch angle to the roll angel

  //Accelerometer angle calculations
  acc_total_vector = sqrt((acc_x*acc_x)+(acc_y*acc_y)+(acc_z*acc_z));  //Calculate the total accelerometer vector
  //57.296 = 1 / (3.142 / 180) The Arduino asin function is in radians
  angle_pitch_acc = asin((float)acc_y/acc_total_vector)* 57.296;       //Calculate the pitch angle
  angle_roll_acc = asin((float)acc_x/acc_total_vector)* -57.296;       //Calculate the roll angle

  angle_pitch_acc -= 0.0;                                              //Accelerometer calibration value for pitch
  angle_roll_acc -= 0.0;                                               //Accelerometer calibration value for roll

  if(set_gyro_angles){                                                 //If the IMU is already started
    angle_pitch = angle_pitch * 0.9996 + angle_pitch_acc * 0.0004;     //Correct the drift of the gyro pitch angle with the accelerometer pitch angle
    angle_roll = angle_roll * 0.9996 + angle_roll_acc * 0.0004;        //Correct the drift of the gyro roll angle with the accelerometer roll angle
  }
  else{                                                                //At first start
    angle_pitch = angle_pitch_acc;                                     //Set the gyro pitch angle equal to the accelerometer pitch angle
    angle_roll = angle_roll_acc;                                       //Set the gyro roll angle equal to the accelerometer roll angle
    set_gyro_angles = true;                                            //Set the IMU started flag
  }

  //To dampen the pitch and roll angles a complementary filter is used
  angle_pitch_output = angle_pitch_output * 0.9 + angle_pitch * 0.1;   //Take 90% of the output pitch value and add 10% of the raw pitch value
  angle_roll_output = angle_roll_output * 0.9 + angle_roll * 0.1;      //Take 90% of the output roll value and add 10% of the raw roll value
  Serial.print(" | Angle  = "); Serial.println(angle_pitch_output);

 while(micros() - loop_timer < 4000);                                 //Wait until the loop_timer reaches 4000us (250Hz) before starting the next loop
 loop_timer = micros();//Reset the loop timer

}

void setup_mpu_6050_registers(){
  //Activate the MPU-6050
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x6B);                                                    //Send the requested starting register
  Wire.write(0x00);                                                    //Set the requested starting register
  Wire.endTransmission();
  //Configure the accelerometer (+/-8g)
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x1C);                                                    //Send the requested starting register
  Wire.write(0x10);                                                    //Set the requested starting register
  Wire.endTransmission();
  //Configure the gyro (500dps full scale)
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x1B);                                                    //Send the requested starting register
  Wire.write(0x08);                                                    //Set the requested starting register
  Wire.endTransmission();
}

void read_mpu_6050_data(){                                             //Subroutine for reading the raw gyro and accelerometer data
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x3B);                                                    //Send the requested starting register
  Wire.endTransmission();                                              //End the transmission
  Wire.requestFrom(0x68,14);                                           //Request 14 bytes from the MPU-6050
  while(Wire.available() < 14);                                        //Wait until all the bytes are received
  acc_x = Wire.read()<<8|Wire.read();
  acc_y = Wire.read()<<8|Wire.read();
  acc_z = Wire.read()<<8|Wire.read();
  temp = Wire.read()<<8|Wire.read();
  gyro_x = Wire.read()<<8|Wire.read();
  gyro_y = Wire.read()<<8|Wire.read();
  gyro_z = Wire.read()<<8|Wire.read();
}

2.Code used for MEMS mic (ADMP401)
int mic = A0;               // A0 is the audio output of the pin, and since sound is analog, its connected to the analog pin in arduino
const int sampleTime = 2;   // sampling time for the input audio sound is 2ms
int micOut;

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

void loop() {
int micOutput = findPTPAmp();       // we use a PTPAmp function to find the peak to peak amplitude
   VUMeter(micOutput);
}

int findPTPAmp(){

   unsigned long startTime= millis();  // Start of sample window
   unsigned int PTPAmp = 0;
// the above two are 2 time variables to find PTP amplitude

   unsigned int maxAmp = 0;
   unsigned int minAmp = 1023;
// these 2 are the signal variables to find PTP AMplitude
// We basically try to Find the max and min of the mic output within the 2 ms timeframe
   while(millis() - startTime < sampleTime)
   {
      micOut = analogRead(mic);
      if( micOut < 1023) //to prevent erroneous readings; cause output can’t be greater than 1023
      {
        if (micOut > maxAmp)
        {
          maxAmp = micOut; //save only the max reading
        }
        else if (micOut < minAmp)
        {
          minAmp = micOut; //save only the min reading
        }
      }
   }

  PTPAmp = maxAmp - minAmp;
  double micOut_Volts = (PTPAmp * 3.3) / 1023; // Convert ADC into voltage formula ; 3.3 is the Vcc.

  //Uncomment this line for help debugging (be sure to also comment out the VUMeter function)
  //Serial.println(PTPAmp);

  return PTPAmp;
}

// Volume Unit Meter function: map the PTP amplitude to a volume unit between 0 and 10.
// Map the mic PTP Amp to a volume unit between 0 and 10.
// We use Amplitude instead of voltage to give a larger and more accurate range for the map function that we use next in the code.

int VUMeter(int micAmp){
  int preValue = 0;

  int fill = map(micAmp, 23, 750, 0, 10);

// val = map(val, 0, 1023, 0, 255);
val equals value of analogRead(0)
0, 1023 is the range of values that a reading from analogRead(0) could be.
0,255 is the range of values you are converting the value to.

  // only print the volume unit value if it differs from the previous value
  while(fill != preValue)
  {
    Serial.println(fill);
    preValue = fill;
  }
}

Hello, what exactly is your problem in doing this? Is it, that you don't know how to combine 2 sketches? The 2 sensors don't have anything in common (one is an I2C sensor, one is an analog sensor connected to the ADC), so I would guess this comes down to "how combine sketches". If yes, you might wanna look at this question, where there are given general instructions on how to do that


text:
Two ports on Uno with ethernet shield
I am making an Arduino mod-bus device and I want to make a webpage as well that will allow me to reset the unit if there is any issues remotely. To do this I would need the mod-bus to operate on port 502 and the webpage to operate on port 80. is it possible for the Arduino to support two ports? I am using an Uno with a Ethernet shield and the standard ehternet.h file with a Modbus library. Any suggestions or ideas?
 #include SPI.h
 #include VL53L0X.h
 #include Ethernet.h
 #include Modbus.h
 #include ModbusIP.h
 #include VL53L0X.h
 #include Wire.h

VL53L0X sensor;
EthernetServer server(80);

//Modbus Registers Offsets (0-9999)
const int SENSOR_Hreg0 = 100;

//ModbusIP object
ModbusIP mb;

short ts;

void setup() {
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  byte ip[] = { 192, 168, 1, 177 };

  Wire.begin();
  mb.config(mac, ip);

  // Add SENSOR_Ireg register - Use addIreg() for analog Inputs
  mb.addHreg(SENSOR_Hreg0);

  ts = millis();

  //Sensor setup
  sensor.init();
  sensor.setTimeout(500);
  sensor.startContinuous();

  //remote reset
    pinMode(13, INPUT);
    digitalWrite(13, LOW);

   // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Ethernet WebServer Example");

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

}

void loop() {

  mb.task();

    //Webpage
    // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin

            client.print("Distance Measures ");
            client.print(sensor.readRangeContinuousMillimeters());
            client.print("mm");
            client.println("
");
            client.print("Filter Count:");
            client.print(-2.2*sensor.readRangeContinuousMillimeters()+404);
            client.println("
");
          }
          client.println("");
          break;
        }

      }

  //Modbus
  if (millis() > ts + 100) {
    ts = millis();

     mb.Hreg(SENSOR_Hreg0, sensor.readRangeContinuousMillimeters() );

     }
}}

Edit:
Note: The issue seems to lie somewhere in with the sensor, because when I run it with out have the sensor code in there is no problem but when I add it the issue starts again.

to test, run two instances of a web server ... one on port 80 and one on port 502 .... access the webpage using two devices so that you are serving a page to two different devices at the same time .... if that works, then try adding some modbus test code (if such a thing exists) instead of a webserver on port 502

I tried that and it didn't take the ip address for the webpage but took it for the modbus, and when I added a second instance of the ip to see that would work it errored out.

EthernetServer has nothing to do with IP. Servers should  run on a different ports on the same IP.

try to print the IP before server.begin()

Same result when I moved the Serial.print("server is at ");
Serial.println(Ethernet.localIP()); before the server.begin()

I don't have the sensor, but the rest of the sketch works.

move the modbus refresh out of the if (client) condition
mb.begin() calls Ethernet.begin(). Do not repeat it in setup()
move client.println(""); break; inside the if block before it
copy the rest of the detection of empty line from the WebServer example
stop() the client after response
change type of ts to unsigned long

I've added to code I am using, I have port 80 assigned and the modbus library sets a port 502 for the modbus. When I use this I can ping the device but Modbus and web communication is not there.

When i check the serial monitor, I planned to remove it once this was working, it reports the IP address as 0.0.0.0

but it is not the IP address of the EthernetServer, it is the IP of the shield. the ip is reported wrong or the shield did not connect. try to connect with DHCP.

when I comment out all the webpage parts it works fine, and I can even ping the device with the code in using the set ip.

I removed Ethernet.begin() and tried it out and it still didn't work, I can still ping the device but getting Modbus data or the webpage still doesn't work.

Let us continue this discussion in chat.


text:
Arduino Time Clock Accuracy
I'm currently trying to create an Arduino time clock by using the PJRC Time library (http://www.pjrc.com/teensy/td_libs_Time.html). I know that since most of the Arduino boards are running with a 16MHz clock and a single resonator, the time can become "out-of-sync" after a certain period of time.
However, I was wondering if anyone has an idea about the accuracy of the Time library when used on the Arduino DUE with a 84MHz clock. I've been testing it out and so far, the clock has been kept in sync for a few hours. Thanks!

The limitations of accuracy of the library depend on accuracy of the crystal. Let's say you have a crystal that is off by .5 second every hour, great for short term, but if you expand that over a year it is over 1 hour off by that time. If you want something to keep an accurate time over a long period I suggest a real time clock (they still have inaccuracies), a GPS module, or an internet connect to sync with.

@jamolnng Thanks for your answer. Do you know the accuracy of the crystal on the Arduino DUE or where I could go about finding it?

The best accuracy you are going to get is 84MHz, when they make, or cook, the crystal they can only make it to a certain degree accurate, also the environment of the crystal (temperature, humidity, etc.) play a role in the accuracy of it.

@jamolnng So can I expect a higher accuracy with the 84MHz crystal rather than the 16MHz crystal on most other Arduinos?

Not necessarily because if the 84MHz and the 16MHz both have the same amount of inaccuracy per clock cycle then the 16MHz clock would have a smaller inaccuracy at the end because it did less cycles. The frequency of the crystal is more for how fast the processor is

"The best accuracy you are going to get is 84MHz" - that doesn't make much sense to me!

He was looking for the exact frequency of the clock crystal including its defects. Appears it is to late to edit...

The Due has an RTC but no pins to add an external battery to keep it running.

The limitations of accuracy of the library depend on accuracy of the crystal. When they make, or cook, the crystal they can only make it to a certain degree accurate, also the environment of the crystal (temperature, humidity, etc.) play a role in the accuracy of it. Let's say you have a crystal that is off by .5 second every hour, great for short term, but if you expand that over a year it is over 1 hour off by that time. If you want something to keep an accurate time over a long period I suggest a real time clock (they still have inaccuracies), a GPS module, or an internet connect to sync with.
For further information look at the wikipedia article on quartz crystals
The use of a 84MHz crystal versus a 16MHz crystal will not necessarily improve the accuracy of the Arduino clock since the frequency of the crystal is more an indicator of processor speed than accuracy. The accuracy of the Arduino clock is primarily dependent on the accuracy of the crystal oscillator.
EDIT: I am no expert on crystal oscillators so if you see anything wrong here please let me know

Re-visiting an old question... as I found a very informative blog post
that sheds new light into it. But let me first provide some context
before giving the link.
When assessing the quality of a time base, be it a crystal, a ceramic
resonator or a lab-grade frequency standard, there are two notions that
should be distinguished:

accuracy: how close is the frequency of the time base to its
nominal value
stability: how much does that frequency drift over time

Accuracy is important if you want your clock to give correct time “out
of the box”. However, if you are willing to spend some time calibrating
your clock, then you do not really care because you are going to
calibrate out any inaccuracy you measure. jfpoilpret's answer provides
an example of a “manual” calibration protocol, which is by necessity
quite lengthy. If you can borrow a GPS module with a 1PPS output, the
calibration could be done in a few seconds.
Stability is a more serious issue. If the frequency of the time base
drifts randomly, this will defeat your calibration efforts. Essentially,
the calibration will tell you how fast or slow your clock is running
right now, but it will not allow you to predict how fast or slow it
will run in the future.
Here is the promised link: Arduino clock frequency
accuracy, by Joris van Rantwijk.
What Joris did is measure the accuracy and stability of an Arduino Pro
Mini (clocked off a ceramic resonator) and an old Duemilianove (quartz
crystal). From my perspective, the main takeaways are:

both clocks are grossly inaccurate, thus both would need user
calibration in order to be used as timepieces
the quartz crystal of the Duemilianove has decent stability, better
than 1.5e-8 at 6 h averaging time
the stability of the Pro Mini’s ceramic resonator is pathetic, more
than two orders of magnitude worse than the crystal, which makes it
essentially useless as a time piece

Here is his Allan deviation plot, which measures clock instability
as a function of observation time:

(source: jorisvr.nl)
Although this study has some limitations (only two boards were tested,
and the observation time is too short), it is well thought and very
informative. I encourage you to read it in whole.

Quartz crystals’ frequency changes slightly with temperature. If you can control the temperature it helps keep the frequency stable.

The best way to know the accuracy of the resonator of your board is to measure it yourself.
To do so, you can use the Arduino millis() function of your board and write a small sketch that will:

enable you to set the beginning time for measuring time drift (eg with a simple push button); you will trigger the button based on an accurate time base.
then repeatedly call millis() until at least 120h ("arduino hours", that would be around 5 days) have elapsed
display a signal when those 120h have elapsed (your sketch should probably "warn" you before the exact time has been reached so you get ready for measure)
when the 120h have elapsed, check your reference time based (used in step 1.) and check how much time have elapsed (should be 120h +/- epsilon)
once you know the drift of your clock, and provided your board will run in the same environental conditions (temperature mainly) of your measure, you can use it in your sketches to adjust the millis() value every hour or so.

Of course, this approach is far from perfect as it requires human intervention and thus will create additional time drifts during measurements, that's why you need to measure your clock time drifts over a long period.
An improved approach would be to connect a high accuracy RTC clock (the accuracy must be chosen based on the accuracy you need for your application) to your board and adapt the sketch so that it automatically calculates the drift. Once you got the time drift you can do the same as step 5 above in your sketches, and disconnect the RTC clock from your board.
Important points:

measure the time drift on the board that will need clock adjustment later on (if you have several boards, you must measure one drift per board)
ensure the stability of the environment in which your board will be used

Finally, if you really need high accuracy, then definitely connect an external clock source (e.g. RTC clock, GPS, NTP) to your board and use it as a SyncProvider for the PJRC library.

Your average system clock crystal will be off by several tens ppm (parts per million. They are great for stable and accurate timing of signals, but dramatic for keeping accurate time. Without special provisions the system crystal may be off by several seconds per day.
The solution is to use a proper Real Time Clock, driven by what is commonly known as a 32768Hz watch crystal. These crystals are easily a factor 10 better in accuracy. You can either set up your own oscillator that interrupts the main processor and keep count in your Arduino sketch or you find a RTC breakout board.
Two random examples that pop up in Google with search terms "RTC breakout":

http://www.cutedigi.com/breakout-board/ds1302-rtc-breakout.html
https://www.sparkfun.com/products/10160


text:
How can I rename how my Arduino shows up on the computer?
I have a clone of a Mega 2560, and the Chinese manufacture apparently had a broken shift key. To my annoyance, whenever I connect it to my computer it reads, arduino compatible mega 2560. With my extreme annoyance with slightly misspelled or incorrectly capitalised English, it has been very distracting to me.
However, the reason that I'm asking this question is for more than how to rename it to be capitalised. Think of how many projects could be simplified by this! Or for many Arduinos, you can label they physically and then rename them Arduino #1, etc. so you can tell which port it is on using device manager. If you designed a product with Arduino, then you can even rename it to your product name.
I would imagine that there would be an easy way to do this by reburning the firmware to the [Insert USB chip model #### here]. I've seen it done for keyboards on the Uno, so I would imagine that you could modify it somehow.

Wait, where does this name come up? If it comes up in the Computer view on Windows (not sure on a Mac), couldn't you just right click, click properties, and then rename the device?

How do you expect this to be answered when you don't state which USB chip is utilized?  With a "compatible" board it could be any of the options, and the programming process (if any) depends entirely on which one.

This string is contained in the FT232 USB to UART interface chip and the manufacturer has released the FT_PROG tool to reprogram it. But do take note of the warning on their website: "PLEASE NOTE - The use of some of these utilities by an end user may result in a device being rendered useless". Another word of warning is to ensure there is only one device connected with an FTDI-chip.
Here is a screenshot of the MProg tool:

In that link you posted they claimed they were the "Future Technology Devices International Ltd", yet their design included a VGA cable. Oops! Where do I edit this string? Is it just not visible because no device is connected?

@AnnonomusPerson For usage you'll have to read the docs for the tool and I am pretty sure the device must be attached to read the current config.


text:
How can I sense when someone is sleeping with my Arduino?
Ignore the stalker-like title.
I am thinking about creating a project with Arduino that can sense you sleep habits, when you're asleep, and how much you sleep. It would be convenient to not have to turn it on/off at night; it should know how to do this.
Some ideas that I have:

Motion sensor
Breathing patterns (if an Arduino microphone could even pick that out... I would be surprised if it could)
A RTC clock could assist in deciding It's midnight. Usual, Steve isn't asleep at this time on Fridays. He's probably not sleeping now. It won't always be there to help you, but you might be able to try to get more accurate results this way

How can I accomplish this? (Extra points for some sort of algorithm that can tell dozing off from a deep sleep.)

Probably one way to detect sleeping state of someone is to measure heart pulses, and detect when pulses get below a threshold (different for each individual but that could be "guessed" by the system after a few days run). With this, you could even see if the person had some nightmares (pulse increasing) :-) That is intrusive (pulse sensor) but is also the only way to know about the sleep of ONE person when 2 are in the same room.

Neurosky EEG brainwave sensor apparently works fine with Arduino. Measure frequency. Up to 4Hz --> NREM sleep. Up to 8-9Hz ---> REM sleep. Above 8-9 Hz up to 16Hz ---> awake, but eyes closed and relaxed. Above that ---> awake.

I actually did something like this, using a PIR Motion sensor.
The motion sensor is good enough to detect a person turning in their sleep, and my simple algorithm just counts movements per minute and when its over a threshold (found by trial and error), it sounds the alarm to wake you up.

The image above represents my body movements during a night. The spikes represent a high movements/minute.

Here we see after about 30 minutes body motion was minimal. This suggests I was in a deeper stage of sleep during that time.
The spike at 250 minutes (around 4:30AM) is when I woke up only to
  realize I could sleep for couple of hours longer. I recall the time
  being 4:38 when I looked at my clock and I was already facing it. This
  means I turned around to face the clock but actually "woke up" 8
  minutes later to see the time, and then turned back around (indicated
  by the shorter spike at 265).
The data suggests I was not able to sleep very well (compared to the
  time period between 30 and 240 minutes) after waking up once and
  finally got up at 400 minutes (7:00AM), when I shut everything down.

Here are a couple of posts from my blog that have a lot more information.

Body Movement During Sleep
Intelligent Alarm Clock Hardware

Thanks for the links on your blog. One question I have is how do you decide that someone isn't reading a book or watching TV while doing something while on a bed? It is some good data. Did you project need to be turned off when you got into bed?

Mine is an alarm clock so it only needs to detect movements during the half hour before the alarm goes off. So that's the only time that matters. The overnight graph is just to collect data to figure out how many movements/pin is considered "light sleep, easy to wake"

do you have any suggestions on how to detect whether it's just idle or if it's sleep? I might have to do some of my own data...

I'd see how the graph looks for sleep vs various activities. Weigh that with the time of day (more likely to be sleeping 3am than reading). Hard to say without collecting lots of data.

To help you with your googling, this technique is called actigraphy. Wikipedia has a decent intro.  Some signal processing is apparently necessary, but nothing too difficult or beyond the capabilities of an arduino.    To classify sleep stages (including awake), I would look at academic papers on the subject.  One thing to decide is whether you want to put the sensors on your bed (easy, low accuracy), or on your wrist (harder, more accurate, and you can measure body temperature, ambient light, and skin conductivity).

I am also searching for how to do it and this is the only relavent link I have been able to find. Unfortunately the blog links have expired. If the author could explain how the measurements were taken. E. G. If PIR sensor digital or analog measurements were taken?

@SubhaniMinhas I don't have the original code, but you can use the wayback machine to read the archived copy links. To answer your specific question, the measurements were taken with a Windows Powershell script that wrote a timestamp to a file every time the arduino serial port transmitted data. The PIR sensor is a digital sensor that changes the stage of a pin when motion is detected. It counts the number of movements in a time period.