body:
Here's an example of a class which crashes the ESP8266-03 causing it to reset:

Test.hpp file:

    #include <map>

    class Test {
    public:
        int data() const;

        Test(int x);
        ~Test();
    protected:
        int _data;

        static std::map<int, Test const *>thing;

        static void _Reserve(Test const * const t);
    };

Test.cpp file:

    std::map<int, Test const *> Test::thing;

    int Test::data() const
    {
        return this->_data;
    }

    void Test::_Reserve(Test const * const t) {
        Test::thing[t->data()] = t; // Works fine if this line is removed.
    }

    Test::Test(int x): _data(x)
    {
        Test::_Reserve(this);
    }

    Test::~Test() {};

Project.ino:

    #include "ESP8266WiFi.h"
    #include "Test.hpp"

    Test test(2);

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

    void loop() {
        Serial.print("Timer: ");
        Serial.println(millis());
     delay(1000);
    }

The following **does NOT** crash the ESP8266-03 and prints the time as it should:

    #include "ESP8266WiFi.h"
    #include <map>

    class Test {
    public:
        int data() const
        {
            return this->_data;
        }

        Test(int x): _data(x)
        {
            Test::_Reserve(this);
        }
        ~Test() {};
    protected:
        int _data;

        static std::map<int, Test const *>thing;

        static bool _Reserve(Test const * const t) {
            Test::thing[t->data()] = t;
        }
    };

    std::map<int, Test const *> Test::thing;

    Test test(2);

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

    void loop() {
        Serial.print("Timer: ");
        Serial.println(millis());
     delay(1000);
    }

When the first version is uploaded to the board, I get the following in the serial monitor:

     ets Jan  8 2013,rst cause:1, boot mode:(1,7)

     ets Jan  8 2013,rst cause:4, boot mode:(1,7)

    wdt reset

When I reset it and boot it regularly, no upload mode, the following repeats every ~1 second:

     ets Jan  8 2013,rst cause:1, boot mode:(3,7)

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v09f0c112
    ~ld

title: Why does static member std::map reset ESP8266 when outside the .ino file?

Answers: 1

body:
> Why does static member std::map reset ESP8266 when outside the .ino file?

What happens if the Test() constructor is run before the map constructor? This is the problem: you are assuming order of execution.

Use a Singleton pattern or init() member function to force the ordering that is required.

Cheers!


body:
Apparently leonardo and UNO are very similar boards.

However, despite that both have the same flash memory size, Leonardo bootloader is considerably bigger than UNO bootloader (4KB vs 0.5KB).

what would be the reason? it is there any way to use smaller bootloader in leonardo?

Uno specs: [https://www.arduino.cc/en/Main/ArduinoBoardUno][1]

Leonardo specs: [https://www.arduino.cc/en/Main/ArduinoBoardLeonardo][2]

Thanks!

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardUno
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

title: why leonardo bootloader is bigger than UNO?

Answers: 1

body:
> Apparently leonardo and UNO are very similar boards.

No, they are very, very different.

The Uno uses an external USB-UART bridge. This means that the bootloader code only has to read from the UART in order to program the device.

The Leonardo has USB support built into the MCU. This means that the bootloader must contain an entire USB Device stack in order to process the USB packets and then pass the payload to the programming routines.


body:
I want to find the timing between HIGH state and LOW state of push button. For that, I made a program. You can see my program below. In my program, I made logic like that when switch is pressed then one variable "currentMillis" store the value of millis() and it store value until button pressed. But whenever I pressed button again then it also add previous value. For example, if button pressed for first time then suppose we got 200ms, now suppose if button pressed second time then we got 500ms and if button pressed third time then we got 1000ms. That mean every time value added. No doubt I made a logic which seem to be perfect but I can't figure out what is problem. Please give me some suggestions.

    const int  buttonPin = 2;

    unsigned long currentMillis = 0;
    unsigned long previousMillis = 0;
    unsigned long finalMillis = 0;

    int buttonPushCounter = 0;

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

       pinMode(buttonPin, INPUT);
       digitalWrite(buttonPin, HIGH);
    }

    void loop()
    {
      if (digitalRead(buttonPin) == LOW)
      {
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(buttonPushCounter);

        while(digitalRead(buttonPin) == LOW)
        {
          currentMillis = millis();
        }

        finalMillis = currentMillis - previousMillis;
        Serial.println(finalMillis);

        previousMillis = finalMillis;
        //finalMillis = 0;
      }
    }

Here, it is my serial monitor output.

    on
    number of button pushes:  1
    0
    on
    number of button pushes:  2
    775
    on
    number of button pushes:  3
    873
    on
    number of button pushes:  4
    1425
    on
    number of button pushes:  5
    1496
    on
    number of button pushes:  6
    2073
    on
    number of button pushes:  7
    2010
    on
    number of button pushes:  8
    2643
    on
    number of button pushes:  9
    3052
    on
    number of button pushes:  10
    3195
    on
    number of button pushes:  11
    3396
    on
    number of button pushes:  12
    3575
    on
    number of button pushes:  13
    3737

title: Find the time between HIGH state & LOW state of push button(switch)

Answers: 3

body:
You wrote

    previousMillis = finalMillis;

This means that you store the duration of the pulse, not the last time it was pressed.

Change it with

    previousMillis = currentMillis;

and you will be able to detect the high + low time.

By the way, constantly reading the millis function is useless. You can change your code to

    while(digitalRead(buttonPin) == LOW);
    currentMillis = millis();

which reads only once.

body:
First of all, frarugi87 is right.
Second, why not use this:

    finalMillis = millis() - previousMillis;
    previousMillis = millis();

Instead of what you wrote.

    if (digitalRead(buttonPin) == LOW) {
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(buttonPushCounter);
        finalMillis = millis() - previousMillis;
        previousMillis = millis();
        Serial.println(finalMillis);
        while(digitalRead(buttonPin) == LOW){}
      }

It works great.

Hope it helps.

Yoav

body:
While the previously given answers should work for you, they share a
couple of problems with your original code:

* they do not debounce the button
* they block while waiting for the button to be released

Blocking the program is not a big deal if you do not have to do anything
else. However, chances are you are showing us only a fraction of what
will ultimately be a larger program. In this case, doing a busy wait
(like `while (digitalRead(buttonPin) == LOW) ;`) will block the _whole
program_, not only this particular feature. Then, I suggest you get
immediately in the habit of writing non blocking code:

* when the button is pressed, record that fact and the current time
* when the button is released, report to the user

The important notion is that you never _wait_ for anything. Instead, you
check whether something has to be done _right now_ and, if so, you do
it.

Here is a non-blocking version of your program, with some debounce
added:

    const uint8_t button_pin = 2;

    void setup()
    {
        pinMode(button_pin, INPUT_PULLUP);
        Serial.begin(9600);
    }

    void loop()
    {
        static int last_button_state = HIGH;
        static unsigned int push_count;
        static unsigned long last_press_time;
        int button_state = digitalRead(button_pin);
        unsigned long now = millis();

        // Record when the button is pressed.
        if (last_button_state == HIGH && button_state == LOW) {
            push_count++;
            last_press_time = now;
        }

        // Report when the button is released.
        if (last_button_state == LOW && button_state == HIGH) {
            unsigned long push_duration = now - last_press_time;
            if (push_duration < 10) {  // discard bounce
                push_count--;
            }
            else {
                Serial.print(F("pushes: "));
                Serial.print(push_count);
                Serial.print(F(", duration: "));
                Serial.print(push_duration);
                Serial.println(F(" ms"));
            }
        }

        last_button_state = button_state;
    }


body:
Hi recently I've could send some messages with the [A6 GSM module][1], which uses **AT commands**. To switch on the board, you need to press the power button about 4 seconds or connecting the VCC pin to the PWR pin to avoid manual switching on. In this [Andreas Spiess' video][2] (minute 2:21), he recommends reset the device to give to the board a defined state. I had not done this until the device didn't work properly with some scripts. To reset it, he advises to reset the modoule. Its RST pin needs 0.70 mA and works at low level. In addition, the Arduino can not provide that current with a single pin so he uses a N-channel MOSFET (3055) to reset the board.

In my case I used a transistor (I don't know if it's NPN or PNP) and I connected the circuit like in his video. It worked! But it given **strange results** to the serial monitor  (yes, I set the baud rate correctly). After reset the board it switched on automatically because it was connected the PWR pin and VCC pin. The mistery occured when I unplugged the board (even its current) and then I reconnected it again. Since that moment it doesn't work, it doesn't switch on its LED to show you that the board is working. So, can anyone explain me **why** the 3055 it's neccesary to reset the board? Can it be done using **Ohm's Law**, a digital pin and a big resistance to give to the board the 70 mA?

Thanks!

  [1]: http://www.electrodragon.com/w/GSM_GPRS_A6_Module#A6_Pin_Definitions
  [2]: https://youtu.be/qtzrVj66IOA?t=2m21s

title: Is the A6 module broken?

Answers: 1

body:
I come across this problem too..based on what you said, i think it works like this:

The parameter you are looking for is power rating.. Arduino digital pin can only tolerate some amount of current, and im guessing it is less than 70mA..if you still do that, it is possible to damage that pin..since you want a LOW level for trigger, you can connect that RST manually to GND.. GND is also 0V just like the DIGITAL LOW, but it has no internal circuitry as of digital pin - meaning that you can sink a lot more current to GND..
If you want to be on the safe side, connect a limiting resistor(use ohm law for value), and also take note on the resistor power rating..


body:
My current project involves embedding an MPU6050 accelerometer into straps, one of which goes below the knee, the other above the knee.

I need to fit the sensor into the strap and currently i have 6-core multi-threaded wire soldered directly into the board. This doesn't facilitate the greatest of long term stability, as too much strain and the wires will just pull out and break.

What I am wondering is if it is OK to:

 1. cover the wire side of the board in glue from a hot glue gun?
                     Would this have any possible conductivity issues or risk damaging the wires or board itself?
 2. If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance. This would leave me with a really solid sensor for embedding if so!

Any answers to the above questions would be greatly appreciated and I would be extremely grateful for any alternative options as well. I would like to keep the wires soldered into the board as it is extremely tidy and makes for easier embedding than if I were to use another connector.

title: MPU6050 safe to use with glue?

Answers: 2

body:
> Would this have any possible conductivity issues

Nope.

> or risk damaging the wires or board itself?

Nope.

> If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance.

Sure.

This is known as "potting". You can get special potting compounds, but hot glue is just as good.

body:
1) I do not see any problem here - I myself used hot glue to fix and isolate power source of robot from the copper side. It does not leak any (measurable by my tools) current, does not show any sign of detorations and works well both electrical and mechanical way. I used it only on copper side, where was risk of shortcuts and where were no heat dissipators (as it isolate also heat). But I think, that the MPU does not generate so much heat, to be worry about - body proximity and weather on summer would affect it more.

2) Hot glue is not as hot as soldering lead/tin so short contact with the MCU should not harm it. (You can shortly touch hot glue to manipulate it and not get burned, so it is not so hot). Anyway I would apply it as fast as possible and would leave it cool down before swithing it on (the working and the storing temperatures are different case). Be carefull with the wires, as the isolator can be melted, if heated by hot glue and moved at the same time. Also take in mind, that the hot glue should be little around the whole, to isolate from humidity. And that it would be complicated to solder anything after the glue is applied - so have all contacts (you may possibly need access) somehow lead out of the glue. And try the construction before applying the glue, to be extra sure, that nothing is missing and everything works.

I personally would place the MCU on some kind of PCB and solder the wires to the PCB organized the way the wires would continue to form "cable" and to have extra sure there is no force on the connection of MCU pins. Also I would fixed the whole cable to the PCB with something, so the solder itself is not under any force, as it is the most probabely place to broke there. An I would ensure, that the cable goes smoothly away from the PBC, as it would be bad, if it would be bent ower sharp edge at the place where it leave its glue support.


body:
This question is an extension of this question.

https://arduino.stackexchange.com/questions/33088/accessing-values-from-array-within-a-library

The answer provided by Mark showed me how to read and print a single value from a particular array by using the index number to print to the serial console.

The second part of this question is how to get these values from the array to map to 0-180 for values that are useful to the servo.

The below code is my attempt that is not working. I used the servo sweep example from the Arduino examples which worked fine with a potentiometer but not with the ppm input. What am I doing wrong here? This won't compile. (I am using TinyServo.h library since this is for an attiny85. Works with with the pot mapping just fine.)

 #include <TinyServo.h>
 #include <TinyPinChange.h>
 #include <TinyPpmReader.h>
 #include <Rcul.h>

 int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

 //int potpin0 = 3;    <---------          // This worked
 int val0;                     // integer to store value

 const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
 const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
             // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

 #define PANSERVO 0
 #define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

 void setup()
 {
   setupServos();
 }

 void loop()
 {
   val0 = analogRead(PPM_INPUT_PIN);  <---------          //Doesnt work// reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
   val0= map(val0, 1000, 2000, 0, 180);
  // scale it to use it with the servo (value between 0 and 180)
     // scale it to use it with the servo (value between 0 and 180)

 moveServo(PANSERVO, val0);

   delay(5);                           // waits for the servo to get there
 }

For some background, the ppm library outputs like this to the serial monitor:

Ch4=**1560** us

These values move from ~1000 - 2000 depending on the ppm signal input. (The input is from a RC remote control receiver)

This example below prints only channel 4 (Ch4=1560 us)from  a total of 8 channels. Now, I want to map this to the values of 0-180:

 #include <TinyPinChange.h>
 #include <TinyPpmReader.h>
 #include <Rcul.h>

 #define PPM_INPUT_PIN  2

 void setup()
 {
   Serial.begin(38400);//attiny tx - rx uno does not work at 9600 baud. Set to 38400 @ attiny 1mhz and uno serial console to 38400 baud
   TinyPpmReader.attach(PPM_INPUT_PIN); /* Attach TinyPpmReader to PPM_INPUT_PIN pin */
 }

 void loop()
 {

 Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us"));

  display results */
   delay(500);
 }

What am I doing wrong?

title: Mapping PPM Signals to Servo Values

Answers: 1

body:
    int PPM_INPUT_PIN = TinyPpmReader.width_us(3);
will save the result into variable `PPM_INPUT_PIN`, while

    val0 = analogRead(PPM_INPUT_PIN);
will save an analog reading results from `PPM_INPUT_PIN` channel into variable `val0`. This is (one of) your problem.
To map the PPM value, you can do:

    #include <TinyServo.h>
    #include <TinyPinChange.h>
    #include <TinyPpmReader.h>
    #include <Rcul.h>

    int val0,                     // integer to store value
     mappedval0;      // integer to store mapped value;

    const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
    const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                           // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

    #define PANSERVO 0
    #define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

    const int PPM_max_value = xxxxx; //put the max value of PPM reading result
    const int PPM_min_value = yyyyy; //put the min value of PPM reading result

    void setup()
    {
      setupServos();
    }

    void loop()
    {
      val0 = TinyPpmReader.width_us(4);   //get PPM reading result from index 4
      mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
        // scale it to use it with the servo (value between 0 and 180)

      moveServo(PANSERVO, mappedval0);
      delay(5);                           // waits for the servo to get there
    }


body:
I hope this stack is the right place for this question.
I have an accelerometer mounted securely on a swaying object -lets say a stick or pole-
this object is swinging back and forth in small angles (+- 20) with a frequency of about 2-3 times a second.
Im using the accelerometer output to calculate the tilt of the object, however since the frequency of the swings is relatively high the accelerometer readings are very high as well, and not reliable for calculating the tilt.

from my research i have seen that accelerometers work best in a stable environment.
Is there any way to improve the reliability of my accelerometer output in this setup?

title: Accelerometer readings on a moving object

Answers: 1

body:
A few things to consider.

First. An accelerometer isn't that great here. Low output frequency is one issue. Noise is another. A pot or an optical encoder would be better.

Secondly. Even if output frequency isn't an issue. You will need some sophisticated math to reconstruct the instantaneous tilt, as the measurements are essentially a sine function, but with an acceleration away from the center of the rotation.  Getting to the max tilt is easier mathematically.

Just for starters.


body:
I am using an external ADC (via SPI) and also a GPS receiver (Software Serial). I tried each one of them and it's working fine. Now, when I try to integrate both of them in one sketch, I can only make the ADC work, the GPS is not receiving something.

    void setup()
    {
      pinMode(ADS1220_CS_PIN, OUTPUT);
      pinMode(ADS1220_DRDY_PIN, INPUT);

      Serial.begin(115200);
      ss.begin(9600);

      //while(!Serial);
      //SPI.begin();                           // wake up the SPI bus.
      //SPI.setBitOrder(MSBFIRST);
      //SPI.setDataMode(SPI_MODE1);

      //ADS1220.begin();
      Wire.begin();
      delay(1000);  // Give things time to "warm-up"

      delay(1000);
      pre_time = millis(); //store current time to be used as "previous" time
    }
I found out that in the setup(), when I comment out all those SPI functions, the GPS returns something. What seems to be wrong with this? thank you so much for any help

title: Arduino Problem with using SoftwareSerial and SPI

Answers: 3

body:
SoftwareSerial is **very** inefficient.  AltSoftSerial is best.  See [this answer](https://arduino.stackexchange.com/questions/26240#26277) for a complete list of alternatives.

You may want to look at my [NeoGPS library.](https://github.com/SlashDevin/NeoGPS)  It is smaller, faster and more accurate than all other libraries.  The examples are structured better.  You don't show your whole sketch -_-, but the loop structure could be your real problem.  Be sure to read the Troubleshooting page for more suggestions.

body: I managed to solve this just by changing the Rx pin to digital pin 4 from digital pin 10, I don't know what causes the problem but it did the job for me

body: For the Arduino to be SPI master, the SS pin (D10) must be an output. Using it as software serial input (Rx) is no good. If you had used it as the Output, Tx, you would likely have been ok.  I try to use 10 as SS for the first SPI device I have connected all the time to avoid that pitfall.


body:
I have connected my ESP8266 to my Arduino Uno on pin 2 & pin 3 as RX & TX. I adjusted the baud rates and I have no issue receiving the data from the ESP8266.

The ESP8266 gets connected as a client to a server and grabs the likes count of a Facebook page. The data on the ESP8266 serial port is updated correctly every time the ESP sends a get request to the server to get the updated likes count of a particular Facebook page.

Unfortunately I'm not receiving this updated likes count on my Arduino serial port. I'm always receiving the same likes count. I have to close the serial window and open it again to receive the new count. Or reset the Arduino itself to receive the new likes count.

So why isn't it posting the latest likes count sent from the ESP to the Arduino instantly without having to reset the Arduino? Maybe I have an issue in the `void loop()`.

Because I display this data on an external display and I need it to be updated without me needing to reset the Arduino every time to receive the latest count.

    void loop() {
      char c;
      while (esp8266.available() && c != '\n') {
        c = esp8266.read();
        response += c;
      }
      //If end of line
      if (c == '\n') {
        //Getting the likes string only
        if(likes = response.substring(response.indexOf("Likes:")+6, response.indexOf("::"))) {
          //Filtering some unneeded strings
          if((strstr(likes.c_str(), "URL")) == NULL) {
            currentLikes = atol(likes.c_str());
            Serial.print(currentLikes);
            //Printing likes count on serial port
          }
          Serial.println();
        }
      }
    }

title: Reading updated serial data from ESP8266

Answers: 1

body:
Thank you everyone I had to just clear the response string every time.

I have just added `response = "";` after the `Serial.print(currentLikes);`


body:
I'm planning my first Arduino project which involves a MPU-6050 accelerometer(3.3V) and a RGB led(5V). I've found this [Arduino Clone][1] but i'm not sure if it has 3.3V and 5V outputs that I can use. The pins do exist on the original Leonardo board but i'm not sure if the clone contains them as well.

  [1]: https://www.amazon.de/gp/product/B01HAZ2M8A/

title: Arduino Leonardo clone voltage question

Answers: 1

body:
That has a 5V pin (Vcc) but no 3.3V. Also the 5V pin can't provide more than a few hundred mA.

Better specifications are here: https://www.sparkfun.com/products/12640


body:
I am using the Adafruit Fona 808 to make a wearable device. One of the main features is GPS but I cannot seem to find a suitable antenna for wearables. My question is: What is a good GPS antenna for a wearable project and should it be active or passive?
Thanks

title: Wearable GPS Antenna

Answers: 1

body:
I too thought whats wrong with a normal Antenna, but the answer is the problem is the human body.

There are manufacturers that make "fabric" antennas, but these tend to be Mil-Spec so are going to cost a fortune.  (http://www.pharad.com/gps-wearable-antenna.html)

I found this site that explains what the effect of the body is, and seems to make their own antenna.  http://www.pharad.com/gps-wearable-antenna.html

I think you might be better off looking for a high gain antenna and the choice of active or passive will probably be based on the interference you get from the body.


body:
I am working with sensors on Arduino and would like to filter the sensor's output to a certain band of frequencies.

I found many examples online on how to implement simple digital low-pass filters in Arduino code, but not for band pass filters.

Is it even possible to achieve this in the scope of an Arduino program?
If anyone can share some tutorial for this, that would be much appreciated.

title: Digital Band pass filter on Arduino

Answers: 1

body:
A band pass filter simply means that it a filter between a certain interval of frequencies thus it can be made from a high pass filter and a low pass filter

e.g. this fact is mentioned here http://www.electronics-tutorials.ws/filter/filter_4.html

as well as lots of other web pages which a search by you can find.
So yes a band pass filter can be implemented on arduino if you can implement the corresponding high pass and low pass filter too.


body:
I am trying to compare whether the user input matches a user ID or not. When I read the input from serial, the program is taking the last character which is newline char '\n' and moving it into the char data value to compare against the stored user ID and I don't understand why it's taking the '\n' value instead of the actual user input.

    int Gled = 7;
    int Rled = 8;
    int wait = 5000;
    char UserID = "12345";
    char data;
    char incoming;

    void setup() {
      Serial.begin(9600);
      pinMode(Gled,OUTPUT);
      pinMode(Rled,OUTPUT);
      Serial.println("Please Enter your username or ID:");
    }

    void loop() {
      if(Serial.available()>0) {
        while(1) {
          data=Serial.read(); //read user input and move to data char
          if(data !='\n')
            incoming = data; //if data doesn't equal newline data = incoming
          if (data == '\n')
            break; // newline char detected break
          if (data == -1) //continue reading all of user input
            continue;
          Serial.print(data);
          Serial.print(incoming);
        }
        Serial.println(incoming);
        if(incoming == UserID) { //if user input matches run statement
          digitalWrite(Gled, HIGH);
          Serial.println();
          Serial.println("Access Granted");
          Serial.println("Hello User Name");
          delay(wait);
          Serial.println("Login time exceeded, you are now logged out.");
          Serial.println("Reenter your UserID to log back in.");
          digitalWrite(Gled, LOW);
          Serial.end();
          Serial.begin(9600);
        } else if(incoming != UserID){
          //user input doesn't match run statement
          digitalWrite(Rled, HIGH);
          Serial.println();
          Serial.println("Access Denied");
          Serial.end();
          delay(wait);
          Serial.begin(9600);
          digitalWrite(Rled, LOW);
          Serial.println("Please Enter a Valid ID to Continue.");
        }
      }
    }

title: Reading serial buffer taking newline character instead of user input

Answers: 1

body:
    if(data !='n')

This should be

    if(data !='\n')

**NEXT**.

    data=Serial.read();

only reads ONE character. You should add to a buffer, not assign a single character.


body:
First of all I'm a noob.

I was trying to do the H-Bridge using 2N2222 controlled by an Arduino Uno.

This is the design--->

[![DESIGN][1]][1]

I joined A1 and A2 to form a common terminal (say A), similarly, I joined B1 and B2 to form B. Now I connected A and B to 2 pins of the arduino (say pin 9 & pin 10 respectively).

So, theoretically, when I should digitalWrite pin 9 HIGH, then current should flow via A1 and A2, i.e. left to right in the motor AND when I should digitalWrite pin 10 HIGH, then current should flow via B1 and B2, i.e. right to left in the motor.

Hence, I can control the direction of rotation of the motor.

BUT.....it wasn't working...!!!!

I need help...!!!

After much thinking I had a hunch...."Perhaps, I am not giving GROUND to the transistors". I thought about it, but was unable to figure out the way of doing it.

So, again, please help me...!!!

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

title: How can I connect H-Bridge motor driver (using four 2n222 transistors) to Arduino?

Answers: 1

body:
I am not an electronics guru yet either so others might give you a better answer, but this is one circuit I have messed with a lot because I keep trying to build robots, so I will take a shot at an answer.

Normally you need both NPN and PNP transistors for an H-bridge:

[![Basic H-Bridge Circuit][1]][1]

The 2N222 is NPN so you'd want to pair two of them with two equivalent PNPs such as the 2N2907.

I've see diagrams that have all NPNs but I have never gotten a circuit to work that way. There is a distinction about where the load goes, before or after the transistor, that makes you chose to use an NPN or a PNP in order to make it all flow properly.

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


body:
I am interfacing two SPI slave module i.e. ADS1262 and 2.2 SPI TFT with the Arduino Ethernet board.

When I test each device on its own it works. Initially, I interfaced the TFT to the Arduino and it is working fine. Likewise, the example code of ADS1262 is working fine when I am running it alone.

So after successfully running the TFT alone, I then wire-up the ADS1262, add the corresponding code, however the ADS1262 doesn't seem to respond.

I think the issue may be related to the `ADS1262_CS` or `ADS1262_START` or `ADS1262_DRDY` pin sequence to access the ADS1262.

I have used the [ProtoCentral_ads1262][1] library from GitHub and have used the example code.

[![Circuit diagram][2]][2]

From Comments:
We have already reserved D10 for Ethernet Controller and D4 for SD Chip select. The issue is, how to communicate both of them, one by one. I can access one of them only when code is prepare for both devices.

----

    // Portion of the code is given here

    // https://github.com/adafruit/Adafruit_ILI9341 library used for TFT

    // Code start from here

    for(j=initvalue;j<=finalvalue;j+=x)
    {

          dacvalue=((j*5)/65535);

          writeValue(j);

          tft.fillRect(30,150,70,28,ILI9341_BLACK);

          tft.setCursor(30,150);

          tft.println(dacvalue,3); // dac value is showing on TFT

          Serial.println(dacvalue,3);

    // ADS1262 is need to communicate here as per https://github.com/Protocentral/ProtoCentral_ads1262 library

    // Which pins are need to control here to communicate with ADS1262???

          volatile int p,data;

          if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data ready(DRDY pin)
         {
           SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
           Responsebyte = true ;
         }

          if(Responsebyte == true)
          {
           for(p = 0; p <5; p++)
          {
            SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + p);
          }
          Responsebyte = false;
          }

           if(SPI_RX_Buff_Count >= 5)
          {
            ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
            ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
            ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
            ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

            uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)|((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
            sads1262Count = (signed long) (uads1262Count);      // get signed value
            Serial.println("sads1262Count:");
            Serial.println(sads1262Count);
            resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
            Serial.println(resolution,15);
            volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
            volt_mV   =   volt_V*1000;                           // voltage in mV
         tft.setCursor(166,150);
         tft.println(volt_mV,3); } //not printed on TFT

In above code, ADS1262 is not activated so not giving value on serial window or TFT.

How to activate the ADS1262 module.

  [1]: https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
  [2]: https://i.stack.imgur.com/n2d2U.jpg

title: ADS1262 and 2.2 SPI TFT (Two SPI Slave) with Arduino

Answers: 1

body:
I would suggest that

1) you debug individual code and to make sure that they work separately before integrating them.

2) you put those code pieces in logical blocks. for example, you are likely going to read something from the adc and displaying it on the lcd. so your code flow should be something like this:

      vol_adc = ad1262_read(ADC1_CH); //read analog from ADC1_CH
      vol_mv = adc2mv(vol_adc); //convert the adc results to mv
      lcd_display(vol_mv);  //display vol_mv on the lcd

this approach allows for much easier programming and debugging for you and your readers.


body:
I am using the [Arduino Websocket Client library][1] to connect my Arduino Uno to a Socket.IO server. But the connection always returns 0 (fail) after the handshake.
Anyone has used this library before? How could I debug this?

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

    byte mac[] = {0xB8,0x27,0xEB,0x7E,0x2D,0xC9};
    char server[] = "labathome.rexlab.ufsc.br";
    int port = 8001;
    WebSocketClient client;

    void setup() {
      Serial.begin(9600);
      Ethernet.begin(mac);
      Serial.println(client.connect(server, port));
      client.setDataArrivedDelegate(dataArrived);
      client.send("Hello World!");
    }

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

    void dataArrived(WebSocketClient client, String data) {
      Serial.println("Data Arrived: " + data);
    }

PS: I tested the server and it works fine, and I also tested with a normal WS server instead of the Socket.IO, and nothing :(

  [1]: https://github.com/brandenhall/Arduino-Websocket

title: Arduino connection websocket always fails

Answers: 1

body: With the help of the library developer, I found out that it was a problem on the handshake version. So, I just downgraded my socket.io app from 1.0 to v 0.9.11 and it worked.


body:
      struct node *root, *currentNode;
      root = (struct node*)malloc(sizeof(struct node));
      root->value = '\0';
      root->next = 0;
      currentNode = root;

title: What does the following code in Morse Code Arduino mean?

Answers: 2

body:
> What does the following code in Morse Code Arduino mean?

Step by step:

      struct node *root, *currentNode;

Pointer variables `root` and `currentNode`. Pointers to `struct node`.

      root = (struct node*)malloc(sizeof(struct node));

Allocate memory for a `struct node` and assign `root` pointer.

      root->value = '\0';
      root->next = 0;

Assign `struct node` members using the `root` pointer. Assign `value` member to character 0. Assign `next` to zero, NULL, i.e. often marks end of list.

      currentNode = root;

Last assign `currentNode` to point to the save value as `root`, i.e. the allocated `struct node`.

Next question?

body:
What's missing from this tiny code excerpt is the definition of 'struct node'. From the name, 'node', the member name, 'next', and the way these are being assigned, it's very likely that these 'struct node's are part of a linked list structure; a collection of data that is arranged, not by location as in an array, but by each node having a pointer (memory address) to the next one in sequence. One fixed memory location (apparently 'currentNode') points to the first datum; that one points to the next, and so on until the last one in sequence whose pointer value iz zero (or NULL, the symbol commonly used for an invalid pointer value).

Sorting a list is quicker than sorting an array or a collection of arrays of data, because only the pointers need to be changed; no data needs to be moved. Adding or deleting data in the middle of the list benefits even more; in an array you'd have to move all of the data following the add- or delete-point to create or close a gap for the new or removed datum.

Look at the rest of the code. It's quite likely that is how the 'node's are being used. Also read about linked lists, if that is a new concept.


body:
I'm doing a project using **Arduino Uno R3** and I'm trying to use two buttons to change **LED** state between **HIGH** and **LOW**. I have already a code but someting its not right because the **LED** should be starting in **LOW** state but it's starting in **HIGH** state. I checked the circuit and its all good none of the components is connected in wrong place or not connected corretly and the resistors I used are the right ones.

Here is the code I'm using:

     int ledpin = 13;
     int pushbutton1 = 8;
     int pushbutton2 = 7;
     boolean lastbuttonstate1 = LOW;
     boolean lastbuttonstate2 = LOW;

    void setup()
    {
      pinMode(ledpin,OUTPUT);
      pinMode(pushbutton1,INPUT);
      pinMode(pushbutton2,INPUT);
    }

    void loop() {

    static bool ledState = false; // LED is off by default
     if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
        digitalWrite(ledpin, HIGH);
        ledState = true;
     }
      if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
        digitalWrite(ledpin, LOW);
        ledState = false;
      }
    }

title: How can I setup a LED state change with push buttons?

Answers: 3

body: You need some PULLUP there - either external resistors or INPUT_PULLUP settings, otherwise disconnected pin have not defined valou (so it can be LOW even if button is not pressed.

body:
This is an excellent tutorial for exactly that:
http://www.instructables.com/id/How-to-use-a-Push-Button-Arduino-Tutorial/

Its a bit hard to give you a specific answer without seeing you circuit.
but as a start, i would set the ledPin to LOW in the setup routine.

    void setup()
    {
      pinMode(ledpin,OUTPUT);
      pinMode(pushbutton1,INPUT);
      pinMode(pushbutton2,INPUT);

      //initialize the pin to low
      digitalWrite(ledpin,LOW);

    }

body:
I think you have just minor changes. First of all, you haven't applied pullup. And here, what is the use of `boolean lastbuttonstate1 = LOW;` and `boolean lastbuttonstate2 = LOW;`? I think it not useful for the code so I remove it. And always initialize flag or something in starting of the code means globally. I update your code, just check it out. It might be helpful.

    int ledpin = 13;
    int pushbutton1 = 8;
    int pushbutton2 = 7;

    static bool ledState = false; // LED is off by default

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

      pinMode(pushbutton1,INPUT_PULLUP); // Provide pullup
      pinMode(pushbutton2,INPUT_PULLUP); // Provide pullup
    }

    void loop()
    {
      if((digitalRead(pushbutton1) == LOW) && !ledState) // 1 pressed & led is off
      {
        digitalWrite(ledpin, HIGH);
        ledState = true;
      }
      if((digitalRead(pushbutton2) == LOW) && ledState) // 2 pressed & led is on
      {
        digitalWrite(ledpin, LOW);
        ledState = false;
      }
    }


body:
I have written a code that remaps the buttons of `TTP229` touch keypad which works as it is. Is there any way to optimize this code:

    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>

    #define SCL_PIN 11
    #define SDO_PIN 12
    #define I2C_ADDR    0x3F
    #define BACKLIGHT_PIN     3
    #define En_pin  2
    #define Rw_pin  1
    #define Rs_pin  0
    #define D4_pin  4
    #define D5_pin  5
    #define D6_pin  6
    #define D7_pin  7

    byte Key;
    String keyRemap[12][2] = {
        {"1","1"},{"2","2"},
        {"3","3"},{"5","4"},
        {"6","5"},{"7","6"},
        {"9","7"},{"10","8"},
        {"11","9"},{"14","0"},
        {"13","Clear"},{"15","Enter"}
    };

    LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

    void setup()
    {
        lcd.begin (16,2);
        lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
        lcd.setBacklight(HIGH);
        lcd.home ();

        pinMode(SCL_PIN, OUTPUT);
        pinMode(SDO_PIN, INPUT);
    }
    void loop()
    {
        Key = Read_Keypad();
        if (Key != 0) {
            lcd.clear();
            lcd.setCursor (0,0);
            for (int x = 0; x < 12; x++) {
                if (Key == keyRemap[x][0].toInt()) {
                    lcd.print(keyRemap[x][1]);
                }
            }
            delay(160);
        }
    }
    byte Read_Keypad(void)
    {
        byte Count;
        byte Key_State = 0;

        for (Count = 1; Count <= 16; Count++)
        {
            digitalWrite(SCL_PIN, LOW);
            if (!digitalRead(SDO_PIN))
                Key_State = Count;
            digitalWrite(SCL_PIN, HIGH);
        }
        return Key_State;
    }

title: Better way to remap 16-Key Touch keypad

Answers: 1

body:
> Is there any way to optimize this code:

Absolutely, yes. Don't use `String` for this, you are seriously wasting memory. Instead you can use a `struct`:

    struct keymap {
     uint8_t code;
     const __FlashStringHelper *value;
    };

    const struct keymap keyRemap[] = {
     { 1, F("1") },
     { 2, F("2") },
     { 3, F("3") },
     { 5, F("4") },
     { 6, F("5") },
     { 7, F("6") },
     { 9, F("7") },
     { 10, F("8") },
     { 11, F("9") },
     { 14, F("0") },
     { 13, F("Clear") },
     { 15, F("Enter") },
     { 0, 0 }
    };

    void loop() {
     int Key = Read_Keypad();

     if (Key != 0) {
      lcd.clear();
      lcd.setCursor(0, 0);

      for (int x = 0; keyRemap[x].code != 0; x++) {
       if (Key == keyRemap[x].code) {
        lcd.print(keyRemap[x].value);
       }
      }

      delay(160);
     }
    }


body:
I just bought a SIM800 module for my Arduino project and I found that I supports Bluetooth too. I have already worked with HC-05 and my Android phone.

I tried to play with this module and able to connect it successfully with my Android mobile. I am able to make a call using it, accept a call, etc. But when I tried to send text data using it (in SPP mode), I ran into problem.

I have an app called Bluetooth Terminal in my mobile with which I use to communicate with my HC-05. But with SIM800, I can't connect.

I have read all the AT commands which are used to make a SPP connection. Here's a screenshot of the PuTTy terminal where I tried to make the connection:

[![Screenshot of PuTTy terminal][1]][1]

As you can see in the image, whenever I try to call
>AT+BTGETPROF=1

It never returns to me. I also tried the command with my Bluetooth visible in the mobile, but still no result.

Whenever I try to run the command or
>AT+BTCONNECT=1,4

My SIM800 goes into state 2 and I have to manually reset it.

Can someone please help me with this problem? I just want to use my SIM800 as a SPP client/server so that I can exchange text data with my Android APP.

Thanks in advance.

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

title: Using SIMCOM SIM800 as a Bluetooth SPP Client

Answers: 1

body:
By default i see that the Android handset i used did not have SPP profile enabled. You need to open a App which enables the SPP profile to be advertised. Then after that you can get that in AT+BTGETPROF list. I made a tutorial for this, Have a look here,

https://youtu.be/zdQb8r2xRK8

and

http://www.raviyp.com/embedded/215-sim800-series-bluetooth-at-commands


body:
I have read about every post about people having issues with their Arduinos on Macs. I have a 100% authentic Arduino UNO, that I cannot by any circumstance manage to connect to my late 2009 iMac with macOS Sierra 10.12.2.

I tried just about anything from disabling Apple FTDI drivers, installing FTDIUSBSerialDriver, D2XX drivers and even the CH34X drivers (for knockoffs). NOTHING works.

Not even setting boot arguments, not disabling default extensions/drivers, not removing extensions/drivers.

I am completely stuck, and no guide has ever worked. I've tried rebooting numerous times, but still no luck. The only port available in the Port menu is the Bluetooth Incoming port.

Does anyone have any tips or hints? I am on the verge of doing a complete reinstallation of my computer just to have all drivers back to default.

title: Yet another "Mac cannot find USB serial port" post

Answers: 0


body:
I have an interesting problem using the Mifare rc522 device similar to http://www.ebay.com/itm/201415107836

I have this device connected to an arduino uno and drawing power from the 5V supply.
It reads cards and tags well.
Provided the card waved by it has previously been waved by it as the first card after power up.

It will recognise ALL the cards and tags I have with no problems but ONLY if each card has been at some time the FIRST card since the device was powered up.  Reset button does not help.  Once each card or tag has been used as the first after power up it will work every time thereafter.

I am using a very simple sketch which simply reads the RFID via serial link and then displays the data on an LCD.

Can anyone help explain this odd behaviour.
Is it something to do with the tags perhaps?
http://www.ebay.com/itm/201611365871 (bought from same seller who is, BTW very quick and cheap to mail parts)

I have tried running off a 12v supply (to the duino) and USB with same effect.  I have added a capacitor (47uf) across the power to the RFID - same issue.

    /*
     Based on  LiquidCrystal Library - Hello World

     * LCD 4  RS pin to digital pin 12   Pin
     * LCD 6  Enable pin to digital pin 11
     * LCD 11 D4 pin to digital pin 5
     * LCD 12 D5 pin to digital pin 4
     * LCD 13 D6 pin to digital pin 3
     * LCD 14 D7 pin to digital pin 2
     * LCD  5 R/W pin to ground
     * LCD  1 VSS pin to ground
     * LCD  2 VCC pin to 5V

     */

    // include the library code:
    #include <LiquidCrystal.h>

    char incomingByte = 0;
    int cursorpos=0;

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    int detonate=10;
    int shownumber=0;
    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(24, 2);
      // Print a message to the LCD.
      lcd.print("Initialised");
      Serial.begin(115200);
    }

    void loop() {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):

      lcd.autoscroll();
       if (Serial.available() > 0) {
                    // read the incoming byte:
                    incomingByte = char(Serial.read());

                    // say what you got:

                    lcd.print (incomingByte, HEX);

            }

    }

further edit:

I have now been able to get the thing to communicate using software serial - it seems to work out the baud rate quite well so despite the datasheet you are not limited to 115200 baud.  Still the same problem though as far as I can see it will now work with any 3 cards - any new card bumps one off the list of acceptables.  AAAARRRGGGGHHH

As requested, code change below - I basically lifted this directly off the arduino forum with changes only to make it work with an uno using software serial.  It does work, after a fashion but still the same problem with recognising only a few of the cards I have.

    //emulate mega with software serial
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(2, 3);

    unsigned char command, devnull;
    unsigned int returnLength;

    void setup() {

    Serial.begin(9600);
    mySerial.listen();
      Serial.println("Waiting for Card\n");
    mySerial.begin(9600);

      mySerial.write(0x02); //Send the command to RFID, please refer to RFID manual

    }

    void loop() {
       if (mySerial.available())
        {
          Serial.print("\n\rCARD SERIAL: ");
          for (unsigned int i=0; i<4 ;i=i){
            //Serial.print("2");
            if (mySerial.available()) {
                //Serial.print("\n\ri is: ");Serial.print(i);Serial.print(" ");
                Serial.print(mySerial.read(),HEX); //Display the Serial Number in HEX
                i++;
              }
            }

           Serial.println("\n\rRead Card Make...");
           mySerial.write(0xAB);mySerial.write(0x02);mySerial.write(0x01);

           Get_Reply();

           mySerial.write(0x02); //Send the command to RFID, please refer to RFID manual
        }

    }void Get_Reply() {
           while (!mySerial.available());
           devnull = mySerial.read();
           while (!mySerial.available());
           returnLength = mySerial.read() - 1;

           for (unsigned int i=0;i< returnLength;i=i){
             //Serial.print("2");
             if (mySerial.available()) {
                //Serial.print("\n\ri is: ");Serial.print(i);Serial.print(" ");
                Serial.print(mySerial.read(),HEX); //Display the Serial Number in HEX
                i++;
              }
            }
    }

title: rc522 RFID reader will only accept first tag after power up

Answers: 0


body:
I have an IMU sensor (MPU 6050) connected with arduino UNO. Pin maps are as follows:

MPU6050 --> Arduino

Vcc --> Vcc

Gnd --> Gnd

SCL --> A5

SDA --> A4

(Not using any pull up resistors)

I am using jeff rowberg's MPU6050 library to get data from sensor. To test the sensor, I am using the raw value example sketch from the library. I am getting readings for both the accelerometer and the gyroscopes.

The problem is after some time the serial monitor just stops printing data. I have tried to figure it out but have not succeeded in solving the problem. It could be due to one of two reasons:

1. The MPU6050 stops giving sensor values
2. There is a problem with the serial monitor

As far as I have figured, the sensor is giving values because when I restart the serial monitor, the data starts to print again on the serial monitor and stops printing after same duration of time as it did before restarting the monitor.

I have tried the serial monitor of the arduino IDE and hyperterminal. In both cases the data stops printing after some time.

Any idea, what causes the serial monitor to stop printing data? Is it the sensor or the serial monitor?

Help would be greatly appreciated. Thanks in advance.

title: Serial Monitor stops printing data

Answers: 1

body:
I had exactly same situation.
I initially started to inspect on FIFO overflow of MPU6050, then experimented setting different clock speed for I2C communication, tried to tweak with pullup resistors as recommended.
Finally, here is the solution which worked for me. Basically, I just disconnected INT pin from MPU6050.

Now the schema is:
(MPU) -> (Arduino)

AD0 -> GND
SDA -> A4 (No pullup)
SCL -> A5 (No pullup)
GND -> GND
VCC -> 3.3V

I used this code as an example:
https://github.com/jarzebski/Arduino-MPU6050/blob/master/MPU6050_gyro_pitch_roll_yaw/MPU6050_gyro_pitch_roll_yaw.ino

from this library:
https://github.com/jarzebski/Arduino-MPU6050


body:
## Components
- [Breadboard Power Supply Module IM120525004][1]
- 1 kOhm resistor
- Green LED
- Arduino Nano
- [LiPo 7.4V battery][2]

## LED Lights Up Fine with USB power from the Arduino
[![powerful][3]][3]

## LED Does Not Light Up with power from the Supply Module
[![powerless][4]][4]
[![supply configuration][5]][5]

What am I doing wrong?

- The Lipo battery is brand new and is charged as the terminals showed about 7.6V on my multimeter. This is confirmed by the LED on the supply module itself lighting up fine.
- I think I can smell just a little bit of burn whenever the supply module is connected and there is power in the circuit.
- The positive jumper wire is connected to the 5V VCC pin on the Arduino, not the VIN pin on the Arduino, not that it matters, because if I remove the Arduino from the breadboard the LED still does not light up

  [1]: https://www.itead.cc/breadboard-power-supply-module.html
  [2]: http://www.ittgroup.ee/et/prototuupimine-ja-toide/604-lipo-aku-2200-mah-2s-40c.html
  [3]: https://i.stack.imgur.com/FQ9yS.jpg
  [4]: https://i.stack.imgur.com/w4ac7.jpg
  [5]: https://i.stack.imgur.com/m4NWH.jpg

title: No power from Breadboard Power Supply Module

Answers: 1

body:
I'm not surprised you can smell burning. You have the power supply connected backwards.

You see that little + and - symbol next to the ON/OFF jumper? That's the polarity of the two runs of pins. You have the + row connected to the - rail of your breadboard (blue) and the - row connected to the (red) positive rail.

Turn the power supply around 180° and connect it to the other end of the breadboard - the rails will be the other way around then.


body:
I am new to this serial communication between Arduino and Java NetBeans.
I am doing some small project and I need to get data from external EEPROM 24LC256 which is connected to Arduino UNO and pass it to the Java NetBeans platform not the Eclipse. So far I am using RXTX driver to communicate with Arduino in Java and easily get the data from serial monitor of Arduino IDE.

So can anyone help me, on how can I serially communicate with this external EEPROM using Java?

    import gnu.io.*;
    import java.util.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import gnu.io.CommPortIdentifier;
    import gnu.io.SerialPort;
    import gnu.io.SerialPortEvent;
    import gnu.io.SerialPortEventListener;
    import java.util.Enumeration;

    public class last extends javax.swing.JFrame implements SerialPortEventListener  {
     SerialPort serialPort;
     private static final String PORT_NAMES[] = {
      "COM3", // Windows
     };
     private BufferedReader input;
     private OutputStream output;   /** The output stream to the port */
     private static final int TIME_OUT = 2000; /** Milliseconds to block while waiting for port open */
     private static final int DATA_RATE = 9600;  /** Default bits per second for COM port. */
     public void initialize() {
      CommPortIdentifier portId = null;
      Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

      while (portEnum.hasMoreElements()) {   //First, Find an instance of serial port as set in PORT_NAMES.
       CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
       for (String portName : PORT_NAMES) {
        if (currPortId.getName().equals(portName)) {
         portId = currPortId;
         break;
        }
       }
      }
      if (portId == null) {
       System.out.println("Could not find COM port.");
       return;
      }
      try {          // open serial port, and use class name for the appName.
       serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
       serialPort.setSerialPortParams(DATA_RATE,  // set port parameters
         SerialPort.DATABITS_8,
         SerialPort.STOPBITS_1,
         SerialPort.PARITY_NONE);

       input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));   // open the streams
       output = serialPort.getOutputStream();
       serialPort.addEventListener(this);   // add event listeners
       serialPort.notifyOnDataAvailable(true);
      } catch (Exception e) {
       System.err.println(e.toString());
      }}

     /**
      * This should be called when you stop using the port.
      * This will prevent port locking on platforms like Linux.
      */
     public synchronized void close() {
      if (serialPort != null) {
       serialPort.removeEventListener();
       serialPort.close();
      }}

     /**
      * Handle an event on the serial port. Read the data and print it.
      */
     public synchronized void serialEvent(SerialPortEvent oEvent) {
      if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
       try {
        String inputLine=input.readLine();
        System.out.println("the state of the led is  "+inputLine);
       } catch (Exception e) {
        System.err.println(e.toString());
       }
      }
      // Ignore all the other eventTypes, but you should consider the other ones.
     }

     public static void main(String[] args) throws Exception {
      last main = new last();
      main.initialize();
      Thread t = new Thread() {
       public void run() { //the following line will keep this app alive for 1000 seconds,
        //waiting for events to occur and responding to them (printing incoming messages to console).
        try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
       }
      };
      t.start();
      System.out.println("Started");
     }
    }

This is the code in Java NetBeans.

title: Serial communication between Arduino and Java NetBeans

Answers: 1

body:
Your EEPROM has I2C interface, so first you shall program Arduino to access it: [An I2C EEPROM Class for Arduino][1]

Then implement some kind of communication protocol over serial, to send commands instructing Arduino to read/write from EEPROM. For example, with following commands:

 - for writing `write:<address>,<count>,<data_as_hex_string>`
 - for reading `read:<address>,<count>`
 - response for reading: `<address>,<count>,<data_as_hex_string>`

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


body:
I'm trying to set up a GPS tracking solution in a rural area. The catch is the GPS trackers need to be lower cost (power and cash), because there will be a good amount of them.

So I'm trying to find a solution where I can benefit from A-GPS using a beacon of some sort to handle any cpu/server calculations while receiving GPS noise from the tracking devices (I think that's the idea). I've read up a bit on Mobile Station Assisted (MSA) GPS, but I'm not entirely sure what solutions there are to handle this.

Any help or advice is appreciated.

Example:

Arduino GPS tracker x 200 ---[RF comms/GPS noise]--->  Beacon/Tower  ---[Internet]---> GPS Server

title: Arduino - Rural A-GPS Station

Answers: 1

body: I'm not sure I get what you want, but the A7 module of Ai-Thinker is a good GPRS module with GPS in it.


body:
I have written a code that remaps the 16-Key touch keypad. When 2 key is pressed, it writes weird characters in the serial monitor even on my 16x2 LCD

[![Weird Char][1]][1]

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

But the other keys work fine.
Here's the code:

    #define SCL_PIN 11
    #define SDO_PIN 12

    struct keymap {
        int     kCode;
        String  kValue;
      };

    keymap keys[] = {
      {1, "1"},
      {2, "2"},
      {3, "3"},
      {5, "4"},
      {6, "5"},
      {7, "6"},
      {9, "7"},
      {10,"8"},
      {11,"9"},
      {14,"0"},
      {13,"CLEAR"},
      {15,"ENTER"}
      };

    void setup()
    {
      Serial.begin(9600);
      pinMode(SCL_PIN, OUTPUT);
      pinMode(SDO_PIN, INPUT);
    }

    void loop() {
      int Key = Read_Keypad();

      if (Key != 0) {
        for (int x = 0; x < 16; x++) {
          if (Key == keys[x].kCode) {
            Serial.println(keys[x].kValue);
          }
        }

        delay(300);
      }
    }

    byte Read_Keypad(void)
    {
      byte Count;
      byte Key_State = 0;

      for (Count = 1; Count <= 16; Count++)
      {
        digitalWrite(SCL_PIN, LOW);
        if (!digitalRead(SDO_PIN))
          Key_State = Count;
        digitalWrite(SCL_PIN, HIGH);
      }
      return Key_State;
    }

title: Weird text when pressing a certain touch button

Answers: 1

body:
It seems by changing `16` to `12` on

    for (int x = 0; x < 12; x++) {
          if (Key == keys[x].kCode) {
            lcd.print(keys[x].kValue);
          }
    }
fixed it.


body: I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode. Hints are welcome, I really don't know where to start.

title: Measuring ADC sample rate - Arduino DUE

Answers: 1

body:
Measure how many times per second was main loop called:

    bool secondPassed()
    {
      static long lastTick = 0;
      long now = millis();

      if (now <= lastTick + 1000)
        return false;

      lastTick = now;
      return true;
    }

    int counter = 0;
    void loop()
    {
      analogRead(A0);
      counter++;
      if (secondPassed())
      {
        Serial.println(counter);
        counter = 0;
      }
    }


body:
I'm having issues with sampling audio with a microphone and NodeMCU v3. I realize this is the Arduino section so if NodeMCU running the Arduino IDE is not meant for this forum, let me know.

The problem: I am sampling audio for an sound reactive RGB LED strip with the NodeMCU v3. When I use USB power from my computer, everything works well. If I power the NodeMCU from a 7805 linear regulator (5v) to Vin, it works fine. "Silent" conditions hang around 0 volts and audio levels show up clearly. When I power the NodeMCU with a 3.3v switching regulator (with the microphone grounded on the NodeMCU and VCC coming from the 3v3 pin) this is where the problem starts. If I have the LED strip unconnected, it detects the sound find (although my "silent" conditions hover more around .1 volts but for my purposes that wouldn't be an issue).

The problem is powering the board and subsequent microphone from the switching regulator with the lights connected I get very erratic voltage readings that are all over the place. You might be asking why not just use the linear regulator then? Well, even at 12 volts the (12v-5v)*(a few hundred mA) is a decent amount of heat to dissipate but sure I could get a heat sink and control it, but the end goal for this project is to power my 10m strip, which is 24 volts, and the linear regulator would have to dissipate (24v-5v) * (a few hundred mA). I really do not think this is sustainable, which is why I got the switching regulator in the first place.

I was told that these switching regulators do not play nicely with microphones. Even with the LED strip unconnected it wasn't as consistent as USB or linear regulator power but it still worked perfectly fine.

Could anybody explain why this issue arises and hopefully a way to fix it? Are there tricks I can use to limit whatever interference is occurring? Should I give up on trying to make the switching regulator work? Would capacitors/resistors solve this?

I really would prefer to use the switching regulator for efficiency reasons. My second option wouldn't be the linear regulator, it would be powering the Node from a wall adapter and USB cable to be honest. This is getting quite frustrating. One problem's fix causes another, but I suppose that's how things go sometimes.

I am including a diagram of my setup. Please note the linear regulator should actually be a switching regulator and the board I am using is not the Huzzah, it's the NodeMCU v3.

Components:

- NodeMCU v3
- Adafruit Electret Mic (won't let me post more links... it's the adj. gain one)
- [Switching Regulator][3]
- N Type Mosfets
- RGB LED strip (currently a 5 meter 12 volt 5050 leds, future: 10 meter 24 volt)

If there is something that will solve my issue, I am not worried that it costs $5 versus the linear regulator being <$1. I am more worried about space, amount of cords, and relative efficiency.

I would really really appreciate any help in solving this issue, this is pretty much the last part of a pretty big and feature-rich controller.

Hopefully I have included as much information as is needed.

Thank you and feel free to ask any questions!

[![ Project Diagram ][1]][1]

  [1]: https://i.stack.imgur.com/4rPqD.jpg
  [3]: https://www.digikey.com/product-detail/en/recom-power/R-78E3.3-1.0/945-2409-5-ND/5327711

title: Issues with analog microphone readings

Answers: 1

body:
The problems mentioned probably result from electrical interference, and as such might be better addressed in  [Electronics Stackexchange](https://electronics.stackexchange.com/).  But here is a quick overview of how to ameliorate the problem: add shielding and filtering.

For shielding, add a housing or braided-wire cable sleeves.  To shield against electrical fields, the housing should be conductive and have no openings larger than the wavelength of the  electrical interference you wish to suppress.  To shield against magnetic fields, it should be made of a [ferromagnetic](https://en.wikipedia.org/wiki/Ferromagnetism) material.  You should have a housing around the switching supply, and can also add housings around any sensitive amplifier circuits.

For filtering, you can add an output filter with a few thousand microfarads of capacitance.  For better filtering, use several large capacitors, with a choke (inductor) to connect each capacitor to the next.  Add ferrite beads on each of the wires out of the power supply.  Besides the large capacitors, add a couple of small ones, eg 0.01 and 0.1 μF before the chain of large filter capacitors, ie, close to the output terminals of the switching supply.  Small capacitors generally have smaller self-inductance and can be more effective than large ones at suppressing high frequency hash.  The big capacitors effectively smooth out lower frequency ripple but if they have much self-inductance may fail to suppress high frequencies.


body:
I'm working on a project in which two Arduinos are to be used. Each Arduino is connected to an RFID reader. The first RFID reader should write an integer value to the tag detected, whereas the second RFID reader will read the value that was written by Arduino 1.

I'm facing a problem writing an integer value to the tag. I've found many libraries that include functions that write only strings or characters to the tag. But I need to write an integer. Can anyone help me solve this issue?

Following is code that I found and I tried to edit, so that the write and read functions accept (integer values) as the blockContent. However as expected it didn't work because those functions are defined to accept arrays.

```c
/******************************************
   PURPOSE:  Learn to use the MF522-AN RFID card reader
  Created by      Rudy Schlaf for www.makecourse.com
  DATE:   2/2014
*******************************************/

/*
  This sketch uses the MFRC522 Library to use ARDUINO RFID MODULE KIT   13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
  The library file MFRC522.h has a wealth of useful info. Please read it.
  The functions are documented in MFRC522.cpp.

  Based on code Dr.Leong   ( WWW.B2CQSHOP.COM )
  Created by Miguel Balboa (circuitito.com), Jan, 2012.
  Rewritten by Søren Thing Andersen (access.thing.dk), fall of 2013
  (Translation to English, refactored, comments, anti collision, cascade levels.)

           This library has been released into the public domain.
*/

#include <SPI.h>//include the SPI bus library
#include <MFRC522.h>//include the RFID reader library

#define SS_PIN 10  //slave select pin
#define RST_PIN 5  //reset pin

MFRC522 rfid(SS_PIN, RST_PIN);

MFRC522::MIFARE_Key key;
char order = 49;

void setup() {
  Serial.begin(9600);        // Initialize serial communications with   the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card (in case you wonder what PCD means: proximity coupling device)
  Serial.println("Scan a MIFARE Classic card");

  // Prepare the security key for the read and write functions - all six key bytes are set to 0xFF at chip delivery from the factory.
  // Since the cards in the kit are new and the keys were never defined, they are 0xFF
  // if we had a card that was programmed by someone else, we would need to know the key to be able to access it. This key would then need to be stored in 'key' instead.

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;//keyByte is defined in the "MIFARE_Key" 'struct' definition in the .h file of the library
  }

}

int block = 2; //this is the block number we will write into and then read. Do not write into 'sector trailer' block, since this can make the block unusable.

byte blockcontent[16] = {"SubScribe______"};//an array with 16 bytes to be written into one of the 64 card blocks is defined!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//byte blockcontent[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};//all zeros. This can be used to delete a block.
byte readbackblock[18];//This array is used for reading out a block. The MIFARE_Read method requires a buffer that is at least 18 bytes to hold the 16 bytes of a block.

void loop() {
  /*****************************************establishing contact with a tag/card**********************************************************************/
  // Look for new cards (in case you wonder what PICC means: proximity integrated circuit card)
  if ( ! mfrc522.PICC_IsNewCardPresent()) {//if PICC_IsNewCardPresent returns 1, a new card has been found and we continue
    return;//if it did not find a new card is returns a '0' and we return to the start of the loop
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {//if PICC_ReadCardSerial returns 1, the "uid" struct (see MFRC522.h lines 238-45)) contains the ID of the read card.
    return;//if it returns a '0' something went wrong and we return to the start of the loop
  }

  // Among other things, the PICC_ReadCardSerial() method reads the UID and the SAK (Select acknowledge) into the mfrc522.uid struct, which is also instantiated
  // during this process.
  // The UID is needed during the authentication process
  //The Uid struct:
  //typedef struct {
  //byte    size;     // Number of bytes in the UID. 4, 7 or 10.
  //byte    uidByte[10];            //the user ID in 10 bytes.
  //byte    sak;      // The SAK (Select acknowledge) byte returned from the PICC after successful selection.
  //} Uid;

  Serial.println("card selected");

  /*****************************************writing and reading a block on the card**********************************************************************/
  writeBlock(block, blockcontent);//the blockcontent array is written into the card block
  //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

  //The 'PICC_DumpToSerial' method 'dumps' the entire MIFARE data block into the serial monitor. Very useful while programming a sketch with the RFID reader...
  //Notes:
  //(1) MIFARE cards conceal key A in all trailer blocks, and shows 0x00 instead of 0xFF. This is a secutiry feature. Key B appears to be public by default.
  //(2) The card needs to be on the reader for the entire duration of the dump. If it is removed prematurely, the dump interrupts and an error message will appear.
  //(3) The dump takes longer than the time alloted for interaction per pairing between reader and card, i.e. the readBlock function below will produce a timeout if
  //    the dump is used.

  //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));//uncomment this if you want to see the entire 1k memory with the block written into it.

  readBlock(block, readbackblock);//read the block back
  Serial.print("read block: ");
  for (int j = 0 ; j < 16 ; j++) {
    //print the block contents
    Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
  }
  Serial.println("");
}

int writeBlock(int blockNumber, byte arrayAddress[]) {
  //this makes sure that we only write into data blocks. Every 4th block is a trailer block for the access/security info.
  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3; //determine trailer block for the sector
  if (blockNumber > 2 && (blockNumber + 1) % 4 == 0) {
    Serial.print(blockNumber);  //block number is a trailer block (modulo 4); quit and send error code 2
    Serial.println(" is a trailer block:");
    return 2;
  }
  Serial.print(blockNumber);
  Serial.println(" is a data block:");

  /*****************************************authentication of the desired block for access***********************************************************/
  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
  //this method is used to authenticate a certain block for writing or reading
  //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A = 0x60 (=1100000),    // this command performs authentication with Key A
  //blockAddr is the number of the block from 0 to 15.
  //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
  //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
  if (status != MFRC522::STATUS_OK) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 3;//return "3" as error message
  }
  //it appears the authentication needs to be made before every block read/write within a specific sector.
  //If a different sector is being authenticated access to the previous one is lost.

  /*****************************************writing the block***********************************************************/

  status = mfrc522.MIFARE_Write(blockNumber, arrayAddress, 16);//valueBlockA is the block number, MIFARE_Write(block number (0-15), byte array containing 16 values, number of bytes in block (=16))
  //status = mfrc522.MIFARE_Write(9, value1Block, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print("MIFARE_Write() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 4;//return "4" as error message
  }
  Serial.println("block was written");
}

int readBlock(int blockNumber, byte arrayAddress[]) {
  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3; //determine trailer block for the sector

  /*****************************************authentication of the desired block for access***********************************************************/
  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
  //this method is used to authenticate a certain block for writing or reading
  //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A = 0x60 (=1100000),
  // this command performs authentication with Key A
  //blockAddr is the number of the block from 0 to 15.
  //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
  //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
  if (status != MFRC522::STATUS_OK) {
    Serial.print("PCD_Authenticate() failed (read): ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 3;//return "3" as error message
  }
  //it appears the authentication needs to be made before every block read/write within a specific sector.
  //If a different sector is being authenticated access to the previous one is lost.

  /*****************************************reading a block***********************************************************/

  byte buffersize = 18;//we need to define a variable with the read    buffer size, since the MIFARE_Read method below needs a pointer to the variable that contains the size...
  status = mfrc522.MIFARE_Read(blockNumber, arrayAddress, &buffersize);//&buffersize is a pointer to the buffersize variable;     MIFARE_Read requires a pointer instead of just a number
  if (status != MFRC522::STATUS_OK) {
    Serial.print("MIFARE_read() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 4;//return "4" as error message
  }
  Serial.println("block was read");
}
```

title: How to write an integer value to an RFID tag?

Answers: 1

body:
Let's say you have an array and an int.

```c
unsigned char blockcontent[16];
int number = 15;
```

To save the int at position 0 of `blockcontent`, you do this:

```c
memcpy(blockcontent, &number, sizeof(int));
```

If you want it at another position, do `blockcontent+offset`.

If you want to read the int from `blockcontent`, do the reverse:

```c
memcpy(&number, blockcontent, sizeof(int));
```

That's all there is to it.


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

I am trying to send some integers to an LCD. But it is not working. I have tried in Proteus. Please help. I have uploaded MATLAB and Arduino code below.

MATLAB code:

    clear all
    clc

     answer=1; % this is where we'll store the user's answer
     arduino=serial('COM1','BaudRate',9600); % create serial communication object on port COM4

    fopen(arduino); % initiate arduino communication

    while answer
    fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
    answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): '); % ask user to enter value for variable answer
    end

    fclose(arduino); % end communication with arduino

Arduino code:

    #include <LiquidCrystal.h>
    int matlabData;
    LiquidCrystal lcd(12,11,5,4,3,2);

    void setup() {
      lcd.begin(16,2);
      Serial.begin(9600);
    }

    void loop() {
      if(Serial.available()>0) {
        matlabData=Serial.read();
        lcd.print(matlabData);
      }
    }

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

title: MATLAB+Arduino+LCD

Answers: 2

body:
You can use Matlab's Arduino support package, it allows you to control the Arduino directly without having to write code in the Arduino IDE. I never used it with an LCD though. Here is [a link][1] that might help.

  [1]: https://www.mathworks.com/hardware-support/arduino-matlab.html

body:
    while answer
      fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
      answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): ');
      % ask user to enter value for variable answer
    end

Is it just me or should asking the user to input something be ***before*** printing it?

Also, more importantly, isn't `fprintf(arduino, '%s', char(answer));` printing raw bytes? In which case, you would be sending 0x01/0x02. Not a great idea... In your Arduino code, print out on Serial what you are receiving, in [hexa]decimal, not as `char`.

        matlabData=Serial.read();
        Serial.print("Received: [0x");
        if(matlabData<16)Serial.write('0');
        Serial.print(matlabData, HEX);
        Serial.println("]");

This should give you a better idea whether you received anything, and if so, what.


body:
I have this statement in my Arduino code :

     byte blockcontent [16] = itoa(order);
and it gives me an error saying:
"Too few arguments to function 'char*itoa(int,char*,int)'. Even though I've looked for the documentation of itoa function and I found that it accepts one input argument.
Can anyone help me fix this error?

title: error: too few arguments to function 'char* itoa(int, char*, int)' byte blockcontent= itoa(order); ^ In file include

Answers: 1

body:
itoa requires a minimum of 2 arguments.

Reference: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaa571de9e773dde59b0550a5ca4bd2f00


body:
I have a program i am working on where a relay is turned on -> waits a delay -> then turns off after either one of two things happen: 1) A set timer is reached OR 2) someone pushes a push button to trigger it.

Right now 90% of my code is working and i am stuck on how i go about "locking out" the push button from triggering the relay, for a select-able amount of delay time.

The timer portion of the code, with select-able times, is working. Depending on what analog 1 see's, it will trigger the relay appropriately after the selected time.

I tried to implement this same approach for the lock out timer, using analog 2 , to determine how long of a delay. I used a variable i called LOK to either read the button if it is unlocked (LOK = 0) or if it is locked (LOK =1) to wait the allotted delay time before unlocking and allowing the button to be read again.

I've tried all sorta of things and it still isn't functioning right. Maybe there is a better or simpler way to do this but I've racked my brain, and key word searching isn't helping.

Code below - please forgive random comments. I've been chopping up and moving things around i haven't edited any comments , so some may be from other snippets of codes from other projects.

    int DUMP = 2; // Pin connected to big dump relay
    int BUTTON = 3; // Pin connected to manual dump push button.
    int BUTTONlight = 4; // Pin connected to push button light.

    int BUTstate; // Current reading from BUTTON pin
    int lastBUTstate = LOW; // Previous reading from BUTTON pin

    long lastDebounce = 0; // Last time output was changed
    long Delay = 50; // Debounce Time

    unsigned long DUMPTIME;
    unsigned long LOT;

    unsigned long prevTIME;

    int a=0;
    int d=0;

    int LOK = 0;

    void setup()
    {
      pinMode(A1, INPUT);
      pinMode(A2, INPUT);

      pinMode (BUTTON, INPUT);
      pinMode (BUTTONlight, OUTPUT);
      pinMode (DUMP, OUTPUT);

      digitalWrite(DUMP, HIGH);
      delay(10000);
      digitalWrite(DUMP, LOW);
      digitalWrite(BUTTONlight, HIGH);
    }

    int readTselector(int pin)
    // returns the button number pressed, or zero for none pressed
    // int pin is the analog pin number to read
    {
      int b,c = 1;
      c=analogRead(pin); // get the analog value
      if (c>1000)
      {
        b=0; // buttons have not been pressed
      }
      else
        if (c<1000 && c>600)
        {
          b=1; // button 1 pressed
        }
        else
          if (c<520 && c>400)
          {
            b=2; // button 2 pressed
          }
          else
            if (c>100 && c<400)
            {
              b=3; // button 3 pressed
            }
            else
              if (c<100)
              {
                b=4; // button 4 pressed
              }
      return b;
      }

    void loop()
    {
      int DUMPTIME = DTselect();
      int LOT = LOselect();

      int reading = digitalRead(BUTTON);

      unsigned long currTIME = millis();

      if ((currTIME - prevTIME) >= DUMPTIME) // Count to 2 minutes
       {
         LOK = 1;
         digitalWrite(BUTTONlight, LOW);
         digitalWrite(DUMP, HIGH);
         delay(10000);
         digitalWrite(DUMP, LOW);
         prevTIME = currTIME;
       }

      if (reading != lastBUTstate)
      {
        lastDebounce = millis();
      }

      if (LOK == 1)
      {
        delay(LOT);
        digitalWrite(BUTTONlight, HIGH);
        LOK = 0;

      }
      if ((millis() - lastDebounce) > Delay && LOK == 0)
      {
        BUTstate = reading;
      }

      if (BUTstate == HIGH)
      {
        digitalWrite(BUTTONlight, LOW);
        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        prevTIME = currTIME;
      }
      lastBUTstate = reading;
    }

    int DTselect()
    {
      a=readTselector(1);
      if (a==0) // no buttons pressed
      {
        DUMPTIME = 210000;
      }
      else
        if (a==1) // someone pressed a button!
        {
          DUMPTIME = 180000;
        }
        else
         if (a==2) // someone pressed a button!
         {
           DUMPTIME = 150000;
         }
         else
          if (a==3) // someone pressed a button!
          {
            DUMPTIME = 120000;
          }
         else
           if (a==4) // someone pressed a button!
           {
             DUMPTIME = 90000;
           }
      return DUMPTIME;
     }

    int LOselect()
    {
      d=readTselector(2);
      if (d==0) // no buttons pressed
      {
        delay(20000);
      }
      else
        if (d==1) // someone pressed a button!
        {
          delay(15000);
        }
        else
         if (d==2) // someone pressed a button!
         {
           delay(10000);
         }
         else
          if (d==3) // someone pressed a button!
          {
            delay(5000);
          }
          else
           if (d==4) // someone pressed a button!
           {
             delay(0);
           }
     }

title: How do I lock out a push button input with a selectable delay?

Answers: 1

body:
I took your code and did a bit of an edit. You had some useless variables and you where redefining DUMPTIME and LOT in a wierd way. I also define some of your constants as #define's because thats the way you should always do it.

    #define DUMP 2          // Pin connected to big dump relay
    #define BUTTON 3        // Pin connected to manual dump push button.
    #define BUTTONlight 4   // Pin connected to push button light.
    #define DELAY 50        // Debounce Time

    int BUTstate;           // Current reading from BUTTON pin
    int lastBUTstate = LOW; // Previous reading from BUTTON pin

    long lastDebounce = 0;  // Last time output was changed

    unsigned long DUMPTIME;
    unsigned long LOT;
    unsigned long prevTIME;

    int LOK = 0;

    int readTselector(int pin)
    // returns the button number pressed, or zero for none pressed
    // int pin is the analog pin number to read
    {
        int c = analogRead(pin); // get the analog value
        if (c > 1000){
            return 0; // buttons have not been pressed
        }
        else if (c<1000 && c>600){
            return 1; // button 1 pressed
        }
        else if (c<520 && c>400){
            return 2; // button 2 pressed
        }
        else if (c>100 && c<400){
            return 3; // button 3 pressed
        }
        else if (c<100){
            return 4; // button 4 pressed
        }
        else return 0; // just in case
        }

    long DTselect()
    {
        switch(readTselector(1)){
            case 0: return 210000; // no buttons pressed
                break;
            case 1: return 180000; // someone pressed a button!
                break;
            case 2: return 150000;
                break;
            case 3: return 120000;
                break;
            case 4: return 90000;
                break;
            default: return 210000; // default
                break;
        }
     }

    int LOselect()
    {
      switch( readTselector(2) ){
            case 0:  return 20000; // no buttons pressed
                break;
            case 1:  return 15000; // someone pressed a button!
                break;
            case 2:  return 10000;
                break;
            case 3:  return 5000;
                break;
            case 4:  return 0;
                break;
            default: return 20000; // default
                break;
        }
     }

    void setup()
    {
        pinMode(A1, INPUT);
        pinMode(A2, INPUT);

        pinMode (BUTTON, INPUT);
        pinMode (BUTTONlight, OUTPUT);
        pinMode (DUMP, OUTPUT);

        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        digitalWrite(BUTTONlight, HIGH);
    }

    void loop()
    {
        DUMPTIME = DTselect();
        LOT = LOselect();

        int reading = digitalRead(BUTTON);

        unsigned long currTIME = millis();

        if ((currTIME - prevTIME) >= DUMPTIME){// Count to 2 minutes
            LOK = 1;
            digitalWrite(BUTTONlight, LOW);
            digitalWrite(DUMP, HIGH);
            delay(10000);
            digitalWrite(DUMP, LOW);
            prevTIME = currTIME;
        }

        if (reading != lastBUTstate){
            lastDebounce = millis();
        }

        if (LOK){
            delay(LOT);
            digitalWrite(BUTTONlight, HIGH);
            LOK = 0;
        }

        if ((millis() - lastDebounce) > DELAY && !LOK){
            BUTstate = reading;
        }

        if (BUTstate == HIGH){
            digitalWrite(BUTTONlight, LOW);
            digitalWrite(DUMP, HIGH);
            delay(10000);
            digitalWrite(DUMP, LOW);
            prevTIME = currTIME;
        }
        lastBUTstate = reading;
    }

A different version with a BUTflag variable to keep track of the button press and release. I have not dealt with the DUMPTIME variable but hopefully this will give you an idea of how to use flags so the logic doesn't fail.

    #define DUMP 2          // Pin connected to big dump relay
    #define BUTTON 3        // Pin connected to manual dump push button.
    #define BUTTONlight 4   // Pin connected to push button light.
    #define DELAY 50        // Debounce Time

    int BUTstate;           // Current reading from BUTTON pin
    int BUTflag = 0;
    int go = 0;
    long lastDebounce = 0;  // Last time output was changed

    unsigned long DUMPTIME;
    unsigned long LOT;
    unsigned long prevTIME;

    int LOK = 0;

    int readTselector(int pin)
    // returns the button number pressed, or zero for none pressed
    // int pin is the analog pin number to read
    {
        int c = analogRead(pin); // get the analog value
        if (c > 1000){
            return 0; // buttons have not been pressed
        }
        else if (c<1000 && c>600){
            return 1; // button 1 pressed
        }
        else if (c<520 && c>400){
            return 2; // button 2 pressed
        }
        else if (c>100 && c<400){
            return 3; // button 3 pressed
        }
        else if (c<100){
            return 4; // button 4 pressed
        }
        else return 0; // just in case
        }

    long DTselect()
    {
        switch(readTselector(1)){
            case 0: return 210000; // no buttons pressed
                break;
            case 1: return 180000; // someone pressed a button!
                break;
            case 2: return 150000;
                break;
            case 3: return 120000;
                break;
            case 4: return 90000;
                break;
            default: return 210000; // default
                break;
        }
     }

    int LOselect()
    {
      switch( readTselector(2) ){
            case 0:  return 20000; // no buttons pressed
                break;
            case 1:  return 15000; // someone pressed a button!
                break;
            case 2:  return 10000;
                break;
            case 3:  return 5000;
                break;
            case 4:  return 0;
                break;
            default: return 20000; // default
                break;
        }
     }

    void setup()
    {
        pinMode(A1, INPUT);
        pinMode(A2, INPUT);

        pinMode (BUTTON, INPUT);
        pinMode (BUTTONlight, OUTPUT);
        pinMode (DUMP, OUTPUT);

        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        digitalWrite(BUTTONlight, HIGH);
    }

    void loop()
    {
        DUMPTIME = DTselect();
        LOT = LOselect();

        BUTstate = digitalRead(BUTTON);

        unsigned long currTIME = millis();
    /*
        if ((currTIME - prevTIME) >= DUMPTIME && !LOK){
            LOK = 1;
            digitalWrite(BUTTONlight, LOW);
            digitalWrite(DUMP, HIGH);
            delay(10000);
            digitalWrite(DUMP, LOW);
            prevTIME = currTIME;
        }
        else */
        if (LOK){
            delay(LOT);
            digitalWrite(BUTTONlight, HIGH);
            LOK = 0;
        }
        else if(!LOK){
            if(!go && BUTstate && !BUTflag){
                lastDebounce = millis();
                BUTflag = 1;
            }
            else if (!go && BUTstate && BUTflag==1 && (millis() - lastDebounce) > DELAY){
                BUTflag = 2;
            }
            else if (!go && !BUTstate && BUTflag==2){
                BUTflag = 0;
                go = 1;
            }
            else if (go){
                digitalWrite(BUTTONlight, LOW);
                digitalWrite(DUMP, HIGH);
                delay(10000);
                digitalWrite(DUMP, LOW);
                prevTIME = currTIME;
                go = 0;
                LOK = 1;
            }
        }
    }