message:
Serial Comm. timing issue between Arduino and Pyserial

This is my first post to Stack Exchange so please forgive any formatting errors.

I am conducting an experiment that has 7 total sensors: 5 thermocouples, 2 humidity sensors and 1 pressure sensor. I am reading their signals via Arduino Mega analog input ports. I chose to use Python to save and compile the data in a nice csv file, therefore I am using Pyserial.

My problem is that I cannot go above 1 sample/second. As you can see in my code, I have a 1 second delay in Arduino and Python. I have ran successful calibration tests with my thermocouples, so I know at that rate Python and Arduino are communicating well. Anything faster than 1 sample/second (i.e. I change my delays to .5 or .25 seconds), a timing error occurs and my data is "cut up" and sent in odd chunks instead of the standard layout I programmed.

Additionally, I tried to increase the baud rate from 9600 and anything above that will send "garbage" ASCII characters (e.g. little blank blocks and odd characters) to the Serial Comm. I changed the baud rate in Arduino, Python *and* the COM port in my devices manager settings to no avail.

I would really like to increase my sampling rate to increase my signal-to-noise ratio and I believe it's good practice as a metrologist to have a higher sampling rate than 1 samp/sec. I am sending ~1072 bits each time I write to the Serial Comm (if I'm counting right??) so I should have enough room to increase the amount of bits to send per second (around 3 times what I am currently sending).

**In summary, my two main issues are: if I increase the baud rate, I get garbage in my Serial Comm and if I try to increase my "sampling rate" by decreasing my delays, timing issues appear and my data is split up erroneously. Should I be using a different function, like Serial.flush()?**

**I greatly appreciate any feedback, thank you for your time!**

    // Data acquisition
    // updated  March 30, 2017

    //Note: This version is for TEMPERATURE, HUMIDITY and PRESSURE data
    acquisition ALONE. No motor/conveyor control.

    //***GLOBAL VARIABLES***//

    float lfactor = 125.0;
    float afactor = 1.15;

    /////////////////////////

    //Standard setup with analogReference to 5Volts.

    void setup() {

    Serial.begin(9600);
    }

    void loop() {

    //******THERMOCOUPLES*******//

    //get voltage reading
    // [code]; TC # - Location

    float tcv1 = analogRead(A4) * ( 5.0 / 1024.0 ); //TC 1
    float tcv2 = analogRead(A7) * ( 5.0 / 1024.0 ); //TC 2
    float tcv3 = analogRead(A8) * ( 5.0 / 1024.0 ); //TC 3
    float tcv4 = analogRead(A9) * ( 5.0 / 1024.0 ); //TC 4
    float tcv5 = analogRead(A10) * ( 5.0 / 1024.0 ); //TC 5

    //convert to temperature using custom equation based on 5V reference
    float tc1 = ( 188.7755 * tcv1 ) - 245.3959;
    float tc2 = ( 188.7755 * tcv2 ) - 245.3959;
    float tc3 = ( 188.7755 * tcv3 ) - 245.3959;
    float tc4 = ( 188.7755 * tcv4 ) - 245.3959;
    float tc5 = ( 188.7755 * tcv5 ) - 245.3959;

    //******HUMIDITY SENSORS********//

    float hs1 = ((( analogRead(A13) * ( 5.0 / 1024.0) ) / 5.0 ) * 100.0 ); //HS
    1
    float hs2 = ((( analogRead(A15) * ( 5.0 / 1024.0) ) / 5.0 ) * 100.0 ); //HS
    2

    //******PRESSURE SENSORS********//

    //obtain voltage signal from Sensirion sensor
    float pvolt = analogRead(A0) * (4.995 / 1024.0);

    //convert to Pascals using equation from datasheet, including altitude
    compensation
    //P = lfactor * (voltage[V] - .250 ) / 3.750

    float pressure =  lfactor * ( pvolt - .250 ) / 3.750;
    float pascals = pressure * afactor;

    Serial.print("TC1");
    Serial.print(":");
    Serial.print(tc1);
    Serial.print(";");

    Serial.print("TC2");
    Serial.print(":");
    Serial.print(tc2);
    Serial.print(";");

    Serial.print("TC3");
    Serial.print(":");
    Serial.print(tc3);
    Serial.print(";");

    Serial.print("TC4");
    Serial.print(":");
    Serial.print(tc4);
    Serial.print(";");

    Serial.print("TC5");
    Serial.print(":");
    Serial.print(tc5);
    Serial.print(";");

    Serial.print("RH 1");
    Serial.print(":");
    Serial.print(hs1);
    Serial.print(";");

    Serial.print("RH 2");
    Serial.print(":");
    Serial.print(hs2);
    Serial.print(";");

    Serial.print("Pressure");
    Serial.print(":");
    Serial.print(pascals);
    Serial.print(";");

    Serial.println("");
    delay(1000);

      }

**Python Code:**

    from threading import Thread
    import time
    import serial
    import os
    global datalist
    global fileName

    global motorspeed

    motorspeed = 0

    def serInitialization():
        #activate the serial port, if possible
        try:
            ser = serial.Serial('COM9', 9600) #initialize the serial port
            print "Serial connection successful."
            return ser
        except:
            print "Error: serial port cannot be initialized"
            while(1):
                voidholder = 1

    def getDateTime():
      """Function grabs current time and date, then returns values in a 2-
     element list. """
       timeNow = time.strftime("%H:%M:%S")
       dateToday = time.strftime("%m/%d/%y")
      return [dateToday, timeNow]

    def writetocsv(data):

        """ function writes datalist values to a csv file. If daily csv file
    exists already,
        list values are simply appended to end of file. If it does not, function
    creates the file,
        then appends values.
        """

        global csv_success

        header = ["date", "time", " ", "TC1", " ", "TC2", " ",
    "TC3", " ", "TC4", " ", "TC5", " ", "HS1", " ", "HS2"," ",
    "PRESSURE", " ", "PRESSURE(alt)", "\n"]

        fileName = str(time.strftime("%m_%d_%y_")+ "log.csv")

        if os.path.exists(fileName):
            f = open(fileName, "a")

        else:
            f = open(fileName, "a+")

            for element in header:
                f.write(element + ",")
            f.write("\n")

        for element in data:
            if type(element)==str:
                f.write(element + ",")
            if type(element) == list:
                for i in element:
                    f.write(i + ",")

        f.write("\n")
        f.close()
        csv_success = True

    def mainprogram():

        data = []

        if ser.inWaiting():
            datetimeData = getDateTime()

            for i in datetimeData:
                data.append(i)

            val = ser.readline().strip('\n\r').split(';')
            print "Current readings: "
            for i in range(0,len(val)):
                sensorData = val[i].split(':')
                data.append(sensorData)

                print sensorData

            writetocsv(data)

            time.sleep(1)

            print "\n" * 50

    #Initializes the serial port with the arduino so now we can read what
    Arduino is sending us!
    print "*******************************"
    print "DATA ACQUISITION PROGRAM       "
    print "*******************************"
    print "Data files are saved under "
    print "C:\\Users\\lpaw\\Downloads\\python workspace"
    print "*******************************"

    ser = serInitialization()

    while True:

       mainprogram()

**Screenshots of errors:**
[![Arduino Serial Comm and Python IDLE - data becomes messed up][1]][1]

[![Baud rate error][2]][2]

  [1]: https://i.stack.imgur.com/agYCD.png
  [2]: https://i.stack.imgur.com/jozIB.png

body:
You certainly should use a single Serial.flush at the end of your loop()

    Serial.println("");
    Serial.flush()
    delay(100);

Remember you have limited SRAM to store characters.
I'd suggest you should use the inbuilt serial monitor in the Arduino IDE with the above alteration, and increase your baud rate. There should be no problems sending data at 115k baud.

You should also consider sending a signal back from Python that you have received a valid reading string (ACK/NAK) that way you can remove delays altogether (you still need the flush).


sender: user

sender: assistant

body:
Your main problem is in erroneously having a delay in both the sender and the receiver.  While this sometimes works by lucky accident, it essentially never does what is hoped for by those who try it.

In a system such as this, you should have a delay in the sender only, in order to produce quasi-regular sample intervals, but no delay in the receiver.  Rather, the receiver should accept data whenever the transmitter produces it, or more specifically in your case, every time it completes a terminated line of data.

But you also seem to want to write the data in an organized way as sets of measurements.  To do that, you should reject data until you see the first "TC1", then collect lines to fill in a data block until and end of data condition is recognized (in your case a blank line), and write it out to disk in a timestamped file.  You may also want to include code that abandons a corrupted block unwritten if any of the intermediate reading headers aren't as expected, and goes back to looking for the next hopefully clean TC1, or marks it as erroneous, or whatever.

To use a different baud rate, you must apply a matching setting in both the Arduino and the python ends of the link.

Also note that while the Arduino serial monitor is indeed useful for debugging, you *must not* have it open while trying to collect data with python - this will either cause an error in that one program is disallowed, or the two programs to fight over the data and each get incomplete results.

Another technique which can be simple and useful, especially during development, is to write every received line of serial data out to a text file with a numeric timestamp at the start of each line.  You can then have a second process which reads this file, grabs complete multi-line records, and writes them out using either the timestamp of the first or last element of the record.  In particular this lets you get an intermediate view of the data to understand any oddities.  With various Unix style command line tricks you can even run the first program both saving the intermediate format and feeding the second record extraction program in real time.


body:
Does your Python code have any way of determining the start & end of a data set?
Does it 'assume' that when it reads a chunk of data from the serial port that the first byte it gets will always be the start of a "Cond.temp" and the last byte will be the ; at the end of Press(alt)?
After reading a chunk of data, do you have any check to see if it is complete or if you should wait a few 10's of milliseconds and go back to read some more?

I'm assuming the answers to these questions are No, Yes & No.

Your PC and your Arduino are running completely asynchronously - neither one really knows what the other is doing.
When your python code reads a chunk of data from the serial port (I'm making another assumption here - that you're not reading it byte-by-byte), you have no way of knowing that the beginning of that chunk is really the beginning of your data set.
Similarly, you also have no way of knowing that the end of that chunk is the end of your data set - maybe it's only a small piece - or maybe you're getting the beginning of the next set glued to the end of this on.

If you're using a USB-Serial adapter then your data is even more likely to arrive in bits & pieces which you'll need to reassemble - just by the nature of how these beasties often work - they could be buffering some number of serial bytes before packaging them together in a single USB packet.

You need some way of flagging the start and/or end of your data sets. Even something as simple as a \n newline character at the end of each one might work for you.
Then, you need to read in *and buffer* the data you're receiving *until you know you've reached the end of a data set*.
So, for the \n example:
 - read some stuff
 - add it to a buffer
 - do you have a \n *anywhere in the buffer*?
 -- yes - pull that section from the start of the buffer up to the \n & process it
 -- no - go back to the beginning and wait for more stuff
 - after you've pulled some stuff out of the buffer to process,
   *don't just forget the rest - it could be the start of your next data set!*
 - move it to the start of your buffer
 - rinse & repeat

For your baud-rate issue I can't say much for sure. The garbage you're seeing is typical for a mismatched baud-rate situation.
Check that your particular Arduino supports the baud rates you're trying to use at whatever clock speed you're running it at.
Check that your USB-Serial adapter (if you're using one) works at those speeds (either loop pins 2&3 and type to yourself in a terminal or get another, preferably different one, and hook them together with a 3-wire link pin 2-3, pin 3-2, pin 5-5).


message:
No such file or directory compilation terminated

I tried a simple blink for my fingerprint sensor which is GT-511C1R, but I have experienced of having an error.

>FPS_Blink.ino:12:26: fatal error: FPS_GT511C1R.h: No such file or directory
compilation terminated.

I downloaded the whole library but still same error.

body: Please learn how to install a library from [here](https://learn.sparkfun.com/tutorials/installing-an-arduino-library). And see if error is coming or not.


message:
Suggest me Arduino device with USB for Mass storage

I want to make a temperature data logger by using Arduino.

I can read a data every 1sec and I want to store 30days data with date&Time.

In data logger, I want to write a temperature data with date&time in the .csv file and this file will be generated after I attaching USB.

So, Please suggest me Arduino board with USB compatible(working on 3V battery) and also suggest me EEPROM who able to store 30 days data.

body:
60 samples per minute, 60 minutes per hour, 24 hours per day, 30 days - that's 2592000 samples. At 10 bytes per sample (a very generous allocation) that's less than 30MB of data.

You could fit that many many times over on even the smallest of today's SD cards, so why mess with the complexity of USB? *Any* Arduino can work with an SD card.

A bigger concern of yours should not be the storage medium, which is trivial - you should instead be thinking about *how you will run the board off a 3V battery for 30 days*.


body:
Despite your poor written question, I'll reply to you with a code, I used in my temperature logger 2 weeks ago. Includes LCD, temp sensor and SD card.

Delay is set for 9,1s which sums up with the calculation times of Arduino to 10 +/- 0.05 sec.
Lower it down to 100ms, if you want to be written every 1 second.

PS: The lower row, most right: There is a sign in letters, the condition of the sistem.

N = something's wrong, not inserted card/not connected SD card module
O = everything's okay, it's data logging

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <LiquidCrystal.h>
    #include <SPI.h>
    #include <SD.h>
    #define ONE_WIRE_BUS 6 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); LiquidCrystal lcd(8, 7, 5, 4, 3, 2);

    const int chipSelect = 10;

    void setup() {

      Serial.begin(9600);   Serial.println("Arduino Digital Temperature // Serial Monitor Version");   sensors.begin();
         lcd.begin(16, 2);   lcd.setCursor(0, 0);   lcd.print("Temperatura:");   //*********************************************
        while (!Serial) {   }   lcd.setCursor(15, 1);   lcd.print("??");   Serial.print("??");

      if (!SD.begin(chipSelect)) {
        Serial.println("NO");
          lcd.setCursor(15, 1);
          lcd.print("NO");
        return;   }   else   {   lcd.setCursor(15, 1);   lcd.print("OK");   Serial.println("OK");   }   //********************************************* }

    void loop() {

      String dataString = "";

      float abc;

      sensors.requestTemperatures();     Serial.print("Temperature is: "); Serial.println(sensors.getTempCByIndex(0));   lcd.setCursor(0, 1);   lcd.print(sensors.getTempCByIndex(0));

      File dataFile = SD.open("datalog.txt", FILE_WRITE);

        if (dataFile) {
        dataFile.println(sensors.getTempCByIndex(0));
        dataFile.close();    Serial.println(sensors.getTempCByIndex(0));
        }
           else {
        Serial.println("error opening datalog.txt");   }

      //delay(9100);    }


message:
EEPROM PUT and GET audio playback

I am new to Arduino.

My project is an electronic piano that has 8 tactile switch keys that can play 8 octaves. I want to record a song that a user plays on the keys into EEPROM. I have implemented it. However, the playback is bad. You can't hear different note frequencies but you can hear soft buzzing when a note is supposed to be played.

Here is my code. Could you please help me find the problem? Thank you in advance.

    #include <EEPROM.h>
    #include "pitches.h"
    #define speaker A5
    #define record_button 3
    #define play_button 5
    #define record_led 2
    #define play_led 4

    int eeAddress = 0;
    int eeAddressplay = 0;
    const int inPot = A1; // potentiometer to change octaves (8 octaves total)
    byte octave;
    byte tone_out;
    int tone_key; // frequency of key
    boolean silence;
    int maxNumber = 500;
    byte time = 20;
    byte check = 0;
    byte buttons[] = {6,7,8,9,10,11,12,13};
    int saveSounds[500];
    int saveNumber = 0;

    byte melody1[8] = {
      NOTE_C1 , NOTE_D1, NOTE_E1, NOTE_F1, NOTE_G1, NOTE_A1, NOTE_B1, NOTE_C2};
    byte melody2[8] = {
      NOTE_C2 , NOTE_D2, NOTE_E2, NOTE_F2, NOTE_G2, NOTE_A2, NOTE_B2, NOTE_C3};
    int melody3[8] = {
      NOTE_C3 , NOTE_D3, NOTE_E3, NOTE_F3, NOTE_G3, NOTE_A3, NOTE_B3, NOTE_C4};
    int melody4[8] = {
      NOTE_C4 , NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5};
    int melody5[8] = {
      NOTE_C5 , NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_B5, NOTE_C6};
    int melody6[8] = {
      NOTE_C6 , NOTE_D6, NOTE_E6, NOTE_F6, NOTE_G6, NOTE_A6, NOTE_B6, NOTE_C7};
    int melody7[8] = {
      NOTE_C7 , NOTE_D7, NOTE_E7, NOTE_F7, NOTE_G7, NOTE_A7, NOTE_B7, NOTE_C8};

    //PIANO FUNCTION
    void freePlay()
    {
      octave = map(analogRead(inPot),0,1023,1,7);
      if (digitalRead(buttons[0]) == HIGH) {
        tone_out = 0;
        silence = false;
      }
      else if (digitalRead(buttons[1]) == HIGH) {
        tone_out = 1;
        silence = false;
      }
      else if (digitalRead(buttons[2]) == HIGH) {
        tone_out = 2;
        silence = false;
      }
      else if (digitalRead(buttons[3]) == HIGH) {
        tone_out = 3;
        silence = false;
      }
      else if (digitalRead(buttons[4]) == HIGH) {
        tone_out = 4;
        silence = false;
      }
      else if (digitalRead(buttons[5]) == HIGH) {
        tone_out = 5;
        silence = false;
      }
      else if (digitalRead(buttons[6]) == HIGH) {
        tone_out = 6;
        silence = false;
      }
      else if (digitalRead(buttons[7]) == HIGH) {
        tone_out = 7;
        silence = false;
      }
      else {
        silence = true;
      }

      if (silence == false)
      {
        switch(octave)
        {
        case 1:
          tone_key = melody1[tone_out]; break;
        case 2:
          tone_key = melody2[tone_out]; break;
        case 3:
          tone_key = melody3[tone_out]; break;
        case 4:
          tone_key = melody4[tone_out]; break;
        case 5:
          tone_key = melody5[tone_out]; break;
        case 6:
          tone_key = melody6[tone_out]; break;
        case 7:
          tone_key = melody7[tone_out]; break;
        }
        tone(speaker,tone_key);
      }
      else {
       noTone(speaker);
       delay (5); }
    }

    //SETUP FUNCTION
    void setup()
    {
     for(int i = 0; i < 8; i++)
     {
      pinMode(buttons[i], INPUT);
     }
     pinMode(speaker, OUTPUT);
     pinMode(melody_button, INPUT);
     pinMode(record_led, OUTPUT);
     pinMode(play_led, OUTPUT);
     pinMode(inPot, INPUT);
    }

    //MAIN CODE
    void loop() {
    freePlay();
    if (digitalRead(record_button) == HIGH) {
      digitalWrite(record_led, HIGH);
        for(int i = 0; i < maxNumber ; i++) {
          octave = map(analogRead(inPot),0,1023,1,7);
            if (digitalRead(buttons[0]) == HIGH) {
            tone_out = 0;
            silence = false;
            }
            else if (digitalRead(buttons[1]) == HIGH) {
            one_out = 1;
            silence = false;
            }
            else if (digitalRead(buttons[2]) == HIGH) {
            tone_out = 2;
            silence = false;
            }
            else if (digitalRead(buttons[3]) == HIGH) {
            tone_out = 3;
            silence = false;
            }
            else if (digitalRead(buttons[4]) == HIGH) {
            tone_out = 4;
            silence = false;
            }
            else if (digitalRead(buttons[5]) == HIGH) {
            tone_out = 5;
            silence = false;
            }
            else if (digitalRead(buttons[6]) == HIGH) {
            tone_out = 6;
            silence = false;
            }
            else if (digitalRead(buttons[7]) == HIGH) {
            tone_out = 7;
            silence = false;
            }
            else {
            silence = true;
            tone_key = 0;
            }

            if (silence == false) {
            switch(octave) {
            case 1: tone_key = melody1[tone_out]; break;
            case 2: tone_key = melody2[tone_out]; break;
            case 3: tone_key = melody3[tone_out]; break;
            case 4: tone_key = melody4[tone_out]; break;
            case 5: tone_key = melody5[tone_out]; break;
            case 6: tone_key = melody6[tone_out]; break;
            case 7: tone_key = melody7[tone_out]; break;
            }
            tone(speaker,tone_key);
            delay(time);
            }
            else {
            noTone(speaker);
            tone_key = 0;
            delay (time);
            }

        saveSounds[saveNumber] = tone_key;
        saveNumber++;
        if (digitalRead(play_button) == HIGH){
        break;}
        }

    digitalWrite(record_led, LOW);
    tone(speaker, 700);
    delay(200);
    noTone(speaker);
    check++;
    }

    for (int i = 0; i<500; i++) {
      EEPROM.put(eeAddress,saveSounds[i]);
      eeAddress = eeAddress + 2;
    }

    if(check >= 1) {
      while (0 == 0){
        freePlay();
        if(digitalRead(play_button) == HIGH) {
          digitalWrite(play_led, HIGH);
            for(int i = 0; i < maxNumber; i++) {
            if(saveSounds[i] != 0) {
              tone(speaker,EEPROM.get(eeAddressplay,saveSounds[i]));
              eeAddressplay = eeAddressplay + 2;
              delay(25);
            }
            else {
              noTone(speaker);
              delay(time);
            }
            }
          noTone(speaker);
          digitalWrite(play_led,LOW);
        }
        freePlay();
      }
    }
    }

body:
NOTE: this is not an answer, but a response not able to put in a comment as request from the submittor mirandamg.

For the first example

Instead of

    if (digitalRead(buttons[0]) == HIGH) {
      tone_out = 0;
      silence = false;
    }
    else if (digitalRead(buttons[1]) == HIGH) {
      tone_out = 1;
      silence = false;
    }
    ...

Use

    for (int buttonIndex = 0; buttonIndex < 8; buttonIndex++)
    {
        if (digitalRead(buttons[butonIndex] == HIGH)
        {
           tone_out = buttonIndex;
           silence = false;
        }
    }

This method does not work directly for variables melody1, 2, 3...
Therefore, make an array, instead of:

    byte melody1[8] = {
    ...

use

    byte melodies[8][8] = {
    ...

The first 8 is for the number of melodies, the second is for the number of notes.

You can improve it even further by making 2 constants:

    const byte NR_OF_MELODIES = 8; // Number of melodies
    const byte NR_OF_NOTES = 8;    // Number of notes per melody

And the array can be created s

    byte melodies[NR_OF_MELODIES][NR_OF_NOTES] = {

If you make a const for the number of buttons:

    const byte NR_OF_BUTTONS = 8; // Number of physical buttons

Then also the first line in the loop in my example can be changed as:

    for (int buttonIndex = 0; buttonIndex < NR_OF_BUTTONS; buttonIndex++)

If you later need to change the number of notes, melodies or buttons, you don't need to iterate over your application to find all values. Especially since they are all 8.


message:
Is it possible to save different values on address 0 and 1 in EEPROM?

I want to save different values on address 0 and 1 on eeprom I tried to change it but when I put data on address 0 and also put data on address 1 the address 0 change its value stored into random number and vice versa .. Is it possible to change the value of respective address without affecting others ..

**CODE**

    in the setup
         int eepromSize=EEPROM.length();
          Serial.print("EEPROM found, size=");
          Serial.println(eepromSize);
            // Get the last fade value (as an integer)
          EEPROM.get(0, WATEREQFORN1);
          Serial.print("Last Value N1: ");
          Serial.println(WATEREQFORN1);

          EEPROM.get(1, WATEREQFORN2);
          Serial.print("Last Value N2: ");
          Serial.println(WATEREQFORN2);

The user will input the value that will be save in eeprom i use switch because the user will input like this example .. 100A or 23B

    case 'A':
            Serial.print("Case A got ");
            Serial.println(val);
            WATEREQFORN1 = val;

                EEPROM.put(0, WATEREQFORN1);
                Serial.print("DATA SAVE TO EEPROM");

            break;
          case 'B':
            Serial.print("Case B got ");
            Serial.println(val);
             WATEREQFORN2 = val;
             EEPROM.put(1, WATEREQFORN2);
             Serial.print("DATA SAVE TO EEPROM");

            break;

The problem is, when I change/write value into address 0 and after that change/write also into address 1 the value on address 0 also change into different random numbers.

body:
Probably WATEREQFORN1 is an int or word, at least more than one byte.

If you write a 2 byte value on address 0, it will occupy address 0 and 1.

When you overwrite address 1 (again with a 2 byte value), it will occupy addres 2 and 3, destroying the LSB part of the value written to byte 0.

Try writing on address 0 and 2 (or 0 and 4 when using 4 bytes).


body:
EEPROM.put() and EEPROM.get() write or read the object you pass them. An `int` is 2 bytes so that is what they write or read. It sounds like you intended for the functions to only handle 1 byte. In that case, make the your variable's data type something that is 1 byte, such as `int8_t`; otherwise allocate 2 bytes of EEPROM to each.

Update:
It works because you had only allocated 1 byte in EEPROM for each variable but you store 2-byte variables. Now you're storing 1-byte variables, which matches your EEPROM allocation.


body:
The variable names in all upper case is a style problem you should address.  Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros.  Contravening that convention can lead to confusion if other people use or maintain the code.  Instead of `WATEREQFORN1` consider `waterEq1`, etc.

The problem of your second value overwriting part of the first in EEPROM is an allocation problem.  Presumably the `WATEREQ...` variables are multiple bytes in length.  `EEPROM.get()` and `put()` read and write data types with multiple bytes using several consecutive bytes of EEPROM.  For example, if `WATEREQFORN1` is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.

The following code snippet shows a way to automatically and systematically allocate EEPROM space.  The `sizeof` operator returns the size in bytes of its argument.  Thus, an expression like `WaterAddr2=WaterAddr1+sizeof waterEq1` correctly sets `WaterAddr2` to be the next available cell after `waterEq1`, no matter what type `waterEq1` is.

    enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
    ...
    case 'A':
      waterEq1 = val;
      EEPROM.put(WaterAddr1, waterEq1);
      break;
    case 'B':
      waterEq2 = val;
      EEPROM.put(WaterAddr2, waterEq2);
      break;
    case 'D':
      Delay = val;
      EEPROM.put(DelayAddr, Delay);
      break;
      ...


body:
> Is it possible to change the value of respective address without affecting others ..

Yes, if the two values are 8-bit types.

Otherwise, No.


message:
Using voltage divider to read voltage from sensor

Good morning,

I would like to use an Arduino Duemilanove to read the voltage signal generated from a current sensor (CSLA2CD). The datasheet for this sensor can be found [here](http://www.scienceshareware.com/articles/measuring-current/csla2cd-current-sensor.pdf).

The problem is that the sensor requires a supply voltage of 6 to 12v. The signal output voltage is half the supply when no current flows through the sensor. I am using a 8v regulator for its supply, so the signal voltage may range from 4v (no current sensed) all the way to about 6v (about 60 amps).

Unless I'm mistaken, the arduino's analog pin can detect from 0v to 5v. So it would only accurately provide me data up to the 5v signal mark.

My questions are:

 1. Would a voltage divider be a good solution to reduce the signal voltage to a range the Arduino can read? If so,

 2. what would be the best resistor combination to use?

If there are better solutions than a voltage divider then please share.

Thanks very much!

body:
It should work, but I don't know if its the best way.

Because the maximum voltage is 12 volts (I know you are only giving it 8, but you don't want to fry your board) you need the divider to send the Arduino 5/12 of the power.  You don't need much current, so you can use big values or resistors.  10K and 24K should work, but you should research or test this before you hook it up to you kit.


message:
Multiplex 7 segment during delay (external IC?)

I am using some sensors with the arduino which take a second to receive the data from them. My guess is that there is a delay used somewhere in the library. During this time the multiplexed displays stop working as the rapidly changing grounds are temporarily paused and only one of the displays has the digit lit up. I could change the sensor I'm using (DHT11) to something I could AnalogRead, however I'm curious if there is an external IC for this which drives multiplexed displays with some sort of serial communication or I2C between the arduino and it. I could use a separate arduino(or ATTiny) and write some code for it to do this, but is there a class of chips which already do this? Something where you could pass bytes of the digits and the multiplex delay and it continues to multiplex until the next data is received.

I don't mind if in this time the digits are left in their last states similar to how it would operate if they were directly driven rather than multiplexed. If anyone has insight that would be great!

body:
Perhaps a [MAX7219][1] would do what you want.

> The MAX7219CNG+ is a 8-digit serially interfaced LED Display Driver for LED matrix displays.
> The MAX7219 is compact, serial input/output common-cathode display drivers that interface microprocessors (¦ÌPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays or 64 individual LEDs.
Included on-chip are a BCD code-B decoder, multiplex scan circuitry, segment and digit drivers and an 8x8 static RAM that stores each digit.
Only one external resistor is required to set the segment current for all LEDs.
A convenient 4-wire serial interface connects to all common ¦ÌPs.
Individual digits may be addressed and updated without rewriting the entire display.
> The MAX7219 also allow the user to select code-B decoding or no-decode for each digit.

  [1]: http://playground.arduino.cc/Main/MAX72XXHardware


message:
Shift Register on ATMEGA328p

I want to learn more about the shiftout function used with Arduinos and used the implementation with my ATMEGA328p.

**The Setup**

This is the original `shiftout` function used in Arduino Programming, except that I replaced 1 with HIGH.

    #define F_CPU 1000000UL
    #define BAUD 9600UL
    #define LSBFIRST 0
    #define MSBFIRST 1
    #define HIGH 0x1
    #define LOW  0x0
    #define INPUT 0x0
    #define OUTPUT 0x1

    #include <avr/io.h>
    #include <util/delay.h>
    #include <USART.h>
    #include <pinDefines.h>

    #define DATA PD7
    #define LATCH PB2
    #define CLOCK PB0

    void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
    {
     uint8_t i;
     for (i = 0; i < 8; ++i) {
      if (bitOrder == LSBFIRST) {
       PORTD |= (!!(val & (HIGH << i)) << DATA);
       } else {
       PORTD |= (!!(val & (HIGH << (7 - i))) << DATA);
      }
      PORTB |= (HIGH << clockPin);
      PORTB &= ~(HIGH << clockPin);
      }
    }

**Main**

    int main(void)
    {
     initUSART();
     DDRD |= (HIGH << DATA);
     DDRB |= (HIGH << LATCH) && (HIGH << CLOCK);

     PORTB |= (HIGH << LATCH);
     shiftOut(DATA, CLOCK, LSBFIRST, 1);
     printBinaryByte(PIND);
     PORTB ^= (HIGH << LATCH);

        /* Replace with your application code */
        while (1)
        {

        }

     return (0);
    }

I created an example to understand more about the function, but the outcome does not add up to what I expected to see.

**Szenario**

    PORTD |= (!!(val & (HIGH << 0)) << DATA);

This is what I expect for `val = 1`

 - `(HIGH << 0)` = `00000001`
 - `val & (HIGH << 0)` = `00000001 & 00000001`
 - `!!(val & (HIGH << 0))` = `1`
 - `PORTD |= (1 << DATA)`

As `PORTD` is the data pin on the shift register, it should get `00000001`.
When I print the binary number within `PORTD` I get: `10000111` and my LED Array connected to the 74HC595 displays: `10101111`

I am really lost.... I checked the connections to the LEDs and they are all good. Can you explain to me why I receive this awkward result?

body:
That is some ugly and needlessly slow code!

Nonetheless, I think the main point you need to keep in mind is that when you `OR` the value `00000001` into `PORTD`, you are *only* changing the bottom bit to a `1` - all other bits will be left untouched to whatever value they already had.

So, it seems that `PORTD` had the value of either `10000111` or `10000110` before you executed `PORTD |= (1 << DATA)` (which is the equivalent of `PORTD |= 0b00000001`)....

       10000110
    OR 00000001
    ===========
       10000111

The output of your shift register is also just an artifact of whatever the most recent series of bits that you sent to it was. Each time you send a new bit, whatever was there will get shifted over and only the single new bit will be shifted in.

Make sense now?


body:
> This is what I expect for val = 1
>
> PORTD |= (1 << DATA)
> As PORTD is the data pin on the shift register, it should get 00000001.

your deduction is correct and the code is correct -> remember this is the case for LSBFIRST. so "val = 0x01" should be sent out as "0b1000 0000", which is precisely what the code is doing.

> !!(val & (HIGH << 0))

the "!!" operator is often used to turn a logic value into either '1' or '0'.

the code for shiftout() can be greatly improved.


body:
First of all, PORTD represents the current output state of 8 physical GPIO pins (I think some devices have fewer pins on a port but usually there's 8).  I think what you're trying to do is shift a sequence out of a single pin. So just reading it will only tell you what each of the 8 pin states are at that moment, not what you shifted out.  I think Arduino's way of doing things is actually harder than just writing the plain C code so I'll ignore it (what is the '!!' ???).

So taking a step back, here's code for pushing an 8bit number serially out of a pin:

    uint8_t serialData = 0b10011101;  // random data to shift out
    uint8_t pin = 3;                  // the pin on PORTD we want to toggle

    uint8_t i;
    uint8_t nextBit;
    for (i = 0; i < 8; i++) {

      // Find the nextBit value to set by shifting our input data by our index
      //   and clearing the other values.  E.g. if serialData == 0b10011101 and
      //   i == 2 then (0b10011101 >> 2) == 0b00100111.  0b00100111 & 1 == 1
      nextBit = (serialData >> i) & 0b00000001;

      // If the next bit is a one, we "or" it to set it
      if (nextBit) {
        // The 'or' operator can only set bits to 1
        PORTD |= 1 << pin;        // in this case, (1 << 3) == 0b00001000
      } else {
        // The 'and' operator can only clear bits to 0
        PORTD &= ~(1 << pin);    // in this case, ~(1 << 3) == 0b11110111
      }
    }

If you want to add a "clock" pin to go along with the data (like the arduino code) then you can set the clock pin to whatever state before the "for" loop then use an "xor" operator to toggle it each time through the loop:

    clockPin = 4;

    // just before the 'for' loop set the clock to whatever starting state you
    //   want.  In this case I'll start it at 0.
    PORTB &= ~(1 << clockPin);
    .
    .
    .
    // Now in the 'for' loop (at the bottom for example)
    PORTB ^= (1 << clockPin);

If you want the clock to toggle up then down in a sing loop cycle then you can just repeat the 'xor' twice in a row or force the state using 'or' and 'and' operators.  Also, pay attention to timing, you might be toggling things too quickly if the microcontroller clock is fast.  You can add delays to the loop to shape the timing of the pattern.


message:
How do I know the IP address assigned to an ESP8266?

I have programmed an ESP8266 using the circuit and program below. I tried to open the SerialMonitor once the program is uploaded to the ESP8266. I am getting an error when I am trying to open the SerialMonitor.

> Error opening serial port 'COM5'. (Incorrect serial port)

What is the way to get the IP address assigned to the ESP8266?

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    //SSID and Password of your wifi router
    const char* ssid = "Moto";
    const char* password = "reset1234";

    ESP8266WebServer server(80);

    void setup() {
      Serial.begin(9600);
      WiFi.begin(ssid, password); //Connect to your WiFi router
      Serial.println("");
      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      //If connection successful show IP address in serial monitor
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());  //IP address assigned to your ESP
      server.begin(); //Start server
      Serial.println("HTTP server started");
    }

    void loop() {
      server.handleClient(); //Handle client requests
    }

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

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/BzYbU.jpg
  [2]: https://i.stack.imgur.com/wbfgI.png

body:
If you give your board a name with

    WiFi.hostname("MyESP8266");

(for example) you can then look on your router in the section that lists DHCP assignments (on my Netgear it's *Attached Devices*). That should then show you the IP address of all the attached devices, including the ESP8266 which you will easily identify by its name.

Another option is to use mDNS. Look at some of the examples that come with the ESP8266 core and libraries to see how.


body: I used the app "Fing" on my phone. It shows you the devices that are connected to your WiFi. After entering all freacking IP adress aviable, found that the last one was the one of my esp8266 and a beautiful window saying "hello from esp8266!" appeared.


message:
loading custom code onto SparkFun Blynk Board

we're trying to add some code to the SparkFun Blynk Board. We don't want to overwrite the firmware, because that allows it to work with the iphone app, but we need to add our own voids and Blynk. Write commands in order to control this servo RC car via wifi wit the Joystick XY. any ideas?

our code:

    #include <Servo.h>
    #include <SPI.h>
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <Adafruit_NeoPixel.h>
    #include <SoftwareSerial.h>
    //#define BLYNK_PRINT Serial

    char BlynkAuth[] = "6dfb81c116d84003a505056239c23559";
    char ssid[] = "Linksys23266";
    char pass[] = "roboboyz";

    Servo servoR;
    Servo servoL;

    int pos = 90;

    void forward()
    {
      servoR.write(110);
      servoL.write(110);
    }

    void turnRight()
    {
      servoR.write(80);
      servoL.write(90);
      delay (2000);
    }

    void turnLeft()
    {
      servoR.write(90);
      servoL.write(80);
      delay(2000);
    }

    void reverse()
    {
      servoR.write(70);
      servoL.write(70);
      delay(2000);
    }

    void Stop()
    {
      servoR.write(94);
      servoL.write(94);
      delay(2000);
    }

    void setup()
    {
      Blynk.begin(BlynkAuth, ssid, pass);  // wifi username and password
      servoR.attach(12);
      servoL.attach(13);
      Serial.begin(9600);
      delay(1000);
    }

    BLYNK_WRITE(V1)
    {
      int x = param[0].asInt();
      int y = param[1].asInt();

      // Do something with x and y
      Serial.print("X = ");
      Serial.print(x);
      Serial.print("; Y = ");
      Serial.println(y);
      if(y>220)
      forward();
      else if(y<35)
      reverse();
      else if(x>220)
      turnRight();
      else if(x<35)
      turnLeft();
      else
      Stop();
    }

    void loop()
    {
      Blynk.run();
    }

body:
That's not how microcontrollers work. You have one firmware and only one firmware. When you upload firmware you replace the existing firmware. You cannot "add" to it.

Instead you will have to write a new firmware that contains *all* the code you need to do the *entire* job.


message:
Wifi proof with WeMos D1 ESP8266 Ad-Hoc

I am trying to use a WeMos module to send a broadcast message through an peer-to-peer network (Ad-Hoc). The thing is that i can't give a SSID nor Password to that network, i just can define it through them IP Addresses. As you suspect i don't have a specific idea of the configuration of the Wemos module.

**What am I talking about?**

I need to receive messages in a IEEE802.11 software-defined radio module. In this module I can't establish a network, just listen to a channel, and read whatever someone is sending. Think about it as a sniffer. But in this case i can assign to this module a MAC and IP within the Network.

**What do I need?**

I need just to:

    Initialize peer-to-peer (Ad Hoc) network without an SSID nor Password.
    Set a channel (I do it with channel 13, it is most times free).
    Send a broadcast message in that channel to the SDR module in the network.

**In other words**
Module SDR:
 - IP:192.168.123.2
 - MAC: xxx
Wemos
 - IP:192.168.123.3
 - MAC: xxx

Through Wemos:

 - wifi, send broadcast message

The mask is /24, then it is going to send the message to all IPs from 192.168.123.2 to 192.168.123.254, then, for sure to the SDR Module, and i could receive it.

Thanks in advance.

Best regards,

Cristian

body: ESP8266 does not currently support Ad-Hoc/IBSS mode.


message:
Speedometer slow reaction arduino

I'm trying to make a speedometer, with utilization of interrupt for get number of pulse and some calculation for getting speed, but when compute speed the arduino freeze for some second and i lose alot of impulse and false all my successive capture of impulse. Why? thanks for reply

    const int contaImpulsi = 2;
    volatile int impulsi =  0;
    int impulsiOld = 0;
    static int appoggio = 0;
    unsigned deltaT[3];
    unsigned vel = 0;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(contaImpulsi, definisciTempi, RISING);
    }

    void loop() {

      if (impulsiOld == impulsi || impulsi > impulsiOld)
      {
        if (appoggio == 3) {
          deltaT[3] = millis();
          appoggio = 0;
        }
        if (appoggio == 2) {
          //Serial.println("ASSEGNO DELTA T 2");
          deltaT[2] = millis();
          //Serial.println(deltaT[2]);
          appoggio = 3;
        }
        if (appoggio == 1) {
          //Serial.println("ASSEGNO DELTA T 1");
          deltaT[1] = millis();
          appoggio = 2;
        }
        if (appoggio == 0) {
          //Serial.println("ASSEGNO DELTA T 0");
          deltaT[0] = millis();
          appoggio = 1;
        }
      }
      impulsiOld = impulsi;

      if (appoggio == 3) {

        int t1 = (deltaT[1] - deltaT[0]);
        int t2 = (deltaT[2] - deltaT[1]);
        int dividi = t1 + t2;
        vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85; // here i think is where the program freeze

        Serial.println("------------------------------------------");
        Serial.print("SPEED: ");
        Serial.println(vel);
        Serial.println("------------------------------------------");
      }
    }

    void definisciTempi() {
      impulsi++;
    }

body:
First off a comment on your variable types. It's not the cause of your problem, but just something to watch for in future:

    int impulsi =  0;

This should be voltatile (Edit: I see you updated that, that's ok).

    unsigned deltaT[3];
    unsigned vel = 0;

These lack a type. As such the default to `int`. Your deltaT array should be `unsigned long` since it stores time. It will overflow very rapidly otherwise.

Now on to your problem.

The core of your problem is your methodology of calculating the speed. This bit:

    if (impulsiOld == impulsi || impulsi > impulsiOld)
    {
      ...
    }
    impulsiOld = impulsi;

is going to be running pretty much always. That's because `impulsiOld` and `impulsi` will either always be the same (since you set them to be the same) or `impulsi` is going to be greater than `impilsiOld` since you received a pulse in the brief interlude when it's not running that bit.

And that means that all your `deltaT` entries are going to be the same most of the time.  Which leads me on to the next bit:

    int t1 = (deltaT[1] - deltaT[0]);
    int t2 = (deltaT[2] - deltaT[1]);
    int dividi = t1 + t2;
    vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85;

If `delatT[1]` and `deltaT[0]` are the same, then `t1` will be `0`. The same goes for `t2`. `0 + 0 = 0`, so `dividi` will also be 0.

And that means:

    690 * 2000 / 0

Which will be a *divide by zero exception* and will cause the MCU either to lock up or to reboot. If the latter you will see the bootloader run for a couple of seconds.

There are two normal methods of calculating the speed from pulses, and I am not sure what your method is trying to be.

The simplest one is to just count the number of pulses over a given period. Increment the count in your ISR, and after a second has elapsed (or longer, or shorter, depending on the frequencies you are working with) you reset the count to 0 (after storing it elsewhere) and calculate the speed from that stored count.

The other way is to just take the time between two successive pulses. You can average it, maybe with a rolling (AKA moving) average, or just take the raw value depending on what you are measuring.  This method is a little harder since you need to do more work per pulse.

The two methods differ in critical ways when it comes to outputting the results. The first method will always give you a value every second (or whatever time period you use), but it can't cope with pulses that are further apart than the time period you use. The second method doesn't much care about the time between the pulses, but you can only get a meaningful reading if a pulse arrives, which if that is a while means you get no reading for a while. It's harder to determine "not moving" from that.

Also you should look at the use of *critical sections* when accessing your `impulsi` variable outside the interrupt routine. It more than 8 bits, so all access to it will be *non-atomic* and could be interrupted by the ISR.


message:
Problem with Arduino and INA226 power meter module

I am new to the use of Arduino in general, and to the INA226 Module for power metering.

I first got everything set up WITHOUT anything plugged to the INA226 module metering pins (V+, ISens+, Isens-, V- not connected to any power source) and running a sample code that gets data being read by the INA226, of course, all values return 0, but at least I know the program runs and the arduino can connect to the INA226. Now, the problem comes when I try to get some reading such as 5V or even 3.3V from the Arduino pins.

I connected the circuit as follows:

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

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

<!-- End schematic -->

(I noticed that I wrote A6 instead of A4, sorry about that)

But when I do this, there is no reading at all from the serial console. I tried connecting the V+ and Isens+ directly to the 5V pin leaving everything else as shown in the diagram, but the Arduino board doesn't even turn on.

I tried referencing other sources, but their tests use external power supplies or other equipment I don't have.

I would be really thankful if someone could lend me a hand here or help me understand why am I having this problem and how can I make it read something basic such as 5V or 3.3V directly from the Arduino board.

Thanks!

body:
There is a discrepancy in pin terminology between your schematic & what TI uses in their datasheets. I don't see anything in their datasheets using I+ or I-. I only see V+ & V-. These 2 pins perform all your voltage & current measurements depending on the "mode" you tell the IC to use.

As near as I can tell based on your schematic, you should be seeing the voltage reading based on what is applied between V+ & V- (In your case, 3.3vdc) if you've told the chip to read the bus voltage channel.

You should also be getting a current reading between the V+ & V- pins if you've told the chip to read the shunt voltage channel. Since the part is designed for a full scale voltage differential of 36v between the V+ & V- pins, I suspect a reading of about 10% of max (based on a 3.3v differential).

I confess to not knowing the board or its operation but having looked it up on the TI website, it does appear to have a few jumper settings & a calibration routine to follow. There's a user guide on TI's website as well as the usual technical data pages. Perhaps those will assist in setting the jumpers correctly. [ina226 data sheet][1] & [eval board user guide][2]
[1]: http://www.ti.com/lit/ds/symlink/ina226.pdf
[2]: http://www.ti.com/lit/ug/sbou113/sbou113.pdf
bc


body:
If this is the usual Arduino-style module with a shunt resistor already in it, then with your schematic, you have [nearly] shorted your supply rail. Your schematic should have the load wired in series to the `Isense+` and `Isense-` terminals, and the `V+` and `V-` terminals should be connected in parallel across the voltage powering the load.

The current must "pass through" the `Isense` terminals, and the module has to measure the voltage across the load in order to be able to get both I and V to compute power consumption.


message:
Wrong computation Number

im trying to make a speedometer with arduino Nano Board but when i use interrupt im getting "strange" number on variables `t1` or `t2` going under 0 there is the code:

    volatile int impulsi =  0;
    int impulsiOld = 0;
    volatile int appoggio = 0;
    //static int inizioDiNuovo = 0;
    volatile unsigned int deltaT[3];
    long t1=0;
    long t2=0;

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

      pinMode(2, INPUT_PULLUP);
      attachInterrupt(0, definisciTempi, RISING);

    }

    void loop() {

      Serial.println(impulsi);
      if (impulsi == impulsiOld || impulsi > impulsiOld)
      {
        ;
      }
      //Serial.print("N IMPULSI: ");
      //Serial.println(impulsi);
      if (appoggio == 3) {
        appoggio = 0;
        Serial.print("DELTA T 0 : ");
        Serial.println(deltaT[0]);
        Serial.print("DELTA T 1 : ");
        Serial.println(deltaT[1]);
        Serial.print("DELTA T 2 : ");
        Serial.println(deltaT[2]);

        t1 = (deltaT[1] - deltaT[0]);
        if (t1 == 0) {
          t1 = 1;
        }
        t2 = (deltaT[2] - deltaT[1]);
        if (t2 == 0) {
          t2 = 1;
        }
        int t = t1 + t2;

        Serial.print("TEMPO T1 ");
        Serial.println(t1);
        Serial.print("TEMPO T2 ");
        Serial.println(t2);

      }

    }

    void definisciTempi() {
      impulsi++;
      switch(appoggio){

        case 2:
        //Serial.println("ASSEGNO DELTA T 2");
        deltaT[2] = millis();
        //Serial.println(deltaT[2]);
        appoggio = 3;
        break;

        case 1:
        //Serial.println("ASSEGNO DELTA T 1");
        deltaT[1] = millis();
        appoggio = 2;
        break;

        case 0:
        //Serial.println("ASSEGNO DELTA T 0");
        deltaT[0] = millis();
        appoggio = 1;
        break;

      }
    }

how suggest i changed

    unsigned int t1=0; unsigned int t2=0; into `long t1=0; long t2=0;`

output on Serial now have negative number it's for the interrupt??:

    DELTA T 0 : 8785
    DELTA T 1 : 8666
    DELTA T 2 : 8706
    TEMPO T1 40
    TEMPO T2 -119  <------how 8706-8666= -119 ?

this is my pulse generator code:

    const int pin = 2;
    void setup() {
      pinMode(pin,OUTPUT);

    }

    void loop() {
     digitalWrite(pin,HIGH);
     delay(40);
     digitalWrite(pin,LOW);
     delay(40);
    }

body:
unsigned int t1=0;
    unsigned int t2=0;

Integers on an 8 bit system can only store 16 bits of data. For `unsigned` that is 0 - 216-1, or 0 - 65535.

Make them `unsigned long` and they can store 0 - 232-1, or 0 - 4294967295.

Also, since they are `unsigned`, any negative value will *wrap around* to the maximum again. An `unsigned` can't store a negative value.


body:
The interrupt may be triggering between the Serial.print and the actual calculations, as stated by @Andrew.

Evidence supporting that fact is that your deltas are recorded in order 0, 1, 2 (ie: delta 0 < delta 1 < delta 2), However in the example output delta 0 is larger than delta 2, which suggests that a new round of delta recordings had started but not yet completed.

Updating this section as follows should fix the issue:

    if (appoggio == 3) {

      noInterrupts(); // Disable interrupts while calculating

      appoggio = 0;
      Serial.print("DELTA T 0 : ");
      Serial.println(deltaT[0]);
      Serial.print("DELTA T 1 : ");
      Serial.println(deltaT[1]);
      Serial.print("DELTA T 2 : ");
      Serial.println(deltaT[2]);

      t1 = (deltaT[1] - deltaT[0]);
      if (t1 == 0) {
        t1 = 1;
      }
      t2 = (deltaT[2] - deltaT[1]);
      if (t2 == 0) {
        t2 = 1;
      }
      int t = t1 + t2;

      Serial.print("TEMPO T1 ");
      Serial.println(t1);
      Serial.print("TEMPO T2 ");
      Serial.println(t2);

      interrupts(); // re-enable interrupts

    }


message:
HMC5883L tilt compensation

I have a HMC5883L 3-axis magnetometer. I would like to add tilt compensation to my Arduino Uno project.

Since the IC has 3 axis that it measures (X,Y,Z) is it possible to add tilt compensation without an accelerometer? If yes would this how do I find an equation to do the calculation. Is this equation found from http://bluelemonlabs.blogspot.fi/2013/08/arduino-simple-compass-with-hmc5883l.html correct?

body:
No. You need an accelerometer.

If you read the article you link to you can see this bit:

> There are many margin of improvement. First, we ought compensate the potential tilt of the device using the accelerometer data from the ADXL345, for example using the info on [my previous post](http://bluelemonlabs.blogspot.it/2013/08/arduino-imu-pitch-roll-from-adxl345.html)!

To do tilt compensation you need three axes of both magnetometer data and accelerometer data to scale and merge those three axes.


message:
Did I damage my Arduino?

[![enter image description here][1]][1]I was trying to build a Bluetooth controlled car. I was near completing it but what I did wrong was that I connected the 5 V output of L298 motor driver to 5V pin of Arduino where I was supposed to connect it in Vin. My Arduino got heated for a couple of seconds. Knowing that I immediately disconnected. Now serial port doesn't work in my Arduino. The serial port option turned gray. I even tried replacing the ATmega IC but got the same result. What might have happened?

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

body:
Yes, it sounds like you fried something.

I can't quite make out what it was you did from your description (I'm sure it makes perfect sense to you with the hardware in front of you), but the symptoms do sound somewhat fatal.

What actually happened depends very much on the Arduino you have - if it's a genuine one or a cheap Chinese clone. Either way the USB circuitry seems to not be functioning. Whether that is because the USB chip (varies depending on if it's a real Arduino [ATMega16U2] or a clone [CH340G]) or one of the voltage regulators is unknown.

You should power the board up normally and test the voltages at the 5V and 3.3V pins. Also if a component is still getting hot you should note which component it is, and that will give more of a clue as to what went wrong.


body: You fried it you should ALWAYS double check connections before powering on your arduino but I do suggest doing a normal power up without any connections to see what happens


body:
The ATmega328 on these boards is 5V tolerant on GPIOs so it depends on where exactly you connected the cable.

GND pins, for example, would've been fatal.


body:
it feel sad to hear that you just fried it up. Every mistakes gives opportunity to learn tons of knowledge.
In this case you supplied 5v supply to 5v output pin. If you've seen the datasheet of  **8-bit AVR Micro-controller ATmega328/P** you'll know that it just possess VCC for 5v supply pin (input) neither an output 5v pin. Its the job of voltage regulator attached next to the power jack to supply 5V to provide the necessary juice to the chip. If you supplied 5v to GPIO output pin then you may or may not have burnt the chip but for sure you burnt the arduino board ,technically its power control system. So i think it'll be better buying a new board rather then fixing it.But i salute your attempts.


message:
How to know positive and negative in breadboard

I have this breadboard, and there is no indication on it about what is positive/negative on it.

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

In comparison, this other breadboard (pic from the internet) DOES have indications:

[![enter image description here][2]][2]

Can anyone give me a hint ?

  [1]: https://i.stack.imgur.com/36SHzl.jpg
  [2]: https://i.stack.imgur.com/CH3KF.jpg

body: As gre_gor said. A simple breadboard contains of rows and columns of connections but sometimes for convenience manufacturer marks or prints Positive and Negative symbol along the row as they are usually used to power a circuit


body:
You decide which rails are positive and which are negative when you connect them to the + an - from your power supply or battery.

A breadboard isn't polarised *per se*. It's just a bunch of cross-connections inside a perforated plastic case. No active or passive components inside.

Some manufacturers may choose to paint indications regarding where to connect the positive and negative rails, but those are just a guideline. Ultimately it's your choice, you're free to connect + and - wherever you want in the breadboard rails.


body:
Connections in the two strips along the edge running top to bottom in your image are connected (in the way you have the image placed) top to bottom.  So, all pins are connected to each other in each of those rows.  Within the inner secions, the connections are (in your image) across from one side to the other.

You decide how you want the power supply cable to be connected to your breadboard,  just becasue there's no indicators means that they simply haven't drawn any coloured lines on the breadboard.  You can draw red and black lines on however you wish.


message:
How to keep a specific bit set all the time for bit masking I2C operations?

I've been working on I2C and I learned how to initialize, send and receive with I2C communication protocol.

Next, I wanted to run the LCD1602 I2C adapter. But the module has a different bit masking, it turns out that I have to keep a specific bit set so I can control the remaining 7-bits, because otherwise I can't control the upper 4-bits if this bit is 0.

So, I put the 8-bit variable for the bit masking operations in the global section and initialize it with uint8_T bitmasking = 0x08; but it's volatile. I used static keyword, but the bit is not constant.

So what's the solution?

Regards,

body:
'static' just avoids reinitialization and is used for local vars in timed interrupts for example.

`volatile` is another keyword you should not be using without thinking about it and does not appear to be useful for your case. See https://stackoverflow.com/questions/4592762/difference-between-const-const-volatile for more information

The appropiate keyword would be `const`, which tells the compiler this var mustn't be changed.

But I suspect there is another problem with your code, which will make the compiler throw an error as soon as you use `const` in the declaration.
I assume you are not using the variable correctly. You are meant to use a bitwise OR `|` in order to set the required bit **along** your actual data.

So do it like this:

    data_byte |= bitmasking;
    write8(data_byte);


message:
How to reset ESP8266 wifi module

I have programmed `ESP8266` to make it accessible over the network using below program.

**First Program**

 #include <ESP8266WiFi.h>
 #include <WiFiClient.h>
 #include <ESP8266WebServer.h>

 //SSID and Password of your wifi router
 const char* ssid = "Moto";
 const char* password = "reset1234";

 ESP8266WebServer server(80);

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

   WiFi.begin(ssid, password);     //Connect to your WiFi router
   Serial.println("");

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

   //If connection successful show IP address in serial monitor
   Serial.println("");
   Serial.print("Connected to ");
   Serial.println(ssid);
   Serial.print("IP address: ");
   Serial.println(WiFi.localIP());  //IP address assigned to your ESP

   server.begin();                  //Start server
   Serial.println("HTTP server started");
 }

 void loop() {
   server.handleClient();          //Handle client requests
 }

It is working fine, What is the way to reset it to run below program? I wanted to send AT commands on serial monitor using below program which has been uploaded successfully but not responding AT commands on Serial Monitor, as ESP8266 is running above program and showing output of above program on running below program on Serial Monitor.

I want to reset ESP8266 so it responds to below program. What is the way ?

    Connected to Moto
    IP address: 192.168.43.115
    HTTP server started

**SecondProgram**

 #include "SoftwareSerial.h"

 SoftwareSerial esp8266(2, 3); // RX, TX

 void setup()
 {
   Serial.begin(9600); // serial port used for debugging
   esp8266.begin(9600);  // your ESP's baud rate might be different
 }

 void loop()
 {
   if(esp8266.available())  // check if the ESP is sending a message
   {
  while(esp8266.available())
  {
    char c = esp8266.read();  // read the next character.

    Serial.write(c);  // writes data to the serial monitor
  }
   }

   if(Serial.available())
   {
  delay(10);  // wait to let all the input command in the serial buffer
  Serial.write("Hello");
  // read the input command in a string
  String cmd = "";
  while(Serial.available())
  {
    cmd += (char)Serial.read();
  }
  // send to the esp8266
  esp8266.println(cmd);
   }
 }

body:
You need to reinstall the AI Thinker AT firmware.

Here's how you do it: [How to flash ESP8266 firmware update ESP-01 AI thinker][1]

Last time I did it I used the [esptool.py](https://github.com/espressif/esptool) program, and used the [ai-thinker-0.9.5.2.bin](http://wiki.aprbrother.com/wiki/Firmware_For_ESP8266) firmware (there's two versions on there, the default 115200 baud, and a 9600 baud variant).

On Linux I then used the command:

    foo@bar:~$ ./esptool.py --port /dev/ttyUSB0 --baud 57600 write_flash 0 ai-thinker-0.9.5.2.bin
    Connecting....
    Detecting chip type... ESP8266
    Uploading stub...
    Running stub...
    Stub running...
    Configuring flash size...
    Auto-detected Flash size: 512KB
    Flash params set to 0x0000
    Compressed 520192 bytes to 165297...
    Wrote 520192 bytes (165297 compressed) at 0x00000000 in 29.0 seconds (effective 143.3 kbit/s)...
    Hash of data verified.

    Leaving...
    Hard resetting...

This was, of course, with GPIO0 held LOW for programming mode (I actually use an adaptor with a programming switch that controls GPIO0), and for other operating systems you will need to change the port name to suit (`COM3:`, `/dev/cu.usbmodem4873`, etc).

  [1]: http://www.esp8266.com/viewtopic.php?f=15&t=12440


message:
Is it any way to connect ESP8266 to wifi faster?

I'm uploading this sketch to try connecting ESP to internet. However, most of the times I've ran it it takes a very long time to connect, a lot of times I've had to break the process because it seems it goes to nowhere. Few times it has connected in less than a minute. Is it any alternative to boost the connection?

Also, when I reset the module, it writes to the terminal 3 strange characters, and freezes without even starting to execute its sketch. Do you mind me asking how to solve that?

Regards!

    #include <ESP8266WiFi.h>

    const char red[] = "CDT10";
    const char pass[] = "G7ZSY74Cs";
    unsigned long muestra = 0;

    void setup() {
      Serial.begin(9600);
      WiFi.mode(WIFI_STA);
      WiFi.begin(red,pass);
      while (WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(1000);
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.print("IP address: "); Serial.println(WiFi.localIP());
      Serial.print("Chip ID: "); Serial.println(ESP.getChipId());
    }

    void loop() {
      delay(5000);
      muestra = millis();
      Serial.println(muestra);
    }

body:
I have also experienced the inability to connect sometimes. I wait a certain amount of time for it to connect then do a ESP.reset() if it fails.

As for the boot problem it sounds like you are keeping GPIO0 low so it goes back into programming mode. Hold it high and it will run your program instead.


message:
7 Segments display with arduino mega2560

I doing a small project with 6 display 7 segment (I will call A1, A2, A3, A4, A5, A6) and 3 cd4543B (I will call Da, Db, Dc) with an arduino mega 2560. I also use 6 transistor to control power supply of display.

Da is use for A1, A2

Db is use for A3, A4

Dc is use for A5, A6

The circuit is done, and work if I use only 4 display I have tried different combination (A1, A2, A3, A4, or A1, A2, A5, A6 or A2, A3, A4, A5, or A3, A4, A5, A6) and all work well.

but If I want to use five or six display, nothing work....

[![here a diagram of my circuit][1]][1]

there is resistance for each segment of each display which not appear on the diagram.

my code for 5 display :

    //Da
    const int bit_A=8;
    const int bit_B=9;
    const int bit_C=10;
    const int bit_D=11;
    //Db
    const int bit_E=22;
    const int bit_F=24;
    const int bit_G=26;
    const int bit_H=28;
    //Dc
    const int bit_I=40;
    const int bit_J=42;
    const int bit_K=44;
    const int bit_L=46;

    // transistors
    const int alim_dizainemillier= 3;
    const int alim_millier=4;
    const int alim_centaine=5;
    const int alim_dizaine=6;
    const int alim_unite=7;

    void setup()
    {

    pinMode(bit_A,OUTPUT);
    pinMode(bit_B,OUTPUT);
    pinMode(bit_C,OUTPUT);
    pinMode(bit_D,OUTPUT);
    pinMode(bit_E,OUTPUT);
    pinMode(bit_F,OUTPUT);
    pinMode(bit_G,OUTPUT);
    pinMode(bit_H,OUTPUT);
    pinMode(bit_I,OUTPUT);
    pinMode(bit_J,OUTPUT);
    pinMode(bit_K,OUTPUT);
    pinMode(bit_L,OUTPUT);
    pinMode(alim_dizainemillier,OUTPUT);
    pinMode(alim_millier,OUTPUT);
    pinMode(alim_centaine,OUTPUT);
    pinMode(alim_dizaine,OUTPUT);
    pinMode(alim_unite,OUTPUT);

    digitalWrite(bit_A,LOW);
    digitalWrite(bit_B,LOW);
    digitalWrite(bit_C,LOW);
    digitalWrite(bit_D,LOW);
    digitalWrite(bit_E,LOW);
    digitalWrite(bit_F,LOW);
    digitalWrite(bit_G,LOW);
    digitalWrite(bit_H,LOW);
    digitalWrite(bit_I,LOW);
    digitalWrite(bit_J,LOW);
    digitalWrite(bit_K,LOW);
    digitalWrite(bit_L,LOW);
    digitalWrite(alim_dizainemillier,LOW);
    digitalWrite(alim_millier,LOW);
    digitalWrite(alim_centaine,LOW);
    digitalWrite(alim_dizaine,LOW);
    digitalWrite(alim_unite,LOW);
    }

    void loop()
    {
     for(int i=0;i<100000;i++)
     {
       afficher_nombre(i);

     }
    }

    void afficher_nombre(int nombre)

    {
     long temps;
     int unite=0,dizaine=0,centaine=0, millier=0, dizainemillier=0;
     dizainemillier=nombre/10000;
     millier=(nombre-(10000*dizainemillier))/1000;
     centaine=(nombre-1000*millier)-(10000+dizainemillier)/100;
     dizaine=(nombre-(centaine*100)-(millier*1000)-(dizainemillier*10000))/10;
     unite=nombre-(dizainemillier*10000)-(millier*1000)-(centaine*100)-(dizaine*10);

     temps=millis();
     while((millis()-temps)<500){

        digitalWrite(alim_dizainemillier,HIGH);
        afficher_CD(dizainemillier);
        digitalWrite(alim_millier,LOW);
        digitalWrite(alim_centaine,LOW);
        digitalWrite(alim_dizaine,LOW);
        digitalWrite(alim_unite,LOW);
        delay(5);

        digitalWrite(alim_dizainemillier,LOW);
        digitalWrite(alim_millier,HIGH);
        afficher_CM(millier);
        digitalWrite(alim_centaine,LOW);
        digitalWrite(alim_dizaine,LOW);
        digitalWrite(alim_unite,LOW);
        delay(5);

       digitalWrite(alim_dizainemillier,LOW);
       digitalWrite(alim_millier,LOW);
       digitalWrite(alim_centaine,HIGH);
       afficher_CM(centaine);
       digitalWrite(alim_dizaine,LOW);
       digitalWrite(alim_unite,LOW);
       delay(5);

       digitalWrite(alim_dizainemillier,LOW);
       digitalWrite(alim_millier,LOW);
       digitalWrite(alim_centaine,LOW);
       digitalWrite(alim_dizaine,HIGH);
       afficher_UD(dizaine);
       digitalWrite(alim_unite,LOW);
       delay(5);

       digitalWrite(alim_dizainemillier,LOW);
       digitalWrite(alim_millier,LOW);
       digitalWrite(alim_centaine,LOW);
       digitalWrite(alim_dizaine,LOW);
       digitalWrite(alim_unite,HIGH);
       afficher_UD(unite);
       delay(5);
     }
    }

    void afficher_UD(int chiffre)
    {
      digitalWrite(bit_A,LOW);
      digitalWrite(bit_B,LOW);
      digitalWrite(bit_C,LOW);
      digitalWrite(bit_D,LOW);

          if(chiffre>=8)
             {
               digitalWrite(bit_D,HIGH);
               chiffre=chiffre-8;
             }
         if(chiffre>=4)
             {
               digitalWrite(bit_C,HIGH);
               chiffre=chiffre-4;
             }
        if(chiffre>=2)
             {
               digitalWrite(bit_B,HIGH);
               chiffre=chiffre-2;
             }
        if(chiffre>=1)
             {
               digitalWrite(bit_A,HIGH);
               chiffre=chiffre-1;
             }
    }

    void afficher_CM(int chiffre)
    {
      digitalWrite(bit_E,LOW);
      digitalWrite(bit_F,LOW);
      digitalWrite(bit_G,LOW);
      digitalWrite(bit_H,LOW);

          if(chiffre>=8)
             {
               digitalWrite(bit_H,HIGH);
               chiffre=chiffre-8;
             }
         if(chiffre>=4)
             {
               digitalWrite(bit_G,HIGH);
               chiffre=chiffre-4;
             }
        if(chiffre>=2)
             {
               digitalWrite(bit_F,HIGH);
               chiffre=chiffre-2;
             }
        if(chiffre>=1)
             {
               digitalWrite(bit_E,HIGH);
               chiffre=chiffre-1;
             }
    }

    void afficher_CD(int chiffre)
    {
      digitalWrite(bit_I,LOW);
      digitalWrite(bit_J,LOW);
      digitalWrite(bit_K,LOW);
      digitalWrite(bit_L,LOW);

          if(chiffre>=8)
             {
               digitalWrite(bit_L,HIGH);
               chiffre=chiffre-8;
             }
         if(chiffre>=4)
             {
               digitalWrite(bit_K,HIGH);
               chiffre=chiffre-4;
             }
        if(chiffre>=2)
             {
               digitalWrite(bit_J,HIGH);
               chiffre=chiffre-2;
             }
        if(chiffre>=1)
             {
               digitalWrite(bit_I,HIGH);
               chiffre=chiffre-1;
             }
    }

I don't understand why it's not working. Could it be a power supply problem ? even if there is never two display used at the same time (delay between them, see code)

Thanks a lot for any help.

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

body:
Try this link [Arduino and CD4543][1]

To control a common cathode seven segment display using CD4543

    PH ( Pin 6 ) should be set LOW.
    LD ( Pin 1 ) should be set HIGH.
    BL ( Pin 7 ) should be set LOW.
[![enter image description here][2]][2]

Try this code for each segment, could be faulty segment too :)

    int Ph  = 6;      //arduino pin connected to the Ph pin of 4543
    int BL  = 5;     //arduino pin connected to the BL pin of 4543
    int LD  = 11;   //arduino pin connected to the LD pin of 4543

    int A   = 7;
    int B   = 9;
    int C   = 10;
    int D   = 8;

    void setup()
    {
        // Declare all the pins as OUTPUT pins

      pinMode(Ph,  OUTPUT);
      pinMode(BL,  OUTPUT);
      pinMode(LD, OUTPUT);

      pinMode(A , OUTPUT);
      pinMode(B  , OUTPUT);
      pinMode(C  , OUTPUT);
      pinMode(D, OUTPUT);

    }

    void loop()
    {

        // Display 0

      digitalWrite(Ph,  LOW);
      digitalWrite(BL,  LOW);
      digitalWrite(LD,  HIGH);

      digitalWrite(A , LOW);
      digitalWrite(B , LOW);
      digitalWrite(C , LOW);
      digitalWrite(D , LOW);

      delay(1000);

        // Display 1

      digitalWrite(A , HIGH);
      digitalWrite(B , LOW);
      digitalWrite(C , LOW);
      digitalWrite(D , LOW);

      delay(1000);

        // Display 2

      digitalWrite(A , LOW);
      digitalWrite(B , HIGH);
      digitalWrite(C , LOW);
      digitalWrite(D , LOW);

      delay(1000);

        // Display 3

      digitalWrite(A , HIGH);
      digitalWrite(B , HIGH);
      digitalWrite(C , LOW);
      digitalWrite(D , LOW);

      delay(1000);

        // Display 4

      digitalWrite(A , LOW);
      digitalWrite(B , LOW);
      digitalWrite(C , HIGH);
      digitalWrite(D , LOW);

      delay(1000);
    }

  [1]: http://www.learnerswings.com/2014/04/control-common-cathode-seven-segment.html
  [2]: https://i.stack.imgur.com/JyAoK.png


message:
Arduino Uno: Receive MIDI data from DAW

I basically want to have my Arduino accept MIDI data from my digital audio workstation, my choice is Ableton Live. I would then like it to check the received data and change the state of a digital pin accordingly. I made a pretty basic schematic to show you.
[![Schematic][1]][1]

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

(Just a very quick diagram, I intend to use RGB LEDs and transistors of some sort in the final product)

I would be happy using a Serial>Midi of some sort if it's the only way, but true USB MIDI would be nice.

body:
The R3's ATmega16U2 supports USB, so all you need to create a USB MIDI device is software.

On AVRs, you typically use the Lightweight USB Framework for AVRs ([LUFA](http://www.fourwalledcubicle.com/LUFA.php)), which has support code for both the basic USB protocol and for USB MIDI.


body:
For USB Midi you could use: Arduino UNO + USB Host Shield + [USBH_MIDI Library](https://github.com/YuuichiAkagawa/USBH_MIDI)

The library is specifically for the USB Host Shield. I've used this to take MIDI over USB from a digital piano and used it to control some LEDs. It's pretty strait forward to get it all working.


message:
LEDs effects changing with a button

So I have a bunch of functions (methods) made and I want to make it so that if the button is clicked (single click) the effects to change... I thought something like:

    buttonState = digitalRead(buttonPin);
    if(buttonState==HIGH) {
      counter++;
      if(counter>2) {
        counter=0;
       }
     }
    if(counter==0) {
      Foo1();
    }
    if(counter==1) {
      Foo2();
    }
    if(counter==2) {
      Foo3();
    }

But I noticed that it will only read the input button(buttonPin) if I click the button in the exact time (when the function has already ended and at digitalRead time)... So is there some way to do it even if the function is in progress to cancel it and go to the other ones (some way that the digitalRead will read it non stop)?

body:
I think you want to look at interrupts.  You are right, unless the button happens to be pressed when you read the state of it you won't see it as pressed.  If you `foo`s take a long time to execute the you will miss button presses.

What you can do is use 'interrupts'.  Certain pins can be configured to stop the main program and run a small bit of code (that can't do certain things).  For instance they can change the value of a global `volatile` variable.  Next time the program reads the variable it will read the new value (volatile prevents the value being cached by the processor).

With you current code, you would remove the digital read line, and the `if (buttonState == HIGH)` block and move those into you ISR.  This would mean every click would be counted.  If you wanted the ISR to stop the current `foo` and move on then you `foo`s would need to check a flag that the ISR also set and when they see it they return.

In the ISR you can't call Serial.print() etc, it takes too long and your ISR won't work.  Keep it fast and small.

https://www.arduino.cc/en/Reference/AttachInterrupt
https://www.arduino.cc/en/Reference/DetachInterrupt


body:
I had been timing single click as part of a minimal button debouncer (wich is part of a larger project).

According to my tests, the duration of button press is as follow:

 - Quick fire press. Average, 40-70 ms per button press.
 - Normal quick. Average, 150 ms per button press.
 - Long press. Over 400 ms (very personal).

Now, if you loop takes less that 40 ms, your sketch still can catch almost any button press. If you restrict to "normal" button presses, your `loop` can take up to 150 ms without trouble.

So, profile your app. Measure your worst case scenario and the take action.

*We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evi*l. Donald Knuth


message:
Is there a Serial write buffer limit and does the Arduino reset if it is hit?

I have an Arduino Mega 2560 that is resetting every 32 seconds if the serial monitor is not attached. Just before it resets, there is a flash of TX, then it goes. If ther serial monitor is attached it runs forever. Clearly I can't use the serial monitor to debug this so am clutching at straws as to what is happening.

**Update:**

Having eliminated *all* code and uploaded an empty sketch, no includes etc., the board still exhibits the reset. However, I have an Adafruit Ultimate GPS attached to the GND, 5V, TX1 and RX1 pins. When I remove it the resets stop. But with it attached and the serial monitor attached to the board, the resets also stop, even with an empty sketch. Spooky.

So, is it possible the GPS unit is filling a receive buffer, even if the serial port isn't set up to receive? I still have a problem that while I'm clearing and logging the GPS data, the resets are still at a regular 32 seconds, thus the reason I'm working on it still.

**Note:** The flash of TX no longer shows up with the empty sketch.

body:
It turns out this problem had a very different cause, once I was able to eliminate the other variables. Having disconnected literally every component from the board and uploaded an empty sketch:

    void setup() {}

    void loop() {}

the board would still periodically reset itself.

I eliminated:

  - flushing the receive buffers,
  - eliminating all receives by disconnecting pins,
  - speeding up/slowing down the serial port/s,
  - speeding up/slowing down the GPS reporting rate,
  - auxiliary hardware,
  - code,
  - includes,
  - defines,
  - laptop power supply noise,
  - board revision in Arduino IDE,
  - Arduino IDE version,
  - USB port on laptop,
  - trying [this hack][1] to prevent the RESET pin from going low,
  - another Mega 2560 and a Due

None of the above influenced the issue.

The thing I did not think to check was whether the board would work with another power supply alone. This was a result of hunting for another power fault in service and with the laptop plugged in, finding a periodic, random reset.

Ultimately, I plugged the board into a monitor USB output, then a car charger power supply and finally found the issue was eliminated. Even plugging into another computer solved the issue. It appears that either the Arduino driver in Windows or the Arduino IDE software itself, would periodically poll the port, causing the board to reset. While the serial monitor was running, I assume the driver or IDE felt no need to poll the port, thereby leaving the board un-reset.

  [1]: http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection


message:
Arduino/Genuino 101 5 volts pin

Still trying to understand the nomenclature of the pins, I am confused of what's the function of the +5V pin, as I read that the 101 should not operate at that tension.

What's it for?

body:
In Genuino 5V pin is a DC regulated pin. That means when you supply Power (9 to 12 V) to Vin or through the DC Jack, a 5V voltage regulator regulates to give constant output at 5 V. The purpose of that pin is to provide 5V output for other use- as a power supply to some sensor you are interfacing or anything.

However, you can power up the Genuino 101 via the 5V pin. But that is not advisable because in that case it will bypass the regulator present in the board and can damage the circuit if improperly regulated.


message:
Run program from SRAM on SAMD21?

I am looking for an example of how to load a program from sd card to SRAM and execute it from there on the SAMD21.

I understand that the given MCU use the Von Neumann architecture and all code is privileged.

body:
There's two aspects to what you want to do - one (relatively) easy, and one (comparatively) hard.

The first thing you will need is some way of getting your program into RAM. That would mean some software running on the chip that will accept the program and place it into RAM then execute it. You will have to write your own bootloader-like program that runs in Flash that will perform the task.

The second, harder, thing is to compile your program in such a way that it will execute from RAM. And that's no easy task.

Ideally you want to compile the code as *position independent code* (with the command line flag `-fPIC`), but that depends on the compiler being able to do that for this chip. If not, you will have to compile it so that the code expects to reside in RAM with all addresses used for jumps, etc, going to the right location. And that brings me to the second aspect of compiling, the *linker script*.

If you have your code in RAM you can't also have your variables in the same place in RAM. You will have to subdivide the RAM into two sections - the code execution section and the variable storage section. This is done through the construction of a custom *linker script* which is used during the linking phase of compilation. It tells the compiler where in memory to place everything - code, variables, etc. You will need to craft your own linker script to divide the RAM up in a suitable manner to give you enough room for your code while at the same time not starving it of variable storage space. This will also make sure all jumps, etc, in your code use the right addresses in case you can't (or don't want to) use `-fPIC`.

So, given all that, do you still *really* want to execute code from RAM?


message:
Why doesn't analogWrite() work

Can anybody tell me why these analogWrite() statements are being ignored. The code is entering the "if"statements because the Serial.println() statements are being executed.

        class Pwm
    {
      unsigned long previousMillis = 0;
      unsigned long currentMillis;
      int LED;
      int DELAY;
      int up;
      int down;
      int x;

      public:
      Pwm(int led, int Delay) {

        int LED = led;
        pinMode(LED, OUTPUT);

        DELAY = Delay;
        up = 1;
        down = 0;
        x = 0;

      }

      void Update() {
        currentMillis = millis();
        if (currentMillis - previousMillis >= DELAY && up == 1) {
        analogWrite(LED, x);
        x++;
        previousMillis = currentMillis;
        Serial.println(x);
        if (x == 256) {
          up = 0;
          down = 1;
        }
      }
      if (currentMillis - previousMillis >= DELAY && down == 1) {
        analogWrite(LED, x);
        x--;
        previousMillis = currentMillis;
        Serial.println(x);
        if (x == 0) {
          up = 1;
          down = 0;
        }
       }
      }

    };

    // create Flasher Objects
    Flasher red(12, 1000, 250);
    //Flasher yellow(11, 500, 500);
    //Flasher green(10, 250, 1000);
    //Flasher blue(8, 250, 500);

    // create PWM Objects
    Pwm pin9(9,8);

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

    void loop()
    {
      red.Update();
      //yellow.Update();
      //green.Update();
      //blue.Update();
      pin9.Update();
    }

if I load this code everything works fine. I only have issues with the OOP method.

    int LED = 9;
    int DELAY = 8;
    int up = 1;
    int down = 0;
    int x;
    unsigned long currentMillis;
    unsigned long previousMillis = 0;

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

    void loop() {
      currentMillis = millis();
      if (currentMillis - previousMillis >= DELAY && up == 1) {
        analogWrite(LED, x);
        x++;
        previousMillis = currentMillis;
        if (x == 256) {
          up = 0;
          down = 1;
        }
      }
      if (currentMillis - previousMillis >= DELAY && down == 1) {
        analogWrite(LED, x);
        x--;
        previousMillis = currentMillis;
        if (x == 0) {
          up = 1;
          down = 0;
        }
      }
    }

body:
The constructor in your `Pwm` class declares a local variable `LED` which it sets equal to the parameter `led`. You use the member variable `LED` in other methods, so you probably meant to set the member variable of the same name, not create a local.

Remove the `int` from before `LED = led` in the constructor.


message:
CurieBLE receive data without pairing

I [read][1] [exist][2] [articles][3] about it, but still not understand how to do that.
I have a Genuino 101 and an EEG Headband (neuro interface). Need to get data from neuro device. With external HC-05 bluetooth module the code look like this:

     SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
     bluetooth.begin(57600);
     while (!bluetooth.available()) {}
     byteRead = bluetooth.read();

Has anyone encountered a similar problem?
Thanks!

  [1]: https://arduino.stackexchange.com/questions/21514/how-to-receive-data-via-bluetooth-on-an-arduino-101
  [2]: https://forum.arduino.cc/index.php?topic=370123.0
  [3]: https://www.arduino.cc/en/Tutorial/Genuino101CurieBLECallbackLED

body: HC-05 module is not BLE (Bluetooth 4.0)! HC-05 implements SPP (Serial port profile) over Bluetooth Classic (Bluetooth 2.0). You will need a module with BLE capability and that is not over yet. BLE implements several (hundred) profiles for each task such as heartrate monitor, neuro monitor, time etc etc. Your BLE module must be condigured to receive a specific profile data.


message:
Communication between Arduino and raspberry Pi

So I am working on a ground surveillance robot using Arduino for coding the Gps, motors and ultrasonic sensors and coding in raspberry Pi for facial recognition but now what I want to do is when my robot has gotten to its final waypoint and has stopped it should excute the python file that does the facial recognition by calling it in the Arduino  sketch but I don't know how to do it would be nice if someone could please help me out I appreciate your help in advance thank you

body:
You can't make the Arduino just run the Python script on the Pi. Instead you will have to run some software (probably of your own devising) on the Pi that listens for instructions from the Arduino.

The simplest way is probably to modify your existing Python script so that it runs all the time but sits idling waiting for instructions through the serial port (using pySerial). When it gets the instruction to perform the task you need it then goes off and runs the main bulk of its code. When that is done it can then return the results back through the serial port to the Arduino (if you need such results returning).

How you arrange those instructions to get it to do things is entirely up to you.


message:
Controlling a LED array from Arduino NANO

I have a project Im currently busy with that I need a lot of help with.

What I want to do i create a flat 8x12 grid of LEDs and be able to control each individual LED independently from the others. I want to make "animations" for it (for now Im jut gona patch HIGH LOW through to the LEDs, but Im planning on making a full fledged program later on).

I saw guys on youtube creating LED cubes using the "column and row" technique, but Im not sure if that will work for me because I want to control each one independantly. Thats when my search led me to Shift Registers. Which will work best?

How would I manage the current for all the LEDs

Thank for taking the time to listen to a n00b like me :D

body:
You can control a grid of 8x12 LEDs using 8+12 (20) GPIO pins if your chosen board has that many. If it doesn't you can use a 3-to-8 decoder (e.g., 74HC138 - active low outputs, ideal for driving a P-channel MOSFET for the anodes of each row) to reduce that to 3+12 (15). You could cascade two of them and rotate the arrangement so it's 8+4 (12), though that's harder to do (although you can get 4-to-16 decoders too which would be simpler).

For multiplexing you don't want to use shift registers, they're too slow for smooth updates. You also don't want to drive each LED individually when you're working with that quantity, it just gets unmanageable and the power consumption would be excessive.

If you wanted to use shift registers you could use one (or multiple cascaded) to clock a single bit along them to select each row in turn. You could then reduce the pin requirement to 8+3 (clock + data + reset) though that gets a little more complex to program.

And yes, before you ask, you can address individual LEDs in the grid with multiplexing. You select one individual row (or column, but I'll just say row from now on) at a time and tell it which LEDs to light on that row, then move to the next row. This is why using a 3-to-8 decoder is good because it can only activate one row at a time which is what you want when multiplexing.


body:
There are a lot of ways to do what you want to do. Wiring them up individually would be one possibility those find a chip with that many pins can be a challenge

You can use shift registers, either statically or dynamically.

You can also use display drivers, like 7219 or the ht variants.

...

End of the day it will depend on your application and constraints it has to live under.


message:
How to include userid, pass to WifiClient connect() api

These are my remote server credentials that I want to connect from my local device.

    Server  m12.cloudserver.com
    User  <myname>
    Password  <mypassword>
    Port  19999
    _ or
    api_key 5678909876-009-00d

I want to use the WiFiClient client() API as shown, but where or how do I include the User credentials ? so that I can make a successful connection to the remote server from my device connected over Wifi.

Cut and paste from my Arduino code.

    const int httpPort = 19999;
    if (!client.connect("m12.cloudserver.com", httpPort)) {
     Serial.println("connection failed");
     return;
    }

body: WifiClient provides low level tcp connection. Your server seems to be implementing a REST API interface. Thus you need to construct HTTP headers (GET, POST, etc.) manually as a string. Then you can add your credentials. Before doing so, try to use your server, I mean call api's with the program named `Postman`. Postman runs on Chrome browser. `Postman` can compose such headers for you. Then you can insert them into your arduino code.


message:
How to Sort Elements of Array in Arduino Code?

/How Can i Sort this Array with Descending Order? I need Simplest syntax to use in iterative code.

    lt[6]={35,15,80,2,40,110};

body:
As mentioned in the comments, `qsort` is a good option:

    // qsort requires you to create a sort function
    int sort_desc(const void *cmp1, const void *cmp2)
    {
      // Need to cast the void * to int *
      int a = *((int *)cmp1);
      int b = *((int *)cmp2);
      // The comparison
      return a > b ? -1 : (a < b ? 1 : 0);
      // A simpler, probably faster way:
      //return b - a;
    }

    void setup() {
      // The array
      int lt[6] = {35, 15, 80, 2, 40, 110};
      // Number of items in the array
      int lt_length = sizeof(lt) / sizeof(lt[0]);
      // qsort - last parameter is a function pointer to the sort function
      qsort(lt, lt_length, sizeof(lt[0]), sort_desc);
      // lt is now sorted
    }

    void loop()
    {
    }


message:
How to work with arduino softwareserial communication using HC-05?

This is my first project using bluetooth module HC-05.i am using two of this module.one is with arduino nano(slave) and another one is with arduino uno(master).I have paired them through AT commands .
for testing,i was giving a pulse in pin 7 on nano.if there is a pulse,then slave will send character "1".if not then it will send "0".

in UNO there is an LED connected with pin 13.if master receives '1',then LED will on and if recieves '0',LED will remain off.
here is my source code ----------

slave code=>
[![enter image description here][1]][1]

master code=>
[![enter image description here][2]][2]

the Arduino IDE isn't showing any bug,but code is not working at all.though,i am giving pulse in pin 7 on NANO, the LED in pin 13 on UNO is remaining off.i am at aloss now.please help me as soon as possible..

  [1]: https://i.stack.imgur.com/Fsxzr.png
  [2]: https://i.stack.imgur.com/lPMSM.png

body:
Don't put pictures of you code in a post again, makes life very difficult!

The problem is the first line of the slaves loop

    loop()
    {
        if (slave.available()>0)  // Here is the bug
    ....

So If the "slave" serial port has data available to read then write data.  The master never writes to the slave so the slave never has any data to write, so your slave never sends any data and your master never reads any data.

In short remove that line and it will work.


message:
ESP 8266-01 Library

I've just bought two of these wifi modules in the hope of setting up some sort of sensor network. Please could somebody recommend a good library for the arduino.

Cheers

[![My ESP module][1]][1]

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

body:
You don't need a library.  At the most basic level you fire AT command to it via a serial connection, but that's like using a Ferrari to go grocery shopping once a week.

It has a 80/160MHz processor 10 digital and one analog port (although you got the version where only one digital port is exposed).  You can program it through the Arduino IDE (You need to go to the board manager to download the BSP for it).  Then like Majenko says, it should be talking to the Arduino (over I2C or SPI) and treating the Arduino is the GPIO expander.


message:
Array Addressing

Is it possible to use a name instead of a number to address an array? I was reading about enum lists and thought it might be possible.
ie
int array[3] = {something, somethingElse, somethingMore]

array[second] => somethingElse

I am asking as I have an array looking after flags for several functions and would like to be able to use the function name instead of a number to address the array.

    bool flag[6] = {1, 1, 1, 1, 1, 0}; // Power, Jump 3, Jump 7, Fade 3, Fade 7, Pause active

body:
No, but you can use a `struct`:

    struct flags {
        uint8_t power;
        uint8_t jump3;
        uint8_t jump7;
        .... etc ....
    };

    struct flags myFlags;

    myFlags.power = 1;
    if (myFlags.jump3) {
        .... stuff ....
    }

Or you can continue to use a simple numeric array and assign names to the numbers, either with `#define`, `const` variables, or an `enum`.

    enum flags {
        power, jump3, jump7, fade, fade7, pause
    };

    bool flag[6] = {1, 1, 1, 1, 1, 0};

    flag[power] = 1;
    if (flag[jump3]) {
        .... whatever ....
    }


message:
Triggering Sound - Arduino + Contact Mic

I previously created a sound installation using contact mics and computer (ableton+max msp) where sound would be triggered when people touched/tapped on the object/surface. Now I want to do something similar but want to get rid of the computer as it will be at a night club space where people will be walking around so I don't want to leave the computer there.
What I exactly want to do is to be able to load some sounds into arduino and again use contact mic on the object and when people touch it, the sound will be triggered. I know it won't be as creative as doing it with ableton where there is live-editing possibility but I'm happy with one type of sound in this one. I can probably find some codes here and there but I'm not sure what I exactly need to use to be able to do this.
I have few uno boards and lots of other bits that I've collected but haven't used before, so I would be very happy if you could help me as a novice.

Thank you

body:
If you're asking what kind of sensor you'll need, look for capacitive sensors or there's even this instructable that could be implemented with a conductive material (see link below).

You can definitely do this project without a computer, you just need to figure out the following things:

1) Power consumption - How much current will your Arduino, speaker, sensors, etc use? Calculate your "mAh" from this and determine what kind of battery (my recommendation) will fit your needs.

2) Housing for the arduino+circuitry. If you're doing this in a nightclub you want this to be waterproof/somewhat durable.

3) SD card shield/adapter to store the sounds you want.

I have lots of experience as a hobbyist so please do not hesitate to ask for more questions. Good luck!!

Link to instructable: https://www.instructables.com/id/DIY-Touch-Sensor/