body:
I'm writing a code to print/update the value of sensors for each 10 ms, and I decide to use Timer instead of delay function (I'm afraid it's not exactly 10ms with delay function).But when I watch the result on terminal, it stops running at about 0.5s. I guess there is a problem with my code in using Timer because when I remove timer, it prints normally. I debug all day but still cannot find any errors. I guess this is related to memory or pointer or print function.

Please help me :( !!

Here is the code. The code is very long but you can ignore all the unnecessary things:

      #include <DueTimer.h>

      int mod_11k = 12;
      int mod_17k = 13;

      int analog1 = 0;              //output pin of signal 1
      int analog2 = 1;              //output pin of signal 2
      int analog3 = 2;              //output pin of signal 3

      float xf; float yf;
      unsigned long t1;
      unsigned long t2;

    void myHandler(){
        Serial.print(t2-t1);
        Serial.print(" ");
        Serial.print(xf,3);
        Serial.print(" ");
        Serial.println(yf,3);
    }

    void setup() {
      Serial.begin(38400);
      pinMode(mod_11k,OUTPUT);
      pinMode(mod_17k,OUTPUT);
      Timer1.attachInterrupt(myHandler).start(10000);
      digitalWrite(mod_17k,LOW);
      digitalWrite(mod_11k,HIGH);
    }

    void loop() {
        afficherSig(analog1,analog2,analog3);
    }

    void afficherSig(int pin1, int pin2, int pin3){
      unsigned int i;
      float mes[3];
      float mesflt[3];
      float x; float y;
      int  nb_ech = 10000;
      float res = 0.0049;
      float Te;
      float Tbeg;
      float QR1[2],QR2[2] ;
      float *sol1;float *sol2;float *sol3;
      float P1[4];float P2[4];float P3[4];
      float xprec1[2];float xprec2[2];float xprec3[2];
      float *s1_11k;
      float *s1f_11k;

      float H = 80;

                                           //------------------------------>>>
      QR1[0] = 1;
      QR1[1] = 10;
      QR2[0] = 1;
      QR2[1] = 100;
      P1[0] =QR1[0]; P1[1] =0; P1[2] =0; P1[3] =QR1[0];
      P2[0] =QR1[0]; P2[1] =0; P2[2] =0; P2[3] =QR1[0];
      P3[0] =QR1[0]; P3[1] =0; P3[2] =0; P3[3] =QR1[0];
      xprec1[0] =0; xprec1[1] =0;
      xprec2[0] =0; xprec2[1] =0;
      xprec3[0] =0; xprec3[1] =0;
                                          //------------------------------>>>
      t1 = millis();
      Tbeg= millis();
      mes[0]  = res*analogRead(analog1);
      mes[1]  = res*analogRead(analog2);
      mes[2]  = res*analogRead(analog3);

      xprec1[0] = mes[0];
      xprec2[0] = mes[1];
      xprec3[0] = mes[2];
      Te = (millis() - Tbeg)/1000;
      Tbeg = millis();
      sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
      sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
      sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

                                          //------------------------------->>>
     for(i=1;i<nb_ech;i++) {

        P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
        P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
        P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];

        xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
        xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
        xprec3[0] =sol3[0]; xprec3[1] =sol3[1];

        free(sol1);
        free(sol2);
        free(sol3);

        mes[0]  = res*analogRead(analog1);
        mes[1]  = res*analogRead(analog2);
        mes[2]  = res*analogRead(analog3);

        Te = (millis() - Tbeg)/1000;
        Tbeg = millis();
        sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
        sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
        sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

        mesflt[0] = sol1[0];
        mesflt[1] = sol2[0];
        mesflt[2] = sol3[0];                               // Envoie des résultats  à la sortie série

    //Traitment du signal
        s1_11k = traitement1(mes[0],mes[1],mes[2]);
        s1f_11k = traitement1(mesflt[0],mesflt[1],mesflt[2]);

        x = H*s1_11k[0];
        xf = H*s1f_11k[0];
        y = -H*s1_11k[1];
        yf = -H*s1f_11k[1];
        t2 = millis();
      }
    }

    float *Fkalman(float xprec[2],float ymes,float P[4],float QR[2] ,float Te){
                         // Filtre proprement dit
        float *sol = NULL ;
        sol = (float*) malloc (sizeof(float) * 6);
        float xpred[2];
        float Ppred[4] ;
        float Kf[2] ;
        int q = QR[0];
        int r = QR[1];

        xpred[0] = xprec[0] + Te*xprec[1];
        xpred[1] = xprec[1];
        Ppred[0] = q*q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
        Ppred[1] = P[1] + Te*P[3];
        Ppred[2] = P[2] + Te*P[3] ;
        Ppred[3] = q*q+ P[3];
        Kf[0]  = (Ppred[0]/(r+Ppred[0]));
        Kf[1]  = (Ppred[2]/(r+Ppred[0]));

        sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
        sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);
        sol[2] = Ppred[0]*(1-Kf[0]);
        sol[3] = Ppred[1]*(1-Kf[0]);
        sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
        sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
        return sol;
      }

      float *traitement1(float mes1,float mes2,float mes3)
      {
        float *sol11 = NULL ;
        sol11 = (float*) malloc (sizeof(float) * 2);
        sol11[0] = (mes1-mes2)/(mes1+mes2);
        sol11[1] = (((mes1+mes2)/2)-mes3)/(((mes1+mes2)/2)+mes3);
        return sol11;
      }

Here is the result using Timer (stop at about 0.5 second):
[![enter image description here][1]][1]

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

title: Problem with TIMER in Arduino DUE

Answers: 1

body:
As noted in the last part of [Nick Gammon's answer](https://arduino.stackexchange.com/a/14035/3917) to the question [How does the Arduino handle serial buffer overflow?](https://arduino.stackexchange.com/q/1726), if the serial output buffer fills up, serial output blocks, waiting for an interrupt telling it it's ok to send the next byte out the serial port.  When interrupts are turned off, that interrupt is never processed, so the program deadlocks. Don't do Serial prints in an ISR.

Looking at your code, it looks like a typical message has about 20 characters.  <strike>Sending at 38400 bps, or 384 characters per second, it seems to me the buffer shouldn't fill, even if it's small (16 bytes) instead of large (64 bytes).  However, I don't know of another explanation for the behavior you describe.</strike>

Summary:  In your ISR, just store the current time and other relevant data in volatile variables, set a flag in a volatile variable, and in your main loop print stuff and clear the flag (or clear the flag and print stuff) whenever you see that the flag has been set.

---

*Edit 1:* I've struck out some erroneous numbers above.  Here is a correction:  100 sends per second at 20 characters each is 2000
characters per second.  38400 bps of asynchronous data at 10 bits per transmitted byte is 3840 characters per second.  So the raw data rate should be fast enough that the buffer ordinarily doesn't overfill.

---

In the summary above, I suggested that the ISR store the current time and other relevant data in volatile variables and set a flag in a volatile variable.  That is, read `millis()` and store it, perhaps as follows:

    // at file level ...
    volatile unsigned long isrMillis;
    volatile byte isrFlag;

    // in ISR ...
      isrMillis = millis();
      isrFlag = true;

    // in main loop ...
      unsigned long mlMillis;
      ...
      // when flag is true...
      cli();
      mlMillis = isrMillis;
      isrFlag = false;
      sei();
      // Now do stuff with mlMillis
      ...

However, looking at your ISR, perhaps it should go like the following instead:

    // at file level ...
    volatile float xf, yf, xfc, yfc;
    volatile unsigned long t1, t2, tdelt;
    volatile byte isrflag;

    // in ISR ...
    void myHandler(){
      tdelt = t2-t1;
      xfc = xf;
      yfc = yf;
      isrFlag = true;
    }

    // in main loop ...
      // when flag is true...
      isrFlag = false;
      // Now do stuff with tdelt, xfc, and yfc
      ...

Note that if an interrupt occurs while `xf` and `yf` are in the middle of being computed via your Kalman filter or whatever, the statements  `xfc = xf;` and   `yfc = yf;`   may pick up partially-stored results.  You can avoid that problem at least in part by protecting stores of `t1, t2, xf, yf` in the main loop:

      cli();
      xf = someXResult;
      yf = someYResult;
      t1 = someT1Result;
      t2 = someT2Result;
      sei();

In the above I've pointed out a few issues with races and concurrency and suggested technical solutions.  Those suggestions may be quite wide of the mark rather than appropriate.  In general I don't have a precise understanding of what you are trying to do with the software and don't know what redesign should be done to make it coherent.


body:
For a school project I Have to make an IoT solution in the retail. We were thinking of a smart clothing hanger. We want to make the hanger smart enough to recognize what clothing is hanging on it. In order to do so the clothing has to be able to send some sort of ID to the hanger.

first thing we thought of was RFID but the hanger next to an one hanger would pick up the signal from the other hanger so that wouldn’t be an option.

Does anyone have any other ideas on what we could try to let the piece of clothing talk to the hanger?

title: Identification of IoT

Answers: 1

body:
Well I guess the [signal strength could be measured][1] but clothes hanged in wardrobe are too close to each other to distinguish them. Maybe close range NFC?

**I have other solution to be considered.**

Maybe you look at the wrong touchpoint of that interaction. What if the desired action occurs not while it's already hanged but when user put the clothes on hanger? During that, it's not with other clothes (as you grab the hanger in your hand to put the clothes on it).

There are a few things to consider. I guess people put things only on one hanger at once while having clothes in second hand. How many % of users puts clothes on hanger by grabbing it outside of wardrobe (as mundane event/behavior)?

Why it's important?

**During that interaction there is a moment when user tries to pair single cloth with single hanger separated from the rest.**

The hanger could have additional sensor to know when it happens:

 - Magnetic field sensor and small magnet in collar?
 - Capacitive sensor?
 - Accelerometer?

...so the device will know when that interaction occurs and then activate the reading from single rfid tag.

I guess my answer is more about user experience and the aesthetics of interaction but it can give you some clues to finish your project.

  [1]: https://stackoverflow.com/questions/14237110/calculate-distance-to-rfid-tag


body:
How to format an integer as 3 digit string? If I give `3` formated string should be `003`

    printf("d\n", 3); // output: 003

This doesn't work in Arduino.

title: Format Integer in Arduino

Answers: 1

body:
The standard C function `printf` print to stdout. Arduino doesn't has a stdout. You can print to Serial, but must prepare/format the string first.

Instead of `printf`, use `snprintf`. It prints to a char array, which you later can use with `Serial.print`, or whatever other function that take a string.

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

      char buffer[4];
      snprintf(buffer,sizeof(buffer), "d", 3);
      Serial.println(buffer);
    }

    void loop() {

    }

Note: all the comments apply to this answers.


body:
Is it possible to connect two oled displays via SPI to my Uno and send a single image to both displays, with each refreshing at an identical rate?

I have gotten a single oled display (SSD1306) to work using the U8g2 library, however i am not sure which pins can be shared in a dual display setup. There are no CS pin on my displays, only GND, VCC, SCL, SDA, D/C, and RST.

thanks!

title: Dual OLED displays showing the same image via SPI?

Answers: 0


body:
I am able to synch my ESP8266 running on Arduino core with the time.nist.gov-Server but how can I achieve to trigger i.e. a digital pin in 2 seconds even? What I mean is that following:

 1. The MC recieves the signal for trigger by the user on 09:25:18:312
 2. It waits until it is exactly 09:25:19:000
 3. It triggers the digital out on +2 seconds, on 09:25:21:000

Thanks!!

Edit: Corrected Times.

title: ESP8266 Timing question / Do something in 2 seconds even

Answers: 1

body:
You can, but I think you are probably not looking at the best solution.  This link has details of how to program the "OS" timer http://www.switchdoc.com/2015/10/iot-esp8266-timer-tutorial-arduino-ide/ I haven't tried it, I'm not even sure it will work, but...

The fact that setting the timer interval to 2uS causes issues with the WIFI implies that it might not be accurate enough for your purposes.  It might be better to use "something" to trigger a HW interrupt.  From the moment the interrupt triggers to the moment the signal is sent out on the pin is a calculable finite time, so rather than 2,000,000 uS you want the event to trigger after 1,999,524uS (that's a made up number).

Of course if you are using a device that can trigger a pin on the ESP8266 there is no reason it can't trigger the 'output' pin, without involving the ESP at all.

You could use an RTC DS3221(?), the ESP sets the time on the RTC and then sets the alarm.  The alarm interrupt pin is connected to the ESP and it relays the signal to the output, or the alarm interrupt pin is directly connected to the output pin.  The limiting factor here is the accuracy you require.


body:
I am trying to get the UID of RFID from Arduino to netbeans. I was able to display it to a textfield, but once another rfid was scanned, it is displayed together with the UID from the prev scan. How do I stop Arduino to send data so the only thing displayed in the textfield was the first UID scanned.

Here is Arduino code:

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9          // Configurable, see typical pin layout above
    #define SS_PIN          10         // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    void setup() {
     Serial.begin(9600);  // Initialize serial communications with the PC
     while (!Serial);  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
     SPI.begin();   // Init SPI bus
     mfrc522.PCD_Init();  // Init MFRC522

     //mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
     //Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
    }

    void loop() {
     // Look for new cards
      String code = "";
     if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
     }
     // Select one of the cards
     if ( ! mfrc522.PICC_ReadCardSerial()) {
      return;
     }
      for (byte i = 0; i < mfrc522.uid.size; i++) {
          code += String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" :" ");
          code += String(mfrc522.uid.uidByte[i], HEX);
      }
      code.toUpperCase();
      Serial.println(code);
      mfrc522.PICC_HaltA();
    }

title: Read data from arduino once only serial communications (jSSC)

Answers: 1

body:
Unless there is a fault in the library you are using there is nothing wrong with the Arduino code, this can be seen from the serial output.

The fault is with the receiving java code, pump test data into that to see what is wrong.


body:
My goal is to measure temperature, pressure and humidity using my Arduino Nano and the BME280 (GY-BME/P280).

[![BME280 back][1]][1]
[![BME280 front][2]][2]

To do this I use [this library][3] from SparkFun and that works almost. What I notice is probably invalid values for temperature and no humidity values at all.

The PINs:

 - GND -> GND
 - VCC -> 3.3V
 - SDO -> D12
 - CSB -> D10
 - SDA -> D11
 - SCL -> D13

I have noticed that I can unplug the VCC pin, it makes to difference to the measurements. I find that odd.
And I have noticed that the results are the same for 5V to VCC.

This is the result, I have tested this with I2C and SPI, it's the same:

    Program Started
    Starting BME280.Program Started
    Starting BME280... result of .begin(): 0x58
    Displaying ID, reset and ctrl regs
    ID(0xD0): 0x58
    Reset register(0xE0): 0x0
    ctrl_meas(0xF4): 0x27
    ctrl_hum(0xF2): 0x0

    Displaying all regs
    0x80:9A 70 90 28 92 2D AF 00 76 6F 7D 67 32 00 93 8C
    0x90:C1 D6 D0 0B CF 18 AD FF F9 FF 8C 3C F8 C6 70 17
    0xA0:00 45 82 00 00 00 00 00 00 00 00 00 33 00 00 C0
    0xB0:00 54 00 00 00 00 60 02 00 01 FF 82 13 4E 08 00
    0xC0:00 87 27 FF 00 00 00 00 00 00 00 00 00 00 00 00
    0xD0:58 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    0xE0:00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    0xF0:00 00 00 0C 27 00 00 58 DD 00 82 72 00 00 00 00

    Displaying concatenated calibration words
    dig_T1, uint16: 28534
    dig_T2, int16: 26493
    dig_T3, int16: 50
    dig_P1, uint16: 35987
    dig_P2, int16: -10559
    dig_P3, int16: 3024
    dig_P4, int16: 6351
    dig_P5, int16: -83
    dig_P6, int16: -7
    dig_P7, int16: 15500
    dig_P8, int16: -14600
    dig_P9, int16: 6000
    dig_H1, uint8: 69
    dig_H2, int16: 0
    dig_H3, uint8: 0
    dig_H4, int16: 0
    dig_H5, int16: 0
    dig_H6, uint8: 0

    Temperature: 24.59 degrees C
    Temperature: 76.26 degrees F
    Pressure: 101121.63 Pa
    Altitude: 18.25m
    Altitude: 59.87ft
    %RH: 0.00 %

My script is almost exactly like the example from the library.

    /******************************************************************************
    I2C_ReadAllData.ino
    BME280 Arduino and Teensy example
    Marshall Taylor @ SparkFun Electronics
    May 20, 2015
    https://github.com/sparkfun/SparkFun_BME280_Arduino_Library

    This sketch configures the BME280 to read all measurements.  The sketch also
    displays the BME280's physical memory and what the driver perceives the
    calibration words to be.

    Resources:
    Uses Wire.h for I2C operation
    Uses SPI.h for SPI operation

    Development environment specifics:
    Arduino IDE 1.6.4
    Teensy loader 1.23

    This code is released under the [MIT License](http://opensource.org/licenses/MIT).
    Please review the LICENSE.md file included with this example. If you have any questions
    or concerns with licensing, please contact techsupport@sparkfun.com.
    Distributed as-is; no warranty is given.
    ******************************************************************************/

    #include <stdint.h>
    #include "SparkFunBME280.h"
    //Library allows either I2C or SPI, so include both.
    #include "Wire.h"
    #include "SPI.h"

    //Global sensor object
    BME280 mySensor;

    void setup()
    {
      //***Driver settings********************************//
      //commInterface can be I2C_MODE or SPI_MODE
      //specify chipSelectPin using arduino pin names
      //specify I2C address.  Can be 0x77(default) or 0x76

      //For I2C, enable the following and disable the SPI section
      //mySensor.settings.commInterface = I2C_MODE;
      //mySensor.settings.I2CAddress = 0x76;

      //For SPI enable the following and dissable the I2C section
      mySensor.settings.commInterface = SPI_MODE;
      mySensor.settings.chipSelectPin = 10;

      //***Operation settings*****************************//

      //renMode can be:
      //  0, Sleep mode
      //  1 or 2, Forced mode
      //  3, Normal mode
      mySensor.settings.runMode = 3; //Normal mode

      //tStandby can be:
      //  0, 0.5ms
      //  1, 62.5ms
      //  2, 125ms
      //  3, 250ms
      //  4, 500ms
      //  5, 1000ms
      //  6, 10ms
      //  7, 20ms
      mySensor.settings.tStandby = 0;

      //filter can be off or number of FIR coefficients to use:
      //  0, filter off
      //  1, coefficients = 2
      //  2, coefficients = 4
      //  3, coefficients = 8
      //  4, coefficients = 16
      mySensor.settings.filter = 0;

      //tempOverSample can be:
      //  0, skipped
      //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
      mySensor.settings.tempOverSample = 1;

      //pressOverSample can be:
      //  0, skipped
      //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
        mySensor.settings.pressOverSample = 1;

      //humidOverSample can be:
      //  0, skipped
      //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
      mySensor.settings.humidOverSample = 1;

      Serial.begin(57600);
      Serial.print("Program Started\n");
      Serial.print("Starting BME280... result of .begin(): 0x");

      //Calling .begin() causes the settings to be loaded
      delay(10);  //Make sure sensor had enough time to turn on. BME280 requires 2ms to start up.
      Serial.println(mySensor.begin(), HEX);

      Serial.print("Displaying ID, reset and ctrl regs\n");

      Serial.print("ID(0xD0): 0x");
      Serial.println(mySensor.readRegister(BME280_CHIP_ID_REG), HEX);
      Serial.print("Reset register(0xE0): 0x");
      Serial.println(mySensor.readRegister(BME280_RST_REG), HEX);
      Serial.print("ctrl_meas(0xF4): 0x");
      Serial.println(mySensor.readRegister(BME280_CTRL_MEAS_REG), HEX);
      Serial.print("ctrl_hum(0xF2): 0x");
      Serial.println(mySensor.readRegister(BME280_CTRL_HUMIDITY_REG), HEX);

      Serial.print("\n\n");

      Serial.print("Displaying all regs\n");
      uint8_t memCounter = 0x80;
      uint8_t tempReadData;
      for(int rowi = 8; rowi < 16; rowi++ )
      {
        Serial.print("0x");
        Serial.print(rowi, HEX);
        Serial.print("0:");
        for(int coli = 0; coli < 16; coli++ )
        {
          tempReadData = mySensor.readRegister(memCounter);
          Serial.print((tempReadData >> 4) & 0x0F, HEX);//Print first hex nibble
          Serial.print(tempReadData & 0x0F, HEX);//Print second hex nibble
          Serial.print(" ");
          memCounter++;
        }
        Serial.print("\n");
      }

      Serial.print("\n\n");

      Serial.print("Displaying concatenated calibration words\n");
      Serial.print("dig_T1, uint16: ");
      Serial.println(mySensor.calibration.dig_T1);
      Serial.print("dig_T2, int16: ");
      Serial.println(mySensor.calibration.dig_T2);
      Serial.print("dig_T3, int16: ");
      Serial.println(mySensor.calibration.dig_T3);

      Serial.print("dig_P1, uint16: ");
      Serial.println(mySensor.calibration.dig_P1);
      Serial.print("dig_P2, int16: ");
      Serial.println(mySensor.calibration.dig_P2);
      Serial.print("dig_P3, int16: ");
      Serial.println(mySensor.calibration.dig_P3);
      Serial.print("dig_P4, int16: ");
      Serial.println(mySensor.calibration.dig_P4);
      Serial.print("dig_P5, int16: ");
      Serial.println(mySensor.calibration.dig_P5);
      Serial.print("dig_P6, int16: ");
      Serial.println(mySensor.calibration.dig_P6);
      Serial.print("dig_P7, int16: ");
      Serial.println(mySensor.calibration.dig_P7);
      Serial.print("dig_P8, int16: ");
      Serial.println(mySensor.calibration.dig_P8);
      Serial.print("dig_P9, int16: ");
      Serial.println(mySensor.calibration.dig_P9);

      Serial.print("dig_H1, uint8: ");
      Serial.println(mySensor.calibration.dig_H1);
      Serial.print("dig_H2, int16: ");
      Serial.println(mySensor.calibration.dig_H2);
      Serial.print("dig_H3, uint8: ");
      Serial.println(mySensor.calibration.dig_H3);
      Serial.print("dig_H4, int16: ");
      Serial.println(mySensor.calibration.dig_H4);
      Serial.print("dig_H5, int16: ");
      Serial.println(mySensor.calibration.dig_H5);
      Serial.print("dig_H6, uint8: ");
      Serial.println(mySensor.calibration.dig_H6);

      Serial.println();
    }

    void loop()
    {
      //Each loop, take a reading.
      //Start with temperature, as that data is needed for accurate compensation.
      //Reading the temperature updates the compensators of the other functions
      //in the background.

      Serial.print("Temperature: ");
      Serial.print(mySensor.readTempC(), 2);
      Serial.println(" degrees C");

      Serial.print("Temperature: ");
      Serial.print(mySensor.readTempF(), 2);
      Serial.println(" degrees F");

      Serial.print("Pressure: ");
      Serial.print(mySensor.readFloatPressure(), 2);
      Serial.println(" Pa");

      Serial.print("Altitude: ");
      Serial.print(mySensor.readFloatAltitudeMeters(), 2);
      Serial.println("m");

      Serial.print("Altitude: ");
      Serial.print(mySensor.readFloatAltitudeFeet(), 2);
      Serial.println("ft");

      Serial.print("%RH: ");
      Serial.print(mySensor.readFloatHumidity(), 2);
      Serial.println(" %");

      Serial.println();

      delay(10000);

    }

  [1]: https://i.stack.imgur.com/iIuyk.jpg
  [2]: https://i.stack.imgur.com/4e6Bb.jpg
  [3]: https://github.com/sparkfun/SparkFun_BME280_Arduino_Library

title: Arduino Nano BME280 weird values

Answers: 3

body:
The photo of the board shows that it is for BM E/P 280. It can take either the BME280 chip which does temperature, pressure and humidity, or the BMP280 chip which only does temperature and pressure.

The Register 0xD0 contains an ID which has a value of 0x60 for the BME280 and 0x58 for the BMP280.

Your output shows the ID as 0x58 which means you have a BMP280 temperature pressure chip.

I have been sold one of these, claiming to be a BME280 chip. I shall be asking for a refund.

body:
I'm after getting a batch of these myself...

I can't get it working with the Adafruit libraries, but it will work with the SparkFun Ones

To get data... the wiring is, well, nonstandard.

I can't get it to work in SPI mode, but it will work in I2C mode
I'm using an Arduino mega so the pin layout is different from an uno.

Pin no|Label|Arduino pin

Pin 1 |VCC  |3.3V

Pin 2 |GND  |GND/Ground

Pin 3 |SCL  | The SCL pin, on a mega its digital 21

Pin 4 |SCA  | The SCA pin, on a mega its digital 20

Pin 5 |CSB  |Do not connect

Pin 6 |SDO  |3.3V

Weird as it sounds, it needs to be connected to power on 2 separate pins

body:
The breakout board photo shows that it is not the original BOSCH BME280 sensor. The dimensions are off. The original is square. This is how it should [look like.][1]

  [1]: https://www.bosch-sensortec.com/bst/products/all_products/bme280


body:
I want to connect a ADXL355 development board accelerometer to an Arduino. I cant get any data form the sensor. The data_ready pin is never high and I can't read the registers.
The connections ([user guide][1]):[![enter image description here][2]][2]

I connected VDD and VDDIO to 5V, ground to ground, DRDY to the correct pin, CS, SCLK, MOSI and MISO all to correct pins.

Code:

    //modeled on https://www.arduino.cc/en/Tutorial/BarometricPressureSensor

    #include <SPI.h>

    const int ID = 0x00;
    const int FIFO = 0x11;
    const byte READ = 0b11111100;
    const byte WRITE = 0b00000010;

    const int dataReadyPin = 6;
    const int chipSelectPin = 7;

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

        // put your setup code here, to run once:
        SPI.begin();

        // initalize the  data ready and chip select pins:
        pinMode(dataReadyPin, INPUT);
        pinMode(chipSelectPin, OUTPUT);

        delay(100);
        readRegister(ID);
    }

    void loop() {
        if (digitalRead(dataReadyPin) == HIGH){
            Serial.println("data ready");
            delay(500);
        }
    }
    void readRegister (byte thisRegister){
        byte inByte = 0 ;
        Serial.println(thisRegister, BIN);

        thisRegister = thisRegister<< 2;
        byte dataToSend = thisRegister & READ;
        Serial.println(thisRegister, BIN);
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(dataToSend);
        inByte = SPI.transfer(0x00);
        Serial.println("data: ");
        Serial.println(inByte);
    }

  [1]: http://www.analog.com/media/en/technical-documentation/user-guides/EVAL-ADXL354-355-UG-1030.pdf
  [2]: https://i.stack.imgur.com/0gpi1.png

title: How to connect a digital sensor through SPI

Answers: 1

body:
You're shifting your address too far.

* Read should be 0b00000001 not 0b00000010.
* Your address should be shifted one bit not two.

Also you need to turn it on. By default the device is in standby mode. You need to enable it by setting bit 0 of register 0x2D to 0.

----

    byte readRegister (byte thisRegister){
        byte inByte = 0 ;
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer((thisRegister << 1) | 1);
        inByte = SPI.transfer(0x00);
        digitalWrite(chipSelectPin, HIGH);
        return inByte;
    }

    void writeRegister (byte thisRegister, byte value){
        digitalWrite(chipSelectPin, LOW);
        SPI.transfer(thisRegister << 1);
        SPI.transfer(value);
        digitalWrite(chipSelectPin, HIGH);
    }


body:
I'm trying to make the piezo speaker play a sound of certain frequency. However, although I think the code is fine, the sound plays with a frequency between 130 ~160 only, and the frequency actually drops when it should be going up.

The code is as below:

    digitalWrite(buzzer, LOW);
    delayMicroseconds(1000000 / frequency);
    digitalWrite(buzzer, HIGH);
    delayMicroseconds(1);

What could be the problem?

title: Making the speaker play a certain frequency of sound

Answers: 1

body:
Have you looked at the [Tone library][1]?  That does what you want, with some other niceties besides.

Anyway, the (or at least "a") problem with your code is that you are leaving the signal LOW almost all the time. You want it to spend half the time high, half the time low:

    digitalWrite(buzzer, LOW);
    delayMicroseconds(500000 / frequency);
    digitalWrite(buzzer, HIGH);
    delayMicroseconds(500000 / frequency);

  [1]: https://www.arduino.cc/en/Reference/Tone


body:
I'm trying to send data both ways between an Arduino Mega 2560 slave and 2  Arduino Nano Zero (ATSAMD21G).

This example is a simplified setup and code. There will be more masters along with passive slaves on the bus (LCD, EEPROM).

[Code and results (txt files)][1]

My code is working fine with one master only and the slave active on the bus (data is sent both ways every 2s). I however notice missing transfers to the masters when more than one master is active. The 2 masters to slave transfers are working properly (once the 2 masters are on, the data is received by the slave every 2s from each master).

Is this problem due to collision? How can I handle it?

  [1]: https://github.com/kb-/Arduino-I2C-2way-anydata/tree/f78aa10354f7706d1aa32f49d3bc647600f2b4ee

title: Two-way communication on multimaster I2C bus

Answers: 2

body:
> notice missing transfers to the masters when more than one master is active.

Because you didn't provide a way for the master's to know of a transmission ISS in progress. Lack of conflict resolution. A problem with all multimeter transmission.

A simpler approach is for the slave to signal a transmission from the master. That can be done via a slave requestion pin from the slave to the master.

body:
The code had several issues leading to a constant flow of wrong data (with correct data in the middle) between the master that won the bus arbitration. This made it keep the bus too long and eventually give it away to the second master at a random time, with missed transfers from the second master in between. The second master was then behaving the same and so on.

`receiveEvent`, on the slave side, contained a `millis` `if` condition timer that made it time out. I moved the timer to the master side before calling `Wire.requestFrom`. Avoid slow code in `receiveEvent`!

`receiveEvent`, on the slave side, was also confusing real data with incoming `requestEvent`. I added an `if` statement to compare the `receiveEvent` data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the `Wire` library)

These fixes solved the busy bus problem. I figured these out after asking question #35092

The bus speed also had to be reduced because 800 kHz was too fast for the Mega 2560 (but worked between 3 Nano).

The slave has to send the data destined to both masters to each of them because `requestEvent` can't tell which master is asking for data. The data is then filtered on each master to only keep the relevant information.

The data is now being transferred both ways between the 2 Nano masters and the Mega slave at the correct interval, without corrupt data.

[fixed Slave code][1]

[fixed Master 1 code][2]

fixed Master 2 code in the same repo (I'm limited to 2 links post)

[1]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/ff9b47bdb17c137731882ec3b1b53c34afd91193/Slave_test_i2c_data/Slave_test_i2c_data.ino
[2]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/7e63e0aaeb7f2a60aad23f67b06f30f55774ce6e/Master_test_i2c_data/Master_test_i2c_data.ino


body:
I must not of understood something. Online, I've heard that the Arduino uses 9v typically (average), and that USB's in general supply 5v@500mA. If this is true:

 1. How can the Arduino even POWER ITSELF with the 5v USB? I've heard the minimum is 7v.
 2. How can there be a 5v pin if the USB supplies 5v... that leaves no room for the Arduino!

My understanding is very bad currently, any explanation would be great. Thanks!

title: If the USB gives 5v, how can the Arduino supply 5v to the 5v pin? (And another question)

Answers: 6

body:
On a basic level, the 5v of the USB port is regulated by the power supply of the external device, be it a computer USB port or a USB type charging module. When you are using the power jack on the Arduino, you can provide a range of voltage, from 7v (recommended minimum) to as much as 20v. This input power passes through a voltage regulator to provide the regulated 5v necessary to operate the Arduino.

Voltage is not "used up" by the Arduino, but you may have little reserve power for additional devices which are tied into the 5v bus.

Consider that voltage can be viewed in a manner similar to water pressure, while current can be compared to the volume of water flowing. If you have a 1000 mA power supply and the Arduino uses 500 mA, you have still available 500mA at 5v for other uses.

You can experience voltage drop in a circuit, depending on the way components are connected. That's more advanced than necessary for this discussion.

This is a very basic overview and details will vary from one model Arduino to another.

Also note that one should not apply 5v to other pins marked 5v as it bypasses the regulator and can damage the board or other devices attached.

body: You might be mixing up voltage and ampereage. The Arduino takes in from 5volts up to 12, and uses a regulator to bring higher voltages down to 5V. Milliamps (mA) is the measure of what is drawn per circuit part. The Arduino itself only draws around 25 of these, which if running off of USB, leaves around 475mA that other things can draw.

body: You can supply five 5V directly to the 5V pin, which is effectively what the USB interface does. The quoted 7 to 12V is only if you are using the power jack. That converts it down to 5V which is what the processor needs.

body:
Actually, Arduino is powered at 5V (the 5V pin and the ATmega328p are connected to the +5V rail in the board). The point here is **where do those 5V come from**. Basically, from 2 possible sources:

 1. **USB**. The 5V line from USB is (or should be) already regulated, so it's feed directly (in fact it goes through a polyfuse) into the +5V rail of the board. The maximum current draw operating this way is 500 mA, limited by the polyfuse so you don't blow up your PC.

 2. **Barrel connector (wall adapter)**. It accepts 7-12V and brings it down to 5V using a [linear regulator][1] whose output goes to the +5V rail of the board. The maximum current draw operating this way is 1,000 mA, limited by the regulator capability.

If both sources are present at the same time, **preference is given to the wall adapter**. The UNO board has circuitry that detects voltage from the adapter and disconnects (using a MOSFET switch) the USB 5V line from the +5V rail of the board.

This is done not only for convenience purposes (so you have more current available), but also for **protection**. Otherwise, you'd be connecting two power sources (+5V from the regulator and +5V from USB) which is a dangerous situation.

I have commented the UNO R3 schematics so you can see for yourself how it's done (both input sources, adapter voltage detection circuitry, etc.), see below.

[![Arduino UNO power supply][2]][2]

  [1]: http://www.onsemi.com/pub_link/Collateral/NCP1117-D.PDF
  [2]: https://i.stack.imgur.com/tEqgz.png

body:
@enric blanco made a good description. I just point out the strange difference between USB (5V) and barrel connector (7-12V).

The barrel connector has to accept different power supplies (with different voltages), moreover they may need voltage regulation; thus arduino needs a "regulator" after the barrel connector. There are different composants that can do it. This simple one will provoke a minimal loss of voltage. That is why you have to input more than 5V.

There are other components (buck/boost) that could accept input voltage from 3V to 12V and always provide 5V as output, but they are more expensive (5$).

body:
No, you don't have to input more than 5V at the raw pin while exactly 5V is output at the VCC pin (at least with the Pro Mini).
How this is done I have no idea.


body:
I got this old junk LCD from my car. The DVD function stopped and the LCD holder on the top of the car broke, so I took it.

Is there any documentation or advice I could use to get this working with an Arduino mega or clone of similar power? I couldn't find anything after looking through Google.

I.e. I'm looking for a way to get a pinout or idea of what those wires on the jack are so that I might be able to get text and/or basic graphics on the screen. Maybe to make an Arduino PC or something idk.

Any advice on either figuring out the connections by hand and how to get a simple connection to the Arduino to get bsic stuff working or a place I can find pinout and such or where someone else has done something similar would be helpful.

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

**Update 2**
A quick Google search reveals that it's made by sharp I believe. I'm looking into it.

**Update**
Here's is the back. It's got quite a few numbers on it. Maybe one of those can help?

Top Numbers:
D 09399847
LQ070T5CRQ2 46009355

And the one on the bottom:
K4013TP

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

  [1]: https://i.stack.imgur.com/CQMvP.jpg
  [2]: https://i.stack.imgur.com/UprEI.jpg

title: Hacking old car dvd monitors with arduino

Answers: 2

body:
Your best bet is to try to take the casing off until you find a company name so that you can get a lead on where to look for documentation. Because until you find out more about how that screen works, it's a black box to you and you don't know what to put in it. No one else will be able to help you until you provide more information to this extent because no one else can hold it in their hands, and the photo of the socket that you showed us doesn't look like a common display format either.

Also, you're very unlikely to make a PC-type thing out of this. That depends on the power of the computer behind the display and an arduino isn't that powerful. You want a Pi. Or maybe I'm misunderstanding what you want. You could easily get a scrolling text type thing going or maybe even a game (if you figure out how to make it work).

Edit: I just looked up a sample LCD screen and it has 6 signal pins and power and ground. Yours looks like it has a lot more. So you definitely have some digging to do.

body:
I realize this is an ancient question, but just in case someone else has one of these things, I'll share what I know. I have one of these Sharp LCDs that I typically use as a monitor for a Commodore 64. I believe mine was originally from a rear seat DVD player in a Ford Explorer.

Looking at the rear of the unit, with the two connectors on the bottom, the leftmost connector is CN2 and the rightmost is CN1. I know nothing of CN2, but here's what I know about CN1:

 Pins 1 through 15, from left to right:

 1. NTSC composite video in
 2. ground
 3. ground
 4. ?
 5. +12VDC in
 6. ?
 7. ?
 8. ?
 9. ?
 10. ?
 11. ?
 12. +12VDC in
 13. +12VDC in
 14. ground
 15. ground

I'm sure the other pins have additional functionality, but I'm not aware of it. Hopefully this helps someone.

EDIT: I found the datasheet in my files: https://byteshiftmusic.com/media/Sharp_LQ070T5CRQ2.pdf


body:
I'm using Atmel Studio with Atmega328P.

I'm trying to send the decimal number 876 continuously from the micro-controller. This was just to learn.

To send 876 I need two bytes which is:

0x036C = 00000011 01101100

So I manipulated a code and here is what I use now:

    #include <avr/io.h>
    #define F_CPU 16000000
    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

    void USART0Init(void)
    {
     // Set baud rate
     UBRR0H = (uint8_t)(UBRR_VALUE>>8);
     UBRR0L = (uint8_t)UBRR_VALUE;
     // Set frame format to 8 data bits, no parity, 1 stop bit
     UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
     //enable transmission and reception
     UCSR0B |= (1<<TXEN0);
    }

    int main (void)
    {
     //Initialize USART0
     USART0Init();

     while(1)
     {

      UDR0 = 0b00000011;
      UDR0 = 0b01101100;

     }

    }

The problem is at the receiving side the data comes as:

01101100
00000011
00000011
.
.
.

Here is the screen shot of the binary data at the receiving end:
[![enter image description here][1]][1]

However it should be received correctly as two byte chunks 00000011 01101100.

And here you can see the problem of the data being received as uint16(not only 876 as desired):
[![enter image description here][2]][2]

How can I fix this and receive the data properly as two bytes with correct order as 876?

  [1]: https://i.stack.imgur.com/E9RzA.png
  [2]: https://i.stack.imgur.com/k3XnI.png

title: Problem with transmitting 2 byte data in correct way

Answers: 3

body:
First, you want to determine what you are trying to send. Send data in binary form is rare.

Secondly, you want to wait for each transmission to send before starting the next one.

body:
The data sheet for the 328P - section 24.7.1 - contains an example of waiting for the transmission to complete before sending another byte.

When sending serial data, you determine the order of bytes and will need to reassembly in the correct order on receipt.  You can use bit shift operators to move the bytes back into the correct location.  If you send the most significant byte first (MSB) and then the least significant byte (LSB), putting them back into a 16 bit integer would look something like:

uint16_t result = (MSB << 8) | LSB;

body:
Your code has a fundamental error: when you write "UDR0 = 0b00000011;", the CPU does not wait until the transmission is complete - that would be terribly wasteful, in terms of time. It just write to the transmit data buffer. Furthermore, if the transmission was not ongoing yet, that instruction also starts transmission (assuming the USART is properly initialized, as it is in your case). However, if a transmission is ongoing, and the data buffer is not empty, this write instruction might be either ignored or it might overwrite the data on the buffer.

Therefore, with your code, you're continuously writing two bytes (at a very high speed, because that loop would result in very few asm instructions), without checking if actually you can write to the transmit data buffer register. This will result in most of the bytes being "randomly" ignored, with some other being randomly picked and trasmitted.

Before sending any data, you must check if the data register is empty:

    while ( !(UCSR0A & (1 << UDRE0)));
    UDR0 = firstByte;
    while ( !(UCSR0A & (1 << UDRE0)));
    UDR0 = secondByte;

Where firstByte and secondByte are either the numeric values or two 8-bit variables.

Instead of the two "while" statements, you can use the built-in macro:

    loop_until_bit_is_set(UCSR0A, UDRE0);


body:
I want to make an external (not related to Arduino) computer application that creates a big 'setup file' (like max. 64 KB). This setup file contains lookup tables (which are configurable and the tables with data themselves).

This 'setup file' needs be stored in the Arduino.

Now I thought of the following alternatives:

- Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).
- Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).
- Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.
- Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

Can you please give me some more information which alternative would work or not? Or maybe I missed out something trivial or an alternative is impossible?

title: Question about configuration EEPROM or Flash

Answers: 1

body:
> Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).

Perfectly viable - although an SPI Flash chip would be more appropriate.

> Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).

It is the bootloader that can write to flash. I don't thing the main program can write to flash, or it would wipe itself out. You may need a special bootloader with your own protocol and upload program to go with it.

> Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.

Perfectly viable, but tricky to say the least.

> Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

Yes, 512 bytes of SRAM, since that is the size of one block on an SD card. But an UNO has 2048 bytes of SRAM - more than enough for SD card support.

The SD card would be my route of choice. It's the easiest from a user's perspective (slip the card into their computer and copy the files), and pretty simple and straight forward to connect and program the Arduino for.

> To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

If you know where in the file the byte are then you can `seek()` straight to them. Takes almost no time. 20ms is an eternity for a microcontroller.


body:
I am working on a project for a friend who is not very tech savvy involving an ESP8266. It will need to be connected to his WiFi network.

The issue is that he occasionally changed the password to his WiFi network. Since I will not be able to access this device at a moments notice, it needs to be able to adapt to a change in the password. Is this possible with the ESP8266, or should I switch to an Arduino WiFi board, or is something more powerful necessary?

title: Arduino WiFi/ESP8266 WiFi Password Changed

Answers: 2

body:
Yes that's possible.

Just don't hard-code the password: store it in EEPROM.

A common way of doing it if for the ESP to present a wifi access point which serves a configuration page when it cannot successfully connect to another access point.  Store the SSID and password in EEPROM.

body:
The [WiFiManager][1] library was written for exactly this purpose.

  [1]: https://github.com/tzapu/WiFiManager


body:
Maybe another problem for trained eyes. I seem to get the alarm to cycle regardless of the state of "trigsensor" and "away" (they should both need to be true in order for the alarm to run after an incorrect code is entered). Thanks for any response to this, as I am still learning C:

    //////////////////////////// initialize & includes //////////////////////////
    #include <elapsedMillis.h>
    #include "SIM900.h"
    #include "sms.h"
    #include "Keypad.h"
    #include <GSM.h>
    SMSGSM sms;

    int PIR_SensorPin = 2;
    int Alarm_OutPin = 11; //green
    int Light_OutPin = 12; //red
    int alarm_count = 0;
    volatile boolean trigsensor = false;
    boolean away = false;
    const byte interruptPin = 2;
    int z = 0;
    int i = 0;

    //////////////////////////// setup keyPad //////////////////////////
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] =
    {
      {
        '1', '2', '3', 'A'
      }
      ,
      {
        '4', '5', '6', 'B'
      }
      ,
      {
        '7', '8', '9', 'C'
      }
      ,
      {
        '*', '0', '#', 'D'
      }
    };
    byte rowPins[ROWS] = {
      6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
    }; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {
      3, A0, A1, A4
    }; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const char PIN[5] = {
      '9', '6', '7', '9', '#'
    }; // PIN number
    char key_input[5] = {
      0, 0, 0, 0, 0
    }; // used for comparison

    //////////////////////////////// setup ///////////////////////////////////
    void setup() {
      Serial.begin (9600);  // Establish Serial connection;
      pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
      pinMode (Light_OutPin, OUTPUT);   // Set pinMode.
      pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
      digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (Light_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (PIR_SensorPin, LOW);
      Serial.println ("GSM Alarm starting up."); // Serial message that GSM shield is starting up
      if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
        Serial.println ("Status = Network READY");
        digitalWrite (Alarm_OutPin, HIGH);
      }
      delay (10000);
      attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
      Serial.println ("System Ready");
    }

    //////////////////////////////// void loop ///////////////////////////////////
    void loop() {
      if (trigsensor == true) {
        alarm();
      }
      else {
        readKeypad();
      }
    }

    //////////////////////////////// void trigger ///////////////////////////////////
    void trigger() {
      trigsensor = true;
      //  alarm();
    }

    //////////////////////////////// void alarm ///////////////////////////////////
    void alarm() {
      Serial.print ("away="); Serial.print (away); Serial.print (" ");Serial.print ("trigsensor=");Serial.println (trigsensor);
      Serial.println("at Alarm");
      if (away == true && trigsensor == true) { ////////////////////////////////
        // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
        Serial.println ("MOTION detected: SMS Sent");
      }
      // else if (trigsensor == true) {  /////////////////////////////////////////////
      for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
        digitalWrite (Light_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
        digitalWrite (Light_OutPin, LOW);
        digitalWrite (Alarm_OutPin, HIGH); delay (1000);
        digitalWrite (Alarm_OutPin, LOW); // End by turning off light
        Serial.println(alarm_count);
      }
      digitalWrite (Alarm_OutPin, HIGH);
      trigsensor = false;
      away = false;
      readKeypad();
    }

    //////////////////////////////// read Keypad ///////////////////////////////////
    void readKeypad() {  //attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // reattach interrupt
      char key = keypad.getKey();
      if (key != NO_KEY) { // if a keypad input
        key_input[z] = key;
        tone(10, 900, 100);
        Serial.print("Key_input["); Serial.print(z); Serial.print("] = "); Serial.println(key);
        z++;
        if (z >= sizeof(key_input)) {
          z = 0;
        }
        switch (key) {
          case '*': // resets key_inputs to "0"
            z = 0;
            break;
          case '#': // pressed to "enter"
            z = 0;
            for ( i = 0;   i < 4 ;  i++ ) {
              Serial.print(key_input[i]);
            }
            Serial.println ("-------");
            delay(100); // for extra de-bounce
            checkPIN();
            break;
        }
      }
    }

    //////////////////////////////// check PIN ///////////////////////////////////
    void checkPIN() {
      Serial.println ("@ checkPIN ");
      int correct = 0;
      int i;
      for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
        if (key_input[i] == PIN[i]) {
          correct++;
        }
      }
      if (correct >= sizeof(PIN) - 1) {
        Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
        correctPIN();
      }
      else {
        incorrectPIN();
      }
    }

    //////////////////////////////// correct PIN ///////////////////////////////////
    void correctPIN() {              // do this if correct PIN entered
      Serial.println ("@ correct PIN ");
      digitalWrite (Alarm_OutPin, HIGH);
      digitalWrite (Alarm_OutPin, LOW);
      detachInterrupt(0);
      trigsensor = false;
    }

    //////////////////////////////// incorrect PIN /////////////////////////////////
    void incorrectPIN() {           // do this if incorrect PIN entered
      Serial.println ("@ incorrect PIN ");
      delay(10000); // a slight delay aded to allow leaving without triggering the alarm
      trigsensor = false;
      away = true; /////////////////////////////////
      digitalWrite (Alarm_OutPin, HIGH);
      attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH);
      alarm();
    }

title: Another problem with code; boolean?

Answers: 0


body:
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    #define trigpinyellow 10
    #define echopingreen 9
    #define Grove_Water_Sensor 8
    void setup()
    {
        Serial.begin(9600);
        pinMode(trigpinyellow,OUTPUT);
        pinMode(echopingreen,INPUT);
        pinMode(Grove_Water_Sensor, INPUT);
        lcd.begin(16, 2);
    }

    void loop()
    {
        long duration,distance;
        digitalWrite(trigpinyellow,LOW);
        delayMicroseconds(1000);
        digitalWrite(trigpinyellow,HIGH);
        delayMicroseconds(1000);
        digitalWrite(trigpinyellow,LOW);
        duration=pulseIn(echopingreen,HIGH);
        distance = (duration/2) / 29.1;
        Serial.println(distance);

        if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) >=20  )
        {
            lcd.clear();
            lcd.print("water_came");
            lcd.setCursor(0, 1);
        }
        if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) <=8 )
        {
            lcd.clear();
            lcd.write("Tank_is_full");
        }
        if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) >=20 )
        {
            lcd.clear();
            lcd.print("Fill The Tank PLEASE");
        }
        if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) <=8 )
        {
            lcd.clear();
            lcd.print("Tank_is_FULL");
        }
    }

title: LCD isn't working with if statement

Answers: 1

body: Every time you instantiate digitalread(), you poll the pin. Here, you're polling pins 8 times every loop. Instead, poll the two pins at the start of the loop to update the variable, and then do your math and make your decisions afterward. Right now you're doing math with your distance variable, and then overwriting the variable during your if conditionals. Not sure if that's what you intend. You're also creating the variables duration and distance every single loop. instead, create those variables globally and just update them every loop.


body:
I'm trying to set up SPI communication between two Arduinos (UNO and Mega),
I want to read the status of the slave output pin from the master.

I connected a diode to pin 9 of Mega and I wanted to display its state on the virtual terminal of the master (Uno). The problem is that when the LED flashes I do not receive values just at the terminal level but when I hold it to zero or 1 the display is correct.
I used another code I found online.

MASTER code
<!-- language-all: lang-cpp -->

    #include <SPI.h>
    const byte btn =8;

    void setup(void) {

    Serial.begin (9600);
    pinMode (btn, INPUT_PULLUP);
    digitalWrite (SS, HIGH);
    SPI.begin ();
    SPI.setClockDivider (SPI_CLOCK_DIV8);

    }

    void loop(void) {

    byte Mvalsent,Mvalreceived;
    digitalWrite (SS, LOW);
    for (int jj=0; jj<255; jj++)
      {
          Mvalsent =jj;
          Mvalreceived =SPI.transfer (Mvalsent);
          Serial.print ("Retou d'etat ");
          Serial.print (Mvalsent);
          Serial.print ("\t ,l'etat de la diode est ");
          Serial.println (Mvalreceived);
          delay (400);
      }

      digitalWrite (SS,HIGH);

    }

SLAVE Code

    #include <SPI.h>
    byte state;
    const byte led =9;
    volatile boolean process_it;
    volatile byte Svalreceived, Svalsent;
    int jj=0;
    void setup (void)
    {
      Serial.begin (9600);
    pinMode (led,OUTPUT);
    //set MISO pin as output
    pinMode (MISO, OUTPUT);
    //turn on SPI in slave mode
    SPCR |= _BV (SPE);
    //get ready for an interrupt
    process_it = false;
    //now turn on interrupts
    SPI.attachInterrupt ();
    }
    ISR (SPI_STC_vect)
    {
      Svalreceived = SPDR;
      process_it =true;
    }
    void loop (void)
    {
     if (process_it)
     {

       digitalWrite (led, LOW);
       state =digitalRead(led);
       SPDR = state;
       Serial.print("l'etat de la diode est: ");
        Serial.println (state);
        delay (400);

        process_it =false;
      }
    }

title: SPI communication Problem Arduino

Answers: 1

body:
Why not use I2C slave-master between arduinos?  You can hook up other arduinos or devices on I2C simultaneously (as long as each uses a distinct address).

And you still keep the SPI for a microsd card adapter, for example.

Follow [this official tutorial][1]:

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

MASTER ARDUINO 1

 // Wire Master Writer
 // by Nicholas Zambetti <http://www.zambetti.com>

 // Demonstrates use of the Wire library
 // Writes data to an I2C/TWI slave device
 // Refer to the "Wire Slave Receiver" example for use with this

 // Created 29 March 2006

 // This example code is in the public domain.

 #include <Wire.h>

 void setup() {
   Wire.begin(); // join i2c bus (address optional for master)
 }

 byte x = 0;

 void loop() {
   Wire.beginTransmission(8); // transmit to device #8
   Wire.write("x is ");        // sends five bytes
   Wire.write(x);              // sends one byte
   Wire.endTransmission();    // stop transmitting

   x++;
   delay(500);
 }

SLAVE ARDUINO 2

 // Wire Slave Receiver
 // by Nicholas Zambetti <http://www.zambetti.com>

 // Demonstrates use of the Wire library
 // Receives data as an I2C/TWI slave device
 // Refer to the "Wire Master Writer" example for use with this

 // Created 29 March 2006

 // This example code is in the public domain.

 #include <Wire.h>

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

 void loop() {
   delay(100);
 }

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

This is an alternative example of a setup using a nodemcu (which doesnt function in slave mode, btw).

[![enter image description here][3]][3]

  [1]: https://www.arduino.cc/en/Tutorial/MasterWriter
  [2]: https://i.stack.imgur.com/y4TDr.png
  [3]: https://i.stack.imgur.com/WOcfL.png


body:
ok... so I am using four 12V motors and one ultrasonic sensor with a motor shield... and I am getting some odd results...
in my code I have it so when the distance to a object is less than 4 cm it will go backwards and when something is not 4 cm in front of the robot it will go forwards... simple!
but the wheels on the left side of my robot will stop! and just do nothing!

The weirdest part about it is when I make some code JUST moving the wheels back and forth the wheels will work PERFECTLY fine. and when I use some code JUST for the sensors... it works fine! but together... it does all that weird stuff.

this is the shield I am using: https://www.pololu.com/product/2507

if there is any information I missed that you need let me know and I will get back with you. I am new to Arduino so I am extremely confused...

the code.

 #include "DualVNH5019MotorShield.h"
 DualVNH5019MotorShield md;

 #define trigPin 7
 #define echoPin 8

 void setup() {
    md.init();  //setting up wheel code
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
 }

 void loop() {
     long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

 //This is the sensor testing if somthing is in range!
   if (distance < 4){
      Serial.println("in range");
      md.setM1Speed(100);
      md.setM2Speed(-100);
   }
   else {
      Serial.println("not in range");
      md.setM1Speed(-100);
      md.setM2Speed(100);
   }

   if (distance >= 200){
      Serial.println("!");
   }
   else {
      Serial.print(distance);
      Serial.println(" cm");
   }
    Serial.println(distance);
    delay(500);
 }

title: Ultrasonic sensors with 12v motors will not work! (ADRUINO)

Answers: 1

body:
**TLDR:** change your project (both program and connection) to use ultrasound sensor on any two of pins 3,5,11 and it should work.

---

You are using `pins 7 and 8` for ultrasound.

At the same time you are using the shield  https://www.pololu.com/product/2507 for motors, but if you look at the shield description on picture `Dual VNH5019 motor driver shield with an Arduino (shield and Arduino powered separately).`https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5 <img src="https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5">
You will see, that the shield is using `pin 7` as `M2INA` and `pin 8` as `M2PINB`

So each loop you push `M2INA` (`trigPin`) LOW, then HIGH then LOW, then wait until the sensor write HIGH to `M2INB` (`echoPin`) just to immediately send PWM pulses to both `trigPin` (`M2INA`) and `echoPin` (`M2INB`) via commands

        md.setM1Speed(100);
        md.setM2Speed(-100);

No way it can work as you expect.

You must use other pins (unused by the shield) for your ultrasound sensor. I suggest to declare

    #define trigPin 3
    #define echoPin 5

and connect your ultrasound sensor there acordingly.

(You can use also pin 11 if you want. I would not recomend pin 13, as there is connected the Arduino LED, which is used by bootloader too so you could confuse the sensor, nor the pins 1 and 2, as they are used by Serial (and USB). Also you can use the "analog pins" A2..A5 as digital pins, but it may confuse you a little (AVR can use "analog" pins as "digital" but many beginers does not like constructs as "digitalWrite(A2)", "digitalRead(A3)").

Also keep in mind, that A4 and A5 are used for I2C communication, if you would use I2C later in project.


body:
<br>
I am using PWM (*analogWrite*) with a common *anode* LED. My previous experience is using a common cathode. My breadboard is as shown:

<!-- 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/TMs6q.png)

<!-- End schematic -->

This creates a semi-bright white (ugly red-green-blue mixture) like I expected. I am using only one PWM output (It is currently fading).

Now, what I ask is how can I use multiple PWM outputs to make different colors display *without* transistors? I was thinking that I could have 3 dedicated pins on the Arduino that switch from ground to floating extremely fast, but is there an easier way?
If not, a little explanation on how to do it with transistors (mostly just a small wiring diagram) would be great. Cheers!

title: Controlling common anode RGB LED with PWM - Can individual colors be done w/o transistors?

Answers: 2

body:
As long as each LED in the array uses 20mA or less you can do it directly with the Arduino:

<!-- 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/C6ESG.png)

<!-- End schematic -->

Note that the blue LED will have a higher forward voltage than the red and green ones, hence the lower resistor.

Also note that the PWM will be inverted. Writing 255 to a channel will switch that LED off, while writing 0 will give it full brightness.

body:
> I am using only one PWM output (It is currently fading).

use three independent pwm channels to drive three leds.

> how can I use multiple PWM outputs to make different colors display without transistors?

the answer depends on the leds. for leds that require small current, it is totally doable, just connect the pwm output to them.

for leds that require lots of current, no solution.


body:
I am trying to use one of the hardware timers on the arduino uno to generate a short pulse some number of microseconds after receiving a pulse on an input.

Currently my code looks like this:

    uint16_t pulse_delay = 12000; //half-microseconds
    uint16_t pulse_length = 20;

    void setup(){
      pinMode(8, INPUT);
      pinMode(9, OUTPUT);
      TCCR1A = 0;
      TCCR1B = _BV(ICNC1)  //input capture noise cancel
          | _BV(ICES1) //positive edge
          | _BV(CS11); // /8 prescaler
      TIMSK1 = _BV(ICIE1); //enable input capture interrupt
    }
    void loop(){}
    ISR(TIMER1_CAPT_vect){
      TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
      TIMSK1 |= _BV(OCIE1A); //enable match interrupt
      OCR1A = pulse_delay; //pulse begin time

      TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                            //the interrupt isn't run immediately
    }
    ISR(TIMER1_COMPA_vect){
      TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
      TCCR1A = _BV(COM1A1); //clear OC1A on match

      OCR1A = pulse_delay + pulse_length;
    }

This code should theoretically do the task, but it doesn't produce any output at all - to my oscilloscope it looks like the output pin just stays low.

However, if I replace the last line (`OCR1A = pulse_delay + pulse_length;`) of the compare match interrupt with the following two lines, it outputs a pulse just fine. The issue with this is that it uses significantly more CPU time, and it can only count time from when the interrupt starts so if the interrupt is executed late the pulse will be longer.

      delayMicroseconds(pulse_length);
      TCCR1C = _BV(FOC1A); //manually trigger match event

All that the first version is doing differently is triggering the match event via an 'alarm' set on the timer, rather than waiting to trigger the match manually.

Why does the first version not work, and how can I make it work??

title: Generating a short pulse after a delay

Answers: 1

body:
Expanding on my comment, after checking experimentally that this was
indeed the issue.

## Short answer

You should do

<!-- language-all: lang-c++ -->

    TIFR1 = _BV(OCF1A);  // clear interrutp flag

right before

    TIMSK1 |= _BV(OCIE1A);  // enable match interrupt

## Explanation

Whenever the timer reaches the value stored in one of its “compare
match” registers, this triggers a “compare match” event, which has the
effect of raising the corresponding interrupt flag (`OCF1A` in your
case). If the associated interrupt is enabled, that fires an interrupt
request, and the flag is automatically cleared when the CPU starts
executing the interrupt vector.

However, if the interrupt is _not_ enabled, the flag just stays set. If
you later enable the interrupt when the flag is already set, the
interrupt request is sent immediately. This is not what you want, you
want the interrupt to fire only on the _next_ match. For this to happen,
you have to clear the interrupt flag prior to enabling the interrupt.

The interrupt flags have a very non-intuitive behavior: you _clear_ the
flag by writing a logic _one_ to it. Thus the line:

    TIFR1 = _BV(OCF1A);  // clear interrutp flag

For completeness, I would also clear `ICF1` before enabling `ICIE1`,
although this seems to not be critical for the working of your program.

Also, as a side note, be aware that the timer can increment while the
CPU is in the middle of executing `TCNT1 = TCNT1 - ICR1;`. If you want
the cleanest possible timings, leave the timer free-running and just set
`OCR1A` to the appropriate values: `ICR1+pulse_delay`, then
`ICR1+(pulse_delay+pulse_length)`.


body: To define the problem, the L6 Helix can generate 6 immediate MIDI messages. These messages are pretty flexible as to what you want, but the Voodoo Labs GCX needs at least 8 CC messages to properly configure it worst case. Also, I don't want to burn all of my immediate commands to control most of the GCX. So I had the idea to create a Arduino project that would take MIDI PC and MIDI Bank Select to produce a 8 bit value which I could then convert into 8 CC messages between CC#80 and CC#87.

title: Arduino MIDI Program Change to Voodoo Labs GCX Converter

Answers: 1

body:
To solve this problem I used an Arduino UNO and a Olimex MIDI shield. I also want to use MIDI PC messages and Bank Selects.

For reference:

 - A Channel 16 PC 77 with Bank select 0 converts to binary 0x4D => Binary 01001101
 - A Channel 16 PC 77 with Bank Select 1 converts to binary 0xCD => Binary 11001101

Just to point out, the Bank Select value basically controls bit 8 and the PC value represents bits 6 down to 0

Based on the binary output, I scroll through bits 0 to 7 and send messages on CC 80 to CC 87. If a bit is a 1, I turn the loop on by setting the corresponding CC value to 127 and if it is a zero, I set the CC value to 0.

The Helix can generate a Bank Select and PC as one message, so for the price of one message, this project will make me 8 CC#'s effectively. ;)

It should allow other messages through, with the Arduino's SW loop latency. There maybe some other side effects to, but those should be limited to channel 16 only.

I have tested this on a Arduino UNO board with an Olimex MIDI Shield.

    // GCX Editor
    // By Rich Maes
    // Converts MIDI PC's on channel 16 to GCX CC's starting at 0x80
    // Allows everything else to pass.

    #define MIDI_PC_CH16 0xCF
    #define MIDI_CC_CH16 0xBF
    #define MIDI_SYSEX 0xF0
    #define MIDI_SYSRT_CLK 0xF8

    boolean byteReady;
    boolean sendCCMessage;
    int ccMsgsToSend;
    unsigned char midiByte;
    unsigned char capturePCByte;
    unsigned char captureCCByte;

    // Queue Logic for storing messages
    int headQ = 0;
    int tailQ = 0;
    unsigned char tx_queue[128];

    int getQDepth();
    void addQueue(unsigned char myByte);
    void addCCQueue(unsigned char captureCCByte, unsigned char capturePCByte);
    unsigned char deQueue();

    static enum {
        STATE_UNKNOWN,
        STATE_1PARAM,
        STATE_1PARAM_CONTINUE,
        STATE_2PARAM_1,
        STATE_2PARAM_2,
        STATE_2PARAM_1_CONTINUE,
        STATE_PASSTHRU
      } state = STATE_UNKNOWN;

    void setup() {
      // put your setup code here, to run once:
      //  Set MIDI baud rate:
      Serial.begin(31250);
      sendCCMessage = false;
      byteReady = false;
      midiByte = 0x00;
      state = STATE_UNKNOWN;
      captureCCByte = 0;
      capturePCByte = 0;
      ccMsgsToSend = 0;
    }

    int getQDepth() {
    int depth = 0;
        if (headQ < tailQ) {
            depth = 128 - (tailQ - headQ);
        } else {
            depth = headQ - tailQ;
        }
        return depth;
    }

    void addQueue (unsigned char myByte) {
        int depth = 0;
        depth = getQDepth();

        if (depth < 126) {
            tx_queue[headQ] = myByte;
            headQ++;
            headQ = headQ % 128; // Always keep the headQ limited between 0 and 127
        }
    }

    void addCCQueue(unsigned char myCaptureCCByte, unsigned char myCapturePCByte) {
        int i;
        if (getQDepth() < 80) {
            // There is enough space to add our CC messages
            for (i = 0; i < 8; i++) {
                addQueue(0xBF);
                addQueue(80 + i);
                addQueue(127 * ((((myCaptureCCByte * 128) + myCapturePCByte) >> i) % 2));
            }
        } else {
            // This is an error condition.  So reset the queue and pointers
            headQ = 0;
            tailQ = 0;
            byteReady = false;
            for (i = 0; i < 128; i++) {
                tx_queue[i] = 0;
            }
        }
    }

    unsigned char deQueue() {
        unsigned char myByte;
        myByte = tx_queue[tailQ];
        tailQ++;
        tailQ = tailQ % 128;  // Keep this tailQ contained within a limit
        // Now that we dequeed the byte, it must be sent.
        return myByte;
    }

    void loop() {
        if (byteReady) {
            if (midiByte >= 0xF0) {
                // This automatically passes all clocks and System Realtime Messages
                state = STATE_PASSTHRU;
            } else if (midiByte >= 0x80) {
                switch (midiByte) {
                case MIDI_PC_CH16:
                    state = STATE_1PARAM;
                    break;
                case MIDI_CC_CH16:
                    state = STATE_2PARAM_1;
                    break;
                default:
                    state = STATE_PASSTHRU;
                    break;
                }
            }  else {
                switch (state) {
                case  STATE_1PARAM:
                    capturePCByte = midiByte;
                    state = STATE_1PARAM_CONTINUE;
                    addCCQueue(captureCCByte, capturePCByte);
                    break;
                case STATE_2PARAM_1:
                    if (midiByte == 32) state = STATE_2PARAM_2;
                    else state = STATE_2PARAM_1_CONTINUE;
                    break;
                case STATE_2PARAM_2:
                    state = STATE_2PARAM_1_CONTINUE;
                    captureCCByte = midiByte;
                    break;
                default:
                    state = STATE_PASSTHRU;
                    break;
                }
            }
        }

        if ((state == STATE_PASSTHRU) && byteReady) {
            // Just pass messages unaltered.  Also don't let any of our modified message through if
            // we are passing though.  Our burst of modified CC# can wait.
            // Serial.write(midiByte);
            addQueue(midiByte);
            // state = STATE_UNKNOWN;
        }
        byteReady = false;

        if (getQDepth() > 0) {
            // We have a byte to send, dequeu and send it
            Serial.write(deQueue());
        }
    }

    // The little function that gets called each time loop is called.
    // This is automated somwhere in the Arduino code.
    void serialEvent() {
      if (Serial.available()) {
        // get the new byte:
        midiByte = (unsigned char)Serial.read();
        byteReady = true;
      }
    }


body:
I miss some data ( mostly, the latest characters of one data) when I want to send several messages from arduino to another arduino.
I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules. If I only want to sent `Hello there` It works very well but if I want to send several things I miss something. for example for this code, it works very well :
Transmitter:

    #include <VirtualWire.h>
    void setup()
    {
    // Initialize the IO and ISR
    vw_setup(2000); // Bits per sec
    }
    void loop()
    {
      char msg[11]="Hello there";
      vw_send((uint8_t *)msg, 11);
      vw_wait_tx();
      delay(1000);
    }

receiver:

    #include <VirtualWire.h>
    void setup()
    {
    // Initialize the IO and ISR
    vw_setup(2000); // Bits per sec
    }
    void loop()
    {
      char msg[11]="Hello there";
      vw_send((uint8_t *)msg, 11);
      vw_wait_tx(); // Wait until the whole message is gone
    delay(1000);
    }

the result is :

`Device is ready
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there`

for this code I missed some data:
transmitter:

    #include <VirtualWire.h>
    void setup()
    {
    // Initialize the IO and ISR
    vw_setup(2000); // Bits per sec
    }
    void loop()
    {

    char msg[11]="Hello there";
      vw_send((uint8_t *)msg, 11);
      vw_wait_tx();
      char msg2[7]="Goodbye";
      vw_send((uint8_t *)msg2, 7);
      vw_wait_tx();
    delay(1000);
    }

The result is :

`Device is ready
Received: Hello there
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t`

title: missing some data after data is sent by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)

Answers: 0


body:
My code:

    const int buttonPin = 2;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

    bool buttonState = 0;         // variable for reading the pushbutton status
    bool ledState = 0;
    void setup() {
      pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
      pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
    }
    void loop() {
      buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
      if (buttonState == HIGH)
     {
      ledState = !ledState;
     }
      if (ledState == HIGH)
     {
       digitalWrite(ledPin, HIGH); // turn LED on:
     }
       else
     {
        digitalWrite(ledPin, LOW); // turn LED off:
     }
    }

So this is supposed to toggle a led's light on and off. currently it does do that but its not always the case. Currently, if the button is pressed on the arduino board, it has a 50-50 chance of changing its state. What part of the code is leading to this outcome?

title: Toggle a led with a switch

Answers: 3

body:
The mechanical switches bounces. That's all. It's too fast for you to see it but MCU is much faster, so output state is switched many times before contacts are stabilized and no more bounces are causing "turning on and off".

The term you are looking for is **debouncing**

body:
If you're connecting the button from pin 2 to ground and not using an external pull-up, it can lead to trouble. Either use an external pull-up or set the internal one:

    pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input:

Also, you need to [debounce the button][1].

  [1]: http://www.ganssle.com/debouncing.htm

body:
In addition to the debouncing suggested by the other answers, you have a further problem: your `loop()` will whiz through in a very short time, and run again while your finger is still on the button, turning the light off.  And then run again, turning it back on again, and so on.

You need to wait for the button to be released before registering another change.

    const int buttonPin = 2;     // the number of the pushbutton pin
    const int ledPin =  13;      // the number of the LED pin

    bool ledState = 0;

    void setup() {
      pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
      pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
    }

    void loop() {
      bool buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
      if (buttonState == HIGH)
      {
        // Poor-man's debounce. There are much better ways of doing this!
        delay(20);

        ledState = !ledState;
        if (ledState == HIGH)
        {
          digitalWrite(ledPin, HIGH); // turn LED on:
        }
        else
        {
          digitalWrite(ledPin, LOW); // turn LED off:
        }

        // Wait for the button to be released
        while (digitalRead(buttonPin)) {}

        // Poor-man's debounce. There are much better ways of doing this!
        delay(20);
    }


body:
I have a sketch that has been running fine on an Uno 24x7 for a few months now.  The part of interest is an interrupt routine associated with a momentary contact switch [on pin 2].  When pressed, the interrupt routine handles debouncing and simply toggles a boolean variable.  The main routine checks status, takes action, warbles a buzzer, and does a Serial.print of the event.

Today, I moved the unit to the other side of the room and plugged it into a different PC via USB. Whilst it was running, I happened to turn on a nearby fluorescent light [not connected to anything but a 120v outlet].

The Uno buzzer went off, and appropriate msgs were written to the serial connection.  I flipped the light back on, and got the same kind of results.  I repeated this numerous times and got the same.  I could flip the light or push the button attached to the Uno, and the results were indistinguishable.

I unplugged the USB cable and used the power jack instead.  I got the same results, sans the print msgs to the serial connection.

The board itself has only a DS3231, an 8x8 LED matrix, a button, two LEDs & resistors, and a buzzer.

What is happening?  How can I resolve the problem?  [If another person had posted this, I would be disinclined to believe it, but surely someone out there understands the situation.]

I can readily supply a minimal code set and a Fritzing if it would help, though I suspect it would not.

title: Interrupt routine for button somehow respondng to room lamp turning off and on

Answers: 2

body:
My guess: pickup on the input line from interference.  (I'd expect this more if the switch were on a long cable away from the Arduino.)

If the button uses an external pull-up resistor, try a smaller value (maybe 5k?).  If it uses the internal pull-up, try adding an external one.

body:
Yours is a problem of EMI (electromagnetic interference). The ballast from the fluorescent light may interfere via two mechanisms:

 1. **Conducted EMI** through the power lines (unlikely). In order to rule out this condition, power your Uno through a battery or a battery-powered device (a laptop disconnected from mains). If EMI effects disappear, then you have a problem of conducted EMI and you must use some kind of power-line filter. If it doesn't disappear, then it's a problem of radiated EMI (continue reading).

 2. **Radiated EMI** (most likely). There are some things you can do to mitigate its effects:

* Use wires as short as possible.
* Twist wire pairs whenever possible.
* Avoid operating conditions that leave inputs unterminated (be sure they're always either pulled up or low). This can easily happen when switchs are used and they leave an input in a high-impedance (disconnected) state.
* Increase the debouncing time or use a more robust, glitch-tolerant debouncing routine.
* Consider polling the input instead of using an interrupt. However, doing this will be of little use if you don't improve your debouncing routine.
* Consider adding hardware debouncing.

Regarding the last three points, I recommend you to read this [this][1]. You'll have a better grasp about the art of debouncing inputs.

SPOILER: One thing you can do to make your debouncing routine far more robust is to **wait for N consecutive readings with the same value** (to happen during a given time T = N x Interval) before considering it good, instead of just waiting for a second reading after a constant time T.

  [1]: http://www.ganssle.com/debouncing.htm


body:
I am using unipolar 1.8 degree stepper motor. I have written code to rotate stepper motor i.e. when A0 pin becomes HIGH it should rotate in clockwise and when A1 pin becomes HIGH it should move anti clockwise but motor is rotating only once when I am making A0/A1 HIGH and then stops. After that it is not rotating even if i am making A0, A1 pin high. I am very new to this please tell how to solve this problem. I am using microstepping drive, nema 17 stepper motor and Arduino Uno board.

<!-- language: lang-cpp -->

    #include <Stepper.h>

    #define STEPS_PER_MOTOR_REVOLUTION 32

    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
    int  Steps2Take;
    int buttonApin = A0;
    int buttonBpin = A1;
    int dirpin = 8;
    int steppin = 9;
    void setup()
    {
      pinMode(buttonApin, INPUT);
      pinMode(buttonApin, INPUT);
      pinMode(dirpin, OUTPUT);
      pinMode(steppin, OUTPUT);
      small_stepper.setSpeed(1900);
    }
    void loop()
    {
      int valA = digitalRead(buttonApin);

      if (valA == HIGH)
      { digitalWrite(dirpin, HIGH);
        for (int x = 0; x < 100; x++)
        { digitalWrite(steppin, HIGH);
          delayMicroseconds(1000);
          digitalWrite(steppin, LOW);
          delayMicroseconds(1000);
        }
      }
      int valB = digitalRead(buttonBpin);

      if (valB == HIGH)
      {
        digitalWrite(dirpin, LOW);
        for (int x = 0; x < 100; x++)
        {
          digitalWrite(steppin, LOW);
          delayMicroseconds(1000);
          digitalWrite(steppin, HIGH);
          delayMicroseconds(1000);
        }
      }
    }

title: Arduino code is not working for unipolar stepper motor

Answers: 1

body:
I have mentioned in the comments that you should read the buttons with `analogRead()`. But you can do it other way by simply connecting the button pin to digital inputs on arduino(any from 0-13). Analog pins are mostly used for accessing the sensor data as far as I know. I am correcting your code as below:

    #include <Stepper.h>

    #define STEPS_PER_MOTOR_REVOLUTION 32

    #define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

    Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
    int  Steps2Take;
    int buttonApin = 4; //connect button to digital pin 4 on arduino
    int buttonBpin = 5; //connect button to digital pin 5 on arduino
    int dirpin = 8;
    int steppin = 9;
    void setup()
    {
      pinMode(buttonApin, INPUT);
      pinMode(buttonApin, INPUT);
      pinMode(dirpin, OUTPUT);
      pinMode(steppin, OUTPUT);
      small_stepper.setSpeed(1900);
    }
    void loop()
    {
      int valA = digitalRead(buttonApin);

      if (valA == HIGH)
      { digitalWrite(dirpin, HIGH);
        for (int x = 0; x < 100; x++)
        { digitalWrite(steppin, HIGH);
          delayMicroseconds(1000);
          digitalWrite(steppin, LOW);
          delayMicroseconds(1000);
        }
      }
      int valB = digitalRead(buttonBpin);

      if (valB == HIGH)
      {
        digitalWrite(dirpin, LOW);
        for (int x = 0; x < 100; x++)
        {
          digitalWrite(steppin, LOW);
          delayMicroseconds(1000);
          digitalWrite(steppin, HIGH);
          delayMicroseconds(1000);
        }
      }
    }


body:
this is my first project on an Arduino platform. My aim is to build up a door lock unlockable by playing a short melody on a one-octave piano keyboard. I think the idea is cool!
I'm thinking at everything, but I can't figure out how to make Arduino move something (which in my case would be the proper door lock). I thought about a little motor, but I don't know if it is or not  feasible...
To be clear, what I want to do is a simple door lock like this [![enter image description here][1]][1]
(or even simpler) being moved from an Arduino program. How can I do that?

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

title: Working on a simple door lock

Answers: 1

body:
You want a [solenoid][1].

Looks like people sell [ones][2] which are specifically made for door locks.

  [1]: http://www.magnetschultz.co.uk/standard_and_special_solenoids/25/Miniature-solenoids
  [2]: https://thepihut.com/products/adafruit-lock-style-solenoid-12vdc


body:
I noticed there are cheap SD modules and complete SD shields.
I assume the last are used for a 'final' product and not for bread-boarding (?)

However, I was wondering, is there also a difference in functionality or more important, support for e.g. the sd library (thus having file I/O in addition  to SPI interface)?

E.g. can I use the file I/O and the SD library with the [This SD module](https://www.aliexpress.com/item/1pcs-lot-Micro-SD-card-mini-TF-card-reader-module-SPI-interfaces-with-level-converter-chip/32735273502.html?spm=2114.01020208.3.19.Rtw72Z&ws_ab_test=searchweb0_0,searchweb201602_1_10000073_10065_10068_10000077_10000074_10000132_10000033_10000030_119_10000167_10000026_10000175_10000126_10000129_10000023_10000123_432_10000069_10000068_10060_10062_10056_10055_10000062_10054_10000063_301_10059_10000120_10099_10000020_10000156_10000158_10000013_10000117_10103_10102_10000016_10000114_10096_10000111_10000056_10000059_10052_10053_10050_10107_10051_10106_10000097_10000094_10000090_10000147_10000091_10000144_10084_10000150_10000101_10083_10000100_10000011_10080_10000153_10000104_10082_10000045_10081_10110_10000108_10111_10000191_10112_10113_10000197_10114_10000089_10000086_10000179_10033_10000083_10000042_10000135_10000080_10078_10079_10000039_10073_10000140_10070_10000036_10122_10123_10121_10126_10124_10000187-10053,searchweb201603_9,afswitch_1,ppcSwitch_5_ppcChannel,single_sort_1_price_asc&btsid=ad51690d-b722-481d-bdec-759a968ea925&algo_expid=1bc7cb28-840e-4c59-ad94-ed0361e2bd1d-2&algo_pvid=1bc7cb28-840e-4c59-ad94-ed0361e2bd1d)?

title: Do (cheap) SD modules support file I/O?

Answers: 2

body:
There are Uno compatible SD shields which are great for prototyping IF you are using an Uno, they don't work too well with a Nano.  The modules are fine, but you end up with wires everywhere, but they do work with more formats of Arduino.

The ability to do file operations is separate to the protocol you use to talk to the module (SPI).  Lots of device (not just SD cards) use SPI, but not all of them do file operations.  An LCD, a GPIO expander, an EEPROM memory chip are all examples of devices that could use SPI.

What actions the SD module/shield is capable of is really up to the library/software.  The module will have to comply to some set of standards and this will let the caller perform certain operations.  Lets say one of the operations is to read one byte from an address.  This operation would need to be used by the library to read a file, also it would need to use it to find where the file is.  It would also need it when writing a file, because it would need to know what free space was left on the card.  You are shielded from all this by the Library you probably have a read file, write file and delete file function.  (This is an example of abstraction which you will see a lot in programming).

The will also have a set of standards to allow a controller to interface with the module, SPI, I2C, Serial or a proprietary one.  These communication protocols allow the controller to send the file commands to the module, like the read command above, and lets the module return data to the controller.

So to answer your question

 1. If you use a module and shield that use the same IC (chip) to access
    the SD card and the same library then they will almost always behave
    the same.

 2. If you use two different shield (different ICs) which
    need different libraries then they MIGHT have different
    functionality.

 3. If you use two different shields which use the SAME library then the MIGHT have the same or different functionality.

Summary : Yes No Maybe :)

If you want something special find a library that does what you want and then find a bit of hardware supported by that library that also does it.  Otherwise, chances are you will be fine.

==== Edit ===

When you think of hardware/software abstraction think of it as a Television.  You deal with the TV at the very highest level, you turn it on/off and change channels.

When you change channel what really happens is the remote control converts your button press into an encoded infra-red signal which hopefully hits the TV and the TV decodes this and executes some code which selects a pre-programmed channel.

Now you don't care about that all you care about is you press the button and you favourite soap opera appears on the screen.

There is another level of abstraction that is happening when the TV selects the pre-programmed channel, it has to convert the signal into some reference to the stored information that produces some information that is passed to the tuner and....  Well it just gets silly, you just want to watch your soap.

So back to the subject in question, you buy a SD reader module, you find a library that works with it and in your code you call `WriteFile()`.  Does it really matter how it does it?  Do you care that the library is scattering you bytes across the SD card? Well as long as it retrieves it no not really?  Does it matter that `WriteFile()` is actually storing it on the hard disk of a PC somewhere in the world?

Your call to `WriteFile()` is abstracted away from the underlying process hiding it, because it doesn't really matter.  Most of the libraries use this Abstraction process, look at the code in Wire.cpp, it looks really simple when you are calling `read()` and `write()` but it isn't.

body:
Short answer. Yes, it will work.

I have used the same MicroSD Card Adapter module [it is marked MOSO instead of MISO on one of the pins] for a few projects.  I found no problems or special considerations doing so [except for getting the pin mapping correct].

In contrast, I've used one shield that worked sporadically, because of intermittent header contact.  It would work for a while, then stop until I "massaged" it properly.  It was probably just a bad assembly, though.

  Many people prefer working with shields, while I do not, and would rather build on PCB board once I have a working version of my project.  It's cheaper as well.


body:
When I read about registers I always encounter the following illustration:

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

So there are 32 registers in the above diagram. They are processor registers.

But in the [data-sheet][2] of ATmega328P at page 428 there is a section called "Register Summary".

Here in that list there are much more than 32 registers. Do the rest of the registers physically stay somewhere else?

Lest's take an example of ADMUX register. Where is that register physically inside the DIP? It is not one of the 32 registers? And if stays somewhere else how does it connected to the ALU?

  [1]: https://i.stack.imgur.com/fszJd.gif
  [2]: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf

title: A question on physical locations of the registers in ATmega328P

Answers: 1

body:
You are confusing CPU registers and SFRs, Special Function Registers.

CPU registers only exist within the CPU core. SFRs exist within the RAM bus's memory map.

CPU registers are used by the CPU to execute instructions and do calculations, etc. SFRs are a part of the logic of the rest of the chip and directly affect the working of the various peripherals.

As far as the CPU is concerned an SFR is just a bit of SRAM, but it affects physical workings when written to, and reflects physical states when read from.


body:
I'm working on a little DIY project in which I intend to make my own dataglove. Now I'm kinda stuck on choosing the right microcontroller. And since it can be quite costly, I thought to ask for some help.

So: I'm going to use 12 flex sensors (maybe 14) and 1 IMU (probably the 6050). now the problem is that I need a total of at least 14 AI.. And the small controllers only have about 6.

The controller can't be too big for dexterity reasons and also will need the availability to add a Bluetooth module.

I've been looking at some multiplexing/shield options but I'm just not confident (and rich) enough start ordering..

Peace out,

Lars

PS: other brands besides Arduino work for me to

title: What controller should i use?

Answers: 1

body:
How about a Teensy? The guys that make Teensy have developed many of the well known Arduino libraries and have also helped develop the Arduino IDE in the past so they know their stuff.

I see the Teensy LC at about $11. the spec says its almost the same as Teensy 3.1 which has 20+ Analog In

https://www.pjrc.com/store/teensylc.html

https://www.pjrc.com/teensy/index.html

The 3.1 and 3.6 are more powerful and more expensive at around $29

note: Read the index for which boards are 5v tolerant if that's what you need.