body:
I'm simply trying to light up some pins on a customized circuit board via Arduino.
 My code below has the seemingly common error "a function-definition is not allowed here before '{' token".  I've scoured my code for open/close curly brackets and semi-colons. I also regularly do a quick ctrl+T to format it.  Now I am at a loss - any info/advice greatly appreciated!  The error occurs at the '{' after the 'void loop()' line towards the bottom:

    // serially read in 32 bytes at a time to send to shift registers.
    // currently updating every 0.1s in Matlab

    // Define which pins will be used for the Shift Register control
    int dataPin = 2;
    int latchPin = 3;
    int clockPin = 4;

    #include <SPI.h>

    void setup()
    {
      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);

      SPI.setClockDivider(SPI_CLOCK_DIV16);
      SPI.begin();

      //Configure each IO Pin
      pinMode(dataPin, OUTPUT);
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);

      Serial.begin(115200);
      delay(1000);

      int seq
      [32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

      int timeElapsed = 2000;
      int timeOld = 0;
      int interval = 100;

      void loop()
      {
        Serial.flush();
        Serial.println('K');
        for (int i = 0; i < 32; i++)
        {
          while (Serial.available() == 0);
          {
            seq[i] = Serial.read();
          }
        }
        digitalWrite(latchPin , HIGH);
        digitalWrite(latchPin , LOW);
        for (int i = 0; i < 32; i++)
        {
          SPI.transfer(seq[i]);
        }
        digitalWrite(latchPin , HIGH); //necessary to tramsit to board
      }

title: Simple code to define pins used for Shift Register control - Error: a function-definition is not allowed here before '{' token

Answers: 1

body: There's no closing bracket for your `setup()` function and your `loop()` function is inside `setup()`. Close off `setup()` with a `}`and then start `loop()`!


body:
I want to take 2 different outputs from my DAC from void setDacOutput function (and it should be switching with/like the timer for both outputs. One output of 2.9375V for 0.9ms from ISR if statement and other of 2.5V for 1.6ms from else statememt) but my DAC only gives one output (in ISR - interrupt service routine only one of the if statement dacfunction or the else statement's (when if statement is commented) runs, not both). I want the DAC to give value for both if and else statement in ISR. For the given code it is only giving 2.9375Volts (called in isr-if statement). Not giving 2.5V (called in isr-else statement).

My timer is giving correct output when I connect oscilloscope to Pin9 and gnd (0.9ms on and 1.6ms off).I am using TLV5616 DAC from TI. And I’ve tried to print something in both if and else of ISR and they work but Dacfunction runs only once giving only one output. Maybe something wrong with SPI. Any help will be extremely appreciated please.

This is my code:

    // TLV5616 DAC communication using SPI
    #include <SPI.h>

    /*  TI TLV5616CP (2.7 to 5.5V) LP 12-Bit Digital to Analog Converter
    For sensor details see: http://www.ti.com/lit/ds/sbas415c/sbas415c.pdf

    Circuit:
    TLV attached to Uno pins as follows:
    TLV Pin         Uno Pin
    1 (DIN)         11 (MOSI - Output)
    2 (SCLK)        13 (SCK - Output)
    3 (/CS)          8 (Chip selec8t - Output)
    4 (FS)          10 (SS - Output)

    Note: TLV5616 has no provision for MISO pin 12, output is in volts

    // Pin 8 = /CS, Pin 10 = SS
    const int chipSelect = 8;
    const int slaveSelect = 10;

    // Variables for TLV5616 Testing
    const unsigned int control = 0x4000;
    const unsigned int msbMask = 0xFF00;
    const unsigned int lsbMask = 0x00FF;
    unsigned int command, data;
    byte commandMsb, commandLsb;

    //Variables for timers setting
    uint16_t timerOneVal[] = {14400, 25600};
    uint8_t timerTwoVal[] = {90, 160};
    bool timerOneItr = 0;
    bool timerTwoItr = 0;

    void setup(void)
    {
      Serial.begin(9600);
      /* To "condition" the hardware we begin with the call: SPI.begin()
      which configures the SPI pins (SCK, MOSI, SS) as outputs. It sets
      SCK and MOSI low and SS high. It then enables SPI mode with the
      hardware in master mode which has a side effect of setting MISO as
      an input.

      The SPI.transfer call does the actual transfer of bytes. I must
      set /CS and SS at the appropriate time */

      SPI.begin();
      SPI.setClockDivider(SPI_CLOCK_DIV2);       // Freq SPI_CLK = 8MHz
      SPI.setDataMode(SPI_MODE1);                // CPOL = 0, CPHA = 1
      pinMode(chipSelect, OUTPUT);
      pinMode(slaveSelect, OUTPUT);

      pinMode(9, OUTPUT);

      digitalWrite(9, LOW);

      setTimers();

    }

    void setTimers()
    {
      cli();

      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1  = 0;
      OCR1A = 0xFFFF;                   // set compare match register first time to full value (change values later on in the Interrupt service routine - ISR)
      TCCR1A = 0x40;                    // toggle OC1A on compare
      TCCR1B = 0x09;                    // Set CS10 and WGM12 bits for no prescaling and turning on CTC mode
      TIMSK1 = 0x02;                    // enable timer compare interrupt

      sei();

    }

    void setDacOutput(unsigned int dacValue)
    {
        digitalWrite(chipSelect, LOW);             // Enable TLV5616 /CS
        digitalWrite(slaveSelect, LOW);            // Enable TLV5616 FS

        /* The TLV5616 control bits are D14 and D13, D15 and D12 is don't care. The data
        to be written to the TLV5616 is in Bits D11 to D0. commandMsb is the (8-bit) MSB
        and commandLsb is the (8-bit) LSB of the 16-bit TLV5616 control word */

        command = control | dacValue;
        commandMsb = (command & msbMask) >> 8;
        commandLsb = command & lsbMask;
        SPI.transfer(commandMsb);
        SPI.transfer(commandLsb);
        delayMicroseconds(1);
        digitalWrite(slaveSelect, HIGH);            // Disable TLV5616 FS
        digitalWrite(chipSelect, HIGH);             // Disable TLV5616 /CS
    //    SPI.end();
    }

    ISR(TIMER1_COMPA_vect)
    {

      OCR1A = timerOneVal[timerOneItr];

      if(!timerOneItr){
        setDacOutput(0x0966);     // 2406/0x0966 for 2.9375V; 2045/0x0800 for 2.500V;
        timerOneItr = !timerOneItr;
      }
      else{
        setDacOutput(0x0800);
        timerOneItr = !timerOneItr;
      }

    }

title: Need help with DAC to show more than one output with SPI (stuck and need help please)

Answers: 0


body:
I've created a simple sketch for an esp32 that hosts a REST API that can be accessed via HTTP. Based on the instructions received from the client, the esp32 controls some neopixels with some various animations I've written.

Everything worked as expected until I got to an animation that runs in a while loop. The loop breaks when a new client is detected so that the light can switch functions. However, when the new client is detected, the client seems to be discarded or consumed, and i just end up back in the loop() function until I make a second HTTP request, then the changes to show up.

I'm sure it's something obvious, but what have I done wrong?

**Code:**

    #include "WiFi.h"
    #include "FastLED.h"
    #include "aREST.h"
    #include "ArduinoJson.h"

    #define NUM_LEDS 64
    #define DATA_PIN 18

    CRGB leds[NUM_LEDS];
    int LED_COUNT = 64;
    int MAX_BRIGHTNESS = 200;

    const char* ssid = "wifi";
    const char* password = "password";
    aREST rest = aREST();
    WiFiServer server(80);
    WiFiClient client;

    void setup() {
      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, LED_COUNT);
      flashAll(CRGB::Black);
      // Bind urls to the handling functions
      rest.function("random-strobe", randomStrobe);
      rest.function("solid-color", solidColor);
      rest.function("reset", reset);

      // Connect to WiFi and wait until we're connected to continue
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        flashAll(CRGB::Cyan);
        delay(500);
        flashAll(CRGB::Black);
        delay(500);
      }
      server.begin();
      flashAll(CRGB::Green);
      delay(2000);
      flashAll(CRGB::Black);
    }

    void loop() {
      if (checkForTask()) {
        rest.handle(client);
      }
    }

    boolean checkForTask() {
      // I have tried making this reassignment conditional
      // when the global 'client' is false, but it did not help
      //if (!client) { client = server.available(); }
      client = server.available();
      if (client) {
        return true;
      }
      return false;
    }

    int randomStrobe(String params){
      client.println("HTTP/1.1 200 OK");
      client.println("Content-type:application/json");
      client.println();
      client.stop();
      StaticJsonDocument<200> jsonDoc;
      Serial.println(params);
      Serial.println("params recieved. parsing...");
      auto error = deserializeJson(jsonDoc, params);
      if (!error) {
        // some setup stuff
        while(!checkForTask()){
          // do stuff in here
        }
        return 0;
      }
    }

title: WifiClient and aREST on esp32 - loop until new instructions recieved?

Answers: 2

body:
`server.available()` doesn't return an already 'claimed' connection again. It returns a new connection or an empty WiFiClient object.

The esp8266 and esp32 Arduino core WiFi library close the underlying connection if the last referring WiFiClient instance is freed. The assignment of empty WiFiClient object frees the previous reference to underlying socket and if it was the last referrence, the library closes the socket.

You get a client with `server.available()` in `checkForTask()` and then you call `server.available()` again. It returns an empty WiFiClient object and you assign it to your WiFiClient object. The library closes the referred connection.

The solution is not to check `server.available` until WiFiClient is valid.

    if (!client) {
      client = server.available();
    }

body:
Okay, I've managed to resolve the issue with some general direction from @juraj.

I now have TWO WifiClient instances:

    WiFiClient client;
    WiFiClient newClient;
This allows me to use the newClient instance to check for a new client:

    boolean checkForTask() {
      newClient = server.available();
      if (newClient) {
        Serial.println("new client detected.");
        return true;
      }
      return false;
    }
and only reassign the main client instance when a new client is actually detected:

    void loop() {
      if (!newClient.connected()) {
        checkForTask();
      } else {
        client = newClient;
        runTask();
      }
    }
This seems to work without any discernible side effects or additional resource usage, but if there is a more efficient way to accomplish this, please share. Thanks!


body:
I have tried several workarounds without success.

    #include <LiquidCrystal.h>
    float tempC;
    int tempPin = 0;// BS E D4 D5 D6 D7
    int buzzer = 4;
    int LED =2;
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    unsigned char i;
    void setup()
    {
    lcd.begin(16, 2);
    lcd.setCursor(0, 0);
    lcd.print("Temp        C ");
    pinMode(LED, OUTPUT);
    pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
    }
    void loop()
    {
    tempC = getTemperature();
    lcd.setCursor(6, 0); // Display Temperature in C
    lcd.print(tempC);
    delay(500);
    }
    float getTemperature()
    {
    int tempReading = analogRead(tempPin); // This is OK
    double tempK = log(1000000.0 * ((1024.0 / tempReading - 1)));
    //Temperature in Kelvin
    tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
    return (tempK - 273.15);

    if (tempC>0)
    digitalWrite(LED,HIGH);
    else
    digitalWrite(LED, LOW);
    }

title: Any idea why my LED fails to operate with the if statement

Answers: 1

body:
The LED fails to operate with the if statement because calling the `return` statement [Terminates a function and returns a value from a function to the calling function, if desired][1]. Try your sketch with the `return` statement as the "last thing" in the function.

    #include <LiquidCrystal.h>

    float tempC;
    int tempPin = 0; // BS E D4 D5 D6 D7
    int buzzer = 4;
    int LED = 2;
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    unsigned char i;

    void setup() {
      lcd.begin(16, 2);
      lcd.setCursor(0, 0);
      lcd.print("Temp C ");
      pinMode(LED, OUTPUT);
      pinMode(buzzer,OUTPUT);//initialize the buzzer pin as an output
    }

    void loop() {
      tempC = getTemperature();
      lcd.setCursor(6, 0); // Display Temperature in C
      lcd.print(tempC);
      delay(500);
    }

    float getTemperature() {
      int tempReading = analogRead(tempPin); // This is OK
      double tempK = log(1000000.0 * ((1024.0 / tempReading - 1))); //Temperature in Kelvin
      tempK = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * tempK * tempK )) * tempK );
      if (tempC>0) digitalWrite(LED,HIGH); else digitalWrite(LED, LOW);
      return (tempK - 273.15);
    }

  [1]: https://www.arduino.cc/reference/en/language/structure/control-structure/return/


body:
I am working with an official Arduino Mega. I have mounted an officiel Ethernet Shield rev 2.

Everything works great, i have wrote a very basic webserver.

I wanted to host a bootstrap css file on my webserver. This file has a size of about 150 kilo-bytes. So i have inserted an SD card on the Ehternet Shield. I have put my css file on this SD card.

I am writing the content of my css file with this code:

    File myFile = SD.open("bootstrap.min.css");
    if (myFile)
    {
        byte clientBuf[2048];
        int clientCount = 0;
        while (myFile.available())
        {
            clientBuf[clientCount] = myFile.read();
            clientCount++;

            if(clientCount > 2048-1)
            {
                client.write(clientBuf,2048);
                clientCount = 0;
            }
         }
         if(clientCount > 0) client.write(clientBuf,clientCount);
         myFile.close();
     }

It works, but it is very slow.
It takes about 30-40 seconds to load file into my browser.
I have tried to change clientBuf size but this is the optimal value i've set.

Any idea ?

Thanks

title: Webserver on Arduino Mega with Ethernet Shield

Answers: 0


body:
Please help me about this program uploading problem.
 Arduino: 1.6.13 (Windows 10), Board: "Arduino Nano, ATmega328P"

Sketch uses 930 bytes (3%) of program storage space. Maximum is 30,720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

title: Program Upload Loading problem

Answers: 1

body:
It can have many options, the main reason is it cannot communicate with the Nano.

I try to create a list with options:

  - Hardware issues
    - Nano is broken (solution: change Nano)
    - USB cable is broken (solution: change cable)
    - USB port is broken (solution: change USB port)
  - Software issues
    - USB port 'corrupt' (solution: use another USB port)
    - USB connection incorrect (solution: reconnect USB cable)
    - IDE is corrupt (solution: reinstall IDE)
    - Nano in illegal state (solution: reset/reconnect power of Nano)
    - Serial communication is used (remove RX/TX wires)


body:
I am working with an Arduino Mega, a 12V micro air pump, and a MP3V5050 air pressure sensor. The sensor outputs an analog voltage depending on the pressure reading in an inflatable member. I'd like to turn on the micro air pump when the pressure is too low and turn off the pump when the pressure exceeds a determined threshold (exact pressure ranges are currently undetermined).

I have been looking for similar tutorials but this is my first experience working with Arduinos and most existing tutorials are either sensing or pump control, not both. I only have minor coding experience with MATLAB, so any help with this is appreciated. Thank you!

title: Control Air Pump Depending on Pressure Sensor

Answers: 1

body:
So you basically want a hysteresis control for the air pump.

    const int lowerLimit;//fill in as needed
    const int upperLimit;

    void loop(){
        int pressure = readPressureSensor();
        if(pressure < lowerLimit) turnPumpOn();
        if(pressure > upperLimit) turnPumpOff();

    }

The helper functions I used should be easy to implement based on the tutorials you found.


body:
I have function to start an NTP service, right after obtaining wifi connection ( using ESP8266 board ).

from time to time, I get an error saying date and time is`01-01-1970`... which I assume is due to not reaching the server as intended.

A retry counter was added to give few more retries, but somehow I does not do the trick since I never get the expected message `NTP CHECK: #` and retry number ( while get an invalid date ).
I know that `NTP.begin()` returns a bool to describe success/ failure obtaining a NTP server

**EDIT1**: using `NtpClientLib`

How can it be done ?
<!-- language-all: lang-cpp -->

    void startNTP() {
            int counter = 0;
            while ( !NTP.begin("pool.ntp.org", 2, true) && counter <=2){
              Serial.print("NTP CHECK: #");
              Serial.println(counter);
              counter +=1;
              delay(1000);
            };
            NTP.setInterval(clockUpdateInt); // in seconds
    }

title: Verifiy NTP server update - at start

Answers: 1

body:
> Having read the NTPClientLib code, I would say that the first sync is not even attempted for 1 second after `NTP.begin()` is called anyway.

You could do this

    void startNTP() {
        NTP.begin("pool.ntp.org", 2, true);
        delay(2000); // there seems to be a 1 second delay before first sync will be attempted, delay 2 seconds allows request to be made and received
        int counter = 2;
        while ( !NTP.getLastNtpSync() && counter <=2) {
            Serial.print("NTP CHECK: #");
            Serial.println(counter);
            counter +=1;
            delay(1000);
        };
        NTP.setInterval(clockUpdateInt); // in seconds
    }

or, you could do this

    void loop() {
        // code that doesn't rely on valid time
        //
        // lets say this bit of code requires sync'd time
        if (NTP.getLastNtpSync()) {
            // this will only run once NTP has been sync'd at least once
        }
        // more code that doesn't require sync'd time
    }

Now, you may want to check how long time hasn't been sync'd for in your code and *do something* if it's been too long


body:
I am building a small electronic project, and I am incorporating module nodeMcU 8266 in a box.
I would like to know which pins are for "flash" and for "reset"
I know there are 2 buttons on the module for those 2 actions, but I would like to add 2 external buttons for those function on the case of the project, like that I will not need to open the box everytime. I looked on the net, and I guess that for "reset", I must connect to pin "Rst" and pin "Grd", I mean those 2 pin must be shorted, but I prefere to get confirmation before to go further.
And also for the "flash", what are both pins that I must connect the external push button to, to replicate the button present on the module itself.

Also I would like to connect an external LED to the module, following the state of the blue SMD led.
The thing is that there is an SMD blue led on the module, I want to know what are the 2 pins that are similar to the contacts of the blue SMD led.
I want the External LED that I plan to incorporate to the case of the project, to light up when the SMD blue led on the module is on, and when the led to be off when the blue SMD led is off. I want that both follow the same state.
Blue SMD led "On" >>> external led "On"
and
Blue SMD led "Off" >>> external led "Off"

Sorry for the little confused explanation, and thanx in advance for any help and support.

title: Correct Pins for Nodemcu 8266

Answers: 1

body:
The v0.9 and v1.0 NodeMCU boards have 2 LEDs: One on the AIthinker module, and one on the actual NodeMCU board.

The AIthinker module's LED is connected between Vcc (3.3V) and `GPIO2` (labeled `D4` on nodeMCU). It turns ON when `D4` is set `LOW`.

The NodeMCU LED is connected between Vcc (3.3V) and `GPIO16` (labeled `D0` on nodeMCU).  It turns ON when `D0` is set `LOW`.

The pin labeled `RST` is the Reset signal from the AIthinker module, and is active-high, meaning you connect `RST` to `GND` to put the device in a reset state.

The pushutton labeled `FLASH` is connected between GND and `GPIO0` (labeled `D3` on nodeMCU). When the this pin is `LOW` when the ESP8266 comes out of a reset state, the chip is in flash-bootloader mode, meaning it is ready to receive a new sketch. On a NodeMCU, however, the ESP8266 chip is placed in flash mode by the USB chip and the flashing software, so there is not a need to manually press this button.


body:
If there's one thing I never managed to do: it's comparing strings.
So I have the incoming message saved here

    String Message2 = IClient[i].readStringUntil('\n');

And every time I try to compare it with

    strcmp(Message2.c_str(),"Red"); //Hopefully comparing the Message2 with "Red"

I never get 0 returned.

I know from printing the Message2 to Serial that Message2 contains the word "Red".

I've tried using different methods (`string.equal(string2);` etc.) but it never said that they are equal. What am I missing out on?

title: Compare incoming message from ESP8266

Answers: 1

body:
Found the answer!

After testing around with changing the terminator of the `readStringUntil('\n')` method it appears that there were leading and trailing white spaces, though not being displayed on the serial monitor they still had an impact on the `strcmp(string1, string2)` method.

I could solve this problem by "trimming" the received string before comparing it by using the `String1.trim();` method.

In the end looking like:

    String Message2 = IClient[i].readStringUntil('\n');

    Message2.trim();

    strcmp(Message2.c_str(),"Red");


body:
**Appears to be something to with Apache configuration, swapping to Nginx solved my issue.**

I'm getting slow responses when using localhost with a NODEMCU 1.0 and esp8266 WiFi library.

If I GET a PHP file on a remote server the response is almost instantaneous and the output of the PHP file is printed extremely quickly after the HTTP headers. If I GET the same PHP file on localhost the response takes over 5 seconds even if that PHP files is echoing just a single character.

I've tried with XAMPP and a local server configuration on a Raspberry Pi but both have the same slow response speed.

    void loop() {
      WiFiClient client;

      if (wiegand.available()) {
        // Convert the code into a suitable type and construct the GET request
        double readWiegand = wiegand.getCode();
        String readWiegandStr = String(readWiegand, 0);
        String httpGet = "GET /verify.php?code=" + readWiegandStr;

        Serial.printf("\n[Connecting to %s ... ", host);

        if (client.connect(host, 80)) {
          Serial.println("connected]");
          Serial.println("[Sending a request]");
          client.print(httpGet + " HTTP/1.1\r\n" +
                       "Host: " + host + "\r\n" +
                       "Connection: close\r\n" +
                       "\r\n"
                      );
        }

        Serial.println("[Response:]");

        while(client.connected() || client.available()) {
          if(client.available()) {
            String line = client.readStringUntil('\n');
            Serial.println(line);
            if(line == "ACCEPT") {
              Serial.println("Code accepted");
            } else if (line == "DECLINE") {
              Serial.println("Code declined");
            }
          }
        }
        client.stop();
        Serial.println("\n[Disconnected]");
      }

title: ESP8266 WiFiClient Slow Over LocalHost

Answers: 0


body:
I have a generic HD44780 compatible 16x2 LCD display, with an already soldered on PCF8574 module. Its backlight is blue, and the characters are supposed to be white (on blue).

It is connected to a generic "Lolin" ESP8266 module which is working fine and is not related to the problem, I hope.

Using the LiquidCrystal_I2C library available at https://github.com/lucasmaziero/LiquidCrystal_I2C, I uploaded the simple "Hello, World" sketch provided, and it works. Used the most current libraries and Arduino IDE as of 2019-03-20.

However, the text displayed is a *very dim black-on-blue* instead of a *bright white-on-blue*.

I do not have any clue on why it happens and how to fix it (and that's my question).

What I know is that if I somehow "glitch" the display (for example by disconnecting and reconnecting the power lead) it will sometimes display gibberish, but in a *very clear white-on-blue*, so I know the LCD hardware is not defective *per se*.

I also tried a few other libraries to the same effect: LiquidCrystal_PCF8574 and LiquidCrystal_I2C (the version available directly from the Arduino IDE, source at https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library)

Below, the example sketch used to generate the problem. Be aware it is for the first LiquidCrystal_I2C library I referred above, but with changes, works with the others I tried.

    #include <LiquidCrystal_I2C.h>

    // Set the LCD address to 0x27 for a 16 chars and 2 line display
    LiquidCrystal_I2C lcd(0x27, 16, 2);
    void setup()
    {
      // initialize the LCD
      lcd.begin(); // Init with pin default ESP8266 or ARDUINO
      // lcd.begin(0, 2); //ESP8266-01 I2C with pin 0-SDA 2-SCL
      // Turn on the blacklight and print a message.
      lcd.backlight();
      lcd.setCursor(0, 0);

    #if defined(ESP8266)
      lcd.print("ESP8266");
    #else
      lcd.print("ARDUINO");
    #endif

      lcd.setCursor(0, 1);
      lcd.print("Hello, world!");
    }

    void loop()
    {
      // Do nothing here...
    }

And a photo of the anomalous display. Turning the constrast potentiometer does not help.

[![anomalous display][1]][1]

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

title: HD44780 display incorrectly black-on-blue instead of white-on-blue

Answers: 3

body:
There is a chance that this LCD would need a negative voltage on contrast PIN. Below there is a simple schematic. You would need to provide pulses on the 'Pulse in' branch. Use Negative voltage branch and potentiometer to feed your contrast pin.

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

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

body:
This answer is just to complement @smajli's answers posted (and accepted) before.

The problem lies in that the contrast pin has to be fed negative voltages when the module is powerered via a 3.3V supply to be able to show text in the correct white-on-blue setting and not on the faint black-on-blue.

@smajli correctly showed how the negative voltage may be generated from the normal positive supply and a pulse generator. However, in my scenario, the pulse generator was connected to the +3.3V rail instead of +5V and the pulses where generated via the ESP8266's PWM feature. Using a duty cycle of 50% it generates about -2V. I'll not reproduce his schematic here, though, but below is a photo of it assembled and in action.

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

The updated code is exactly the same, with only the PWM generation added inside the setup() function:

      pinMode(D8, OUTPUT);
      analogWrite(D8, 512);   // 10-bit!

Finally, the photo below illustrates the final result.

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

Again, thanks again to @smajli for the previous insights and answer.

P.S.: Keen readers will notice the module used now is NOT the same used when I asked the question originally. It is another generic HD44870 module, but without the I2C interface, working in 4-bit mode. However, the exact same problem (black-on-blue text) occurs when the contrast pin is set to anywhere between +3.3V and GND and is promptly solved when using negative voltage.

  [1]: https://i.stack.imgur.com/zbNTo.jpg
  [2]: https://i.stack.imgur.com/Vmyxa.jpg

body:
I have a similar LCD display (I assume it's virtually identical, hard to confirm).  In my case, driving the display VCC (and SCK and SDA) at 3.3v produced the same behaviour you described (dim black text on blue background), but setting VCC to 5v gave me the correct white-on-blue display (even with SCK and SDA still driven at 3.3v, since those are the outputs of the MCU I was using).

It's curious that setting the VCC to 5v did not work in your case.


body:
I am still not sure what should be the exact Title for this question, because I don't know where the problem is.

I am using `#include <MQTTClient.h>` mqtt library to subscribe on a topic.
This topic is created dynamically depending on the name of the device. Currently I am testing with device name `myDeviceAbc`.

    String baseTopic  = "arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing";
    String espInTopicStr  = baseTopic + "/" + config.machineName + "/espIn"; //config.machineName is a string "myDeviceAbc"

    const char* espInTopic  = "";
    espInTopic = espInTopicStr.c_str();

    const char* hardCodedTopic = "arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing/myDeviceAbc/espIn";

    int rc = client.subscribe(espInTopic, MQTT::QOS0, messageArrived);
    if (rc != 0) {
      Serial.print("rc from MQTT subscribe is ");
      Serial.println(rc);
      return;
    }
    Serial.println("MQTT subscribed");

    Serial.print("size of hardcoded topic: ");
    Serial.println(strlen(hardCodedTopic));
    Serial.print("size of actual topic: ");
    Serial.println(strlen(espInTopic));

    Serial.print("hardCodedTopic >>>");
    Serial.print(hardCodedTopic);
    Serial.print("<<<");
    Serial.println(".");

    Serial.println("---");

    Serial.print("espInTopic topic >>>");
    Serial.print(espInTopic);
    Serial.print("<<<");
    Serial.println(".");

I have defined two variables for same topic
```arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing/myDeviceAbc/espIn```
. one is hardcoded `hardCodedTopic` and other is created dynamically `espInTopic`.

when I subscribe on `espInTopic`, I get `MQTT subscribed` message on serial console BUT nothing is received on this topic when I publish from AWS portal.
but when I subscribe on `hardCodedTopic` I then receive all published messages. I cannot figure out what is the issue. I checked the mqttClient subscribe method inside the library header file, which is defined like this

    int subscribe(const char* topicFilter, enum QoS qos, messageHandler mh);

    /** MQTT Unsubscribe - send an MQTT unsubscribe packet and wait for the unsuback
     *  @param topicFilter - a topic pattern which can include wildcards
     *  @return success code -
     */
    int unsubscribe(const char* topicFilter);

It does takes const char* as topic name. I though maybe due to conversion from String to char array, there might be some unknown characters appended in the char array `espInTopic`, but I also checked the size and content of both topics which is exactly the same.

    size of hardcoded topic: 52
    size of actual topic: 52
    hardCodedTopic >>>arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing/myDeviceAbc/espIn<<<.
    ---
    espInTopic topic >>>arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing/myDeviceAbc/espIn<<<.

**Full Code:**

    #include <Arduino.h>
    #include <Stream.h>
    #include <EEPROM.h>
    #include <ArduinoJson.h>
    #include <SoftwareSerial.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266WiFiMulti.h>
    #include "helpers.h"
    #include "global.h"

    //AWS
    #include "sha256.h"
    #include "Utils.h"

    //WEBSockets
    #include <Hash.h>
    #include <WebSocketsClient.h>

    //MQTT PAHO
    #include <SPI.h>
    #include <IPStack.h>
    #include <Countdown.h>
    #include <MQTTClient.h>

    //AWS MQTT Websocket
    #include "Client.h"
    #include "AWSWebSocketClient.h"
    #include "CircularByteBuffer.h"

    #define ACCESS_POINT_NAME  "VM"
    #define ACCESS_POINT_PASSWORD  "12345678"

    extern "C" {
      #include "user_interface.h"
    }

    //AWS IOT config, change these:
    char wifi_ssid[]       = "TALKTALKAF521F";
    char wifi_password[]   = "xxxxxxxx";
    char aws_endpoint[]    = "xxxxxxxxxxxxxxxx.iot.us-east-2.amazonaws.com";
    char aws_key[]         = "xxxxxxxxxxxxxxxx";
    char aws_secret[]      = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    char aws_region[]      = "us-east-2";

    String baseTopic  = "arn:aws:iot:us-east-2:xxxxxxxxxxxx:thing";
    //const char* espInTopic  = "";        // was global before, but later I also tried to keep this local on subscribe() method
    const char* espOutTopic  = "";
    int port = 443;

    //MQTT config
    const int maxMQTTpackageSize = 512;
    const int maxMQTTMessageHandlers = 1;

    const char response[] = "{\"response\": {\"request_id\":, \"data\":}}";

    String nodeName = ""; // Name needs to be unique
    String nodeMac = "";

    ESP8266WiFiMulti WiFiMulti;

    AWSWebSocketClient awsWSclient(1000);

    IPStack ipstack(awsWSclient);
    MQTT::Client<IPStack, Countdown, maxMQTTpackageSize, maxMQTTMessageHandlers> client(ipstack);

    //# of connections
    long connection = 0;
    unsigned long timer = 0;
    unsigned long maxTimeOut = 7000;  //7 seconds

    //generate random mqtt clientID
    char* generateClientID () {
      char* cID = new char[23]();
      for (int i=0; i<22; i+=1)
        cID[i]=(char)random(1, 256);
      return cID;
    }

    //count messages arrived
    int arrivedcount = 0;

    //callback to handle mqtt messages
    void messageArrived(MQTT::MessageData& md)
    {
        MQTT::Message &message = md.message;

        Serial.print("Message ");
        Serial.print(++arrivedcount);
        Serial.print(" arrived: qos ");
        Serial.print(message.qos);
        Serial.print(", retained ");
        Serial.print(message.retained);
        Serial.print(", dup ");
        Serial.print(message.dup);
        Serial.print(", packetid ");
        Serial.println(message.id);
        Serial.print("Payload ");
        char* msg = new char[message.payloadlen+1]();
        memcpy (msg,message.payload,message.payloadlen);

    }

    //connects to websocket layer and mqtt layer
    bool connect () {

        if (client.isConnected ()) {
            client.disconnect ();
        }
        //delay is not necessary... it just help us to get a "trustful" heap space value
        delay (1000);
        Serial.print (millis ());
        Serial.print (" - conn: ");
        Serial.print (++connection);
        Serial.print (" - (");
        Serial.print (ESP.getFreeHeap ());
        Serial.println (")");

       int rc = ipstack.connect(aws_endpoint, port);
        if (rc != 1)
        {
          Serial.println("error connection to the websocket server");
          return false;
        } else {
          Serial.println("websocket layer connected");
        }

        Serial.println("MQTT connecting");
        MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
        data.MQTTVersion = 4;
        char* clientID = generateClientID ();
        data.clientID.cstring = clientID;
        rc = client.connect(data);
        delete[] clientID;
        if (rc != 0)
        {
          Serial.print("error connection to MQTT server");
          Serial.println(rc);
          return false;
        }
        Serial.println("MQTT connected");
        return true;
    }

    //subscribe to a mqtt topic
    void subscribe () {
       //subscript to a topic
      String espInTopicStr  = baseTopic + "/" + "myDeviceAbc" + "/espIn";
    //  String espOutTopicStr = baseTopic + "/" + config.machineName + "/espOut";
      const char* espInTopic  = espInTopicStr.c_str();
    //  espOutTopic = espOutTopicStr.c_str();

      const char* hardCodedTopic = "arn:aws:iot:us-east-2:xxxxxxxxxxxxxx:thing/myDeviceAbc/espIn";
      Serial.print("size of hardcoded topic: ");
      Serial.println(strlen(hardCodedTopic));
      Serial.print("size of actual topic: ");
      Serial.println(strlen(espInTopic));

       Serial.print("hardCodedTopic >>>");
       Serial.print(hardCodedTopic);
       Serial.print("<<<");
       Serial.println(".");

       Serial.println("---");

       Serial.print("espInTopic topic >>>");
       Serial.print(espInTopicStr.c_str());
       Serial.print("<<<");
       Serial.println(".");
       int rc = 99;
       while (rc != 0){
          rc = client.subscribe(hardCodedTopic, MQTT::QOS0, messageArrived);
          if (rc != 0) {
            Serial.print("rc from MQTT subscribe is ");
            Serial.println(rc);
            return;
          } else {
            Serial.println("");
            Serial.println("MQTT subscribed");
          }
          Serial.println("rc: " + String(rc));
          delay(500);
       }

    }

    //send a message to a mqtt topic
    void sendmessage (const char* topic, String msg) {
        //send a message
        MQTT::Message message;
        char buf[100];
        strcpy(buf, msg.c_str());
        message.qos = MQTT::QOS0;
        message.retained = false;
        message.dup = false;
        message.payload = (void*)buf;
        message.payloadlen = strlen(buf)+1;
        int rc = client.publish(topic, message);
    }

    void setup() {

        wifi_set_sleep_type(NONE_SLEEP_T);
        EEPROM.begin(1024);
    //    for (int i = 0; i < 1024; ++i) { EEPROM.write(i, 0); }
        Serial.begin(115200);
        ardMegaSerial.begin(9600);

        delay (2000);

        //////////////////////////////////////////
      if (!ReadConfig())
      {
        // DEFAULT CONFIG
        config.configMode = true;
        config.ssid = "N.A";
        config.password = "N.A";
        config.machineName = "N.A";
        config.dhcp = true;
        config.IP[0] = 192;config.IP[1] = 168;config.IP[2] = 1;config.IP[3] = 100;
        config.Netmask[0] = 255;config.Netmask[1] = 255;config.Netmask[2] = 255;config.Netmask[3] = 0;
        config.Gateway[0] = 192;config.Gateway[1] = 168;config.Gateway[2] = 1;config.Gateway[3] = 1;
        WriteConfig(true);
        Serial.println("default configs applied");
        //////////starting web config server hotspot
            Serial.println("No configuration stored, starting access point.");
            ESP.eraseConfig();
            WiFi.disconnect();
            WiFi.setAutoConnect(false);
            WiFi.setAutoReconnect(false);
            WiFi.mode(WIFI_AP_STA);
            nodeName = String(ACCESS_POINT_NAME) + String("-") + String(WiFi.softAPmacAddress().c_str());
            WiFi.softAP(nodeName.c_str() , ACCESS_POINT_PASSWORD);
            Serial.print("Connect to ssid " + nodeName + " to configure Node on IP: ");
            Serial.println(WiFi.softAPIP());
            ConfigureWifi();
            server.on ( "/favicon.ico",   []() { Serial.println("favicon.ico"); server.send ( 200, "text/html", "" );   }  );
            server.on ( "/", send_gateway_node_config_html  );
            server.on ( "/admin/values", send_gateway_node_config_values_html );
            server.on ( "/admin/connectionstate", send_connection_state_values_html );
            server.on ( "/style.css", []() { Serial.println("style.css"); server.send ( 200, "text/plain", PAGE_Style_css );  } );
            server.on ( "/microajax.js", []() { Serial.println("microajax.js"); server.send ( 200, "text/plain", PAGE_microajax_js );  } );
            server.onNotFound ( []() { Serial.println("Page Not Found"); server.send ( 400, "text/html", "Page not Found" );   }  );
            server.begin();
            Serial.println( "HTTP server started" );
      } else {
          nodeName = String(ACCESS_POINT_NAME) + String("-") + String(WiFi.softAPmacAddress().c_str());
          Serial.println("Device already configured");
          Serial.println("Wifi SSID: " + config.ssid);
          Serial.println("Wifi password: " + config.password);
          Serial.println("Node name: " + config.machineName);

          setupWifiAndAws();
      }

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

    }

    void setupWifiAndAws() {
        char ssidBfr[500];
        strcpy(ssidBfr, config.ssid.c_str());
        char passBfr[100];
        strcpy(passBfr, config.password.c_str());
        //fill with ssid and wifi password
        WiFiMulti.addAP(ssidBfr, passBfr);
        Serial.println ("connecting to wifi");
        while(WiFiMulti.run() != WL_CONNECTED) {
            delay(100);
            Serial.print (".");
        }
        Serial.println("\nconnected");
        ardMegaSerial.println("ESP Started\n");
        //fill AWS parameters
        awsWSclient.setAWSRegion(aws_region);
        awsWSclient.setAWSDomain(aws_endpoint);
        awsWSclient.setAWSKeyID(aws_key);
        awsWSclient.setAWSSecretKey(aws_secret);
        awsWSclient.setUseSSL(true);

        if (connect ()) {
            String espOutTopicStr = baseTopic + "/" + config.machineName + "/espOut";
            espOutTopic = espOutTopicStr.c_str();
            subscribe();
            sendmessage (espOutTopic, "{\"device\":\"connected\"}}");
        }
    }

    void loop() {

      receiveFromArduino();
      //responseTimeOutCheck();
      //keep the mqtt up and running
      if (awsWSclient.connected ()) {
       client.yield(50);
      } else {
     //handle reconnection
     if (connect ()){
       subscribe ();
     }
      }

    }

title: Mqtt not subscribe on topic that's converted from String to char array

Answers: 1

body:
The `c_str()` function of the `String` class returns a pointer to current internal char array. This pointer is valid only until the String exists and is not changed.

Variable `espInTopicStr` is defined in a function and is destroyed at the end of the function. It frees the memory allocated for the internal char array.

You send a pointer to the internal char array of the `espInTopicStr` to `client.subscribe`. The MQTT library doesn't copy that char array, it only stores the pointer. Later the library uses the pointer to call the topic, but the memory on that location already changed and doesnt't contain the name of the topic.


body:
I've written this code for a reaction timer game. The reaction time is to be displayed in milliseconds to the serial monitor as accurately as possible. The reaction time is not being displayed correctly. I'm including my timer setup routine and where I increment milliseconds.

    TCCR1A=0;
    TCCR1B=0;
    timer1_counter=65536;
    TCNT1=timer1_counter;
    TCCR1B |=(1<<CS12);

    TIMSK1 |=(1<<TOIE1);
    interrupts();
    }

    ISR(TIMER1_OVF_vect)
    {
      TCNT1=timer1_counter;
      int_flag=1;
     }

      digitalWrite(LED,LOW);
      randomSeed(analogRead(A1));
      NumSecs=random(1000,7000);
      delay(NumSecs);
      digitalWrite(LED,HIGH);
      while(digitalRead(PUSHBUTTON) == HIGH)
      {
      }
      if (int_flag==1){
      millisecs++;
      int_flag=0;
      }

title: Reaction timer using millis

Answers: 2

body:
Your ISR is not counting the elapsed milliseconds. Instead, it just sets
a flag and lets the main program do the counting when it sees the flag.
Here:

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

    while(digitalRead(PUSHBUTTON) == HIGH)
    {
    }

you are waiting for the user to press the button. The program does
nothing else during the wait. It doesn't event count the time. Here:

    if (int_flag==1){
        millisecs++;
        int_flag=0;
    }

you increment _once_ the millisecond count _after_ the wait.

The obvious solution is to count the milliseconds while waiting for the
button press:

    millisecs = 0;  // don't forget to reset the stopwatch!
    while (digitalRead(PUSHBUTTON) == HIGH) {  // button not pressed
        if (int_flag) {
            millisecs++;
            int_flag = false;
        }
    }

(side note: `int_flag` should be a `bool`).

There are still many issues with this program. First of all, it should
check that the user did not press the button before the LED came up.

Then, the interrupt period is not one millisecond, because the interrupt
takes some time to be processed by the CPU and to go through its
prologue. By the time you do `TCNT1=timer1_counter;` you are at least
several tens of cycles late. You should instead configure the timer to
keep the correct period by itself, typically using CTC mode.

Also, there is no point in letting the main program count the
milliseconds when the ISR could do it. E.g.

    ISR(TIMER1_OVF_vect)
    {
        millisecs++;
    }

    // Avoid a race condition when reading millisecs.
    static inline unsigned int getMillisecs()
    {
        noInterrupts();
        int millisecsCopy = millisecs;
        interrupts();
        return millisecsCopy;
    }

Note that the time keeping variables should be unsigned in order to
avoid undefined behaviour on overflows.

Finally, it may be a good learning experience for working with
interrupts, but in the end just using `millis()` or `micros()` would be
the easiest way to achieve what you want.

body:
You're over-thinking this:

      digitalWrite(LED,LOW);
      randomSeed(analogRead(A1));
      NumSecs=random(1000,7000);
      delay(NumSecs);
      digitalWrite(LED,HIGH);
      unsigned int startTime = millis();
      while(digitalRead(PUSHBUTTON) == HIGH)
      {
      }
      unsigned int elapsed = millis() - startTime;

After that code, `elapsed` will contain the number of milliseconds it took the user to press the button. Note, however, that the user could cheat and simply press the button the whole time while waiting for the LED to change states. You could add logic to make sure the button isn't pressed just before you change the LED state, but I'll leave that up to you.


body:
I am doing mice behavioral training.
I have an arduino-controlled box for that.
The sounds are play using Mp3 player controlled b the arduino.
However, the mp3 player is not good enough for my needs.

I need two clear sounds of 10 msec duration and freqiencies of 5000Hrz and 1000Hrz.
(I prefer pure sine waves but can compromise on triangle or, for now, even square).
The problem is that the mp3 is not fast enough and the volume is too low for 10 msec durations. When I tried to build gain circuit it became too noisy.

I tried to use the Tone function but it is again not good for 10 msec sounds. espacially in the jigj frequency/

I created the wavefiles in Matlab.
The PC plays the file in the right volume with no nose.
However, I don't know how to make the arduino play the files from the computer.

Is there a relative simple way to do it, without bying extra hardware?
If now, is there ANY way of doing it?

or another option, Is there a way for the arduino to play files from a wave generator? (I have these in my lab)

Thanks!

title: Play computer *.wav files through Arduino

Answers: 2

body:
Two options:

1. Write software for the PC to react to serial commands sent by the Arduino, or
2. Use a more powerful Arduino-like board with a DAC and do wavetable synthesis.

The Arduino Due and many of the other smaller ARM-based boards (like M0 boards) are a good candidate for option 2 because they are faster than a traditional Arduino and have a built-in DAC.  However, a proper I2S CODEC chip attached to a powerful MCU would be the preferred method for high-quality playback.

Note that your amplification system is of critical importance. It's common for many cheap amplifiers to limit higher frequencies. You need an amplifier with a good flat response over and above the maximum frequency you want to reproduce. Just slapping together any old "gain" circuit is probably not going to be good enough. Most op-amp based solutions have a ratio (*[Gain Bandwidth Product](https://en.wikipedia.org/wiki/Gain–bandwidth_product)*) that reduces the bandwidth as the gain increases.

body:
This code will create a steady 20 KHz output. Adjust the duration to reflect the period of your frequencies.

    byte triggerOut = 19;

    unsigned long currentMicros;
    unsigned long nextMicros;
    unsigned long duration = 25UL; // flip every 50uS = 20KHz pulse
    unsigned long elapsedMicros;

    void setup() {
      pinMode (triggerOut, OUTPUT);
    }
    void loop() {
      while (1) {
        currentMicros = micros();
        elapsedMicros = currentMicros - nextMicros;
        if (elapsedMicros >= duration) {
          nextMicros = nextMicros + duration;
          PINC = PINC | 0b00111111; // toggle D19 output by writing it input port.
        }
      }
    }

Add some lines to start the output after a button push, and count the number of cycles to only output the time duration you want.
10,000 KHz = 0.1mS period, 10ms/0.1ms = 100 cycles.

Divide the 0 to 5V output down to 1V, and drive a computer self powered speaker to create the noise you want.


body:
So recently I made code that used two custom sensors that are connected to the analog pin A0 & A5. Schematic can be seen here (http://inmoov.fr/test-your-finger-sensor/).

    const int ono = A0;
    const int twe = A5;

    int one;
    int two;

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

      }

    void loop() {
      one = analogRead(ono);
      two = analogRead(twe);

      Serial.print(one);
      Serial.print(" ");
      Serial.println(two);

    }

So after I follow the schematic i did the code, but the data value from the Serial Plotter of both sensors are always equal even though I was only pressing down on one sensor. So is this a code problem or the circuit? if so is there any fix for it? Thx.

[![The circuit that I made is like this, the sensor is NOT an FSR it is just used to represent since its a custom sensor, look at the link for more detail][1]][1]

[![This is what the values look like, so when sensor red is pressed it will rise and blue following behind but slightly lower, and when blue is pressed blue will rise and red slightly lower][2]][2]

[![third image][3]][3]

  [1]: https://i.stack.imgur.com/XuDXv.png
  [2]: https://i.stack.imgur.com/ZSmoB.png
  [3]: https://i.stack.imgur.com/gEzA0.png

title: Analog pins giving off the same value

Answers: 0


body:
I'm using the ssd1306_128x64_i2c example file from the 1306's library.

It works perfectly until I add the ***#include SD.h*** line, after which it gives the allocation failed error.

Please advise.

    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #include <SD.h>

    Adafruit_SSD1306 display(128, 64, &Wire, 4);

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

      // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        Serial.println(F("SSD1306 allocation failed"));
      }

      display.clearDisplay();
      display.display();
      testdrawchar();
    }

    void loop() {
    }

    void testdrawchar(void) {
      display.clearDisplay();
      display.setTextSize(1);
      display.setTextColor(WHITE);
      display.setCursor(0, 0);
      display.cp437(true);

      for(int16_t i=0; i<256; i++) {
        if(i == '\n') display.write(' ');
        else          display.write(i);
      }
      display.display();
    }

title: "SSD1306 allocation failed" when #include SD.h

Answers: 2

body:
Both the SD library and the SSD1306 libraries want big buffers. That means lots of memory.  You don't have lots of memory.

* The SD wants at least 512 bytes for a sector buffer (which is allocated at compile time).
* The SSD1306 wants at least 1kiB for a display buffer (which is allocated at runtime).
* Serial wants at least 128 bytes for TX and RX buffers (which is allocated at compile time).
* The Wire library needs 32 bytes for a TX buffer.

That's 1696 bytes of a total 2048, and that's not taking into account any of the other variables and things that your program, the various libraries, and the Arduino core itself needs, plus the stack (and its specified minimum size safety zone).

There's nothing much you can do about it, short of upgrading your Arduino to one with more memory, or splitting your design across multiple Arduinos.

body:
I was able to make it all fit by using the text-only library for the OLED.

[SSD1306Ascii Library][1]

Much thanks to Majenko for explaining the problem and greiman for writing the library!

  [1]: https://github.com/greiman/SSD1306Ascii/blob/master/examples/HelloWorldAvrI2c/HelloWorldAvrI2c.ino


body:
ok, im having problems with my bh1750, here is all info i got:

board: esp32s nodeMCU v. 1.1

Pins:
[![Pins:][1]][1]

Wiring: (the 2 reds go to pin 21 and 22)
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/YiF1z.png
  [2]: https://i.stack.imgur.com/XDHCo.jpg

code:

    #include <BH1750.h>
    #include <Wire.h>

    BH1750 lightMeter;

    void setup(){

    Wire.begin();
    Serial.begin(115200);
    lightMeter.begin();
    if (lightMeter.begin()) {
    Serial.println(F("BH1750 initialised"));
    }
    else {
    Serial.println(F("Error initialising BH1750"));
    }
    }

    void loop() {
    uint16_t lux = lightMeter.readLightLevel();
    Serial.println(lux);
    delay(500);
    }

Sorry for bad formating

Serial output:

13:01:41.926 -> [BH1750] ERROR: received NACK on transmit of address

13:01:41.926 -> [BH1750] ERROR: received NACK on transmit of address

13:01:41.926 -> Error initialising BH1750

13:01:41.926 -> [BH1750] Device is not configured!

13:01:41.926 -> 65534

13:01:42.430 -> [BH1750] Device is not configured!

13:01:42.430 -> 65534

13:01:42.932 -> [BH1750] Device is not configured!

13:01:42.932 -> 65534

and that goes on forever

Hope someone got an answer :D

title: bh1750 lightsesor won't work

Answers: 2

body:
Your code looks good. I2C configuration is default which depends on your board manager.
Then your wiring may be wrong.

1. Using a multimeter to check supply voltage on the BH1750 module. It should be 3.3V
2. Using a multimeter to check the connection between the BH1750 module with ESP32.
3. Difference ESP32 vendor may provide a difference I2C pinout. Make sure you connect everything correctly.
4. Using an oscilloscope or logic analyzer to capture data on an I2C bus.
5. If everything good, try to use another module.

From your log, I guessed, the power supply is good. I2C connection is your problem.
More, you should use the different color wire for the difference signal. It helps prevent unexpected connections.

body:
The SCL and SDA silkscreen was reversed on my chips.
Took an hour of faffing to figure that out.

Never "Just presume" it is correct


body:
I want to use the ADG731 32 ch multiplexer to read 32 potentiometers, I have wired everything and it works but it doesn't works as fast as I would want.

The problem is that If I turn a potentiometer between the range of 10-90% of the rotation, the analog reading is so slow, for example, if I have my POT at 0, and i turn it to 50%, it goes so slow until it reach the 512 value(like an hysteresis effect), BUT, if I turn the potentiometer back to 0 or up to 1023 it makes the reading as quick as I would expect.

So in resume it reads slowly the values except the edges values.

This is my code(I have set it to read only one potentiometer at pin S16 to test how the ADG731 works:

    #include <SPI.h>

    void loadDrain(void);
    const int slaveSelectPin = 53;
    void setup() {
      pinMode(slaveSelectPin, OUTPUT);
      SPI.begin();
      Serial.begin(9600);
    }

    void loop() {
      loadDrain();
    }

    void loadDrain(){
      SPI.beginTransaction(SPISettings(30000000, MSBFIRST, SPI_MODE2));
      digitalWrite(slaveSelectPin, LOW);
      SPI.transfer(00001111);
      digitalWrite(slaveSelectPin, HIGH);
      SPI.endTransaction();
      Serial.println(analogRead(A0) >> 3);
    }

title: Arduino SPI Multiplexer problems

Answers: 3

body: Take a deep look into the library you are using to read the POT. Most HW and / or SW will take many readings & average them to remove the randomness and improve the accuracy of the ADC HW. It could be that your setup is so noisy that the SW is compensating by taking even more readings to average. Hats off the the SW developer who had the foresight to adapt the code to noisier situations. If true, and you think that too much automation, remember you are using the Arduino platform where the libraries are designed to make things simple by abstracting (hiding) the hardware details.

body:
Some things look odd:

Why do this every time? You only need to set these up one time in setup():

    SPI.beginTransaction(SPISettings(30000000, MSBFIRST, SPI_MODE2));

Most 16 MHz Arduinos, including the Mega you appear to be using, won't do 3 MHz, choices are 8 MHz, 4,MHz, 2 MHz, 1 MHz  and 3 or 4 more slower speeds.

The chip seems to support higher speeds, 8 MHz should work:

>fSCLK 30 MHz max SCLK Cycle Frequency

So run it faster to same on time.

Why take a 10-bit reading and shift it down to 7?

    Serial.println(analogRead(A0) >> 3);

You could speed up the reads by doing an 8-bit read instead of 10-bit, and use a faster Serial speed, up to 115200, to send the results out.

Instead of digitalWrite() to control the slaveSelect pin, you could use direct port manipulation to toggle that pin.  You can write a 1 to the Input port to toggle the output bit. From the Atmega2560 datasheet:

>Toggling the Pin
>
>Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI
instruction can be used to toggle one single bit in a port.

body:
You can modify beginT and endT
// test SPI slave n=1
 SPI.beginTransaction(1, SPISettings(30000000, MSBFIRST, SPI_MODE2));
 SPI.transfer(00001111);
 SPI.endTransaction(1);


body:
I want to ask is there a possible code to prioritize a specific part of a code? So I'm doing this project where I want to utilize muscle sensor, servo, and a button on an app over Bluetooth. The problem is since all is running in void() loop, even though I am not using the muscle sensor I can't move the servo with the app, since it reads the muscle sensor first. So is there a possible code to make the muscle sensor stop for a period of time after the button is pressed on the app and the servo is moved?

Here is the code:

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

          if (data == 'a')
           {
            myservo.write(15);
           }
      }

    int value = analogRead(EMG_PIN);

     if(value > THRESHOLD)
      {
       myservo.write(15);
      }

      else{
           myservo.write(140);
          }

So the first code is a bluetooth code where the servo is controlled through a button on an app. The second one is a muscle sensor. As stated above the problem is it will always read the muscle sensor even though the button is pressed from the app.

    #include <Servo.h>

     int increment = 0;

     Servo myservo;

     void setup() {

       myservo.attach(1);

     }

     void loop()
     {

       Serial.println(increment++);

       if (increment > 9);
        {

         if(Serial.available()>0)
          {
           char data = Serial.read();

           if (data == 'a')
           {
            myservo.write(15);
           }
     }

          else if (increment = 0);

          int value = analogRead(EMG_PIN);

          if(value > THRESHOLD)
           {
            myservo.write(15);
           }

         else{
           myservo.write(140);
          }
      }

title: Prioritizing one sensor

Answers: 1

body:
You have to think of your program as having two distinc modes of
operation:

* The "fixed servo" mode is entered when you press the button on the
  app. In this mode the servo is kept at a fixed position. The mode
  lasts for a predefined delay.

* The normal (not fixed servo) mode is the default mode. In this mode
  the servo is positioned according to the reading of the sensor.

So you need a boolean variable to remember whether the "fixed servo"
mode is active or not, and the code in `loop()` should take care of
providing the correct behavior depending on the mode, and updating that
variable when needed. For example:

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

    void loop()
    {
        static bool fixed = false;  // whether we are in "fixed servo" mode
        static uint32_t fixed_started;  // when the mode started
        uint32_t now = millis();

        // On button press, start "fixed servo" mode.
        if (Serial.available() && Serial.read() == 'a') {
            servo.write(SERVO_LEFT);
            fixed = true;
            fixed_started = now;
        }

        // Get out of "fixed" mode after some delay.
        if (fixed && now - fixed_started >= FIXED_DELAY) {
            fixed = false;
        }

        // If not in "fixed" mode, react to the sensor.
        if (!fixed) {
            if (analogRead(EMG_PIN) >= THRESHOLD) {
                servo.write(SERVO_LEFT);
            } else {
                servo.write(SERVO_RIGHT);
            }
        }
    }


body:
I need help. I am making motion detector that calls you when sensor activates
and i have done the code for that, but the thing is i am beginner and i need to make it when it first time boots i send a message with the number that will be called when sensor activates

`

    int LED1 = 12;
    int GND1 = 13;
    int LED2 = 8;
    int GND2 = 9;
    int pirOutput = 5;
    void setup()
    {
      Serial.begin(9600);
      pinMode(LED1, OUTPUT);
      pinMode(GND1, OUTPUT);
      pinMode(LED2, OUTPUT);
      pinMode(GND2, OUTPUT);
      pinMode(pirOutput, INPUT);

      digitalWrite(pirOutput, LOW);
      digitalWrite(GND1, LOW);
      digitalWrite(GND2, LOW);
      digitalWrite(LED1, LOW);
      digitalWrite(LED2, LOW);
      delay(15000);
      digitalWrite(LED1, HIGH);

    }
    void loop()
    {
      if (digitalRead(pirOutput) == HIGH)
      {
        digitalWrite(LED2, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.println("ATD+381xxxxxxxx;");
        delay(15000);
        Serial.println("ATH");
        digitalWrite(LED2, LOW);
        delay(1000);
      }
    }

that is the code i found and it works fine for me

title: Motion detection alarm that calls back

Answers: 0


body:
I'm super confused right about now!

I've been working on project involving Xbees in API mode, and I need to send different arrays of bytes to the Xbee depending on which buttons I press. Mostly what I have is working fine, but I'm having a lot of issues with the following questions; I figured I'd summarize all my questions first, then further explain them with code examples.

 1. Arduino requires arrays contain to a size. How can I declare `byte data[]` without a size?
 2. Arrays sizes must be declared with a number, or a const integer. So how come I can declare `byte packet[arraySize];` when `arraySize` is being passed the integer `ledOn_len` that isn't constant?
 3. How can I create a global array within a function?

I've taken the liberty to condense my code for readability purposes. Everything you see is here is mirroring my issues with my Xbee code.

    byte ledOn[] = { 0x7E, 0xAA, 0x1C, 0x3B }; // turn led on
    byte ledOff[] = { 0x7E, 0xAB, 0x1D }; // turn led off

    int ledOn_len; // to be used for the array size of ledOn[] NOT a constant
    int ledOff_len; // to be used for the array size of ledOff[] NOT a constant

    // this doesn't work, because the array length must be a constant
    //int arrayLength = 4;
    //byte rando[arrayLength];

    // this works just fine, since arrayLength is now a constant
    //const int arrayLength = 4;
    //byte rando[arrayLength];

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

      // since using sizeof(data) inside of changeLed() doesn't
      // work (it returns with 2, which is the size of a pointer)
      // set them here, and pass them along.
      ledOn_len = sizeof(ledOn);
      ledOff_len = sizeof(ledOff);
    }

    void loop()
    {
      changeLed(ledOn, ledOn_len);
      delay(1000);
      changeLed(ledOff, ledOff_len);
      delay(1000);
    }

    void sendToXbee()
    {
      //Xbee.write(packet); // packet isn't global, this doesn't work
      // yes I know I didn't include any software serial in this demonstration
    }

    void changeLed(byte data[], int arraySize)
    {
      byte packet[arraySize]; // how does this work???? Pass by value
      memcpy(packet, data, arraySize); // clone data to packet

      // this is all the Serial print code

    }
**1)** I created the function `void changeLed()` to calculate the checksum (xbee crap). I need to pass it the array `ledOn[]` or `ledOff[]` for the checksum calculations to occur. So I simply added `void changeLed(byte data[])`  (and then void loop calls `changeLed(ledOn)` ) which works, but why?! Anywhere else if you declare an array without an array size it says you must provide one. Confusing to me, but it still works. . . kinda. When I serial print `data[i]` byte by byte, it perfectly displays each byte in `ledOn[]`, which is what I'm passing it. But when I call `sizeof(data)` it says it's only 2 bytes. How can it contain the exact data of 4 bytes I give it while only being 2 bytes? Here is the serial monitor of it. The first line is the printout of `data[]`, following the 4 bytes is the length which it claims is 2. The second line is the array of bytes `packet[]`. I set `packet[]` equal to `data[]` with this: `memcpy(packet, data, arraySize);`. Now you'll notice that the array size is correct. Interesting.

**Update #1:** It seems like this all has to do with pointers somehow. I guess `data[]` is just pointing to or referencing the array `ledOn[]`, and using `memcpy(packet, data, arraySize);` is actually copying the array `ledOn[]` to the array `packet[]`?

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

----------

**2)** I try to declare a random array (`byte rando[]`) using `int arrayLength` as the size. This does not work because the array size must be a constant. So I simply add `const int arrayLength` and that works. Great. So how am I able to do `byte packet[arraySize];`!? `ArraySize` is being passed `ledOn_len` which is not a constant, so how come that works?

----------

**3)** I need to be able to use the array `packet[]` inside of another function `void sendToXbee()`. `Packet[]` will be my final array of bytes to send to the Xbee containing either the array `ledOn[]` or `ledOff[]` which are different array lengths. As is, I cannot use `packet[]` in `void sendToXbee()` because `packet[]` is local to `void changeLed()`. But here's the catch 22: I cannot declare `packet[]` in the setup making it  global, because I don't have a size for that array yet!! The size of that array must be calculated within `void changeLed()`, depending on which array I need to send to the Xbee, `ledOn[]` or `ledOff[]`.

I know this is a lot but I'd appreciate the help! Thanks guys.

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

title: Passing arrays, global arrays within functions, pointers, and declaring array sizes

Answers: 1

body:
> Arduino requires arrays contain to a size. How can I declare byte data[] without a size?

You can't. Pure and simple. The compiler can infer a size from a declaration time assignment.

> Arrays sizes must be declared with a number, or a const integer. So how come I can declare byte packet[arraySize]; when arraySize is being passed the integer ledOn_len that isn't constant?

It is a feature of C99 which GCC have also included in C++.

> How can I create a global array within a function?

Simple: you can't.*

Ok. Now we've to that out of the way, let's look at what you *want* to do and how you should do it.

First off, you have a number of arrays of data:

    uint8_t ledOn[] = { 0x7E, 0xAA, 0x1C, 0x3B }; // turn led on
    uint8_t ledOff[] = { 0x7E, 0xAB, 0x1D }; // turn led off

Those arrays have an associated length, which is the size of the array divided by the size of one array entry:

    const int ledOn_len = sizeof(ledOn) / sizeof(ledOn[0]);
    const int ledOff_len = sizeof(ledOff) / sizeof(ledOff[0]);

At the moment you're getting away with just using `sizeof(ledOn)` because `sizeof(ledOn[0])` is 1. But if you ever do this with arrays of anything other than `byte` you will come unstuck unless you get into this habit.

Now, those arrays are just blocks of memory with a fixed size, in a fixed location.  That means that the arrays, as well as being arrays, are also *pointers*.  That is, they are in effect just variables that contain the address where the data for the array is stored.

So you pass the pointer to the array, along with the length of the array, to your function:

    void changeLed(const uint8_t *data, int len) {
    }

    changeLed(ledOn, ledOn_len);

When you have done is pass the address of the array to the function, not the array.

Now you can do things with that array data using that address. What you can't do is change the data (because I've marked it `const`).

One of the things you can do, though, is just send it.  You know where the data is. You know how long it is. You know where you want to send it to.

So you just do:

    void changeLed(const uint8_t *data, int len) {
        Xbee.write(data, len);
    }

That is, write `len` bytes starting at the address pointed to by `data`.

There is no need to have variable size arrays. There is no need to have global packet buffers. There is no need to copy any data anywhere with `memcpy()`. Just pass the data and send it.

If you need to send more data than just the content of your array, then just send it.  For example you may have to (I don't know the XBee protocol) add a header and footer to the packet.

    void changeLed(const uint8_t *data, int len) {
        Xbee.write(0x01);
        Xbee.write(0x02);
        Xbee.write(len & 0xFF);
        Xbee.write(data, len);
        uint8_t cs = 0;
        for (int i = 0; i < len; i++) {
            cs += data[i];
        }
        Xbee.write(cs);
    }

Just because they're not together in the same `write` function doesn't mean that they aren't "together".  With serial communication, there is no such thing as "together". It's just one byte after another.

> I need to be able to use the array packet[] inside of another function void sendToXbee(). Packet[] will be my final array of bytes to send to the Xbee containing either the array ledOn[] or ledOff[] which are different array lengths. As is, I cannot use packet[] in void sendToXbee() because packet[] is local to void changeLed(). But here's the catch 22: I cannot declare packet[] in the setup making it global, because I don't have a size for that array yet!! The size of that array must be calculated within void changeLed(), depending on which array I need to send to the Xbee, ledOn[] or ledOff[].

Why do you think you need to copy the data into a separate packet variable? You already have the data in a variable.

If you really want to do that, then just pass `packet` to the next function in the same way as you already pass your other arrays.

----
<sup>* Actually there are ways, using dynamic memory allocation, but I won't condone using that</sup>


body:
I am using the RFID module to read mifare NFC chips and the library has only methods to send the data to the serial monitor. I need them to be saved to an SD card file. I have been adding custom methods to the library files to return strings that I then write to the SD card but this is a pain; there must be a quicker way to simply pipe all the data automatically but I do not know how to do this in cpp.

Here is an example of the function to dump to serial, that needs to be piped to the file on the SD card.

    void MFRC522::PICC_DumpDetailsToSerial(Uid *uid) {
     Serial.print(F("Card UID:"));
     for (byte i = 0; i < uid->size; i++) {
      if(uid->uidByte[i] < 0x10)
       Serial.print(F(" 0"));
      else
       Serial.print(F(" "));
      Serial.print(uid->uidByte[i], HEX);
     }
     Serial.println();

     // SAK
     Serial.print(F("Card SAK: "));
     if(uid->sak < 0x10)
      Serial.print(F("0"));
     Serial.println(uid->sak, HEX);

     // (suggested) PICC type
     PICC_Type piccType = PICC_GetType(uid->sak);
     Serial.print(F("PICC type: "));
     Serial.println(PICC_GetTypeName(piccType));
    }

Thanks!

title: Pipe serial dump to SD card file

Answers: 1

body:
Have the MFRC522 objects remember where you want them to send the output
by adding a data member to the class like this:

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

    private:
        Print &output;

This is a reference to a `Print` object, i.e. any object where you can
`print()` or `println()` to. This reference should be initialized in the
constructor, like this

    MFRC522:MFRC522(...other arguments..., Print &my_output = Serial)
    : ...other initializations..., output(my_output)
    {
        ...constructor body...
    }

Notice that, by default, the `output` is initialiazed as a reference to
`Serial`. Thus, unless you explicitly ask for the output to go
elsewhere, the class will behave as before.

Last step is to change, in the implementation of the class, _every_
reference to `Serial` by `output`. This is just a global find and
replace.

At this point, the `MFRC522` class can be used exactly as before, and it
will behave identically. This means that _every_ user of the library
should be able to use your modified version with no issues. I thus
encourage you to submit the changes to the original author, so that they
have a chance to be incorporated into the canonical version of the
library.

Now, if you want this debugging output to be sent elsewhere, just
provide the destination as the last argument of the constructor:

    MFRC522 my_RFID_module(...other arguments..., my_SD_card_file);

As long as the destination is an instance of the `Print` virtual class
(basically anything you can `print()` to should be OK), it should work
as expected.


body:
    // each "event" (LED) gets their own tracking variable
    unsigned long previousMillisLED12=0;
    unsigned long previousMillisLED13=0;

    unsigned long previousMillisLED3=0;

    // different intervals for each LED
    int intervalLED12 = 500;
    int intervalLED13 = 5000;

    int intervalLED3 = 2000;

    // each LED gets a state varaible
    boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
    boolean LED12state = false;     // need to seed the light to be OFF

    void setup() {
       pinMode(13, OUTPUT);
       pinMode(12, OUTPUT);

       pinMode(3, OUTPUT);

    }
    void loop() {
       // get current time stamp
       // only need one for both if-statements
       unsigned long currentMillis = millis();

       // time to toggle LED on Pin 12?
       if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
          LED12state = !LED12state;
          digitalWrite(12, LED12state);
          // save current time to pin 12's previousMillis
          previousMillisLED12 = currentMillis;
       }

    // time to toggle LED on Pin 13?
      if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
          LED13state = !LED13state;
          digitalWrite(13, LED13state);
          // save current time to pin 13's previousMillis
          previousMillisLED13 = currentMillis;
      }
    }

My questions:

1. Didn't see the led12 and led13 have 10 times defferency, almost same intervals, why?

2. How can I use `millis()` as simple as delay?

3. Is that a must to use if?

title: millis() replace delay() question

Answers: 1

body:
Your Timing is working, you can test it with the Serial monitor. So your problem is at some other place. Using delay() is from my perspective not a good solution, you did it better the way you already made.

For testing your sketch I included the communication for the Serial Montior (I had to comment out the LED activation since this is working in a different way on my board, and I also made the intervalls Shorter to see better the effect within the test sketch). Here you find the necessary changes and the output of the Serial Monitor.

My recommendation is to look with a simple Sketch if you are able to switch on/off your LEDs sperately without Timing to come closer to your problem. I dont think it is the Timing/use of millis().

    #include <M5Stack.h> // needed for my board

    // each "event" (LED) gets their own tracking variable
    unsigned long previousMillisLED12 = 0;
    unsigned long previousMillisLED13 = 0;

    unsigned long previousMillisLED3 = 0;

    // different intervals for each LED
    int intervalLED12 = 50;
    int intervalLED13 = 500;

    int intervalLED3 = 2000;

    // each LED gets a state varaible
    boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
    boolean LED12state = false;     // need to seed the light to be OFF

    void setup() {
      Serial.begin(9600);
      //  pinMode(13, OUTPUT);
      //  pinMode(12, OUTPUT);
      //  pinMode(3, OUTPUT);
    }
    void loop() {
      // get current time stamp
      // only need one for both if-statements
      unsigned long currentMillis = millis();

      // time to toggle LED on Pin 12?
      if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
        LED12state = !LED12state;
        // digitalWrite(12, LED12state);
        // save current time to pin 12's previousMillis
        previousMillisLED12 = currentMillis;
      }

      // time to toggle LED on Pin 13?
      if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
        LED13state = !LED13state;
        // digitalWrite(13, LED13state);
        // save current time to pin 13's previousMillis
        previousMillisLED13 = currentMillis;
      }
      Serial.print("LED12: ");
      Serial.print(LED12state);
      Serial.print("  LED13: ");
      Serial.println(LED13state);

    }

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

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


body:
Am new to Arduino, wanted to know how to give motor direction to move and the duration of those movements. Goal is to move forward for say 5 seconds, turn left, move for 0.5 seconds, turn right, move for 5 seconds.

```
void loop() {
  //turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  analogWrite(ENA, 100);
  //turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  analogWrite(ENB, 100);
  delay(1000);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(5000);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  delay(500);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(500);

  analogWrite(ENA, 100); //speed 0 - 255
  analogWrite(ENB, 100); //speed 0 - 255
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(5000);
```

title: How do you move motor car forward for set amount of time and turning left/right

Answers: 0


body:
At the moment, I am engaged in a project in which I have to drive Epson LQ-310 printer with Arduino Mega ADK (USB Host). There is already a library  USB_Host_Shield_2.0 on Github which includes usb drivers for keyboard, flash drive etc. but not for a printer.

I am thinking to modify the current header files (adk.h and adk.cpp) based on Android drivers to suit for a printer. Do the things workout in this way?

Could anyone of you please suggest me the things to modify to achieve the required functionality?

Thank You

title: How to modify current driver files in USB_Host_Shield2.0 on github for Arduino Mega ADK USB driver for Epson LQ-310 printer?

Answers: 0


body:
How should I inherit from `Stream`, for creating a new class `MySerial` able to be initialized from a `Stream0` instance?.

The error so far is: `"cannot declare variable 'mySerial' to be of abstract type 'MySerial'"`.

If I make a class `MySerial` not inheriting, but adding a property `Stream`, everything works fine, except the new call mechanism for the `resend()` function, created to accept `Stream` instances.

EDIT: This is the edited code. Current error is: `"expected unqualified-id before '=' token"`.

*MySerial.h*
<!-- language-all: lang-cpp -->

    class MySerial:public Stream{
        private:
            int param;
        public:
      MySerial(){}; // OK
            MySerial(Stream &Serial0){MySerial=&Serial0} // Here is the question
            // Stream Implementation
            int available(){return available();}
            int read(){return read();}
            int peek(){return peek();}
            size_t write(uint8_t c){return write(c);}
            using Print::write;
    };

*MySerial.ino*

    #include <MySerial.h>
    #include <SoftwareSerial.h>

    SoftwareSerial swSerial(6,7);
    MySerial mySerial(swSerial);

    void setup(){}
    void loop(){
        if (mySerial.available()){
            c=mySerial.read();
            resend(mySerial,c);
        }
    }
    // This function should accept any Stream: SoftwareSerial, MySerial, Serial...
    void resend(Stream &Stream0, char c){
        Stream0.write(c);
    }

title: Create New Serial Class Inheriting from Stream

Answers: 1

body:
The `Stream` class has pure virtual methods which must be implemented in derived not abstract class.

The pure virtual method from base class `Print` is:

    virtual size_t write(uint8_t) = 0;

The pure virtual methods from `Stream` are:

    virtual int available() = 0;
    virtual int read() = 0;
    virtual int peek() = 0;

additionally add in your class the line

    using Print::write;

to pull in overloaded methods write(str) and write(buf, size) from`Print`

[Here][1] I have an example of a simple class derived from `Stream`.

----------

EDIT: Most of your question seemed to focus on wrapping some Stream implementation. Now I see that you maybe want to enhance the SoftwareSerial class and add a new method in the inherited class. It is simple:

MySerial.h

    #ifndef _MYSERIAL_H_
    #define _MYSERIAL_H_

    #include <SoftwareSerial.h>

    class MySerial: public SoftwareSerial {
    private:
      int param;

    public:

      MySerial(uint8_t receivePin, uint8_t transmitPin) :
          SoftwareSerial(receivePin, transmitPin, false) {
        param = 0;
      }

      void resend(char c) {
        write(c);
      }
    };
    #endif

MySerial.ino

    #include "MySerial.h"

    MySerial mySerial(6, 7);

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

    void loop() {
      if (mySerial.available()) {
        int c = mySerial.read();
        mySerial.resend(c);
      }
    }

  [1]: https://github.com/jandrassy/TelnetStream/blob/master/src/TelnetStream.h


body:
When I have tried interfacing my 16*2 LCD with Arduino I am getting only the black coloured boxes on my screen. What might be the problem?

Is there any solution to that? Do I need to connect any additional physical device to avoid that situation?

[product is here lcd display 16*2][1]

  [1]: http://uitechies.co.in/BBBcircuits/product.php?product=lcd-16x2-alphanumeric-display-jhd162a-8051-avr-arduino-pic-arm

title: I am getting blocks on my lcd screen 16*2

Answers: 1

body:
There are two possible problems, and you haven't stated which it is.

1. A single row of blocks (just the top row)

This is caused by either bad communication (wrong wiring) or incorrect code. Basically, the display isn't being initialized properly by your code for whatever reason.

2. Two rows of blocks (the entire display full of blocks)

The display is being initialized properly, so both your code and wiring are correct.  However, the contrast setting of the display is wrong. You need to check the wiring for your contrast potentiometer and adjust as necessary.


body:
i got an error
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

can [esp8266][1]anyone rectify this

  [1]: http://uitechies.co.in/BBBcircuits/product.php?product=serial-wi-fi-wireless-transceiver-module-iot-esp8266

title: i am getting an error while working with esp8266

Answers: 1

body:
oh i got the solution for the above question

it might be because i used TX AND RX pins of the arduino. what i observed is as tx and rx pins are for serial communication pin during the process of uploading i have to leave that pins disconnected.[arduino][1]

  [1]: http://uitechies.co.in/BBBcircuits/product.php?product=arduino-uno-r3-atmega328p


body:
I am trying to split an incoming string into 2 integer values since I have to control 2 dc motors with it. The processor is node MCU and I get following error:-

Com Port Reading:-

    WiFi connected
    Received: "84+62"
    "84+62"

    Soft WDT reset

    >>>stack>>>

    ctx: cont
    sp: 3ffffd90 end: 3fffffc0 offset: 01b0
    3fffff40:  2b343822 00223236 3ffee70c 40204148
    3fffff50:  3ffe85ee 3ffee6d8 3ffee70c 402043c5
    3fffff60:  3ffe85dc 3ffee70c 3ffee6d8 402043c5
    3fffff70:  3ffe85f0 3ffee69c 00000000 00000001
    3fffff80:  00000000 40200038 3ffefca4 0000000f
    3fffff90:  00000007 00000000 00000001 402048f9
    3fffffa0:  3fffdad0 00000000 3ffee744 40204984
    3fffffb0:  feefeffe feefeffe 3ffe851c 401009a5
    <<<stack<<<

     ets Jan  8 2013,rst cause:2, boot mode:(3,6)

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

Code:-

    if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
            char charBuf[50];
            msg.toCharArray(charBuf, 50);
            Serial.println(charBuf);

            char left[3] = {};
            char right[3] = {};
            int n = 0;

            while (charBuf != 0) {
              for (int i = 0; i < strlen(charBuf); i ++) {
                if (charBuf[i] != '+') {
                  left[n] += charBuf[i];
                  n++;
                }
                else {
                  n = 0;
                  break;
                }
                right[n] += charBuf[i];
                n++;
              }
            }
            Serial.println("Left Motor: "); Serial.print(left);
            Serial.println("Right Motor: "); Serial.print(right);

        }

My desired result is following:-

    Left Motor: 84
    Right Motor: 62

So what changes I need to make?

title: Not able to split string into 2 char

Answers: 3

body:
You get this memory leak because you overflow the variable `right`. This does not happen in the for loop itself even though this could be implemented more straight forward. But it's the while loop that doesn't come to an end (`charBuf` doesn't change and will not become 0) and in the second iteration `n` will be 1 initially (due to `n++` at the end of the for loop). That causes the overflow at `right[n] += charBuf[i];`.

So: remove the `while` loop (and use `strtok()`).

body:
> "84+62"

The additional doublequote characters are part of your string and charBuf

        Serial.println(charBuf);  // Text with " and  +

        char* cpl = nullptr;
        char* cpr = nullptr;
        for (char* cp = charBuf; *cp != 0; cp++) {
            if (*cp != '"' && ! cpl )  cpl = cp;
            if (*cp == '"') *cp = 0;
            if (*cp == '+' ) {
              *cp = 0; // split
              cpr = cp+1;
            }
        }
        Serial.println("Left Motor: "); Serial.println(atoi(cpl));
        Serial.println("Right Motor: "); Serial.print(atoi(cpr));

body:
Here's an example sketch that uses `strtok()`.

    char charBuf[] = "\"84+62\"";

    // Set array size to maximum number of integers you will receive.
    uint16_t myArray[2];

    void setup(){

      Serial.begin(9600);

      int counter = 0;
      char* pch = strtok(charBuf, "\"+");

      while(pch != NULL){
        myArray[counter] = atoi(pch);
        pch = strtok(NULL, "\"+");
        counter += 1;
      }

      // Print out the contents of the integer array.
      for(int i = 0; i < counter; i++){
        Serial.println(myArray[i]);
      }
    }

    void loop(){}

`myArray[0]` contains 84 and `myArray[1]` contains 62.


body:
can anybody assist me with a code? I am using arduino uno with adafruit v2 motor shield stacked on top. I am using a pushbutton and one DC motor and I want the state of the push button to change after it has been pushed for a few seconds. That is I want the motor to stop running even though the push button is still pushed down.

Here is the code I'm using:

        /*
    This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
    It won't work with v1.x motor shields! Only for the v2's with built in PWM
    control

    For use with the Adafruit Motor Shield v2
    ----> http://www.adafruit.com/products/1438
    */

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

    // Create the motor shield object with the default I2C address
    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    // Or, create it with a different I2C address (say for stacking)
    // Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

    // Select which 'port' M1, M2, M3 or M4. In this case, M1
    Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

    // You can also make another motor on port M2
    //Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

    // digital pin 2 has a pushbutton attached to it. Give it a name:
    int pushButton = 4;

    void setup() {
      Serial.begin(9600);           // set up Serial library at 9600 bps
      Serial.println("Adafruit Motorshield v2 - DC Motor test!");

      // make the pushbutton's pin an input:
      pinMode(pushButton, INPUT);

      AFMS.begin();  // create with the default frequency 1.6KHz
      //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

      // Set the speed to start, from 0 (off) to 255 (max speed)
      myMotor->setSpeed(150);
      myMotor->run(FORWARD);
      // turn on motor
      myMotor->run(RELEASE);

    }

    void loop() {
      uint8_t i;

        // read the input pin:
      int buttonState = digitalRead(pushButton);
      // print out the state of the button:
      Serial.println(buttonState);
      delay(0);        // delay in between reads for stability

      if (buttonState==1){
         delay(1000);

      myMotor->run(FORWARD);
        myMotor->setSpeed(150);
        delay(1000);

     }

     else if (buttonState==0){
      myMotor->run(FORWARD);
        myMotor->setSpeed(0);

      }

    }

title: Help with code for pushbutton connected to adafruit motorshield v2

Answers: 1

body:
You need to do various things:

You need to change your logic not to use delay. Search on "Arduino Blink Without Delay" to find examples of doing timed actions with `millis()` instead of using delay.

Then you need to adjust your logic to start running the motor when the user presses a button, and stop running the motor when either the user releases the button or enough time elapses.


body:
    #include <PulseSensorPlayground.h>
    #include <Timer.h>
    #include <SPI.h>
    #include <Ethernet.h>

    Timer t;
    PulseSensorPlayground pulseSensor;

    // Local Network Settings
    byte mac[] = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network
    // ThingSpeak Settings
    char thingSpeakAddress[] = "api.thingspeak.com";
    String writeAPIKey = "UVGOLIA40B9YHKU8";
    const int updateThingSpeakInterval = 16 * 1000; // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
    // Variable Setup
    const int PulseWire = A0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
    const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
    int Threshold = 550;           //for heart rate sensor
    float myTemp;
    int myBPM;
    String BPM;
    String temp;
    int error;
    int panic;
    int raw_myTemp;
    float Voltage;
    float tempC;

    long lastConnectionTime = 0;
    boolean lastConnected = false;
    int failedCounter = 0;
    // Initialize Arduino Ethernet Client
    EthernetClient client;
    void setup()
    {
      // Start Serial for debugging on the Serial Monitor
      Serial.begin(9600);
      pulseSensor.analogInput(PulseWire);
      pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
      pulseSensor.setThreshold(Threshold);

      // Double-check the "pulseSensor" object was created and "began" seeing a signal.
      if (pulseSensor.begin()) {
        Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
      }

      // Start Ethernet on Arduino
      void startEthernet();
    }
    void loop()
    {
      // Read value from Analog Input Pin 0
      String analogPin0 = String(analogRead(A0), DEC);
      // Print Update Response to Serial Monitor
      if (client.available())
      {
        char c = client.read();
        Serial.print(c);
      }
      //temp---
      raw_myTemp = analogRead(A1);
      Voltage = (raw_myTemp / 1023.0) * 5000; // 5000 to get millivots.
      tempC = Voltage * 0.1;
      Serial.println(tempC);

      //Serial.print(temp);
      //Serial.print(" ");

      //-----BMP180-----------
      //
      int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
      // "myBPM" hold this BPM value now.
      if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".

        Serial.println(myBPM);
        char buffer1[10];
        char buffer2[10];
        String BPM = dtostrf(myBPM, 4, 1, buffer1);
        String temp = dtostrf(tempC, 4, 1, buffer2);
        // Print the value inside of myBPM.
      }
    }
    //----------------
    void panic_button() {
      panic = digitalRead(8);
      if (panic == HIGH) {
        Serial.println(panic);
      }
    }
    // Disconnect from ThingSpeak
    if (!client.connected() && lastConnected)
    {
      Serial.println("...disconnected");
      Serial.println();
      client.stop();
    }
    // Update ThingSpeak
    if (!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
    {
      updateThingSpeak("field1=" + BPM + "&field2=" + temp + "&field3=" + panic);
    }
    // Check if Arduino Ethernet needs to be restarted
    if (failedCounter > 3 ) {
      startEthernet();
    }
    lastConnected = client.connected();
    }
    void updateThingSpeak(String tsData)
    {
      if (client.connect(thingSpeakAddress, 80))
      {
        client.print("POST /update HTTP/1.1\n");
        client.print("Host: api.thingspeak.com\n");
        client.print("Connection: close\n");
        client.print("X-THINGSPEAKAPIKEY: " + UVGOLIA40B9YHKU8 + "\n");
        client.print("Content-Type: application/x-www-form-urlencoded\n");
        client.print("Content-Length: ");
        client.print(tsData.length());
        client.print("\n\n");
        client.print(tsData);
        lastConnectionTime = millis();
        if (client.connected())
        {
          Serial.println("Connecting to ThingSpeak...");
          Serial.println();
          failedCounter = 0;
        }
        else
        {
          failedCounter++;
          Serial.println("Connection to ThingSpeak failed (" + String(failedCounter, DEC) + ")");
          Serial.println();
        }
      }
      else
      {
        failedCounter++;
        Serial.println("Connection to ThingSpeak Failed (" + String(failedCounter, DEC) + ")");
        Serial.println();
        lastConnectionTime = millis();
      }
    }
    void startEthernet()
    {
      client.stop();
      Serial.println("Connecting Arduino to network...");
      Serial.println();
      delay(1000);
      // Connect to network amd obtain an IP address using DHCP
      if (Ethernet.begin(mac) == 0)
      {
        Serial.println("DHCP Failed, reset Arduino to try again");
        Serial.println();
      }
      else
      {
        Serial.println("Arduino connected to network using DHCP");
        Serial.println();
      }
      delay(1000);
    }

title: expected unqualified-id before 'if' if (!client.connected() && lastConnected)

Answers: 1

body:
If you look at this fragment of your code:

    void panic_button(){
      panic = digitalRead(8);
        if(panic == HIGH){
        Serial.println(panic);
        }
    }
    // Disconnect from ThingSpeak
    if (!client.connected() && lastConnected)

You see that the function panic_button() stops at the last }, the next is a statement which is not part of a function.

I think the } should be removed, but your code is aligned quite badly, so:

- First align all { and }
- Indent each level with a tab or 2, 3 or 4 spaces
- You will see a misalignment, add/remove a { (like above) or }.