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

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.");
        }
      }
    }

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.


sender: user

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

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

sender: assistant

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


message:
Arduino connection websocket always fails

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

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.


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

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

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.


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

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;
      }
    }

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;
      }
    }


message:
Better way to remap 16-Key Touch keypad

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;
    }

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);
     }
    }


message:
Using SIMCOM SIM800 as a Bluetooth SPP Client

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

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


message:
Serial Monitor stops printing data

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.

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


message:
No power from Breadboard Power Supply Module

## 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

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.


message:
Serial communication between Arduino and Java NetBeans

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.

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


message:
Arduino - Rural A-GPS Station

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

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.


message:
Weird text when pressing a certain touch button

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;
    }

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.


message:
Measuring ADC sample rate - Arduino DUE

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.

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;
      }
    }


message:
Issues with analog microphone readings

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

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.


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

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");
}
```

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.


message:
MATLAB+Arduino+LCD

[![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

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.


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

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?

body:
itoa requires a minimum of 2 arguments.

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


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

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);
           }
     }

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;
            }
        }
    }


message:
How do I squeeze code to fit onto an ATTiny

I am using an ATTiny85 for the first time and at compile I receive the following errors

    Arduino: 1.6.11 (Windows 10), Board: "Digispark (Default - 16.5mhz)"

    C:\Users\Steve\AppData\Local\Temp\build129e80c0e73568918bca55047472d138.tmp/Smoke_Auto-ATtiny.ino.ino.elf section `.text' will not fit in region `text'

    c:/program files (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: region `text' overflowed by 562 bytes

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling for board Digispark (Default - 16.5mhz).

The chip is

    Atmel 1344
    Tiny85
    20SF

I think what is happening is that my code is too big for the board.  Am I right?

Assuming so, ignoring any obvious programming errors (I can't debug for this board until I can upload :P ) how can I squeeze code like this onto an ATTiny?  I am not looking for someone to rewrite it for me, I am more interested in learning where there is any obvious bloat - I suspect the IR library (IRremote Version 2.0.1 June, 2015 by Ken Shirriff : 11Kb)

FWIW this is a project to convert a manually operated smoke machine into an automatic one and be able to manipulate the smoke time and delay via a remote. It works on a Mega, proof of concept complete, I want to shrink the board to fit into the mouse-sized controller if that is possible.

    #include <IRremote.h>

    long smokeTimeInit = 5000;  // initial smoke time
    long smokeWaitInit = 60000;  // initial interval between smoke

    long smokeIncrement = 1000; // timer increment value
    long delayIncrement = 5000; // timer increment value

    unsigned long previousMillis = 0; // this is our stored time
    unsigned long currentMillis;  //where we keep count of time

    const int smokeOnPin = 2;  // output to relay
    int smokeStopped = false; // flag to stop smoke
    const int LED = 0;
    const long RECV_PIN = 1;  // input from IR receiver

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    long  smokeTime = smokeTimeInit;
    long  smokeWait = smokeWaitInit;

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

      irrecv.enableIRIn(); // Start the receiver

      digitalWrite(smokeOnPin, LOW);  // start with the smoke on
      digitalWrite(LED, HIGH);

    }

    void loop() {
      if (irrecv.decode(&results)) {

        switch(results.value){
          case 284157975 :
          //more smoke time
            smokeTime = smokeTime + smokeIncrement;
            smokeStopped = false; // smoke on

          break;
          case 284104935 :
          //less smoke time
            if(smokeTime > smokeIncrement){ // don't let the smoke time become less than the increment value i.e. negative
              smokeTime = smokeTime - smokeIncrement;
            }
            else{
              smokeTime = 1000;
            }
            smokeStopped = false;

          break;
          case 284125335 :
          //reduce interval
            if(smokeWait > delayIncrement){
              smokeWait = smokeWait - delayIncrement;
            }
            else{
              smokeWait = 1000;
            }
            smokeStopped = false;  // smoke on

          break;
          case 284141655 :
          // increase interval
            smokeWait = smokeWait + delayIncrement;
            smokeStopped = false;  // smoke on

          break;
          case 284140125 :
          // reset to initial time values
            smokeTime = smokeTimeInit;
            smokeWait = smokeWaitInit;
            smokeStopped = false;  // smoke on

          break;
          case 284148285 :
          // reset but with shorter smoke time
            smokeTime = 1000;
            smokeWait = 60000;
            smokeStopped = false;  // smoke on

          break;
          case 284123805 :
          // reset with short smoke and shorter interval
            smokeTime = 2000;
            smokeWait = 30000;
            smokeStopped = false;  // smoke on

          break;
          case 284131965 :
          // stop
            smokeStopped = true;
          break;

        }

        irrecv.resume();
      }
    currentMillis = millis();

    if(smokeStopped){  // don't even do this if smoke stopped
        if (currentMillis - previousMillis >= smokeTime && digitalRead(smokeOnPin)==0) {
          digitalWrite(smokeOnPin, HIGH); // turn the smoke on
          digitalWrite(LED, LOW);
          previousMillis = currentMillis;
        }
        else if (currentMillis - previousMillis >= smokeWait && digitalRead(smokeOnPin)==1 ) {
          digitalWrite(smokeOnPin, LOW); // turn the smoke off
          digitalWrite(LED, HIGH);
          previousMillis = currentMillis;
        }
    }

    }

body:
Yes, the message “... Smoke_Auto-ATtiny.ino.ino.elf section `.text' will not fit in region `text'” suggests the code is too big to fit in the 8K available on the ATtiny85.

[In a .elf file, the TEXT section contains executable code.]

In IRremote.h from  Ken Shirriff et al, some comments at line 28 say to disable protocols you don't need:

    // Supported IR protocols
    // Each protocol you include costs memory and, during decode, costs time
    // Disable (set to 0) all the protocols you do not need/want!

By default, about 13 protocols are enabled and three disabled.  If you only use one or two kinds of remotes, you can  disable a bunch of the protocols.

Here are a couple of minor things for reducing memory, etc.:

• Instead of switching on  `results.value`, a `long`, you could compute an `unsigned int` equal to `results.value-284100000`, since all of your case values start with 2841 and the largest is 284157975.

• Instead of having `smokeStopped = false; // smoke on` seven times within various cases, and `smokeStopped = true;` in one of them, set `smokeStopped` to `false` before the switch, and drop the seven settings-to-false from within the switch.

• Some of your time-related variables would be better as `unsigned long` instead of just `long` variables.

Generally, your code looks clean enough except for those items.  Also, the IRremote code doesn't look bloated; but its tables can take a lot of memory.

*Edit 1–*
Addressing crowie's comment about using `#define` instead of `const int`, one *can* use `#define`'s, but in general the modern thought is that `const int` is preferable for type safety.  Typically there is no difference in generated code – aside from type checking, the compiler treats a `const int` the same way as a `#define`, ie does not allocate memory for it if it isn't used, or if the value is small, may use a load-immediate instead of fetching a value from memory.

My own preference is to use `enum { ... }` to declare integer constants.  For example, instead of

    const int smokeOnPin = 2;  // output to relay
    const long RECV_PIN = 1;  // input from IR receiver

I'd write

    enum { smokeOnPin=2, IRinPin=1 }; // Pin# for smoke on and IR input


body:
The `avr-nm` tool is great for figuring out what is using up all your memory.

You need to get to a command-line in the temporary directory where your program is compiled. You can find this directory by looking at the scrolling bottom window when you compile your program.

You run the tool like this...

```
C:\Users\passp\AppData\Local\Temp\arduino_build_965235>"C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-nm" -S --size-sort blink.ino.elf
```

...where in my case...

`C:\Users\passp\AppData\Local\Temp\arduino_build_965235` is  the temporary directory that the Arduino was using

`C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\` and the directory where the Arduino toolchain was installed

`blink.ino.elf` is the output generated from compiling my `blink.ino` sketch.

The `-S` parameter tells the tool to output the sizes of the symbols listed. By looking at these sizes, we can figure out what is using up all the memory and where to focus our reduction efforts.

The `--size-sort` shorts the symbols in size order so we can easily see which are the biggest.

The output of the tool on my program looks like...

```
0080010b 00000001 b click
0080008e 00000001 B datLen
00800088 00000001 b IRcount.1978
00800089 00000001 B msgNum
00800086 00000001 b prevVals.1995
0080008f 00000001 B progDir
00800087 00000001 b sendState.1979
00800109 00000001 b state
0080010a 00000001 b sync
00800092 00000001 B wake
00800066 00000002 D buttonCB
00800068 00000002 D clickCB
0080010c 00000002 B comBuf
00800115 00000002 B datBuf
0000006a 00000002 T emptyCB
00800075 00000002 D holdoff
0080008c 00000002 B ledMode
00800062 00000002 D longButtonCB
0080006f 00000002 d longPressTime
00800090 00000002 b longPressTimer
00000068 00000002 T loop
0080006a 00000002 D mode
00000d00 00000002 T setPort
00800064 00000002 D timerCB
0080008a 00000002 B timerCBcount
00800060 00000002 D timerCBtime
0080007d 00000003 D black
0080007a 00000003 D dark
0080006c 00000003 D outColor
00800077 00000003 D wakeColor
00000da6 00000004 T __mulsidi3
00800093 00000004 b powerDownTimer
00800131 00000004 B prevTimer
00800097 00000004 B sleepTimer
0080009b 00000004 b startTime
00800071 00000004 D timeout
00800105 00000004 b timer
00000a7a 00000006 T disAD
00800080 00000006 b pulseCount.1996
0080009f 00000006 b timeBuf
0080010e 00000007 B blinking
00800117 00000007 B pulsing
00000a80 00000008 T enAD
000000d4 0000000c T setColorRGB
00000a88 0000000e T initTimer
0000005a 0000000e T setup
00000044 00000010 T __do_clear_bss
0080011e 00000013 B fading
0000002e 00000016 T __do_copy_data
00000d66 00000018 T __udivmodqi4
00000a5c 0000001e T initIO
00000ce0 00000020 t sendByte
00000d44 00000022 T __mulhi3
00000822 00000022 T __vector_3
0000006c 00000022 T getTimer
00000d7e 00000028 T __udivmodhi4
00000e18 00000036 T __epilogue_restores__
00000daa 00000036 T __umulsidi3
00000de0 00000038 T __prologue_saves__
000003e8 00000038 T updateLed
0000027c 0000003a T blink
00000d02 00000042 T sendColor
0000008e 00000046 T tileSetup
00000e4e 0000005c T __muldi3
008000a5 00000060 b times
0000035e 0000008a T pulsingUpdate
000002b6 000000a8 T blinkUpdate
00000a96 000000d4 T hsv2rgb
00000b6a 00000176 T main
000000e0 0000019c T fadeUpdate
00000844 00000218 T __vector_2
00000420 00000402 T __vector_9
```
The second column is the amount of space used by the symbol.

So just looking at the bottom of our list, we can see that much of the space is being used by the functions `main`, `fadeUpdate`, `__vector_2` , and `__vector_9`.

`main` and `fadeUpdate` are obvious, but the `__vector_x` functions are actualy interrupt service routines. The actual mapping of numbers to interrupt sources can be different for different chips, so probably the easiest way to figure out what a given vector is would be to comment out the ISR in your code and then do the above process and see which vector evaporates in size.

You will have to look at each function carefully and individually to see how to possible reduce its size, but at least with this procedure  you know where too look!


message:
Storing latitude and longitude floats as chars with specified precision

I am receiving lat and long data from a GPS and want to store these numbers in the middle of a sequence of chars.

E.g. lat = -23.123456

long = 135.123456

I am after something like "Your coordinates are -23.123456,135.123456" as an array of chars.

I have tried:

    float latitude = -23.123456;
    float longitude = 135.123456;

    String one = "Your coordinates are ";
    String two = ","
    String message = one + latitude + two + longitude;

    // Convert String to char array
    int str_len = message.length() + 1;
    char textmessage[str_len];
    message.toCharArray(textmessage,str_len);

    Serial.println(textmessage);

but the result is: Your coordinates are -023.12,0135.12

How can I correct this?

Thanks in advance!

body:
When formatting serial output is a concern, it's worthwhile to download and use the `Streaming.h` [contributed library](https://www.arduino.cc/en/Reference/Libraries) that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size.  If you don't have `Streaming.h` installed, you can get [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/).

At present, `Streaming.h` doesn't support `setw()` and `setfill()`, which in ordinary C++ set a field width and a fill character.

However, it does support  four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and `endl`.

Thus, to print  “Your coordinates are -23.123456, 135.123456” one would write:

    Serial << "Your coordinates are " << _FLOAT(latitude,6) << ", " << _FLOAT(longitude,6) << endl;

Note that unlike the `String` class, use of `Streaming.h` does not entail any dynamic memory management – everything it does happens at compile time – and it does not increase code size – it translates stream-style operations into ordinary `.print()` and `.println()` calls.  It should result in somewhat smaller, faster, and more-robust code, by avoidance of `String`.  Use of dynamic memory on small-memory embedded systems can be problematic, and this avoids those problems.

---

*Edit 1a:* As Chris Stratton points out, Arduino floats don't support 9-digit precision.  I think Arduino floating-point arithmetic is intended to comply with [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point), which sets out standards to be used on modern computers that support floating-point arithmetic.

In the [binary32 format](https://en.wikipedia.org/wiki/Single-precision_floating-point_format#IEEE_754_single-precision_binary_floating-point_format:_binary32) used to implement IEEE 754 single-precision binary floating-point, significand precision is 24 bits.  That equates to about 7.22 decimal digits (ie, 24*log₁₀(2)), so for simple calculations, 7-digit accuracy is realistic, more than that is not.

---

*[Part of] Edit 1b:*  In the larger scheme of things perhaps there's no need to create and save a formatted string like that.  It is not useful for computing – the float values are better for that.  It is not needed for communication – another streaming write can be done.

---

*Edit 2 [replaces most of 1b]:* Streaming.h  doesn't build any strings, but just delivers the text of its `<<`-arguments character-by-character to a stream.  However, a [PString class at arduiniana](http://arduiniana.org/libraries/pstring/) can build strings from stream inputs, as in the following example code.

    #include <Streaming.h>
    #include <PString.h>

    char buffer[28];
    PString pstr(buffer, sizeof(buffer));

    void setup() {
      Serial.begin(115200);
      pstr.begin();  // Empty the buffer
    }

    void loop() {
      int first=50, second=100;
      pstr.begin();  // Empty the buffer
      pstr << 'X' << first << 'Y' << second << 'T';
      pstr += " hihi ";
      pstr << millis() << endl;
      Serial << pstr;
      delay(1000);
    }

Here's what some of its output to Serial looks like:

    X50Y100T hihi 263198
    X50Y100T hihi 264199
    X50Y100T hihi 265199
    X50Y100T hihi 266201
    X50Y100T hihi 267201
    X50Y100T hihi 268201

What the sample of code does is first initialize a string buffer, then build part of a character string using streaming operator `<<`, then part of it using concatenation, then some more with `<<`, then print the string.  Note that the strings involved here are in fixed buffers, rather than dynamically allocated buffers like the String class uses.


message:
Measuring ADC sample rate - Arduino DUE

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.

body:
I think using an interrupt controlled measurement might provide the best results for you.

Note: you might get more complete feedback using the Arduino forum.

In general the process would look like this:

 1. Set up an interrupt vector for the ADC peripheral (in this case support for ID37).
 2. Setup ADC registers (res, clock etc)
 2. Set up a timer to time the conversion.
 3. Create Active flag and Timer variables for processing inbound timer values.
 4. Start timer and ADC conversion.
 5. Loop waiting for active flag to set (it gets set in the ISR), when detected do average or store timer values, then clear active flag.

This methodology times each individual conversion using a high speed timer, which could mean a lot of values to process. You could equally not time each conversion, but simply set up say a 1 second timer, and count the total number of conversions in 1 second for your particular ADC configuration.

Peripheral ISR

 1. Waiting for Interrupt.
 5. In peripheral ISR, read and store timer value, reset timer, set active flag
 6. Return from ISR


body:
To expand on [Jack Creasey's answer](https://electronics.stackexchange.com/a/279740/11683), timestamping the samples as they are taken is the most direct way to do it. If you have a block of N samples, the average sample period is simply

$$\frac{Time_{last} - Time_{first}}{N - 1}$$

(Note that there are N-1 time intervals between N samples.)

If you want the sample rate, just invert the expression:

$$\frac{N - 1}{Time_{last} - Time_{first}}$$

---

However, you can also infer the sample rate from a known signal. For example, you can feed a tone signal into the ADC and count the number of samples between some well-defined feature of the waveform, such as rising zero crossings. If you count N samples, then the sample rate is N times the tone frequency. Averaging over multiple cycles of the tone will give you a more precise measurement.


message:
Control the "TV remote"

My idea is to use Arduino to control the TV remote. Not make the Arduino become a TV remote, I want to make an Arduino that can touch button of a remote control.

Any ideas?

body:
My rather fancy solution would be to make a 3 axis device with x and y controlled by stepper motors and z a simple solenoid to press the buttons.
For extra marks you could add a camera and try to recognise the buttons in software so any remote would work.
How do you plan to control the arduino?  Perhaps with a remote controller?


message:
How to programmatically upload an Arduino sketch generated by node.js (electron) or from browser?

We are trying to make an app that generates an Arduino sketch (.ino) using Google's Blockly and node.js, and uploads it to Arduino.

Even after searching a lot, I am unable to find how to build and upload the generated code to the board. Is there any tool or API available for node.js to do the same?

Or could I call some binary for this function. Please help.

body:
There are two things you need to do:

1. Compile the sketch into a .HEX file
2. Upload the sketch to the board

The first part can be done with `arduino-builder` which is part of the IDE since 1.6.6, or you can use one of various `Makefile` projects on a platform that supports `make`, or you can manually script it yourself calling the correct `avr-gcc` and `avr-g++` commands. You can check the output of the IDE for what those are.

The second part is done, usually, using `avrdude` - again see the output of the IDE for the correct command format.


message:
shiftOut using SPI isn't working

I made a sample using two of them using Arduino UNO.
So I did that like this:

[![Arduino with 74HC595][1]][1]
(There aren't any resistor on that image, but there are 220ohm resistor on every LEDs.)
And uploaded this code.

    //1.6us+62.5ns
    #include <SPI.h>

    #define sbi(port, bit) (port) |= (1 << (bit))
    #define cbi(port, bit) (port) &= ~(1 << (bit))

    int latchPin = 12;
    int clockPin = 13;
    int dataPin = 11;

    byte data[]={ 0b10101010,0b11001100 };

    void _595_out() {
     cbi(PORTB, 4);
     SPI.transfer(data[0] );
     SPI.transfer( data[1] );
     sbi(PORTB, 4);
    }

    void setup() {
     pinMode(latchPin, OUTPUT);
     pinMode(clockPin, OUTPUT);
     pinMode(dataPin, OUTPUT);

     SPI.setClockDivider(SPI_CLOCK_DIV2);
     SPI.setBitOrder(MSBFIRST);
     SPI.setDataMode(SPI_MODE0);
     SPI.begin();
    }

    void loop() {
     _595_out();
    }

And this worked as I expected. But, when I changed sketch like this,

    //1.6us+62.5ns
    #include <SPI.h>

    #define sbi(port, bit) (port) |= (1 << (bit))
    #define cbi(port, bit) (port) &= ~(1 << (bit))
    #define CHIPNO 2
    int latchPin = 12;
    int clockPin = 13;
    int dataPin = 11;

    byte data[]={ 0b10101010,0b11001100 };

    void _595_out() {
        cbi(PORTB, 4);
        SPI.transfer(data[0]);
        SPI.transfer(data[1]);
        sbi(PORTB, 4);
    }

    void setup() {
        pinMode(latchPin, OUTPUT);
        pinMode(clockPin, OUTPUT);
        pinMode(dataPin, OUTPUT);

        SPI.setClockDivider(SPI_CLOCK_DIV2);
        SPI.setBitOrder(MSBFIRST);
        SPI.setDataMode(SPI_MODE0);
        SPI.begin();
        Serial.begin(9600);
    }

    void loop() {
        for(unsigned int z = 0; z < 65535; z++) {
            data[0] = z & 255;
            data[1] = (z & 65280) >> 8;
            Serial.println("A");
            Serial.print(data[0]);
            Serial.print("/");
            Serial.println(data[1]);
            Serial.println("B");
            _595_out();
            Serial.println("C");
            delay(500);
        }
    }

74HC595s aren't working. Any LEDs aren't on.
Printing Serial works well. Only 74HC595s aren't working.
And Removing all Serial-related thing doesn't solved this problem.
Where did I do wrong?

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

body:
    int latchPin = 12;

You use pin 12 as the latch pin. Once you activate SPI the hardware takes over control of the pins MOSI, MISO and SCK. Pin 12 is MISO and thus attempting to change it in your code will have no effect.

You should use some other pin as the latch pin (pin 10 is often used).

---

> And shiftOut using SPI is working when I use first code

`shiftOut` is a software-based method of clocking out bits. It doesn't use hardware and thus it doesn't take control of pin 12.

---

Note: Answered originally on [the Arduino Forum](https://forum.arduino.cc/index.php?topic=448017.0)


message:
Peak counting in serial Arduino

I want to count peak of photocell data with serial communication in Arduino.

Here is the question. My problem is when I count one of the peaks it continues the counting and doesn't stop counting. My project is count Michelson Morley fringes with a photocell and Arduino.

If somebody can help me with the coding part I would appreciate it.

Here is the code that I used:

    int count=0;
    int val;
    int data;

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

    void loop() {
      data=analogRead(A0);
      val=map(data,0,1023,1000,0);
      if(val>700) {
       count++;
      }
      Serial.println(count);
      delay(100);
    }

This picture shows what I am trying to achieve:
[![Counting the peaks][1]][1]

Example Michelson Morley fringes:
[![Example Michelson Morley fringes][2]][2]

  [1]: https://i.stack.imgur.com/fRiFh.jpg
  [2]: https://i.stack.imgur.com/mqzq0.jpg

body:
keep in mind that since you used

    delay(100)

your 'loop' code runs in 10HZ (10 times a second)
So, every time you are lighting on your sensor, if its for longer than 1/10 of a second, you are likely going through several instances of 'loop', in which the condition

    (val>700)

is satisfied.

If you **know** that your peaks are going to take several loops, and only want to count each peak once- a simple way would be to make sure you dropped from the previous peak before incrementing the counter. you can achieve that with something like:

    int count=0;
    int val;
    int data;
    bool inPeak = false;

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

    void loop() {
      data=analogRead(A0);
      val=map(data,0,1023,1000,0);
      if(val>700) {
         if (!inPeak)
         {
            count ++;
            inPeak = true;
         }
      }
      else
      {
          inPeak = false;
      }

      Serial.println(count);
      delay(100);
    }


message:
Help: convert Arduino code to avr-gcc code

I need to convert Arduino code to avr-gcc code. This is code:

    #include <Servo.h>

    Servo myservo;

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

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

I use Arduino Mega.

body:
Try this:

    #include <Servo.h>

    extern "C" void init(void);

    Servo myservo;

    int main()
    {
        init();
        myservo.attach(11);
        for (;;) {
            myservo.write(67);
        }
    }

Note that this still needs the Arduino core library, as the Servo
library depends on it, which means all this is an exercise in futility.
If you are using the Arduino core, the simplest thing is to use it the
Arduino way. If you do not want to use Arduino core, then you will have
to partially re-implement the Servo library.


message:
Possibility of getting a UID on Arduino

Im working on a project where I will be using multiple Arduino (pro mini)'s which emit sensordata through LoRa.

The problem I am currently facing is, when I have multiple sensors, how do I know what data is coming from which Arduino (given they all have exactly the same source-code)?

1. Does the arduino have a UID like some sort of MAC code?
2. What could be a solution to give the Arduino a UID?
3. Do you guys have any other solutions for my issue?

In order to answer #2, I could add a random number calculator to create, but this doesn't feel right to me.

body:
You could use a small silicon serial chip like the Maxim DS2401 (http://pdfserv.maximintegrated.com/en/ds/DS2401.pdf)

An other method is to use good old dipswitches. That way you set each of your 'transmitter' to different address using the dipswitch. On boot the Arduino reads the switches to know it's address and uses that.


message:
How to use multiple SPI slaves in MKR1000 if it doesn't have Slave Select (SS/CS) pin?

I'm using a `Genuino MKR1000` and I want to use the `SPI` interface, which I've seen that there is no `Slave Select (SS)/Chip Select(CS)` pin usage.

How can I use the `SPI` interface with multiple slaves then?

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

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

body:
The Arduino doesn't care what pin you use for SS since you just use `digitalWrite()` on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.

The ATMega-based boards need pin 10 to be set as an output for SPI to function, but you don't then have to use that for the actual slave select. The only time it becomes a real slave-select pin is when using the Arduino itself as a slave.


body: If the number of slaves is large, consider using a multiplexed arrangement for select lines.  As an example, the 16-pin 74LS138 Decoder/Demultiplexer pulls one of eight lines low depending on the state of its three address lines, while the 24-pin 74LS154 pulls one of sixteen lines low depending on the state of its four address lines.  Both of these chips have two or three enable lines, allowing use of two to four of them together to multiply the number of output lines by two to four via use of one or two more address lines.


message:
Graphical programing language for Arduino

I am looking for a graphical programming language for a project of mine, where I am using an Arduino.

It HAS to meet the following conditions:

 - It supports uploaing sketches to ATmega328 (Arduino Uno/Nano)
 - New functions can be defined inside the programming enviroment (I am trying to use a motor connected to an H-bridge with a single command block)
 - The program can run on Windows 7
 - Libraries can be used inside the code
 - C++ can also be used to write the code inside the same program
 - Sketches can be uploaded via Bluetooth 4.0

It would be nice if it met the following condition:

 - The programming enviroment is easy to use
 - The graphical programming language is somewhat similar to Scratch
 - The program can be understood by 10-14 year olds with no programming experience

body:
The most full featured Scratch-like environment for Arduino, to my knowledge that is close to your listed criteria is http://www.mblock.cc/

It's currently in beta development for enabling bluetooth uploads and supports a range of "extension" plugins.  I believe you can also add functionality by writing your own extensions if you have sufficient programming knowledge.

The software has more features if you use their mblock hardware, while offering a reduced set of commands for other boards such as the Uno.

[![Supported Boards][1]][1]

[![Arduino code with scratch][2]][2]

I'm sure you can add library's to your code but at the expense of the scratch-like interface.  A children's visual design tool being able to provide graphical API to libraries written by an open source community is quite a coding challenge.  You can get a feel for this by trying to use any reverse engineering C++ to UML diagram tools.

I recommend perhaps using one of these scratch tools to build simple firmware as a learning tool with the idea of progressing to an actual programming language soon after.

In any case I hope you find what you're looking for among these options for your project.

 - http://www.mblock.cc/
 - http://s4a.cat/
 - http://blog.minibloq.org/p/documentation.html
 - http://blog.ardublock.com/engetting-started-ardublockzhardublock/
 - https://www.visuino.com/

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


body: Give Visuino a look, they are making noise lately: https://www.visuino.com/


message:
How to setup OpenCV with Arduino?

**My question is how to do it (set it up), not if I can do it or with what Arduino.**

I've previously setup OpenCV with Visual Studio 2015. It was a tough one, but I made it through. Now I want to set it up so that it would work with the Arduino and its IDE.

***How should I proceed? Is there any specific things to do?***

My setup:

- Windows 7
- Arduino IDE 1.8.1
- OpenCV 3.1

body:
If you are thinking of using OpenCV with a "normal" Arduino, such as the Uno or Mega, then think again. OpenCV runs on a computer - be that a desktop computer or an embedded computer. Basically you need an operating system; "normal" Arduinos don't have an operating system.

It may be possible to run OpenCV on an Arduino that runs Linux (some of the strange Intel things that are being marketed as Arduino do, as does the Yún), but in that case you will be writing a Linux application, not working in the Arduino IDE. You would need to treat it as a normal Linux computer and use the normal Linux tools for developing on it (note that OpenWRT that the Yún runs is tricky to develop for - the best way is to cross-compile on a real computer running Linux using the OpenWRT "Buildroot" system).


body:
As some people said before, you just can't run OpenCV on Arduino.
but, you can use Arduino/Raspberry Pi to capture information and send it to a server for analysis. For example, Azure, Bluemix or your main computer.

In your case, I would use Raspberry Pi + camera to capture images/videos.
then, send it through Wi-Fi to a server. Then, on the server, process all images using OpenCV.


message:
LED doesn't register as LOW after a switch has cut all power to it

I have the following build:

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

And the following code:

    const int buttonPin = 3;
    const int ledPin = 2;
    int buttonState = 0;

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

      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);

    }

    void loop() {
      while (digitalRead(ledPin) != LOW){
        buttonState = digitalRead(buttonPin);

        if (buttonState == LOW){
          digitalWrite(ledPin, LOW);
        }
      }
    }

But it doesn't seem like anything is registered, as my program doesn't respond to the shut down of the LED. What have I done wrong?

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

body:
The diagram is open to several different interpretations, depending on what's inside the four-terminal switch.  On many such SPST switches, two adjacent terminals are connected to each other inside it, and the other two likewise.  Which are which in the diagram isn't indicated.

That aside, what is clear from the diagram is that pin 2 is connected by wires to +5V, and will always read in as high.

---

*Edit 1:*
The schematic [posted later] is unclear.  It should be arranged so that solid lines represent wires or pins, with solid lines between things that are connected.  Place items in the drawing to reduce unnecessary and confusing crossing lines.  For example, supposing that the dashed line from pin 2 of R1 represents a wire between pin 2 of R1 and pin 2 of LED1, it is unclear whether the wire bends around the top right pin of S1 (can't read number) or connects with that pin on its way to LED1.  For another example, nothing is shown connecting to pin 1 of R1, and only one long dashed line connects the R1/S1/LED1 group to the Uno.


body:
Looking at your schematic, I get a bit confused.
You should start out with creating the schematic, try to base it on existing schematics on the web/tutorials.

I believe you're trying to read out a button and set an led accordingly?

So start out with the schematic and then try to build a breadboard setup for this. Randomly wiring things up on your breadboard doesn't really make sense, you need a plan.

I've created a shematic of which I believe should work a treat.

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

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

<!-- End schematic -->

*Using internal pull-ups on the SW1, to avoid the input floating.
Using 220ohms resistor, based on "Basic Red 5mm - Sparkfun LED", 5V source, 2V forward 16mA (http://led.linear1.org/1led.wiz).
Be carefull not to set the SW1 as an output (high) and push the button, this theoretically burns out the I/O pin.
But even then, this is only basic, you may want to consider input protection (http://www.thebox.myzen.co.uk/Tutorial/Protection.html)*

It's very easy to mess something up or do something incorrectly in electrical engineering. To be honest, it may help to watch a lot of tutorials or read books on electronics. It's very usefull to have a basic understanding before wiring things up.

At least base your actions on a (good) tutorial or reference material from Arduino self.

Try to wire up the circuit according to my schematics

Mouseover for example (but please try it yourself before checking!)
>! [![enter image description here][1]][1]

The same actually counts for programming, first try to make it clear what you want to achieve. Maybe even write out the steps that your program should do on a functional level.

I have no idea how you program could actually compile, the while and if statements don't have any closing brackets.

    const int buttonPin = 2;//I switched the LED and button in my design.
    const int ledPin = 3;//So the LED is on a PWM pin, which makes more sense.

    void setup() {
      //Serial.begin(9600); //We're not using serial, so why start serial?
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
       int value = digitalRead(buttonPin);
       digitalWrite(ledPin, value);
       //or digitalWrite(ledPin,digitalRead(buttonPin));//for short
    }

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


message:
Serial Communication Issue with Telit LE910 LTE Modem

I have a project that uses a Telit LE910 4G LTE Modem to allow me some basic monitoring via SMS and HTTP POST to Exosite.

I can connect to a Exosite server with and send a successful HTTP GET request to pull a UNIX timestamp (as a test).

**Problem**

The problem lies with receiving.  The information received cuts off halfway through the HTTP headers, before reaching the body of the information.

This image shows what prints out on the Serial monitor:

[![Serial Monitor][1]][1]

This image shows what the expected result should be:

[![Expected][2]][2]

And this image shows the code the executes to send the request:

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

The result is the same with PrintModemResponse() and with GetModemResponse().  Additionally, I have the same issue with receiving SMS messages.  The data appears to cut off partway through the expected response.  The modem serial (SW_Serial) baud rate is set to 115200.

**Question**

Am I doing something wrong with reading the Serial information from the modem?  Am I hitting a timeout of some sort?

  [1]: https://i.stack.imgur.com/sQiXt.jpg
  [2]: https://i.stack.imgur.com/o3TEx.jpg
  [3]: https://i.stack.imgur.com/e9bd8.jpg

body:
First, please don't post screen images.  Just select the text and paste it into your questions.  You can copy code from the editor or messages from the Serial Monitor window.  Paste into your post, select the section again, and press ctrl-K to format it as a code block in your question (like below).

> Am I doing something wrong with reading the Serial information from the modem?

Yes, you are using delay to "wait" for the response to appear.

> Am I hitting a timeout of some sort?

In a way.  The input buffer only has room for 64 characters.  If you don't read any of them because you're blocked at a `delay` statement, the 65th character (and all others) will be ignored.  **These answer your specific questions.**

<hr>
###Further Suggestions:

To fix the real problem, not just the symptoms, you will have to change your sketch structure.

There are many ways to implement this in a non-blocking way (i.e., without using `delay`).  I prefer [Finite-state Machines](https://en.wikipedia.org/wiki/Finite-state_machine); there are many good tutorials for this  technique (e.g., Nick Gammon's site).

Although it's not as flexible, you could also use your own `while` loop for each response, with a timeout.  Here's a simple example that reads one line.

    char resp[20];
    char resp_Len = 0;
    const uint32_t TIMEOUT_MS = 5000UL; // 5 seconds

    AltSoftSerial modem_port; // pins 8 & 9 ONLY

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

    void loop()
    {
      uint32_t startTime = millis();
      while (millis() - startTime < TIMEOUT_MS) {
        if (modem_port.available()) {
          char c = modem_port.read();
          if (c == '\n') {
            resp[ respLen ] = '\0'; // NUL terminate
            respLen = 0; // reset for another line
            break;

          } else if (respLen < sizeof(resp)-1) { // Room for more?
            resp[ respLen++ ] = c; // accumulate one more character
          }
        }
      }

      Serial.print( F("Response = '") ); // F macro saves RAM
      Serial.print( resp );
      Serial.println( '\'' );
    }

But when the response is long (hundreds of bytes), you may not have sufficient RAM to save the whole response, and then parse it.  You MUST use an FSM to parse the bytes *as they are received*.

For your application, you should skip all the stuff at the front and watch for the "Content-type:" pattern and the two newlines, then save the next line (as above) for parsing:

    enum state_t { SKIP_TO_CONTENT_TYPE, SKIP_TO_EMPTY_LINE, SAVING_TIMESTAMP };
    state_t state = SKIPPING
    uint8_t index = 0;

    const char ContentType[] = "Content_type:";

    bool watchForTimestamp()
    {
      if (modem_port.available()) {
        char c = modem_port.read();

        // Handle this one character, based on our current "state"

        switch (state) {
          case SKIP_TO_CONTENT_TYPE:
            if (c == '\n')
              index = 0;

            else if ((index < sizeof(ContentType) && (c == ContentType[ index ])) {
              // next char matches
              index++;

              if (index == sizeof(ContentType)) {
                // All matched!
                state = SKIP_TO_EMPTY_LINE;
                index = 0;
              }
            }
            break;

          case SKIP_TO_EMPTY_LINE:
            if (c == '\n') {
              index++; // this counts newlines since "Content-type:"

              if (index == 2) {
                state = SAVING_TIMESTAMP;
                index = 0;
              }
            }
            break;

          case SAVING_TIMESTAMP:
                ... Hint: something like the line-saving technique above.
            if (something) {
              return true;
            }
            break;
        }
      }

      return false;
    }

Some part of `loop` will just call `waitForTimestamp` over and over:

    void loop()
    {
        ...

      bool gotResponse = false;
      state = SKIP_TO_CONTENT_TYPE;

      while (millis() - startTime < TIMESTAMP_TIMEOUT) {
        gotResponse = waitForTimeStamp();
        if (gotResponse) {
          // parse the timestamp from the resp array
             ...
          break;
        }
      }

      if (gotResponse) {
        Serial.print( F("Timestamp = ") );
        Serial.print( resp );
        // now you can parse the small response array
           ...

      } else {
        Serial.println( F("Didn't receive timestamp!") );
         ... other error code
      }
    }

This may be a "main" FSM for loop, with a nested FSM for parsing the HTTP response.  The rest is up to you.  :)

BTW, SoftwareSerial is **very** inefficient.  It cannot send and receive at the same time, and it disables interrupts for long periods of time.

If you can use pins 8 & 9, you should use AltSoftSerial instead.  It is very efficient.

If you can't switch to those pins, you could use [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) if the modem is running at 9600, 19200 or 38400.