text:
Serial Monitor listing rapidly
I am using an infrared sensor and a flex sensor to read values from the serial monitor in arduino, however after maybe ten seconds or so it seems the serial monitor breaks and the printed values start to print out rapidly. Does anyone have any suggestions on why this might occurring. Any information would be highly appreciated.
Thanks.
int previousMillis = 0;

long interval1 = 300;
long interval2 = 350;

void setup() {

    Serial.begin(9600);
}

void loop() {

    unsigned long currentMillis = millis();

    if ( currentMillis - previousMillis >= interval1 ) {
        previousMillis = currentMillis;

        Serial.println( "TIMER IS DONE!" );

        int val1 = analogRead(0);
        Serial.print("Sensor Value 1 is ");
        Serial.println(val1);
        delay(5);
    }
    if ( currentMillis - previousMillis >= interval2 ) {
        previousMillis = currentMillis;

        int val2 = analogRead(1);

        Serial.print("Sensor Value 2 is ");
        Serial.println(val2);
    }
    delay(10);
}

why the two separate intervals?

Two separate intervals are for different sensors, photocell and infrared.

If it's a case you're simply wanting to test sensor 1 precisely every 300ms and sensor 2 at precisely every 350ms, then you'll have to monitor two previousMillis values. I've taken it to mean you wanted to test sensor 2 50ms after sensor 1 as per my code below. Alternatively you could use real timers and interrupts! That's a nice little exploration for you (but unnecessary unless you just want to have a little fun) :)

I'm not completely sure what is going wrong, but you're having two intervals using the same interval variable. So, make a previousMillis1 and previousMillis2, one for each interval.

I hate to start with "I hate delays", but I hate delays :)
Why have you included them? If you want your outputs to be slower, increase your intervals.
Use a state machine instead:
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;

unsigned long interval1 = 300;
unsigned long interval2 = 350;

#define LEDPIN  13

int state = 0;
// 0 = waiting for sensor one interval
// 1 = another 50ms for sensor two

void setup() {
    currentMillis=millis();
    previousMillis=currentMillis;
    Serial.begin(9600);
    pinMode(LEDPIN, OUTPUT);
    digitalWrite(A0, HIGH); // internal pullups
    digitalWrite(A1, HIGH); // internal pullups

}

void loop() {
    currentMillis = millis();
    if ( state == 0 )
    {
        if ( currentMillis - previousMillis >= interval1)
        {
            int val1 = analogRead(0);
            Serial.print( currentMillis );
            Serial.print(" Sensor Value 1 is ");
            Serial.println(val1);
            digitalWrite(LEDPIN, HIGH);
            state = 1;
        }
    }
    else
    {
        if ( currentMillis - previousMillis >= interval2)
        {
            int val2 = analogRead(1);
            Serial.print( currentMillis );
            Serial.print(" Sensor Value 2 is ");
            Serial.println(val2);
            digitalWrite(LEDPIN, LOW);
            state = 0;
            previousMillis = currentMillis;
        }
    }
}

This way, test 2 will only be conducted 50ms after test 1 and then previous millis is reset
edit: I fixed the interval test regarding overflow (which you had correctly in the first place)
edit2: (I'm having too much fun with this)
assuming you want each test conducted at specifically the interval requested (ie sensor 1 every 300ms and sensor 2 every 350ms), I have come up with v2 (and removed the state machine, since it's just not needed)
unsigned long previous1 = 0;
unsigned long previous2 = 0;
unsigned long currentMillis = 0;

unsigned long interval1 = 300;
unsigned long interval2 = 350;

const int LEDPIN = 13;

void setup() {
    currentMillis=millis();
    previous1=currentMillis;
    previous2=currentMillis;
    Serial.begin(9600);
    pinMode(LEDPIN, OUTPUT);
    digitalWrite(A0, HIGH);
    digitalWrite(A1, HIGH);
}

void loop() {

    currentMillis = millis();
    if ( currentMillis - previous1 >= interval1)
    {
        previous1 = currentMillis;

        int val1 = analogRead(0);
        Serial.print(currentMillis);
        Serial.print(" Sensor Value 1 is ");
        Serial.println(val1);
        digitalWrite(LEDPIN, HIGH);
    }
    if ( currentMillis - previous2 >= interval2)
    {
        int val2 = analogRead(1);

        Serial.print(currentMillis);
        Serial.print(" Sensor Value 2 is ");
        Serial.println(val2);
        previous2 = currentMillis;
        digitalWrite(LEDPIN, LOW);
    }
}

edit: including some sample output to indicate a working state:
188609 Sensor Value 1 is 15
188659 Sensor Value 2 is 14
188959 Sensor Value 1 is 14
189009 Sensor Value 2 is 15
189309 Sensor Value 1 is 15
189359 Sensor Value 2 is 14
189659 Sensor Value 1 is 14
189709 Sensor Value 2 is 1017
190009 Sensor Value 1 is 15
190059 Sensor Value 2 is 1002
190359 Sensor Value 1 is 14
190409 Sensor Value 2 is 1013
190709 Sensor Value 1 is 14
190759 Sensor Value 2 is 1019
191059 Sensor Value 1 is 15
191109 Sensor Value 2 is 1004
191409 Sensor Value 1 is 14
191459 Sensor Value 2 is 1019
191759 Sensor Value 1 is 15
191809 Sensor Value 2 is 15
192109 Sensor Value 1 is 14
192159 Sensor Value 2 is 15
192459 Sensor Value 1 is 14
192509 Sensor Value 2 is 14
192809 Sensor Value 1 is 15
192859 Sensor Value 2 is 15
193159 Sensor Value 1 is 14
193209 Sensor Value 2 is 16
193509 Sensor Value 1 is 14
193559 Sensor Value 2 is 15
193859 Sensor Value 1 is 1005
193909 Sensor Value 2 is 1021
194209 Sensor Value 1 is 1021
194259 Sensor Value 2 is 1003
194560 Sensor Value 1 is 1004
194609 Sensor Value 2 is 1020
194909 Sensor Value 1 is 1020
194959 Sensor Value 2 is 1004
195259 Sensor Value 1 is 15
195309 Sensor Value 2 is 1001
195609 Sensor Value 1 is 14
195659 Sensor Value 2 is 1022
195959 Sensor Value 1 is 15
196009 Sensor Value 2 is 998
196310 Sensor Value 1 is 15
196359 Sensor Value 2 is 1019
196659 Sensor Value 1 is 15
196709 Sensor Value 2 is 1002
197009 Sensor Value 1 is 14
197059 Sensor Value 2 is 15
197359 Sensor Value 1 is 14
197409 Sensor Value 2 is 15
197709 Sensor Value 1 is 15
197760 Sensor Value 2 is 13
198060 Sensor Value 1 is 14
198110 Sensor Value 2 is 15
198410 Sensor Value 1 is 15
198460 Sensor Value 2 is 14

this is assuming you want test2 50ms after test1

Thanks for an additional solution, however, I am still getting the issue where only one sensor value displays. Also, the value doesn't get reset over a certain duration, it's static.

Do you mean you're only getting data for sensor 1 and never sensor 2? can you give a sample output of what you are getting? possibly include state and millis values to further diagnose.

You're enabling my procrastination here... I'm setting up a board for a "quick" (LOL) test...

my appologies, I had several bugs in that code. I was hand coding without an ide... try the edited code above, should be better :)

me too, I've had the arduino packed away for far too long... IDE reinstalled, board running... Now I can get back to some of the other projects I've shelved for so long :)

I do have a question and forgive me if it seems obvious, but what is the LED relaying. Is it reacting to the sensors. I seem to be getting a repetitive pattern.

That was for my own testing and just shows when each state activates (it's a more interesting pattern in v2), you can simply remove all that, and the internal pullups if you have them in circuitry (or otherwise not needed)

You are doing math with 2 different types.   One is long and the other is an int.  So, eventually the long will always be lager than the int and the test will always be true.  (A 32 bit long can count up to over 2 billion.  A 16 bit int can only count up to about 32 thousand.)
Also, the method millis() is of type "unsigned long".  So change all your variables to match this type.
Also note that when the millis() timer overflows and start over your program may perform unexpectedly.  Since this rarely happens it may not concern you.

Thank you! This works however, now the monitor won't print both values at the same time. Instead it prints sensor val1 until I stop the program. If I comment out the first if statement with the sensor 1 value and keep the sensor 2 statement the monitor will print val2.

Because it's always the first test that is executed first and previous millis is reset within it

If the types are right, and the test is performed correctly (it is), then the millis() overflow will cause no issue. In fact, in this kind of situation I may use unsigned int rather of unsigned long just to save some memory.


text:
RC522 RFID reader doesn't read NTAG216 chip
I have an RFID-RC522 module based on the MFRC522 chip. This chip is described in the datasheet as supporting "ISO/IEC 14443 A/MIFARE and NTAG" protocols. I have wired it up to an Arduino Uno using the recommended wiring in the documentation for the MFRC522 library I'm using. I have a sketch that (among other things) polls for presence of a new card:
void setup() {
    lcd.setup ();       // initialise LCD display
    SPI.begin();        // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
    lcd.println ("Found new card");
    ...
}

This sketch correctly detects the presence of the card that was supplied with the module (I believe this is a Mifare Classic card) but does not detect my NTAG216 implant. Does anyone have any idea why it might be failing to find the implanted chip?

please provide more of your code, from what you've provided all I can see is that your LCD will constantly print "Found new card" over and over again... plus, you've got a return in the main loop???

@Madivad that code would be enough to print "Found new card" when any compatible card is brought close to the reader - perhaps the card itself is faulty?

Hi @JaromandaX the problem is that the print statement is outside the if conditional but within the main runtime loop which will just continually print Found new card. Found new card. Found new card. ad infinitum

@Madivad you'd be correct if the conditional return was absent, however, it is not absent, and therefore you are incorrect

@JaromandaX I get your point, and I stand corrected. The return is executed if there is no new card and execution stopped, but for as long as a card is present, the println will just keep repeating. Which the OP is not getting to. I get that now. I hadn't considered a return in the main loop before, nor did I understand the implications of it. Until I just did some experiments :)

My apologies for reviving such an old post, but was this ever solved. I am having the exact issue. Any assistance will be appreciated.

I got my RFID kit (RF522) just this week, but I haven't had a chance to play with it yet - nor do I have an NTAG216 implant. But I remember when I was researching them seeing a couple of posts that had to do with "Authentication errors". The problem for you (maybe) is that they were in Python rather than C:
https://github.com/mxgxw/MFRC522-python/issues/24
and Cotix's link
https://github.com/mj3052/MFRC522-Pi
Give them a lookover and see what they can tell you.
The problem with the PICC_IsNewCardPresent() function is that it gives a Yes/No answer, not a "Yes, but there's an error". In that case it would also return false. But the other code may give you a clue - you'll have to delve into the library...

Hmm.  AIUI I should be able to read the UID of the chip without authenticating (otherwise how would you know which passcode to use to authenticate with in a system with multiple cards?), but as you suggest I'll have a look through the library and see if there's a way of finding out about errors while detecting cards. It's a shame that this seems to be the only available arduino library for this chip and AFAICT almost entirely lacks documentation :(

Having investigated this further, this doesn't sound like the right answer.  Authentication requires the chip to be in 'active' state before you can begin the authentication process, and the PICC_IsNewCardPresent method is supposed to find cards that are in the 'idle' state and put one of them into 'active', so must be able to handle locating the card without authenticating first.

source: Stack Exchange

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

authors: Алексей Канев

sort: votes


text:
If - else statement in Arduino
I'm starting to learn how to use Arduino and I tried to make this code, which is just a simple if else statement; what I want to make is when the input is LOW, LED 1 is HIGH and LEDs 2,3 are LOW, and when the input is HIGH, the LEDs 2,3 are HIGH and LED 1 is LOW. I wrote this code but when I put the switch in LOW, instead having just like what I intended, all the outputs are HIGH.
I try changing the output and I checked all the wiring to the LEDs so my mistake is in the code.
Could you guys tell me what's wrong with the code?
int switchstate = 0;
void setup() {
  pinMode (13,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(3,INPUT);
}

void loop() {
  switchstate = digitalRead(3);
  if (switchstate == LOW) {
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);
  } else {
    digitalWrite(11,LOW);
    digitalWrite(12,HIGH);
    digitalWrite(13,HIGH);
  }
}

Can you post a schematic of your circuit.

do you check voltages ?
When input is HIGH, does it give right answer ?

What type of switch, a push button or a slide switch?

You say your circuit is correct, yet by looking at your code,  the leds should never be lit at the same time.. You do not debounce the input in software, but it should not matter as if the input flickered, it should change the state of all the leds. Review the circuit again.

Pull-up/-down in place?

Your problem is definitely not in the code.

First of all, whoever change this to this forum is amazing. Thanks. I will upload the schematic as soon as I got home.

Your code doesn't seem to be the problem. Contrary to what you are saying I think your problem is most definitely in your hardware setup.
Most likely, your digitalRead doesn't register a HIGH input, so it doesn't get 5V. Instead of digitalRead, go for analogRead(A0). So change your circuit and attach it to pin A0.
Use serial.println(switchstate) to print the results to the serial monitor and then decide what your top value (HIGH) and bottom value (LOW) for detection will be. Perhaps include a pull down resistor as well on the A0 pin.

Thanks, I will try that as soon as I got home. One more thing thou, how the output generate all high even I put the wrong wiring. is the arduino have NC thing when there is no logic in it will just outputing high ?

I don't know what you are using to create this HIGH input. Switchstate also is an integer so it could be possible your thing that is supposed to create a HIGH output, isn't creating a HIGH output and as such Switchstate is filled as an integer, not a boolean (booleans have two states: true or false, or HIGH or LOW). Experiment.

To debug this, as Len has suggested I would recommend putting in some Serial.println("Debug info") commands into your code. This will confirm that you are programming the Arduino as you expect, and that the Arduino is running.
To do this simply include a Serial.begin(9600) command in your setup block, and then a Serial.println("Some text") wherever you want to check if you are reaching a certain part of the code. You can then read these messages via the serial monitor (which you can get to from Tools->Serial Monitor in the Arduino IDE).
For hardware debugging if you have a multi-meter available I would check that you are getting 0V/5V on digital pin 3 when you expect (i.e. when you are / are not pressing the button). Also, to check your LEDs are working, and connected to the output pins you think they are, write a script which just scrolls through them with a short delay (See the Blink example under File->Examples->01.Basics->Blink for an example of how to do that).

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


text:
Why send my Arduino sometime Hex and sometimes the wrong?
Hi i have an Arduino mega 2560 i send data from the Arduino over USB to PC. That works when i test a simple Serial.print("Hello"); but that is not that what i need. I send a timestamp as a longe Value and the databyte as a short Value. When i send the timestamp as BIN like that:
      //Initialisisation

const int RX = 0;
const int TX = 1;
const int RX1 = 19;
const int TX1 = 18;
unsigned long currentMillis;

void setup()
{
  pinMode(RX, INPUT);   //Readpin for USB
  pinMode(TX, OUTPUT);  //Writepin for USB
  pinMode(RX1, INPUT);  //Readpin for bus
  pinMode(TX1, OUTPUT); //Writepin for für bus

  Serial.begin(38400);   //open interface for USB
  Serial1.begin(4800);   //open interface for bus

  while (!Serial & !Serial1 &! Serial2)
  {
    ;//wait for serial port connect.
  }
}

void loop()
{
  //Ask if the timestamp over 8 hours, when yes,
  //send the time to the pc and reset currentMillis.
  currentMillis = millis();
  if (currentMillis >= 28800000)  //milli() 8 hours is a 4 byte  timestamp 28.800.000 millisec.
  {
    unsigned long timestamp = currentMillis;
    sendBinaryTime(timestamp);
    currentMillis = 0;
  }//end if

  //if the businterface available, read a byte
  //and send it with the timestamp to the PC.
  //If the businterface not available send an error.
  //short incomingByte = Serial1.read();
  //sendBinaryValue(incomingByte);
  if(Serial1.available()>0) //if the bus (serial1) available?
    {
      short incomingByte = Serial1.read(); //read the next byte from _rx_buffer
      sendBinaryValue(incomingByte);
      sendBinaryTime(currentMillis);   //sendBinary send a long over the bus
    }//end if
}//end Loop()

//Methods for sending long values

void sendBinaryValue(short incomingByte)
  {
    int temp = (incomingByte & 0xFF00)>>8;
    Serial.println(temp, HEX);
    temp = (incomingByte & 0x00FF);
    Serial.println(temp, HEX);
    return;
  }

void sendBinaryTime(unsigned long currentMillis)//send milliseconds after every byte
{
  int temp = (currentMillis & 0xFF000000)>>24; //send 16 bit of the low value
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x00FF0000)>>16;      //send 16 bit of the high value
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x0000FF00)>>8;
  Serial.print(temp, BIN);
  temp = (currentMillis & 0x000000FF);
  Serial.print(temp, BIN);
  return;
}

All is fine i haven´t any error. But i want the timestamp as DEC so i have changed the code to:
       void sendBinaryValue(short incomingByte)
 {
   int temp = (incomingByte & 0xFF00)>>8;
   Serial.println(temp, HEX);
   temp = (incomingByte & 0x00FF);
   Serial.println(temp, HEX);
   return;
 }

void sendBinaryTime(unsigned long currentMillis)
{
 int temp = (currentMillis & 0xFF000000)>>24;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x00FF0000)>>16;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x0000FF00)>>8;
 Serial.print(temp, DEC);
 temp = (currentMillis & 0x000000FF);
 Serial.print(temp, DEC);
 return;
}

Now when i look on the serial monitor i get an error.
Here you can see it:

I send an A as ASCII sign that must be Hex 41 and i receive a Hex 5 but why? When i send the timestamp as BIN i get the 41 and haven´t any problem.
I hope someone can help me with friendly wishes sniffi

Please, post a testable code, with setup() and loop(), so we can reproduce your problem. I tried the obvious and got “41”, as expected, which proves you have a problem in a piece of code you are not showing to us. How do you expect us to help you with that?

I have fix it, i think perhapes it is an already known problem.

I have found several problems with your program, although they may not
be related with your primary problem:
while (!Serial & !Serial1 &! Serial2)

You mean while (!Serial || !Serial1 || !Serial2), although this is
only useful with virtual serial ports, like on the Leonardo. On the
mega, all of these ports are real hardware ports.
void sendBinaryValue(short incomingByte)

The way you name the parameter is misleading: a short is not a byte,
it's two bytes.
int temp = (incomingByte & 0xFF00)>>8;

You are bit-shifting a signed number, which is going to do a sign
extension. This is probably not what you want.
Serial.print(temp, DEC);

You are printing several numbers one after the other with no separator.
This is going to cause ambiguities: you cannot know whether "345" means
"3 45" or "34 5".
Finally, I don't get the purpose of your functions. Why don't you just
print the numbers like this?
Serial.println(incomingByte, HEX);
Serial.println(currentMillis);

Ok i have delete the while(!Serial & !Serial1 & !Serial2) . I have changed the ringbuffer to 16bit (my short) because i want handle flags at the high byte. Can i send a short and a long over Serial.print?

Yes, you can print() numbers from 8 to 32 bits, signed or unsigned.

Ok i have change all now the bug is fixed thanks for all


text:
How to use same sketch on two different computers in two different directories
I have the same sketch one that I use at my desk and in the lab, but they are in different directories on the different computers.  This means that I have to change the paths to the includes which I have to fixup every time I transfer back and fourth.  Is there a way to put in a #ifdef that I can set at the start of the build that would include correct path.

Please edit your question and show the different forms of the includes.  Also say what operating system is on the lab system and on the desk system.   What directories are you allowed to rename on each system?

To do this I usually use a github repository

Having two copies of the code will result in disaster at some point.  Create a shared folder on a server, or your desktop, and place all the code there and then point both machines at the share.

Open preferences.txt in C:\Users\YourUserName\AppData\Roaming\Arduino and change the path of sketchbook.path=C:\Users\YourUserName\Documents\Arduino to sketchbook.path=YourDesiredPath.


text:
Using micros() to measure analogRead() time varies based on Serial.print location?
I'm trying to use micros() to measure the time it takes to execute an analogRead() cycle, but am having some issues.  Originally, I just printed out the measured time for the analogRead() right after doing the subtraction, but I wanted to change that to printing out all of the time values for the 100 loops at once.  When I print the start times, end times, and values both in the if statement (right after calculating them) and at the end, the values printed are the same.  I'm not sure if they're accurate because they fluctuate a lot within those 100 tests.  For example, some of these measured times consecutively are 216, 97, 153, 34, 89, 145, 27.  I put the ADC in freerun mode, so I figured it could be normal for that.  However, when I don't print the start times, end times, or values immediately after calculating them and instead try to print them in the else if statement, it gives a stream of values that are all either 407 or 408.  If I print "Test" instead of the values right after calculating them, it still gives the (I'm assuming) correct values that vary a lot, not the 407s.  If, instead of printing them in the if statement, I print them just in the general loop (currently commented out) and the else if statement, they are still the varying maybe-correct values.  I assumed that even if the values aren't being printed, they're still being stored in the array correctly.  I don't understand why printing something unrelated right after storing the values would change them.  Any ideas?
Thanks
    int sensorPin = A1;    // select the input pin for the potentiometer
    int ledPin = 13;      // select the pin for the LED
    int sensorValue[1000];  // variable to store the value coming from the sensor
    int ind = 0;
    int starts[1000];
    int ends[1000];
    int vals[1000];
    int stopprint = 0;
    int i = 0;
    int countto = 100;

    void setup() {
      // declare the ledPin as an OUTPUT:
      Serial.begin(57600);
      analogReadResolution(12);
      pinMode(ledPin, OUTPUT);
      Serial.println("ready to begin");
        analogReadSetup(A1);
      for (i = 0; i < 1000; i++) {
        starts[i] = 0;
        ends[i] = 0;
        vals[i] = 0;
      }
    }

    void loop() {
      // read the value from the sensor:
      if (ind < countto) {
      starts[ind] = micros();
    //  delay(50);
      sensorValue[ind] = analogRead(sensorPin);
      ends[ind] = micros();
      vals[ind] = ends[ind] - starts[ind];
    //  Serial.println("Test");
        Serial.print(ind);
        Serial.print('\t');
        Serial.print(starts[ind]);
        Serial.print('\t');
        Serial.print(ends[ind]);
        Serial.print('\t');
        Serial.print(vals[ind]);
        Serial.print('\t');
        Serial.print('|');
        Serial.print('\t');
      Serial.print('\n');
      Serial.print('\r');
      ind++;
      }
      else if (stopprint == 0) {
        Serial.println("~~~~~~~~~~~~~~~~~~~~~~~~~");
        for (int j = 0; j < countto; j++) {
    //        Serial.println(j);
            Serial.print(starts[j]);
            Serial.print('\t');
            Serial.print(ends[j]);
            Serial.print('\t');
            Serial.print(vals[j]);
            Serial.print('\n');
            Serial.print('\r');
            stopprint = 1;
        }
      }
      else if (stopprint == 1) {
        while(1);
      }
    //  Serial.print(ind-1);
    //  Serial.print('\t');
    //  Serial.print(starts[ind-1]);
    //  Serial.print('\t');
    //  Serial.print(ends[ind-1]);
    //  Serial.print('\t');
    //  Serial.print(vals[ind-1]);
    //  Serial.print('\n');
    //  Serial.print('\r');
   }

Also, I'm using the Arduino Zero if it makes a difference.

Not sure if it is related to your problem but... if I were to try such a
measurement, I would use local variables, like
unsigned int start = micros();
int value = analogRead(sensorPin);
unsigned int end = micros();
sensorValue[ind] = value;
starts[ind] = start;
ends[ind] = end;
vals[ind] = end - start;

This way you would be measuring the time it takes to call both
analogRead() and micros(), and very little more. If you do something
like
sensorValue[ind] = analogRead(sensorPin);

then you are also measuring the time taken by the pointer arithmetic and
the memory access.
I generally program AVR-based Arduinos. These have a load-store
architecture, where saving to a local variable costs essentially
nothing, as the variable is typically assigned a CPU register by the
compiler. Saving to a global takes more time because of the RAM access.
I have no experience with ARM-based Arduinos, like the Zero, but I
believe it's also a load-store architecture, thus the same
considerations should probably apply.
Update: I tried the following experiment on my Uno:
#define PRINT_WHILE_READING

#define READ_COUNT 100

void setup() {
    unsigned int starts[READ_COUNT];
    unsigned int ends[READ_COUNT];
    unsigned int vals[READ_COUNT];

    Serial.begin(57600);
    Serial.println("Ready to begin");

    // Take the readings.
    for (int i = 0; i < READ_COUNT; i++) {
        starts[i] = micros();
        analogRead(A1);
        ends[i] = micros();
        vals[i] = ends[i] - starts[i];
#if defined(PRINT_WHILE_READING)
        Serial.print(i);
        Serial.print('\t');
        Serial.print(starts[i]);
        Serial.print('\t');
        Serial.print(ends[i]);
        Serial.print('\t');
        Serial.println(vals[i]);
#endif
    }

#if !defined(PRINT_WHILE_READING)
    // Print them now.
    Serial.println("All data taken");
    for (int i = 0; i < READ_COUNT; i++) {
        Serial.print(i);
        Serial.print('\t');
        Serial.print(starts[i]);
        Serial.print('\t');
        Serial.print(ends[i]);
        Serial.print('\t');
        Serial.println(vals[i]);
    }
#endif
}

void loop() {}

If PRINT_WHILE_READING is defined as above, I get times that fluctuate
between 108 and 116 µs. If I comment out the line
#define PRINT_WHILE_READING, I get mostly 116 µs and,
occasionally, 124 µs. In both cases, the first reading takes longer
(208 and 212 µs respectively).
The fact that the first reading takes longer is explained in the
datasheet: the ADC does some initializations in that first reading. All
measured times are multiples of 4 µs because that is the resolution
of micros().
Now, trying to understand the differences between the two cases:

With PRINT_WHILE_READING the times are shorter on average. This is
because the numbers are not stored in RAM, as the compiler figured
out the arrays starts[], ends[] and vals[] are not really
needed and optimized them away. When PRINT_WHILE_READING is not
defined, I can see the “store in RAM” instructions in the generated
assembly.
With PRINT_WHILE_READING the numbers fluctuate more. I guess this
is due to the printing through the serial port taking a variable
amount of time depending on the numbers being printed, and thus
creating timing inconsistencies.

The last point deserves some explanation. The ADC is clocked by a
prescaler that divides the frequency of the main clock by 128. This
gives a clock period of 8 µs. When an ADC conversion is started,
the ADC waits for the next rising edge of its clock, which can take
anywhere between 0 and 8 µs, then it does the conversion in
13 cycles of its clock. This means the whole process can take
anywhere between 104 and 112 µs depending on the exact time the
conversion is started relative to the phase of the prescaler. If the
conversions are started at irregular intervals, you expect to see
roughly 8 µs of fluctuation in the measured times.
All these observations have been done on an Uno, which is based on an
AVR clocked at 16 MHz. I know the Zero is quite different. You will
have to look at the datasheet of the ATSAMD21G18 to see whether anything
of the above can be extrapolated to the Zero.

I tried changing it to your format and nothing changed.  Thanks for the idea though.  If you have any more ideas about what could be causing it I'd really appreciate it!

If you understand ARM assembly, you could disassemble the program to see the code generated by the compiler. That's what I would do on an AVR to try to understand that kind of issue, but I cannot read ARM assembly.

That's more or less what I've been doing for about an hour now, but I haven't really found anything that would explain it

@Alexandra: I've updated the answer with some experiments done on my Uno. Maybe some of these results could be extrapolated to the Zero.

Thanks for the information.  I'm now just trying to get the time down from what the analogRead() timing is.  The datasheet says it should take ~100 microseconds per read (on the Arduino Zero at least which I'm using), but by driving pins high to measure it, it's still taking about 400 microseconds.  I've put the ADC in freerun mode and tried changing the prescaler but it doesn't even get close to 100 microseconds.  I saw posts of people trying to get it below 100 us previously, but I'm not even reaching that baseline and I'm not sure why.  Any ideas? (also posted on other comment, sorry)

@Alexandra: No idea, sorry. I think at this point only someone with good knowledge of that particular chip could help.

If you have access to a digital scope, try bracketing your code with changes to the state of an output pin. print() has a lot of moving parts, some (like buffer size, interrupt implementation) will vary with various Arduinos as others have noted. I am mostly using ARM Cortex M4 on Teensy 3.2. If I want to time something really precisely I will drive an I/O pin (with digitalWrite()) at the beginning and end of what I want to time. This has super fast execution. You could use more than one pin to see two things at once. Then, look at them on an oscilloscope. Trigger on the starting edge of the most important signal. Adjust the time scale to encompass the active pin level time. With a digital scope you can set persistence to infinite and then you can see the variation on the trailing edge of the pulse. You can move the digitalWrite points around in your program until you see what is causing the variation. millis() and micros() are 32-bit values so on an 8-bit AVR that is multiple machine cycles to access. A single digitWrite is usually one machine cycle so it is quick even on a slowly-clocked 8-bit AVR. Once you find the place where most of the variation occurs you at least have a quantified smoking gun to tell you what details to excavate further.

A call to digitalWrite() on an AVR takes anywhere from 78 to 108 cycles, depending on the pin number and the value written. That's why, for time-critical tasks, people resort to direct port access: something like PORTB |= _BV(5) compiles into a single machine instruction and executes in two cycles.

On the other hand, for precise timing, you can set the 16-bit timer to run at F_CPU and read it directly, which only takes 4 cycles. If you want to be accurate to the cycle, you will have to look at the generated assembly to see what exactly you have between the timer reads.

Thanks for the information.  I'm now just trying to get the time down from what the analogRead() timing is.  The datasheet says it should take ~100 microseconds per read (on the Arduino Zero at least which I'm using), but by driving pins high to measure it, it's still taking about 400 microseconds.  I've put the ADC in freerun mode and tried changing the prescaler but it doesn't even get close to 100 microseconds.  I saw posts of people trying to get it below 100 us previously, but I'm not even reaching that baseline and I'm not sure why.  Any ideas?


text:
ESP 01 - reset settings to default values
I set up communication between Arduino UNO and ESP 01 module. ESP replied to AT commands, but sometimes I got result from ESP uncompleted or with wrong characters, so I tried to set AT+IPR=9600, I didnt receive any output to this command and after reboot I only can see random characters on every baudrate, blue diode on ESP shines all the time. Is there any way how I can reset ESP 01 to default settings? Tried to set RESET pin to GND, but it didnt help.
I use remote power supply 3,3V/1A
Pins connected:
Vcc = external power supply 3,3V
GND = GND (interconnected bot Arduino and power supply GND)
Tx = Arduino Rx(changed pin to 11 by SoftwareSerial)
Rx = Arduino Tx(changed pin to 10 by SoftwareSerial)
CH_PD - 3,3V

reflashing will reset it

Current ESP-01 firmware versions do not have an AT+IPR command. If you're trying to change the ESP's baud rate to use it with SoftwareSerial, the command to do so (in recent versions of the firmware) is: AT+UART=9600,8,1,0,0 for 9600 baud, 1 stop bit, no parity, no flow control.
The full syntax is: AT+UART=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>, where <databits> is the number of data bits per frame, 5,6,7,or 8; <stopbits> is 1, 2, or 3 for 1, 1.5, or 2 stopbits (respectively); <parity> is 0, 1, or 2 for None, Odd, Even (respectively); and <flow control> is 0, 1, 2, or 3 for None, RTS, CTS, RTS and CTS (respectively). Most serial communication and devices that most of us will ever see will be 8 data bits, no parity, and 1 stop bit, abbreviated as "8N1". Flow control is sometimes used, but often it is contained in the data stream itself, such as sending Ctl-S and Ctl-Q from the keyboard to manually stop and resume incoming data transmission.

While this technically is not an answer, I can highly suggest the ESP 8266 Arduino library. This way you can program in the Arduino IDE and upload to the ESP module. It's so much faster and efficient than AT commands and because you can see the code in the IDE, you have a better overview of what is happening in the code.
https://github.com/esp8266/Arduino


text:
Arduino + ultrasonic rangefinder behaving unexpectedly
I'm using an HC-SR04 ultrasonic rangefinder to control the frequency at which an Arduino pin turns on and off, with the output going via a 1/4" jack plug into my computer's audio interface. (i.e. it's a simple audio oscillator that responds to gestures). This is the code (based on that given here):
#define trigPin 10
#define echoPin 12

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(9, OUTPUT);

}

void loop() {

  float duration, distance;
  digitalWrite(trigPin, LOW); // Sends a 2 µs LOW signal to the trigPin
  delayMicroseconds(30);

  digitalWrite(trigPin, HIGH); // Sends a 10 µs HIGH signal to the trigPin
  delayMicroseconds(30);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); //Defines the duration variable

  digitalWrite(9, HIGH); //square wave oscillator
  delay(0.1+duration*0.01);
  digitalWrite(9, LOW);
  delay(0.1+duration*0.01);
}

Pin 9 is the output, and sounds roughly as expected, but what's confusing me is that making any kind of gesture other than very slow ones (i.e. if the distance isn't changing very slowly) causes the output to stop completely for a few seconds, then start again, as if something is overloading and then resetting. What am I doing wrong?

@DaveTweed: I reckon this shouldn't have been migrated. The problem is probably in the hardware specification. See my answer.

I do not really understand the behaviour of your program, but I would
like to point out a couple of points that may be problematic:

Your comment says “Sends a 10 µs HIGH signal to the trigPin”, just as
the program you based yours on, yet you have a 30 µs delay. If
this extra delay makes you miss the rising edge on the echo pin, then
pulseIn() will believe it is seen the previous pulse, and it will
wait for the next raising edge before starting its measurement. Since
that next rising edge will never happen, pulseIn() will eventually
time out after one second. This is probably the silence you are
hearing.
Your sound frequency may not be what you expect, because the time
needed to run through the loop is not only the two calls to
delay(), but also the time taken by pulseIn() and the various
delayMicroseconds(). You should have more consistent timings if you
use the tone() function instead of trying to bit-bang the sound.

Your comments don't match your timing delay values and the datasheet specifies a 10 µs pulse. You're giving it 30 µs but you might get away with it.
I'd look at how often you're triggering the device.

Figure 1. Don't trigger the device more frequently than 40 times per second.


text:
Which Protocol to use to control WiFi (ESP8266) enabled Led Light
I am developing a Wifi based Led light (Got Inspired from Philips hue, Lifx). I have little knowledge about web server, clients, Web protocols. I will be using ESP8266 as Controller cum WiFi module.
There are two ways to control Led light over WiFi.

Locally
Remotely

Android/iOS app will be handling all the control part.
Which protocols can I use to control Led light, locally? HTTP or Websockets?

Note :- The speed is critical, android/iOS app can send around 50-60 values per second.

Also, which protocol should I go with if Led light is controlled Remotely.? So far, MQTT seems reliable. Any suggestion?
Kindly help!

why not use a single protocol for both local and remote - far simpler code - MQTT should suffice

What if internet is not working, in that case as well, Local transmission of data will not happen, because MQTT works over Internet. I should have the option of controlling it locally.

MQTT works over a network, doesn't have to be "the internet" if you have a local MQTT server

But I see what you mean. My setup is more flexible because all my IOT servers are within my LAN - still externally accessible, but all under my control and I have a router that loops back requests for external IP from within the LAN ... so, it just works with one single domain, I don't have to do anything different for external vs internal access

UDP :D
Seriously though, ESP8266 is limited in resources, AND you want to send 50-60 updates a second, just UDP will be the most lightweight, and you won't run out of connections (5 I think on ESP), because UDP has no connection state.
This is what was used here to control a RGB strip: https://github.com/cnlohr/esp8266ws2812i2s , it just listens for UDP packets on port 7777, and each packet contains rgb values, one byte for R,G,B, etc.
MQTT is nice, but it doesn't work well for 60hz updates, I Tried :D
It resulted in un-smooth animation, and frames out of order.


text:
Quadrature Encoder:Interrupts: Reset Count
I'm working on a quadrature encoder(with a 500ppr codewheel) with a Channel A, B and an Index pulse output.  Using an Arduino Mega I'm counting the number of pulses on Channel A on the rising edge. The code for counting pulses on channel A using an interrupt is straight forward enough with plenty of sources and examples out there to work with.
I've used the the code below to the count the pulses(in an increasing manner). What I'm trying to figure out is how I can reset the overall count using a second interrupt. The second interrupt is invoked when the Index channel pulses high.So in another words when the index channel pulses to indicate a full rotation on the code wheel the main count will reset to zero
#define CHA 2
#define CHB 3
#define CHI 19

volatile int count = 0;
volatile byte INTFLAG1 = 0;

void setup()
{
  pinMode(CHA, INPUT);
  pinMode(CHB, INPUT);
  pinMode(CHI,INPUT);

  Serial.begin(9600);
  Serial.println(count);

  attachInterrupt(0, flag, RISING);

 }

void loop()
   {

       if (INTFLAG1)
             {
               Serial.println(count);
               INTFLAG1 = 0; // clear flag
             }

    }

void flag()
    {
       INTFLAG1 = 1;
       if (digitalRead(CHA) && !digitalRead(CHB))
               {
                count++ ;
               }
     }

Is it possible to implement the reset of the main pulse count with a second interrupt as described?
From what I've read interrupts work at the same level of priority- so I'm thinking there might be a problem here to implement this approach as the interrupts would have to be nested
Any help is appreciated if anyone has done anything like this using interrupts or can point me in  the right direction.

Is it possible to implement the reset of the main pulse count with a
  second interrupt as described?

Yes, and it's quite straightforward. Your index signal goes to pin 19,
which is interrupt 4 on the Mega, so you can simply
attachInterrupt(4, reset, RISING);

in setup(), where reset() is a function that resets the counter:
void reset()
{
    count = 0;
}

I'm thinking there might be a problem here to implement this approach
  as the interrupts would have to be nested

In general you do not want to nest interrupts. If an interrupt is being
serviced when a second interrupt fires, the second one will just wait
for the first one to finish. This approach works fine as long as you do
not have interrupt handlers that take too long to execute.

Very Straightforward and works accordingly.Thanks for the information.


text:
NeoPixel Blink/Glitch
I'm having this weird effect where my NeoPixel will blink/glitch after every cycle of a fading sketch. I'm not certain whether the issue is hardware or in my code. The blinking only occurs during the if statement portion of the code and not during the else statement which blinks red. I have tried multiple sources of power, 5V 2amp, 9V 1 amp, 12V 1amp and a Mac Usb and the problem persists on each power supply.
Any suggestions or ideas would be greatly appreciated.
#include <Adafruit_NeoPixel.h>
#include <DistanceGP2Y0A21YK.h>

#define PIN 6
#define PIXEL 16

Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL, PIN, NEO_GRBW + NEO_KHZ800);

DistanceGP2Y0A21YK Dist;
int distance;
int R = 0;
int G = 0;
int B = 0;

void setup() {
  strip.begin();
  strip.show();
  strip.setBrightness(127);

  Serial.begin(9600);
  Dist.begin(A0);
}

void loop() {
  distance = Dist.getDistanceCentimeter();
  Serial.print("\nDistance in centimers: ");
  Serial.print(distance);
  delay(2); //make it readable

  if (distance > 10) {

    for (R && G && B; R < 150 && G < 150 && B < 150; R++ && G++ && B++) {
      for (int i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(R, G, B));
        strip.show();
        delay(1);
      }
      delay(2);
    }

    // fade off
    for (R && G && B; R > -1 && G > -1 && B > -1; R-- && G-- && B--) {
      for (int j = 0; j < strip.numPixels(); j++) {
        strip.setPixelColor(j, strip.Color(R, G, B));
        strip.show();
        delay(1);
      }
      delay(1);
    }

  } else {

    for (int j = 0; j < 256; j++) {
      for (int i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, strip.Color(255, 0, 0));
        strip.show();
      }
      delay (1);

      //blink off
      for (int j = 64; j > 0; j--) {
        for (int i = 0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, strip.Color(j, 0, 0));
          strip.show();
        }
        delay (2);
      }
    }
  }
}

Pick a brace style and stick with it. You'll find that other people can read your code that way.

for (int j = 0; j < 256; j++) {

  ...

  //blink off
  for (int j = 64; j > 0; j--) {
    ...

Notice that you are re-declaring the variable j.

Thanks for all the responses however I diagnosed the problem and figured out the fix. The problem comes from my for loop where I use a boolean expression for (R && G && B;. Rather the values should be initialized to 0 and look like  for (R = G = B = 0;


text:
Why do I get negative voltages for a PWM waveform?
I used my Arduino Uno's pin 3 to generate a PWM output. The code is:
void setup() {
  // Put your setup code here, to run once:
}

void loop() {
  analogWrite(3, 180);
}

I connected the output directly with a oscilloscope.
And the output waveform is shown below:

I found it's weird that the minimum voltage is negative! And with the duty cycle increasing, both the maximum voltage and minimum voltage decrease.
Why does it behave in such a way?

Oh my god! It's due to the setting of the oscilloscope. I reset it and now it's  works normally.

But I still don't know which setting is not right...Can you guys help me?

There is no need to have the analogWrite call in loop() - it only needs to be called once (the hardware automatically generates the PWM signal - no software is involved). It can and should be moved to setup().

At first you had the scope AC (Alternating Current) coupled.  Then you switched it to DC (Direct Current) coupled.
AC coupling is used to remove the DC component of a signal.  It places a large capacitor between the probe and the internal amplifier.  This is used, for instance, if you want to see a small signal with a large DC offset.  But it can also attenuate and / or alter signals that are low in frequency.
When a PWM signal is AC coupled to an oscilloscope, an interesting phenomenon occurs.  As the duty cycle goes from a minimum (almost always off) to a maximum (almost always on) the DC component of the PWM signal changes.  Since the DC component is blocked by the AC coupling, the PWM signal appears to move lower on the screen as the duty cycle increases.
DC coupling is where there is no coupling capacitor between the probe and the internal amplifier.  Everything comes through.  For digital electronics where the signal travels a small distance from 0 to 5 volts or from 0 to 3.3 volts, this is the best way to use the scope.

Incidentally - you see how the top and bottom of the waveform are sloping down and up slightly? This is indicative of the charging and discharging of the AC coupling capacitor by the low frequency component of the waveform.


text:
How to send data from arduino to Temp Controller for setting temp?
I send data from arduino by method following.
Configure the value : byte message[ ];
#include <SoftwareSerial.h>
#define RX 2
#define TX 3
int incomingByte = 0;

SoftwareSerial mySerial(RX, TX);

void setup()
{
  pinMode(5, OUTPUT);

  Serial.begin(9600);
  mySerial.begin(9600);
}

void loop()
{
  incomingByte = Serial.read();

  if (incomingByte == 's')
  {
    digitalWrite(5, HIGH);
    byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
    mySerial.write(message1, sizeof(message1));
  }
}

It works. But I want to input from "Serial monitor" to set the temperature.
It does not work when input from "Serial monitor".

You're not writing any data to incomingByte and you're not detecting if data is sent towards the Arduino over serial.
You should change your void loop() into this:
void loop(){

  //Detects if something is sent over serial.
  if(Serial.available() > 0){

    //reads the byte and puts it into the incomingByte variable
    incomingByte = Serial.read();

    //below is your old code
    if (incomingByte == 's') {
      digitalWrite(5, HIGH);
      byte message[] = {0x01, 0x06, 0x00, 0x01, 0x02, 0x58, 0xD8, 0x90} ;
      mySerial.write(message1, sizeof(message1));
    }
  }
}

When you're using the serial monitor to send data towards the Arduino, also make sure the baudrate you use is the same as the Arduino's. In this case you set your baudrate to 9600 Serial.begin(9600).

Thank you. And I can send hexadecimal from "serial monitor" into the variable "byte message[ ]" ?

Yes and no. As far as I know, the serial monitor connection already sends data as HEX but it is converted automatically on both ends. So, sending HEX would actually be encrypted to HEX, sent to the Arduino, decrypted to ASCII which still gives you the original HEX value. But, I honestly don't know for sure. You should experiment, it's quite easy to make a HEX converter as well.

No, the serial monitor just sends what you type (typically ASCII) as is. No encoding is automatically applied.

@TW_JM: You can send HEX from the serial monitor, but you will have to convert the data to binary in the Arduino. That could be done with the strtol() function from avr-libc.

authors: คำผาน ขี้ดื้อ


text:
Which pins of an Arduino UNO can be used as Tx and Rx pins for connecting to GSM GPRS SIM 900A
I am using Arduino UNO and SIM 900A. Pins 0 and 1 are used as TX and RX. Is it possible to use any other pins?

SoftwareSerial... Google GSM shield and Arduino, how then did you have the SIM module working in your other question?

The best choice for serial communications is obviously the HardwareSerial object, Serial, on pins 0 & 1.  However, it is really dedicated to the USB connection (via the onboard Serial-to-USB adapter).  There are ways to connect other devices to these pins, but it is an advanced topic, and should not be attempted by beginners.
The second best choice would be pins 8 & 9, because AltSoftSerial requires those pins.  It is very efficient and reliable.
After that, any other pins can be used with one of these two software serial libraries:
NeoSWSerial is less efficient than AltSoftSerial, but much more efficient than SoftwareSerial.  It only supports baud rates 9600, 19200 and 38400, but it does support simultaneous TX and RX.  I maintain this library.
If you must use a different baud rate, SoftwareSerial is the last choice.  It blocks interrupts for long periods of time and can interfere with other libraries.  It cannot transmit and receive at the same time.


text:
I have four servos connected to an arduiono uno and I cannot control them
I am making a simple bipedal robot. I have four 9g servos connected to my uno. Whenever I try to even do the simplest command, like move right foot 45 degrees it does not work properly. I have tried on my second Uno and i have the same result.
My program for testing the servos:
#include <Servo.h>

Servo myservo;

void setup(){
myservo.attach(6);
}

void loop(){
 myservo.write(45);
}

Each servo wire is attached to a breadboard where they all share power and ground from the arduino. Each servo wire then has another wire going to pins 3,5,6 and 9.
Does anyone know what the problem is and what I can do? Thanks

Maybe it's your wiring. Maybe it's the servos. Maybe four servos are too many for a single Uno to power. Please show your schematic.

Powering one micro-servo through the +5V pin of the Uno should be OK, and I would expect the program you posted to work. Powering four of them may be too much, especially if they are somewhat loaded.

Please let us know how the +V and 0V connections to the servos are made. Ideally they should be connected to an external battery or something similar.

An Arduino is not capable of powering four servos. Power them externally, but make sure the ground of the Arduino and servos is connected.

This has done nothing. Also I believe an arduino can power four servos but I tested it anyway.

Could you share your current setup of the servos and the Arduino?

Have you even tried powering the servos externally?

I don't think this answer should have been marked down - the arduino's regulator really isn't suitable for directly supplying power to that many servos as Len has said, partly due to electrical noise etc.

@Len yes I have tried powering the servos externally

With the grounds of the servos and Arduino connected? Because then I really don't know why it wouldn't work, unless your Arduino is already fried or something.

Keep in mind that you may also be limited by the USB power supply.  By definition that power source can cut you off at 500mA.  Also, servo current demand is hard to figure out.  As others have pointed out, you should be able to control 1 "unloaded-small" servo using the Arduino Uno's on board linear 5 volt regulator.  However, from your picture, you are only using the USB port.  This mean that you are not using the internal 5 volt regulator and that you are relying directly on what ever your are plugged into to provide 5 volts.  continued in next comment...

... So, given you have swapped around Arduino Uno boards and servos (you have swapped around servos, right?),  you should now swap out the USB power source.  Note: According to this schematic, there is a 500mA fuse in line with the USB 5 volt power line on the Arduino Uno.  So be careful not to exceed this.

I strongly advise against using the Arduino Uno to power your servos. The maximum current of the VCC and GND pins is 200 mA according to their official documentation. You can go over a bit, but 500 mA? That's just asking for a failure in your Arduino device.
Power the servos from an external power source, connect the grounds of the servos and the Arduino and you're good to go.

OK thanks everyone but I am still unsure how to properly power the servos externally, could you explain how. Secondly what power should I supply? 9v?

Depends on your servo. Mostly it's 4.8V, but sometimes 6 or 12. Too much volts also fries the servos, so you need a voltage regulator or a 5V external power source (like a phone charger).
Then you just split the VCC to the VIN of the Arduino and the servos. Then you connect all the grounds. That's basically all. But make sure you have the right voltage for your servos, you can find this information in the datasheet.

@Len: The 200 mA you are quoting is the absolute maximum for the Vcc and GND pins of the ATmega328P. It is not a limit of the Arduino. The current you source from the Arduino's +5V does not go through the ATmega's Vcc pin, thus that limit is irrelevant.

You're completely right. I didn't even know that. A quick search shows that the max values are between 500mA and 1A. So, it might actually be possible to power multiple servos, albeit it's still a risk.

As others have said, the Arduino cannot drive 4 servos - my experience is that it can have problems powering one if you try to move it too often due to the voltage drop caused by the high current consumption.  When you move a servo the power consumption rises considerably.  A large (220uF or more) capacitor near he servo can help, but even so, by far the best option is to supply the servos from a separate supply.
If the Uno resets when you try to move the servos (especially multiple times per second) then the power supply is most likely your culprit.


text:
Serial communication between arduino and raspberry pi works once, then stops working
I'm using a Arduino Uno Rev 3 connected over usb to a Raspberry Pi Modell B+ running Rasbian.
Here ist the arduino code:
int input = 0;
String command = ""; // beinhaltet den aktuellen befehl
int Action = 1;

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

void loop() {
  if (Serial.available() > 0)
  {
        input = Serial.read();
    char currentChar = input;

    if(currentChar  == '!') // frage nach trennzeichen
    {
      Serial.println(command);
      //Serial.write(Action);
      Action = command.toInt();

      command = ""; // befehl wieder leeren
    }else
    {
      command = command + currentChar ; // falls noch kein trennzeichen vorhanden, erweitere kommando
    }
    }
}

Here is the Raspberry Pi code (in python)
import serial
from time import sleep as sleep
ser = serial.Serial('/dev/ttyACM0',9600)
s = [0]
while True:
        ser.write(b'2!')
        a =  ser.read(1)
        print a
sleep(2)

It always works if once after the code was uploaded to the arduino, but if I stop the script on the pi and restart it it stops working. What is the problem here?

Does the PI close the serial port as it exits?  If it doesn't can it open it again?

It works on my PC running Ubuntu, although it prints tons of CR and LF. You may have noticed that you are overflowing the Arduino's input buffer.

@EdgarBonet how do I prevent the input buffer from overflowing?

Speak slowly, e.g. by moving the sleep(2) inside the loop. You may also want to read the whole answer (3 bytes) in each iteration.

You do know that the Uno resets, when you create a new serial connection to it, right?

You might find this interesting about buffers on both sides of a Nano connected to a Raspian system running a Python data logger, using just a regular USB programming cable between the two:
https://arduino.stackexchange.com/questions/11710/does-data-came-on-serial-port-store-for-some-time

"It always works if once after the code was uploaded to the arduino...."
Whenever you you reset the arduino the link between the arduino and the rasperry pi is broken momentarily thus causing the code on the raspberry pi to hang/ffreeze and not responding/ showing any valid results.
Try giving a keyboard interrupt by ( Ctrl + Z ) and restart the python script and that should work just fine!


text:
Atmega8 with Arduino bootloader - wrong serial characters
I recently flashed bootloader of Arduino to Atmega8. Unfortunately I stumbled on a problem I can't solved.
I am testing SerialEvent example on Atmega8. I modified it but started debugging it on my code (I think the same problem stops SerialEvent example from working).
I think the Atmega8 reads the characters sent through serial wrongly. That's why SerialEvent 'if' condition doesn't work also. Because it never gets '\n' symbol (it receives it but wrongly interprets it).
boolean prevState = true;
boolean OnOff = false;
boolean stringComplete = false;
String inputString = "";
String OnString = "on\n";
String OffString = "off\n";

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

    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
    }

    // reserve 200 bytes for the inputString
    inputString.reserve(200);

    DDRD |= 0b00001100;
    PORTD |= _BV(PD2);

    // synchronization info for RPi
    Serial.println("ARD - OK\n");
}

void loop() {
    // turn on
    if (OnOff == true && prevState == false){
        PORTD |= _BV(PD2);
        prevState = OnOff;
    }
    // turn off
    if (OnOff == false && prevState == true){
        PORTD &= ~_BV(PD2);
        prevState = OnOff;
    }

    if (stringComplete) {
        Serial.println(inputString);
        // clear the string:
        inputString = "";
        stringComplete = false;
    }
}

void serialEvent() {
    while (Serial.available()) {
         // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
        Serial.println(inputString);
        if (inChar == '\n') {
            stringComplete = true;
            Serial.println("test\n");
        }

        if (stringComplete && inputString.equals(OnString)){
            OnOff = true;
            Serial.println("Turning on.\n");
        }
        else if (stringComplete && inputString.equals(OffString)){
            OnOff = false;
            Serial.println("Turning off.\n");
        }
    }
}

I tested a lot of behaviors. Below I attach one of the tests from Realterm:

First I reset the board - it responded with 'ARD - OK\n' - expected behavior.
Then I sent 'on\n' and it responded with two lines but the characters aren't the same as 'on\n'.
Then I sent 'test123\n' but once again got wrong characters.
It prints multiple lines because it sends the string in which it accumulates the data every time SerialEvent() is fired.
Also sending for example variabl OnString works ok.
I really don't know why is it acting like that... Help would be appreciated :).

Does a simple “echo” program work? E.g. void loop(){if(Serial.available()) Serial.write(Serial.read());}.

Same behavior. It sends string variable normally but returns gibberish. It seems like there is problem with reading then.. ?

I can't understand your answer: there is no string variable in the simple echo program above. Can you try another terminal emulator?

I just added one simple variable to test it. My bad I didn't say it specifically. I tried Realterm and built in Arduino terminal. I don't think another one will bring different results.

Gibberish usually means wrong baud rate, but those seem to match between the arduino code and realterm.

How do you have the ATMega8 connected to your PC?

Through USB to TTL dongle.

Try changing the stop bits to 2; this increases the time between characters.

You have chosen the wrong build configuration which mismatches your hardware.
An ATmega8 with an 8 MHz oscillator works just fine, but all timing aspects of your code must be complied based on knowledge of that clock rate. If they are built for 16 MHz, then everything clock related will take twice as long as intended, for example baud rates will be half of what was intended.
In the Arduino world code is built for a clock rate specified in the chosen boards.txt file entry or in a dropdown menu for recent versions and boards with multiple clock variants. So the answer is that you have chosen the wrong build configuration for your hardware.

Ok I found a solution (rather workaround).
I uploaded the same program to Arduino Uno. It worked perfectly. I transplanted the Atmega328 from Uno to breadboard. Still worked BUT the Atmega328 is using external 16Mhz crystal (which I added to the breadboard).
So what if I uploaded bootloader for 16Mhz external crystal on Atmega8?
It makes it work properly.
So in short:
Atmega8 with 8Mhz internal oscillator doesn't work properly.
Atmega8 with 16Mhz external oscillator works properly.
Don't know why does it make it work. If anyone can think of a reason I would be glad to know it. Thanks for all your help.

Not true.  An ATmega8 with an 8 MHz oscillator works just fine, but all timing aspects of your code must be complied based on knowledge of that clock rate.  If they are built for 16 MHz, then everything clock related will take twice as long as intended, for example baud rates will be half of what was intended.  In the Arduino world code is built for a clock rate specified in the chosen boards.txt file entry or in a dropdown menu for recent versions and boards with multiple clock variants.  So the answer is that you have chosen the wrong build configuration.


text:
Powering 3.3V Arduino and 12V peripherals from single 12V power supply?
Given:

I have some home alarm peripherals (motion detectors, glass break sensors) which operate at 12V and draw a nominal current of 20mA when in alarm state.
I have a Particle Photon (3.3V logic level) which will accept up to 5.6V on its VIN pin.
I have a 12V @ 2A switching power supply.

Can someone describe to me an efficient circuit which would allow me to power all of the peripherals @ 12V and the Arduino (Particle Photon) at 3.3ishV?
I have on hand an LM7805 linear regulator, which I believe will work, but will be inefficient. I also have on hand a DC-DC step down converter (4.5V-28V IN, 0.8V-20V OUT @ 2A) but I am a novice and don't know how to use it for the scenario described here.

"I am a novice and don't know how to use it for the scenario described here." - Put 12V on the IN, connect the OUT to a volt meter, twiddle the knob till it reads 5V. Disconnect the volt meter. Connect it to the VIN of your photon.

You could use the arduino's built in regulator, no?

How inefficient will the 7805 be, in the big picture? Depends on the current draw. How much current will be drawn?

@Dampmaskin For the 3.3V Arduino (Photon) current draw will not exceed 500mA. For the 4x 12V peripherals, if all were in an "alarm" state simultaneously, current draw will not exceed 110mA.

Ok, dropping 8.7V at 500mA wastes 4.35W so OK you're right, that is inefficient. A buck converter is probably the best approach  then.

Not just inefficient, but remember that the dissipated power has to go somewhere.  7805s are generally designed (physically) to handle 1 Amp of throughput, though some can handle 1.2-1.5..  If you start dissipating such large amounts of current it will generate heat and require ever-larger heat sinks.  Yes, a voltage converter is the way to go instead.  If you use a screw-terminal barrier block you can have both 12V and your lower voltages available at the same time.

I copy-paste-edited the comments into an answer. Please, accept it to close your question.

@Majenko remarked:
Put 12V on the IN, connect the OUT to a volt meter, twiddle the knob till it reads 5V. Disconnect the volt meter. Connect it to the VIN of your photon.
@loopforever added:
For the 3.3V Arduino (Photon) current draw will not exceed 500mA. For the 4x 12V peripherals, if all were in an "alarm" state simultaneously, current draw will not exceed 110mA.
@Dampmaskin added:
Dropping 8.7V at 500mA wastes 4.35W so OK you're right, that is inefficient. A buck converter is probably the best approach then
@SDsolar added:
If you use a screw-terminal barrier block you can have both 12V and your lower voltages available at the same time


text:
What is the proper way to implement PID?
I'm having some trouble conceptualizing how to go about implementing PID into my drone. There are a few ways I'm thinking about implementing the pipeline:

Having one PID Object for each of the six motors.
Having one PID Object for each axis.

How I would implement PIDs on a per-motor basis?

How I would implement PIDs on a per-axis basis?

I'm guessing that the second one will be the best course of action, as it can all be put into its own loop, where the PID data will be available on-demand, as opposed to calculating it on the spot. It is object-oriented, and runs in the background.
The first one has its appeals, too. It eliminates some of the calculations needed in order to find the actual value. It is procedural, and very straightforward and performs on the spot.
What do you guys think?

Each unique variable you want control over should have a single pid loop, and each loop should only ever stretch across one "order" of time.
For example, to control the craft's roll rate, you should have one PID loop that takes the target roll rate and outputs the controlled roll torque value, which gets transformed somehow into motor accelerations. The trig weights for that part can be precalculated so it doesn't have to happen at runtime.
To control the craft's roll rotational position, you would need one PID loop that takes the target roll position and outputs the target roll velocity, that target roll velocity then becomes the setpoint for the roll-velocity pid loop.
I don't see why each motor would need its own PID loop unless you are measuring the actual thrust each motor produces. If you did measure each motor's thrust their pid loops would still come after the target torque value were calculated. The target torque PID calculations don't need to know about what motors exist or where they are located.
I may not be understanding the intention of your diagrams or what "order" the PID loops are in, so feel free to comment with clarifications. This is complicated stuff.
Its also worth noting that the actual implementation pid often has some features that don't appear in theoretical pid loops like integral windup prevention. You also need a way to either call them at exactly the same interval each time, or accurately keep track of the time delta since the last update. You may want to take the derivative of the process variable only, not the error, so you don't observe setpoint changes in the D term; you could also "outsource" the derivative term if you IMU has a better calculation of it (like the raw gyroscope values).

I will give a generic C-answer to it:
1) figure out what parameters / variables involved in a PID control loop;
2) structure those parameters / variables into a struct;
3) pass that struct to a common set of PID algorithm.
4) done.
with this approach, the algorithm is only implemented once and the can be used / reused as many times as you want.


text:
problem with bitwise OR
I have this code, in which I try to "glue" four bytes in order to construct an unsigned int. I shift left the bytes and "add" them using the OR operator.
unsigned long number1;
unsigned long number2;
unsigned long number3=0;

byte byte0 = 1;
byte byte1 = 40;
byte byte2 = 107;
byte byte3 = 238;

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

void loop(){
  number1 = byte1 <<8 | byte0 ;  //(=10.241 O.K.)

  //(should be 4.000.000.001, it produces 10.241)
  number2 = byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0;

  //(should be 4.000.000.001, it produces 4.016.777.217)
  number3 = number3 | byte3;
  number3 = number3<<8;
  number3 = number3 | byte2;
  number3 = number3<<8;
  number3 = number3 | byte1;
  number3 = number3<<8;
  number3 = number3 | byte0;

  Serial.print("number1 = ");Serial.println(number1);
  Serial.print("number2 = ");Serial.println(number2);
  Serial.print("number3 = ");Serial.println(number3);
  Serial.println(" ");
}

The problem is that the OR operator applies only to byte1 <<8 | byte0 and ignores the rest. That is number1 and number2 appear to have the same value (10241).
I also tried "adding" them up separately, as shown with number3, but it also produces a wrong result as well.
I tried the same code in python, and it works fine.
byte3, byte2, byte1, byte0 = 238, 107, 40, 1
print byte1 <<8 | byte0
print byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0

number3 = 0;
number3 = number3 | byte3;
number3 = number3<<8;
number3 = number3 | byte2;
number3 = number3<<8;
number3 = number3 | byte1;
number3 = number3<<8;
number3 = number3 | byte0;
print number3

So, the question is:
Why both number2 and number3 produce a false result?

Correction from another answer for number2:
number2 = (unsigned long)byte3 <<24 | (unsigned long)byte2 <<16 | byte1 <<8 | byte0; // = 4.000.000.001

And in the first round of loop number3 is correct, all others are wrong as number3 holds a result from previous loop.
  number3 = byte3; // all magic lays here
  number3 <<= 8;
  number3 |= byte2;
  number3 <<= 8;
  number3 |= byte1;
  number3 <<= 8;
  number3 |= byte0;

Correction for number two works fine. As for number3, I should be more careful and reset number3 in every loop. Thank you.


text:
Record a duration of time as data
I have very little experience with the Arduino and am hoping that you may provide me with some helpful info.
I would like to build a device that records time spent on a project.  I envision the main Uno with a switch, microSD breakout, and an LED to indicate its tracking your time. When setup the user could simply press the switch/button (light up the LED to show you're "working") and while you plug away on your day job the Uno will track the time between switch on and switch off. Then at the time the switch is turned off, have the Uno write a simple data file containing the total time spent on that activity.
I have a basic idea of what I need hardware wise, but am hoping to find insight to the backbone of software programming to make something like this begin to take shape.

Use an RTC and record a start time and an end time (timestamp) for each job. This will give better quality raw data that is easy to use, and flexible, for calculations and reporting.

If you can live with an accuracy of only ~ 0.5%, then you don't need an RTC, millis() is fine. For more precise timekeeping, you do want the RTC.

There are two ways of doing this:

Using a Real Time Clock (RTC) chip, which you connect to your Arduino.
Using the millis() function of the Arduino.

Needless to say, they aren't completely the same in efficiency. An RTC is a dedicated chip for measuring time and is incredibly accurate. The millis() is not as accurate, but still pretty accurate.
So, it really depends on how accurate you want it to be. You can make millis() more accurate through code, which isn't something difficult. But an RTC always works fine and is always more accurate, if only by milliseconds. In general: need to time long durations, an RCT is probably better.
Regardless of the method you will use, you can convert the data into the desired format so it can be read easily when looking at the files on the SD card. So, for example: you can write code that simply checks how many hours fit in the saved time data, and after that you can check the minutes and even after that you can check for the last seconds. For this you're going to need modulo.
Here are some resources you might want to check out:

An Arduino tutorial for an RTC chip: http://playground.arduino.cc/Main/DS1302
Official documentation on millis(): https://www.arduino.cc/en/Reference/Millis

Your link about millis() inaccuracy is way out of date. The 9.54 hours rollover issue was solved in 2008.

Well, good to know because that basically means millis() is almost as accurate as an RTC without needing to correct it with code.

That depends on the Arduino. Many of them, like the Uno, are clocked off a ceramic resonator, not nearly as accurate as the quartz you have in a typical RTC.

Yep. So if OP is going to be using it for long periods of time, he's definitely better off using an RTC.

Thank you guys, this is all very helpful!! I don't need extreme accuracy for this application - only looking to deal in nearest tenths of an hour (0.1 or every six minutes) so the millis will probably work for me.  Happy to hear its nearly as simple as my brain is saying it should be :)

An RTC is a dedicated chip for measuring time and is incredibly accurate.

its accuracy will depend on the crystals used.  a temperature controlled one will be very accurate. But a regular one will just be as accurate as the crystal used, like a mcu.

The millis() is not as accurate, but still pretty accurate.

stock millis() undercounts. however, that undercounting can be mitigated via code. for long durations, the undercounting can be practically (but not completely) eliminated.

“stock millis() undercounts”. Do you have some evidence to back this?


text:
which is the number of bits in a float variable
Since the maximum value of a float variable is 3.4028235E+38, shouldn't it represented with 128 bits instead of 32? (2^128=3.4028235E+38).

No, it is not integer, so you cannot calculate it that way. It have floating point (not in fixed place).
It is stored as
1.significand x 2 ^ exponent.
It takes one bit for sign (+/-), 23 for significand (0 is not stored it is implicit) and 8 more for exponent.
Because of this, you have fixed precision (number of significant digits) for very large numbers and also for numbers which are close to zero.
You have it all explained here:
https://en.wikipedia.org/wiki/Single-precision_floating-point_format

That is a completely different approach. Indeed the wikipedia article is very useful. Thank you.

The implicit bit is actually a 1.

@Edgar thanks, it was long time ago when I learned this :) Fixed.

No, because IEEE 754 floats use a decimative compressed format. 64-bit floats allocate 1 bit to the sign, 11 bits to the exponent, and 52 bits to the mantissa, 32-bit floats allocate 1, 8, and 23, and so on.
You convert from it by adding an offset to the exponent, multiplying the mantissa by the exponent to the power of 2, and then applying the sign.

Just adding a little piece of information to the previous answers: it's
worth noting that a float can represent exactly all integers from
−224 to +224 (i.e. ±16777216).
The next integer, namely 16777217, is not representable as a float. A
calculation giving this value would suffer a rounding error.

Another way of looking at it is that a float variable is actually a list of 4294967296 numbers. That's far less than the possible range of numbers and fractions that a float can represent, so only a subset of the numbers are actually represented. Any number you try and use that's not in that list of numbers is rounded to the nearest one.


text:
Bidirectional communication between Arduino and Raspberry Pi over USB possible?
Is it possible to have bidirectional communication betweeen an Arduino Uno Rev 3 and a Raspberry Pi Modell B+ running Rasbian? They're connected ofer USB, and it would be good if I could use Python on the Pi.

Other than with the normal serial object?

@IgnacioVazquez-Abrams can you explain what you mean? Sorry I'm pretty new to this

Yes.  The Arduino Uno implements a serial protocol inside the USB signal using hardware.  This is how it is built.  The Linux side is a bit more complex as there are many USB protocols.  Here is a howto which talks about the Linux side of the Arduino / Linux connection.
To be clear, Rasbian is a derivative of Linux.

Yes, it is possible to have a USB serial communication between a raspberry pi and an Arduino. And it is  much more easier when using Python on the raspberry pi.
Python has a serial library within it's standard library which you can import on the raspberry pi and then use it to send or receive data to/from the Arduino or the raspberry pi.(Just connected via USB cable).
Here is the link for a very similar requirement on YouTube.


text:
Is it possible to reprogram an atMega328 chip inside of a pcb?
I have already soldered the atMega chip with instructions onto the perfboard, and I may need to make changes to it. Is it possible to reprogram it without taking it out of the PCB?

I'm assuming you're trying to program using an AVR programmer.
Yes, it's very likely you'll be able to do that. You need to connect the AVR programmer to the correct MCU pins (Sck, Si, So and Rst), including ground and vcc... as you would do with the chip by itself.
If you have any othe SPI device connected to the same pins, make sure it's not enabled - that might be as simple as having the device's CS pulled high.
The way you'll make the connection is up to you, you might need to use some clips, pogo pins or simply solder some wires to the MCU pins.
If you have other things connected to any of the MCU programming pins, you might need to disconnect, but that will vary case by case.
Cheers


text:
Is it possible to move a servo without knowing it's current position?
My Servo has already been built into my project, and I can't remove it without damaging many other things. During the process of inserting it, it was turned by hand. So I don't know at what position it is in. It turns a potentiometer that doesn't rotate fully. So I'm worried that if I just set a degree it could turn too far and damage the potentiometer or the servo.
What should I do to find the current position? Is it even possible?

Your final question is quite different from the title one. Yes, you can command an RC hobby servo without knowing its position, but no, you cannot move it relative to the current position if you do not know the PWM width that put it at that position, or where that position is within its range of movement.

A normal servo is an absolute positioning device. The position of the servo is directly proportional to the length in time of the sync pulse.  This means if you tell the servo to be in a given position, it will seek that position with out regard to the initial position.  It will simply figure out which way to go on it's own and stop when it gets there.
I should add, that in all likely hood, when you manually moved the servo you moved the positioning potentiometer inside the servo.  So it is expected that if the servo is told to go to a particular angle, it will still go to the same angle as it did before you manually moved it.

tahnks, that really helped me :D

Yes. Servo can rotate to a particular angle irrespective of previous position.
But you may face an issue here if you rotated the shaft manually by hand (when servo is not powered), and if you reassembled the shaft to the servo in a different orientation. Actually it is really hard to re assemble a removed shaft to the same angle position.


text:
ATtiny44 millis() not working with 16 MHz external clock
I'm using ATtiny44 with Arduino IDE according to this tutorial: http://highlowtech.org/?p=1695
I have a problem with millis(). When I use an internal 1 MHz clock it works correctly but when I use external 16 MHz clock it takes millis() much more time than one second to be divisible by 1000.
I tested it with LCD and Hello World sketch, modified to correspond ATtiny's pins. Do millis() actually work with Tiny's?
Why does it work properly with 1MHz and not with 16 MHz which is the same as used in Arduino platform.

Did you forget to unprogram CKDIV8?

Testing whether millis() is divisible by 1000 is a terrible idea. With a 16 MHz clock millis does not count every millisecond: it is updated only every 1024 µs and occasionally jumps by 2 ms.

Please post the Fuses config

If you are specific about 'much more time', that will help people to explain the specific problem you observed. As you can see, there are several possible interpretations of the problem.

Let me guess: "much more time" is about, ohhh, 16 times?
When millis() was written, it had to assume what the input clock was. There is no way to detect the speed of the input clock: to do so would require another clock! So the writers of the function defined a starting constant, set it to 1000000, and required anyone that changed the clock would have to change that constant.
Find the constant, and set it to 16000000. Voilà!
Here's an article on the source code of the function:
https://ucexperiment.wordpress.com/2012/03/16/examination-of-the-arduino-millis-function/

I think faster clock and F_CPU 1000000UL results in "much less time", not in "much more time".

Except that he's dividing by 1000 - or is he dividing 1000 by it? There's an inversion going on... Or @EdgarBonet is correct, and he's missing the crucial point in time when it is exactly divisible


text:
Bit shifting fails with warning: left shift count >= width of type
Given the following minimal working example. I tested this initially with uint16_t and it worked with no warnings. After that, I adjusted everything to work with uint32_t.
#include <stdint.h> /* needed for the uint16_t type*/
#include <inttypes.h> /* needed for sscanf uint16_t format placeholder  */
#include "printf.h"

#define SET_CMD_ID(ID)    ( (ID) << 27)
#define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
#define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
#define SET_CMD_PKT(PKT)  ( (PKT)    )

void setup() {
  Serial.begin(115200);
  printf_begin();
  Serial.print(F("\n\rExample command\n\r: "));

}

void loop() {
  uint32_t payload = 0;

  uint8_t id = 3;   // 00000 - 5
  uint8_t cmd = 2;  // 00    - 2
  uint8_t type = 1; // 000000 - 6
  uint32_t pkt = 0; // 0000000000000000000 - 19

  payload =
        SET_CMD_ID(id)   |
        SET_CMD_CMD(cmd)  |
        SET_CMD_TYPE(type) |
        SET_CMD_PKT(pkt);
  Serial.print(F("Now sending "));
  Serial.println(payload);
  delay(2000);        // Try again soon
}

Verifying this sketch outputs:
/path/to/ino/Arduino32bitTest.ino: In function 'void loop()':
/path/to/ino/Arduino32bitTest.ino:5:37: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_ID(ID)    ( (ID) << 27)
                                     ^
/path/to/ino/Arduino32bitTest.ino:28:9: note: in expansion of macro 'SET_CMD_ID'
         SET_CMD_ID(id)   |
         ^
/path/to/ino/Arduino32bitTest.ino:6:39: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
                                       ^
/path/to/ino/Arduino32bitTest.ino:29:9: note: in expansion of macro 'SET_CMD_CMD'
         SET_CMD_CMD(cmd)  |
         ^
/path/to/ino/Arduino32bitTest.ino:7:41: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
                                         ^
/path/to/ino/Arduino32bitTest.ino:30:9: note: in expansion of macro 'SET_CMD_TYPE'
         SET_CMD_TYPE(type) |
         ^

Sketch uses 3,174 bytes (9%) of program storage space. Maximum is 32,256 bytes.
Global variables use 216 bytes (10%) of dynamic memory, leaving 1,832 bytes for local variables. Maximum is 2,048 bytes.

Executing the sketch on an Arduino Uno results in:
Example command

: Now sending 0
Now sending 0
Now sending 0
Now sending 0

I googled the message of the warning and found out that it could mean that I'm trying to shift 32bit which is undefined, but I'm not sure on that. So my question is:
What am I doing wrong here? How can I get this to work?

It is basically duplicate of Problem with bitwise OR

@KIIV : Thanks, the thread pointed me in the right direction

It's basically an inability of the compiler to auto-promote the source variables to a size big enough to fit the shifted version.
The default type for all operations, unless otherwise specified, is 16-bit. By shifting more than 16 bits you are overflowing that default type.
To get around it you have to manually tell the compiler that you want to work with 32-bits:
#define SET_CMD_ID(ID)      ( ((uint32_t)ID) << 27)
#define SET_CMD_CMD(CMD)    ( ((uint32_t)CMD)  << 25)
#define SET_CMD_TYPE(TYPE)  ( ((uint32_t)TYPE) << 19)
#define SET_CMD_PKT(PKT)    ( ((uint32_t)PKT)    )

Another solution would be to not shift values at all.
It seems to be very common in Arduino and other micro-controller projects to use antique ANSI C. But ALL major compiles support "bit fields". The language removes your headache of packing bits into and unpacking bits from a larger type.
It goes like this:
struct {
    uint32_t pkt  : 19;
    uint32_t type :  6;
    uint32_t cmd  :  2;
    uint32_t id   :  5;
} payload;

As long ans 19 + 6 + 2 + 5 does not exceed 32, the struct will still take up only 32 bits.
Setting values works like this:
payload.id = 3;
payload.cmd = 2;
payload.type = 1;
payload.pkt = 0;

Reading values works the same way. No need to shift mask or do any other operations by hand. The compiler does everything for you without making any mistakes or without forgetting about to mask when reading...
The only thing you have to remember is that bitfields are packed from least significant bit to the most significant bit. So a struct like this:
struct {
    uint8_t r :  2;
    uint8_t g :  3;
    uint8_t b :  2;
    uint8_t a :  1;
} someType;

Will result it a byte where the values are layout like this:
abbgggrr

This also works for signed values. But you have to make sure they fit and be aware of the twos complement representation.
Hopefully more Arduino and micro controller developer will adopt this and take advantage of the compiler.

Note: depending on the compiler and version you may need to manually pack the struct by adding __attribute__((packed)) to the end of it. I do that always by default to ensure proper packing regardless of compiler version or target chip.

The order of the fields in the word, and whether a field can straddle a byte boundary, is implementation defined. Thus your usage of bit fields is not portable.


text:
Serving binary file with ESP8266WebServer
I am currently using a Nodemcu ESP8266-12E with the Arduino IDE in order to control my boiler. Everything is working fine, however I haven't figured out yet how to serve binary files, eg. images. (I am hosting them on a server at the moment).
ESP8266WebServer server(80);

void setup()
{
  [...]
  server.on("/", handleResponse);
  server.onNotFound(handleResponse);
  server.begin();
}

void handleResponse() {
  if (server.uri() == "/style.css") {
    server.send(200, "text/css", "[css]");
    return;
  }
  if (server.uri() == "/favicon.ico") {
    server.send(404, "text/html", "Not set");
    return;
  }
  [...]
}

unsigned char favicon_ico[] = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};
unsigned int favicon_ico_len = 894;

Converting the arary to a string and serving it with server.send does not work and  server.stream expects a file.

It looks like you can use the send_P function to send raw PROGMEM data:
void send_P(int code, PGM_P content_type, PGM_P content, size_t contentLength);
I.e., (from what I can gather):
PGM_P favicon = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};

server.send_P(200, "image/x-icon", favicon, sizeof(favicon));

Incidentally, PGM_P is just a typedef for const char *.

Thank you very much, after changing unsigned char favicon_ico to const char favicon_ico it worked with server.send_P()! Setting it to PGM_P somehow threw an error.


text:
Arduino WebSocket Client "Connection Failed"
I use this code to connect Arduino MKR1000 to API through Web Socket, but it didn't connect to the server.
Can any one help me to correct the code.
This is the Arduino code:

#include "Arduino.h"
#include <WiFi101.h>
#include <SPI.h>
#include <WebSocketClient.h>

char server[] = "192.168.2.128";
IPAddress server1(192, 168, 2, 128);
WebSocketClient webSocketClient;
WiFiClient client;

char path1[] = "/api/WebSocketTest";
int port1 = 8060;
char ssid[] = "**************";
char pass[] = "**************";

void setup() {
  pinMode(LDR, INPUT);
  pinMode(LED, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(SWITCH, INPUT);
  Serial.begin(115200);
  delay(10);
  while (!Serial) {
  }

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  printWifiStatus();
  delay(3000);
  Serial.println("setup done");
  delay(1000);

  //  webSocketClient.setDebug(&debug);
  webSocketClient.connect(server, port1, path1);
  if (webSocketClient.connected() == true) {
    Serial.println("Connected");
  }
  else {
    Serial.println("Not Connected");
  }
  webSocketClient.onMessage(onMessage);
  webSocketClient.onOpen(onOpen);
  webSocketClient.onError(onError);
}

void loop() {
  webSocketClient.monitor();
}

void onOpen(WebSocketClient webSocketClient) {
  Serial.println("EXAMPLE: onOpen()");
}

void onMessage(WebSocketClient webSocketClient, char* message) {
  Serial.print("Received: ");
  Serial.println(message);
}

void onError(WebSocketClient webSocketClient, char* message) {
  Serial.print("ERROR: ");
  Serial.println(message);
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

And this is a part from the library used "WebSocketClient.h":
void WebSocketClient::connect(char hostname[], int port, char protocol[], char path[]) {
  _hostname = hostname;
  _port = port;
  _protocol = protocol;
  _path = path;
  _retryTimeout = millis();
  _canConnect = true;
}

Edit 1: The output:
Connecting to WiFi-Repeater1

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.147
signal strength (RSSI):-68 dBm
setup done
Not Connected
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!
ERROR: Connection Failed!

What output do you get from the printWifiStatus() function?

WiFi connected
SSID: WiFi-Repeater1
IP Address: 192.168.2.147
signal strength (RSSI):-68 dBm

And to what are you connecting?

the problem is how to enter hostname, port number, and path

No, the problem is you cannot connect to some unknown service on some unknown computer. You already specify the hostname, port number, etc.

i am connecting it to api, which is hosted from my laptop, which act as a server

No, you aren't connecting. That's the problem. It says not connected. I would guess the problem is with the configuration of your laptop - server software configuration, firewall configuration, etc.

as you see at the top of the code I define the ip address of the server, port number and the path

i try the same api with other applications and it works perfect

and i try it also with raspberry pi and it works 100%

had you specified this port number 8060 while creating the server on your laptop?

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


text:
Where can i get touch sensitive buttons with RGB-LED like in Ableton Push
I am searching for this component: a touch sensitive button with LEDs like in the Ableton Push or in other Launchpads. Does anyone have an idea about where I can buy something like this? The best would be an RGB LED.
This is what I've found so far. It has no RGB LED though.
Thanks!

https://www.adafruit.com/products/1929 ?

Touch-sensitive? As in, an on/off switch? I've seen kits (such as the ones mentioned in comments and answers), but none that are pressure-sensitive

Just a little more searching would have led you to this, along with its associated breakout board, bezels, and LEDs.

The specific buttons you link to are custom made. They're not something you can buy off the shelf. In fact they aren't even buttons.
What they are is a translucent moulded silicone rubber sheet with conductive pads behind (typically in a ring shape) with an LED mounted on a PCB behind them.  The pad is pressed, which flexes the silicone rubber, to press the conductive portion against exposed tracks on the PCB behind.
There are some similar products around, such as the Sparkfun one Ignacio points to but it is highly unlikely you will find anything off-the-shelf that does exactly what you want.  Coupling a pre-moulded translucent rubber keypad membrane (if you can find one somewhere) with your own custom designed PCB to take the RGB LEDs you want (preferably surface mount to keep the size small enough) and provide the exposed tracks is probably the only way you can get exactly what you want.
You may be able to create your own sheet by first making a suitable mould, maybe with wood or modelling clay or something like that, then filling it with silicone (translucent bathroom sealant) and then impress on the back of that a second mould to provide the contact points and indents etc. Then, after a few days when it's all dry, add to the contact points some self-adhesive copper foil, or paint them with conductive paint. Don't quote me on that though, I haven't tried it ;)