message:
My code isn't adjusting the speed of one of the motors and i'm not sure why

I'm trying to change the speed of motors depending on the amount of light hitting the LDRs. Here i'm trying to make it so that if the LDR has a high value than another, then the motor associated with that LDR slows down so it turns towards the light.

    const int motorDirectionA = 9;
    const int motorEnableA = 10;
    const int motorDirectionB = 5;
    const int motorEnableB = 6;

    const int leftLDR = A0;
    const int rightLDR = A1;

    int motorSpeedA = 250;
    int motorSpeedB = 250;

    void setup()
    {
      Serial.begin(9600);
      pinMode(motorDirectionA,OUTPUT);
      pinMode(motorEnableA, OUTPUT);
      pinMode(motorDirectionB,OUTPUT);
      pinMode(motorEnableB, OUTPUT);

      pinMode(leftLDR, INPUT);
      pinMode(rightLDR, INPUT);

    }

    void loop()
    {
      int ldrReadL = analogRead(leftLDR);
      int ldrReadR = analogRead(rightLDR);
      int leftLDRread = ldrReadL;
      int rightLDRread = ldrReadR;

      digitalWrite(motorDirectionA, LOW);
      analogWrite(motorEnableA, motorSpeedA);
      digitalWrite(motorDirectionB, HIGH);
      analogWrite(motorEnableB, motorSpeedB);

      Serial.print("Left LDR reading: ");
      Serial.println(ldrReadL);
      Serial.print("Right LDR reading: ");
      Serial.println(ldrReadR);

      if (leftLDRread > rightLDRread)
      {
        motorSpeedA = 80;
        motorSpeedB = 210;
      }
         else
         {
            motorSpeedA = 210;
            motorSpeedB = 210;
         }

      if (leftLDRread < rightLDRread)
      {
        motorSpeedB = 80;
        motorSpeedA = 210;
      }
          else
         {
           motorSpeedA = 210;
           motorSpeedB = 210;
         }
    }

@Maximillian Gerhardt If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.

If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

body:
>If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.
>
>If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

In code you would express this as

    void loop()
    {
     int ldrReadL = analogRead(leftLDR);
     int ldrReadR = analogRead(rightLDR);
     int leftLDRread = ldrReadL;
     int rightLDRread = ldrReadR;

     digitalWrite(motorDirectionA, LOW);
     analogWrite(motorEnableA, motorSpeedA);
     digitalWrite(motorDirectionB, HIGH);
     analogWrite(motorEnableB, motorSpeedB);

     Serial.print("Left LDR reading: ");
     Serial.println(ldrReadL);
     Serial.print("Right LDR reading: ");
     Serial.println(ldrReadR);

     //assuming motorSpeedA is the left motor
     // left > right
     if (leftLDRread > rightLDRread) {
      motorSpeedA = 80;
      motorSpeedB = 210;
     } else if( leftLDRread < rightLDRread ) {
      //left < right
      motorSpeedA = 210;
      motorSpeedB = 80;
     } else {
      // left == right
      motorSpeedA = 210;
      motorSpeedB = 210;
     }
    }

Also note that this is a quite primitive form of a PID controller. You want to respond to environmental influences in some kind of way, for which a PID is for.

You might find these videos interesting:

* https://www.youtube.com/watch?v=1pKJ-KcHZ8g
* https://www.youtube.com/watch?v=VVOi2dbtxC0

Edit: The code was fixed, a wrong variable was used (the pin number vs the read value)


sender: user

message:
FastLed LED Strip Output Checksum

I am wondering if anyone has ever connected the output of their LED strip back to the Arduino to read and make sure the strip is functioning correctly, kinda like checksum functionality.

I am using the FastLed library and it doesn't appear that this has been done.

The reason why I want to do this is because when an LED breaks on the strip, it causes all of the following LEDs to flicker wildly. I need to be able to shut the LED strip off immediately if it starts flickering because my device is being used as a visual therapy aid in a school.

I am using an Arduino Due with WS2812B LED strip.

sender: assistant

body: I don't think LED strips support this feature, however, probably there is a voltage reduction depending on how many LEDs are on. So you could check the voltage at the end of the strip, based on the LEDs which are on (assuming you store this) and compare the values.


body:
Look at timing on sheet 4 of the datasheet, and the times on sheet 3

A Low bit is 400 +/- 150nS wide Low followed by a 800 +/- 150nS wide High

A High bit is 850 +/- 150nS wide High follow by a 450nS wide Low.

To do what you suggest with a checksum, you'd have to send the checksum (minimum of 3 bytes to fake the data for an extra WS2812B for example) first, and see if the 24 bits were received correctly while at the same time the last 3 bytes were being sent out.

A Due might be fast enough to do that. I don't think a 16 MHz Arduino could.

Checking power level is not really feasible, as many strips get power attached to the beginning, middle, and end of a strip to ensure uniform brightness and to keep the strip's power traces from overheating from excess current flow.


message:
Can I simulate a clock without an RTC connected?

I want to program for a timer that works as set timer such as in an oven where user can set their own time. One of the way I know is using an IC(RTC) for the timer. However, I don't have the IC yet only the coding and Arduino.

Is it possible to simulate the Arduino code without having the RTC? Or is there any electrical component that I can use to replace the IC for the time being?
Thank you for your help and comment.I really appreciate that.

body:
There are programs to simulate Arduino code, but they are very limited. To really simulate the circuit the program would have to also know about the IC you are using. You didn't told us what IC this is, so we can only speculate, that it might not be something, that these programs know (though you can try it). And sometimes Arduino Simulators have problems with simulating time sensitive code. If you want to try, just google for Arduino Simulator and check out the possibilities. I cannot suggest one, since I didn't use one until now.

At this point it might be the better option to write time-keeping code using the `millis()` function, which returns the number of milliseconds since the Arduino started. Save a timestamp from when you started and compare the difference between `millis()` and your timestamp to the wanted bake time.

You can pack this code in extra functions, that can later be replaced by code managing the "timer IC". With dividing your code this way you can write the rest of the logic without bothering about the timing part (after writing the `millis()` part as a "dummy").

For an oven timer the accuracy of the Arduinos clock should be ok, since it doesn't really matter, if it is a few seconds off. And for testing and writing the first code version it is also sufficient.

---

If the IC you are referring  to is a RTC (Real Time Clock) module, the code for it should be pretty simple to write. There are libraries for the most common RTCs. You might want to try the [Arduino Time library][1].

  [1]: https://playground.arduino.cc/Code/Time


body:
TimeLib.h has a virtual clock that can be updated and corrected from multiple sources, including an RTC chip or an NTP server on the internet (assuming an internet connection).

It doesn't *need* that clock source, though, but it will drift with time. Once you have set the clock correctly it will keep close to the right time (assuming no reset or power loss of the Arduino). Not perfect (because the Arduino's main clock isn't perfect) but close enough for many simple applications.


message:
ESP8266 Led is not working

My led is not blinking, I have no idea why it's not working.
I am running it on "generic esp8266 module" plate.

     /*Blink

      Turns an LED on for one second, then off for one second, repeatedly.

      Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
      it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
      the correct LED pin independent of which board is used.
      If you want to know what pin the on-board LED is connected to on your Arduino
      model, check the Technical Specs of your board at:
      https://www.arduino.cc/en/Main/Products

      modified 8 May 2014
      by Scott Fitzgerald
      modified 2 Sep 2016
      by Arturo Guadalupi
      modified 8 Sep 2016
      by Colby Newman

      This example code is in the public domain.

      http://www.arduino.cc/en/Tutorial/Blink
    */

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(13, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }
My scheme
[![Scheme][1]][1]

Wifi module is working fine, but led is not working at all.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/FbZ0h.png
  [2]: https://i.stack.imgur.com/mbC3Q.png
Another sketch

    #include <ESP8266WiFi.h>
    #include <WiFiClientSecure.h>
    #include <UniversalTelegramBot.h>
    #include <Servo.h>
    // Initialize Wifi connection to the router
    char ssid[] = "---";     // your network SSID (name)
    char password[] = "---"; // your network key
    int tempsensorPin = 0;
    int lightsensorPin = 1;
    bool searchState = false;
    bool starting = false;
    bool lightState = false;
    Servo servo_test;
    // Initialize Telegram BOT
    #define BOTtoken "----"  // your Bot Token (Get from Botfather)

    WiFiClientSecure client;
    UniversalTelegramBot bot(BOTtoken, client);

    int Bot_mtbs = 1000; //mean time between scan messages
    long Bot_lasttime;   //last time messages' scan has been done

    void setup() {
      //servo_test.attach(8);
      Serial.begin(115200);

      // Set WiFi to station mode and disconnect from an AP if it was Previously
      // connected
      WiFi.mode(WIFI_STA);
      WiFi.disconnect();
      delay(100);

      // Attempt to connect to Wifi network:
      Serial.print("Connecting Wifi: ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);

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

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
      pinMode(13, OUTPUT);
    }

    void loop() {
     digitalWrite(13,lightState);
      if (millis() > Bot_lasttime + Bot_mtbs)  {
        int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

        while(numNewMessages) {
          Serial.println("got response");
          for (int i=0; i<numNewMessages; i++) {
            String id = bot.messages[i].chat_id;
            String text = bot.messages[i].text;

           //bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
            if(searchState){
              searchState=false;
              bot.sendMessage(bot.messages[i].chat_id, "http://lmgtfy.com/?q="+text, "");
            }else{
              bot.sendMessage(bot.messages[i].chat_id, answerMe(text), "");
            }
          }
          numNewMessages = bot.getUpdates(bot.last_message_received + 1);
        }

        Bot_lasttime = millis();
      }
    }
    String answerMe(String request){
     int tempSensor = analogRead(tempsensorPin);
     int lightSensor = analogRead(lightsensorPin);
     float voltage = tempSensor * 5.0;
     voltage /= 1024.0;
     Serial.print(voltage); Serial.println(" volts");
       float temperatureC = (voltage - 0.5) * 20 ;
     Serial.print(temperatureC); Serial.println(" degrees C");
     float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
     Serial.print(temperatureF); Serial.println(" degrees F");
     if(starting){
      if (request=="/temperatureF"){
        return "Current temperature is " + String(temperatureF) + " F";
      }
      if (request=="/temperatureC"){
        return "Current temperature is " + String(temperatureC) +" C";
      }
      if(request=="/lightIntensity"){
        return "Current light intensity is " + String(lightSensor);
      }
      if(request=="/lightON"){
        lightState=true;
        return "Current light state is true!";
      }
      if(request=="/lightOFF"){
        lightState=false;
        return "Current light state is false!";
      }
      if(request=="/lightDepend"){
        analogWrite(13,lightSensor);
        return "Here we go!";
      }
      if(request=="/google"){
        searchState=true;
        return "What you want to google?";
      }
      if(request=="close"){
        starting=false;
        servo_test.write(0);
        return "Bye bye!";
      }
    }else if(request=="/open"){
        starting=true;
        servo_test.write(90);
        return "What's next?";
    }else
        return "Open the box first!";

    }

body:
The esp8266 will not blink the LED on pin 13 or any other pin of the Uno. It has no access to pins of Uno. And your analogRead calls return some random values.

The RX to RX, TX to TX connection reduces the Uno to an "USB to Serial" adapter for the esp8266. You upload the Blink to esp8266. If the Blink sketch would have the original LED_BUILTIN pin number, then the LED on the esp8266 module would perhaps blink.

After you changed the connection RX to TX and TX to RX, you can't upload to esp8266 because the esp8266 is not anymore connected to PC over USB.

If you want to read and write the pins of Uno from esp8266, use ConfigurableFirmata sketch in Uno and [FirmataMaster library][1] in esp8266.

Other option is to write your own sketch for Uno and handle the communication between esp8266 and Uno over Serial.

Or you can use the esp8266 as network adapter with some firmware (AT firmware or WiFi Link) and port your sketch to Uno.

  [1]: https://github.com/gmag11/FirmataMaster/blob/master/Readme.md


message:
attiny85: ISR not triggering for PCINT2?

I am using an attiny85 to read the fan speed reported by a pair of 4-wire fans. I had planned to attach the TACH output from the fans to pins 1 and 2, but I ran into a problem: I was able to handle interrupts on pin 1 without a problem, but I can't get the ISR to trigger for changes on pin 2.  Code demonstrating the problem looks like this:

    #define PIN_LED 0
    #define PIN_TACH2 2

    void setup() {
      cli();
      pinMode(PIN_TACH2, INPUT_PULLUP);
      pinMode(PIN_LED, OUTPUT);

      GIMSK |= _BV(PCIE);
      PCMSK |= _BV(digitalPinToPCMSKbit(PIN_TACH2));
      sei();
    }

    void loop() {
      digitalWrite(PIN_LED, 1);
      delay(2000);
    }

    ISR(PCINT0_vect) {
      byte tach2;

      tach2 = (PINB & _BV(PIN_TACH2));

      if (! tach2) {
        digitalWrite(PIN_LED, 0);
      }
    }

If I replace the definitions of `PIN_TACH2` and `PIN_TACH2_INT` with
pin 1, such as...

    #define PIN_TACH2 1
    #define PIN_TACH2_INT PCINT1

...it works just fine (interrupts also works for pins 0 and 3).

Why can't I handle pin change interrupts for pin 2?

**for @chrisl**

This is just testing code. The LED remains on until the ISR fires, at which point it will go out for up to 2 seconds.  With interrupts attached to pins 1 or 3, it works as expected: a falling edge on the pin causes the LED to go off.

On pin 2, the ISR never triggers.

body:
So, it turns out that it was a really stupid problem and entirely my fault, but I'm going to leave this question here in the hopes that it will prevent someone else from running into the same issue.

The answer is...

**DISCONNECT THE PROGRAMMER BEFORE TESTING YOUR SKETCH**

That's it.  With the programmer disconnected, it all behaves as expected.


message:
Can I switch from Serial to SoftwareSerial at runtime with the same baud?

I'm trying to use a GPS and the Adafruit thermal printer module with an Arduino Nano in the same project (both use baud 9600) and was wondering if I could do something like in the code below? Basically, in the example I made, I'm getting the time from the GPS and when it's on the minute, it will call the `printTime()` method.

What I'm wondering is if it's okay to do what I did in my `disableGPS`, `enablePrinter` methods by ending the serial connection for GPS and starting it for my printer? I feel like this should work, but I don't fully understand serial connections.

If this doesn't work, is there an alternative I could do? I never need to read from GPS and write to the printer at the same time in code.

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

    #include <Adafruit_Thermal.h>
    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    #define PrinterTXPin 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
    #define PrinterRXPin 5 // Arduino receive   GREEN WIRE   labeled TX on printer

    static const uint32_t baud = 9600;
    //Printer
    SoftwareSerial PrinterSerial(PrinterRXPin, PrinterTXPin);
    Adafruit_Thermal printer(&PrinterSerial);
    //we only want to print on the minute
    boolean havePrinted = false;

    //GPS
    TinyGPSPlus gps;
    TinyGPSDate lastDate;

    void setup() {
      enableGPS();
    }

    void loop()
    {
      if(gps.time.isValid() && checkDate(gps.time)){
        printTime(gps.time);
      }
    }

    boolean checkDate(TinyGPSTime theTime)
    {
     if(theTime.second() == 0 && !havePrinted)
     {
        havePrinted = true;
        return true;
     }
     if(theTime.second() == 1){
        havePrinted = false;
     }
    }

    void printTime(TinyGPSTime theTime)
    {
      //Disable since we can only have 1 serial connection per baud
      disableGPS();
      enablePrinter();

      printer.doubleHeightOn();
      printer.println(theTime.hour() + ":" + theTime.minute());
      printer.feed(1);

      disablePrinter();
      enableGPS();
    }

    void enablePrinter()
    {

      PrinterSerial.begin();
      printer.begin();
      printer.wake();
    }

    void disablePrinter()
    {
      printer.sleep();
      PrinterSerial.end();
    }

    void disableGPS()
    {
      Serial.end();
    }

    void enableGPS()
    {
      Serial.begin(baud);
    }

body: I think you are missing what the baud rate is.  It is the speed at which the data is transmitted.   So the fact that your two devices are the same is not an issue.   It looks like from the code that your gps is connected to the hardware serial(pins 0,1 on uno) and the printer is on a software serial( pins 5,6)   If this is the case, there is no reason to turn off either of them, they can both work. In the case of using multiple SOFTWARE serial connections, only one can be 'listening' at any time, so you must switch between them. This is not the case in your code, as there is only one software serial connection.


message:
Power consumption for arduino

I am using an Arduino SMD UNO r3 board ,and connecting thermal sensor MLX 90614 , wifi modem ESP 8266 , a buzzer and an arduino based sound sensor .
How much power distribution will it require ?
What should be the capacity of the battery ?

body:
You need to create a power budget. This means pouring through the datasheets of each component and finding the max and nominal current consumption info and then summing it up. From this, you should be able to come up with a battery capacity value.

There is a [great article called "What is a Power Budget"][1] written by Chris Gammell (from [The Amp Hour][2]) that goes into power budgets in more detail. Here are the key items from that page:

> So what is a power budget? Much like a budget you might have for your personal finances, a power budget shows where all the possible power will be used by a device to by breaking it down into components and categories.
>
> As you can see, not much more is required than your datasheets and a spreadsheet type program. ... The first two columns (A&B) are simply identifiers to allow you to recognize which components correspond to which set of data. The next two columns (C&D) determine the multiplicative factor. If you have 5 components that contain 4 op amps per, then that will consume 20x the power of a device that has the same supply current needs but only one op amp per and there is only one on the board.  The next two columns (E&F) show how much current each individual component contributes and then the sum of all the components of that type contribute. Note that this parameter on a data sheet would be listed as “supply current” or “active current”. The “quiescient” number is when the device is in a resting state and will likely be much less than the active number (and not relevant for this example). Finally, the supply voltage is listed (in column G) to calculate power (using the formula P=I*V) which is listed in column I per device. All of these contributors are summed, an efficiency is estimated (I assumed a poor efficiency linear type supply) and the total power required input to the device is given. Further calculations could result from much of this initial data.

  [1]: http://chrisgammell.com/what-is-a-power-budget/
  [2]: https://theamphour.com/


message:
Will Nodemcu support 4AAA

batteries which is 6v approx, or should i go with 3AAA batteries which is 4.5V approx. And one more question , is it ok to use AA instead of AAA ?

body:
Yes, yes and yes.

> Will Nodemcu support 4AAA batteries which is 6v approx

Yes, it will. However there is no back-powering protection on the USB, so having that connected whilst the board is connected to your computer could potentially damage your computer's USB port. That's why VIN's label was changed to 5V on the newer boards.

> or should i go with 3AAA batteries which is 4.5V approx.

Yes, you should. Not only does that mean your USB port won't die, but you're not wasting as much power. The NodeMCU employs a linear "LDO" regulator to get 3.3V from the incoming power source. That means that the voltage difference between incoming power and 3.3V is thrown away as heat. The higher the incoming voltage the more heat is generated to discard that voltage.  Using a lower voltage, therefore, means that you don't waste as much. That fourth battery is doing absolutely nothing towards powering your project and is just being used to generate more heat.  One thing to note though is that 5V coming in from USB could try and charge your 3xAAA batteries. If they're not rechargeable then they could cause problems (overheat, leak, cause a fire, etc).  Adding a schottky diode in series with them would protect them from that.

> is it ok to use AA instead of AAA ?

Yes. Your project will last longer before you need to replace the batteries, since AA batteries have a higher mAh capacity than AAA.


message:
General confusion about how to start

I want to test around with my ESP32 and an E-Paper display - yet i am stuck at uploading sketches via Arduino IDE. I get those kind of errors:

    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48

and looking into tools,i dont even see my board there - i bought it on amazon and the article just says "ILS - LOLIN32 Lite V1.0.0 Wifi and Bluetooth Board with ESP-32 Rev1 MicroPython 4MB FLASH".

What am i missing here? I am 99% sure i got the pins correct (finally), i got the USB-Serial driver, i got the right port - yet even a simple test sketch i found on the internet didnt work.

body:
The Arduino IDE does not have a core for the ESP32 installed by default.

The problem was solved by explicitly installing the [ESP32-Arduino Core][1] in the Arduino IDE according to their manuals

* https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/windows.md
* https://www.smart-prototyping.com/blog/How to Install-ESP32-Core-Arduino-IDE

  [1]: https://github.com/espressif/arduino-esp32


message:
Share I2C pins with other device when lacking GPIOs

We're Using [`ESP12E`][1] as our `MCU` and we have three functionality :

* `SIM800` connected to TX(GPIO1), RX(GPIO3)
* `Matrix Keypad` connected to `GPIOs: 14,13,2,10,0,4,5,16`
* `GLCD` connected to `GPIOs: 15,12`

And we also need to communicate with an `RTC(DS3231)` module via `I2C` bus!

So i'm wonder how we could do this?

Is it possible to share `I2C` pins with any other pins ?

And BTW for some reason we can't use IO expander such as `PCF8574`

  [1]: https://potentiallabs.com/cart/image/cache/catalog/ESP8266/ESP12E_Pinouts-800x800.jpg

body:
Since you already want to use I2C it makes sense to move other things onto that same I2C bus to save IO pins.  And even off-load processing.

For instance, you could move your keypad to a dedicated matrix keypad interface chip, such as the MAX7365 (probably overkill for a small keypad), or a general I2C GPIO IO expander, such as the MCP23017.


body:
We found `74C922` at long last! without any other choices.

A cheap, available, reliable and easy setup `IC`.

The simple schematic we use:

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

[here][2] is a good topic to start with

  [1]: https://i.stack.imgur.com/LpOdK.png
  [2]: http://www.instructables.com/id/16-key-Keypad-Decoding-with-an-AVR-MCU/


message:
How to set sampling rate for digital pin input?

I have an ADC that have sampling rate up to 40 MSPS, but i use 8 MHz clock so it will be 8 MSPS. The board used is arduino nano. The problem is i have to sampling it just 2 MHz (because the capacity of array variable in arduino Nano, which is around 10.000 elements in array variable). I know that using direct port reading will increase the speed of the digital read, but how can i set the direct port reading to just read every 0.5 us? Micros function cannot do the job of course

Thank you

body:
You need:

1. A timer
2. A board that is capable of running fast enough to do what you want.

The Nano fits the first criteria, but not the second.

At 16MHz you get a clock period of 63ns.  That means you get a mere 8 clock ticks (actually gives you 504ns) per interruption from the timer. That's *at most* 8 assembly instructions that can be executed within that time.

Since an interrupt service routine's preamble is longer than 7 instructions you can see there would be a slight problem there.  No time for actually reading a digital IO port - and if you are using a serial protocol to communicate with your ADC you can multiply the reading time by the double the number of bits you need to read. That's a *long* time compared to 500ns.

So no. Think again. Use a more suitable board. Maybe an ARM based board (like the Teensy 3.x) would be a better fit.


body:
**Note**: this is an attempt to answer the question as asked. This
answer is unlikely to be of any use to the original poster, who
presumably asked the wrong question. I am writing this only as a way to
explore the limits on how fast a modest AVR can sample a port. For an
answer that genuinely attempts to address the OP’s problem, see
Majenko’s answer.

I read the question as follows: can we sample a digital port at
2 MHz on an Arduino Nano clocked at 8 MHz? Can we do so while
storing the values in a RAM-based buffer?

The answer is yes, but it is non trivial, and it requires some assembly.
To see the problem, let’s start by trying to do it in C++:

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

    uint8_t buffer[1024];

    void fill_buffer()
    {
        cli();
        for (size_t i = 0; i < sizeof buffer; i++)
            buffer[i] = PINB;
        sei();
    }

Note that the loop runs with interrupts disabled, otherwise the timer
interrupt would wreak havoc with the loop timing. This is translated by
gcc into an assembly equivalent to this:

<!-- language: lang-none -->

        cli
        ldi  r30, lo8(buffer)      ; load the buffer address into pointer Z
        ldi  r31, hi8(buffer)      ; ditto
    0:  in   r24, 0x03             ; read the port
        st   Z+,  r24              ; store into buffer, increment the pointer
        ldi  r24, hi8(buffer+1024) ; save (buffer+1024)>>8 in r24
        cpi  r30, lo8(buffer+1024) ; compare the pointer with buffer+1024
        cpc  r31, r24              ; ditto
        brne 0b                    ; loop back
        sei
        ret

The loop takes 8 cycles per iteration. With an 8 MHz clock, that
would be one reading per microsecond. Too slow by a factor two.

One could save one cycle by using a different register for the port data
and for the end-of-loop condition, and by moving the third `ldi` out of
the loop. Another cycle could be saved by testing only the high byte of
the Z pointer, but that would require aligning the buffer to
256 byte boundaries. With those two optimizations, we still need
6 CPU cycles per iteration, i.e. 0.75 µs at 8 MHz.

In order to make this faster, the only solution is to unroll the loop.
This can be done in assembly by using the `.rept` (meaning “repeat”)
directive:

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

    void fill_buffer()
    {
        cli();
        asm volatile(
            ".rept %[count]\n"  // repeat (count) times:
            "in r0, %[pin]\n"   //   read the port input register
            "st Z+, r0\n"       //   store in RAM
            "nop\n"             //   1 cycle delay
            ".endr"
            ::      "z" (buffer),
            [count] "i" (sizeof buffer),
            [pin]   "I" (_SFR_IO_ADDR(PINB))
            : "r0"
        );
        sei();
    }

This takes 4 cycles, or 0.5 µs per iteration. Note that a
delay cycle had to be introduced, otherwise the sampling would be too
fast : 3 cycles, or 0.375 µs, per iteration.

This is not the fastest one can get. It is possible to take one sample
per CPU cycle with something like this:

<!-- language: lang-none -->

        in r0, 0x03
        in r1, 0x03
        in r2, 0x03
        ...

However this technique is limited to burst readings of at most
32 samples.


message:
Arduino HTTPClient passing string to variable

For some reason I can't seem to pass a simple string from one variable to another. Below is my code:

      HTTPClient http; // Declare an object of class HTTPClient
      http.begin(address); // Specify request destination
      int httpCode = http.GET(); // Send the request

      Serial.println("String: " + http.getString());

      String prp = http.getString();
      Serial.println("temp string: " + prp);

It prints out:

> String: < ! DOCTYPE HTML>
> 26
>
> temp string:

Why doesnt my string get correctly passed on to my temporary string variable?

Tom

body: The getString() method calls `writeToStream` which is documented `write all  message body / payload to Stream`. It writes all the data of the http response to he output and doesn't store them internally. The next call has nothing to read because the first call to getString() put everything out.


message:
Avrdude verification error

I use an Arduino UNO with IDE 1.8.5 and for the last few days it doesn't let me upload any code. When I try, it pops up with the following error:

    avrdude: verification error, first mismatch at byte 0x0042
             0x65 != 0x8d
    avrdude: verification error; content mismatch
    avrdude: verification error; content mismatch

I really don't know what happened it used to work perfectly well. I even tried to upload blank code with nothing wired on and still the same error appears. I also tried with another USB cable, another PC, an older Arduino IDE but still nothing happens.
Any ideas ??

After checking so verbose output during compilation& upload it shows this:

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\kat_t\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\kat_t\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\kat_t\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827 -warnings=none -build-cache C:\Users\kat_t\AppData\Local\Temp\arduino_cache_621253 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.1.1 -prefs=runtime.tools.avrdude.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2 -verbose C:\Users\kat_t\AppData\Local\Temp\untitled1895278478.tmp\sketch_may18b\sketch_may18b.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\kat_t\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\kat_t\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\kat_t\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827 -warnings=none -build-cache C:\Users\kat_t\AppData\Local\Temp\arduino_cache_621253 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.1.1 -prefs=runtime.tools.avrdude.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2 -verbose C:\Users\kat_t\AppData\Local\Temp\untitled1895278478.tmp\sketch_may18b\sketch_may18b.ino
    Using board 'uno' from platform in folder: C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21
    Using core 'arduino' from platform in folder: C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21
    Detecting libraries used...
    "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "nul"
    Generating function prototypes...
    "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\preproc\ctags_target_for_gcc_minus_e.cpp"
    "C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\preproc\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using precompiled core
    Linking everything together...
    "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp.o" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/..\arduino_cache_621253\core\core_arduino_avr_uno_7e7efc521bfa236d1e5438b10f2a9ebf.a" "-LC:\Users\kat_t\AppData\Local\Temp\arduino_build_834827" -lm
    "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.eep"
    "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex"
    Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/bin/avrdude -CC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino
             Hardware Version: 3
             Firmware Version: 4.4
             Vtarget         : 0.3 V
             Varef           : 0.3 V
             Oscillator      : 28.800 kHz
             SCK period      : 3.3 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.01s

    avrdude: Device signature = 0x1e950f (probably m328p)
    avrdude: reading input file "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex"
    avrdude: writing flash (444 bytes):

    Writing | ################################################## | 100% 0.06s

    avrdude: 444 bytes of flash written
    avrdude: verifying flash memory against C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:
    avrdude: load data flash data from input file C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:
    avrdude: input file C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex contains 444 bytes
    avrdude: reading on-chip flash data:

    An error occurred while uploading the sketch
    Reading | ################################################## | 100% 0.06s

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x0002
             0x6b != 0x34
    avrdude: verification error; content mismatch

    avrdude done.  Thank you.

body:
I feel there is an issue with the bootloader that you are using with your Arduino, or maybe there is a fuse bit error.

Do you have a programmer with you, such as the usbtiny or the usbasp. IF you have another Arduino which works, than you can use it as a programmer as well.
Read up about it here

https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

Connect the programmer to the Arduino Board, and your computer.

Go to tools, select the Arduino board.
 Then tools>programmers>select the programmer you are using.
Then tools>burn bootloader.

This will fix any fuse bit issues, while also uploading a fresh version of the Bootloader which works with your Arduino IDE.

I hope this helps.


message:
Line following robot problems

I am making line following robot using Arduino Uno but every time I connect everything together and upload the code and put the sensors on the line the motor does not work can anyone help me?

I use an L298n motor and Arduino Uno. This is the circuit diagram i am using:

![Motor circuit][1]

And this is the code:

    // First the line following (IR) sensors
    const int irLeft = 2; //Left line sensor is on pin A2
    const int irRight = 3; //Right line sensor is on pin A3

    //Motor A (Right)
    int enableA = 11;
    int pinA1 = 10;
    int pinA2 = 9;

    //Motor B (Left)
    int enableB = 7;
    int pinB1 = 6;
    int pinB2 = 5;
    //Define Run variable
    boolean run;
    void setup() {
    pinMode(enableA, OUTPUT);
    pinMode(pinA1, OUTPUT);
    pinMode(pinA2, OUTPUT);
    pinMode(enableB, OUTPUT);
    pinMode(pinB1, OUTPUT);
    pinMode(pinB2, OUTPUT);
    }
    void loop(){
      int valleft= analogRead(irLeft);
       int leftsensor = analogRead(A2);  //in the side of motor B
      int rightsensor = analogRead(A3);  //in the side of motor A

       if ((leftsensor >= 700) && (rightsensor >= 700))
         forward();
            else if((leftsensor <= 150) && (rightsensor <= 150))
         backward();
         else if((leftsensor <= 150) && (rightsensor >= 700))
         turnright();
         else if((leftsensor >= 700) && (rightsensor <= 150))
         turnleft();
    }
    //Motors Foward
    void forward(){
      digitalWrite(pinA1,HIGH);
      digitalWrite(pinA2,LOW);
      digitalWrite(pinB1,HIGH);
      digitalWrite(pinB2,LOW);
    }
    // Motors Backward
    void backward(){
      digitalWrite(pinA1,LOW);
      digitalWrite(pinA2,HIGH);
      digitalWrite(pinB1,LOW);
      digitalWrite(pinB2,HIGH);
    }
    // turn left
    void turnleft(){
      digitalWrite(pinA1,HIGH);
      digitalWrite(pinA2,LOW);
      digitalWrite(pinB1,LOW);
      digitalWrite(pinB2,HIGH);
    }
    // turn right
    void turnright(){
      digitalWrite(pinA1,LOW);
      digitalWrite(pinA2,HIGH);
      digitalWrite(pinB1,HIGH);
      digitalWrite(pinB2,LOW);
    }

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

body:
Wire, write and debug just one part of your project at a time.

 - Can you just run a motor?
 - Can you run it in either direction?
 - Can this code do the same for *either* motor?
 - Can you run two motors?
 - Can you set either of them to run forward, reverse, or to
   stop, independently of each other?

Then the sensors (forget the motors for now):

 - Can you read the right sensor and detect light or dark?
 - Can you adapt the code to read either sensor?

Then using the above pieces and knowledge:

 - Can you make one of the motors run or stop in response to one of the sensors?

Now you have enough pieces - *known working!* - to reassemble them into a device that uses sensors and motors to navigate. If it fails at this point, there's a whole lot you *don't have to debug*, and you can concentrate on whatever you haven't tested yet - your navigation algorithm, any rewiring you've done since you tested each part, and whether you've included the final known-working pieces from your tests, e.g., you used all of the latest and greatest bits of code you developed above.


message:
What is the output of A0 - A5?

I'm new to Arduino Uno, When I run this piece of code, I get numbers 340 to 370.

This is my question, why it returns 340 to 370 which correspond to 1.66 to 1.80 actual voltage? since I don't have any input equipment plugged into these pins so it must return zero voltage if i'm right in other words why default values in these pins are in this range of numbers ?

    void loop() {
    int val = analogRead(A0) ; //A1, A2 ...
    Serial.println(val) ;

    }

body:
You will get varying values on each read. A pin’s input is said to be floating if nothing is connected, which in simple terms can be explained as it just acting as an antenna for whatever electric noise is present in your environment. Its state is unknown, and utterly meaningless. If you hold a spinning electric motor close to the pin, you can see the values rise and fall more clearly.

Use a high value (10K or more) pull-down or pull-up resistor to partially mitigate this jitter. A pull-down would bring the read value down to around 0, and a pull-up would bring it up to around 1023.

Furthermore, it’s a good idea to always smoothen out analogRead (5-10 reads, ~25-50ms apart, average the values out) to get a good reading if precision is important. This is especially valid if you use longer wires, have an unshielded case, or use a switched mode power supply. Twisting the wires (GND and wiper IIRC, otherwise correct me) to a potentiometer helps.

Edit: You can use `pinMode( A0, INPUT_PULLUP );` - it provides a 20-50Kohm pull-up, though I don’t trust this and always use 1/4W resistors instead. It saves space though, and is quite handy.


message:
Arduino reading value from external devices on

For [this device][1] it says:

*The PC Interface Option has all the features of the standard DC1100, but also has a COM Port interface that allows you to capture the air quality data to a PC for graphing and analysis. A 9pin serial cable or USB-to-COM Port Adapter (not included) links the DC1100 to your PC or laptop which then captures the data as it samples.*

Is it possible to connect such a device directly to an Arduino so that measured data are sent through the Serial Interface and Arduino is able to read them and manipulate them?

  [1]: http://www.dylosproducts.com/dcairqumowip.html

body:
Yes, with a small converter board it can be connected to an Arduino. The "[9 pin serial cable][1]" is very likely an RS-232 interface.

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

RS-232 is like UART with a few extra connections. Here is what the cable looks like:

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

Basically UART with flow control and other modem lines. Most likely it hasn't any of them conencted but that standard RXD, TXD and GND. These are all the connections needed for the microcontroller.

The voltage level of RS232 is however specified in a wide range ([plus/minus 3V to 25V][4]), so you need a converter chip (e.g. [this one](https://www.ebay.com/itm/1pc-RS232-to-TTL-Converter-Board-Serial-Module-3-3V-5-5V-MAX3232-for-Arduino/311620589193?hash=item488e08d689:g:McoAAOSwgsxaWsLI) with a MAX3232, search for "RS232 to TTL Converter Board"). You need to measure the voltage levels with a multimeter to see what converter for what voltage rage you need.

[![enter image description here][5]][5]

Then conencting it to an Arduino is as simple as just connecting these 3 wires to the Arduino, either to the Hardware Serial port (D0, D1, GND) or via a software serial port.

Reference project:

* http://www.picprojects.net/rs232_communication/

However, receiving the communication data is only half the battle. You still have to figure out what the sent data represents and what commands you can send the device. Without datasheets from the vendor, you are left alone. This is where reverse-engineering starts.

As a starting point, you can "eaves-drop" on the communucation that PC software does with the device by just connecting a USB-RS232 converter to your computer and connecting the RX line line to either the TX or RX line of the the target device's COM port. This allows you to see the entire communication exchange. From this you might be able to see what commands you're supposed to send. But as I said, from there it's unchartered territory.

  [1]: https://en.wikipedia.org/wiki/Serial_cable
  [2]: https://i.stack.imgur.com/6o3RD.png
  [3]: https://i.stack.imgur.com/vvQY4.jpg
  [4]: https://www.electronics-notes.com/articles/connectivity/serial-data-communications/rs232-signal-voltage-levels.php
  [5]: https://i.stack.imgur.com/6p2sG.jpg


message:
How to connect a 240x320 37-pin TFT to an Arduino Nano?

I have an old TFT display (extracted from an MP5 player) and I can't figure out how to connect it with an arduino nano, pls help.
here's the datasheet of the TFT:
http://read.pudn.com/downloads137/sourcecode/embed/586271/Varitronix-2.8-lcd/vl-ps-cog-t280mbqi-041.pdf
Thank you.

body:
The Nano isn't a good choice for driving that screen. You need almost all the pins of the Nano to connect to the screen alone, and there's not enough to include the touch-screen as well. And that's when you're *not* using the serial port of the Arduino (TX/RX pins) for communication with the PC.

You need to connect:

* 16 data pins
* /CS pin
* /RS pin
* /WR pin
* Optionally RD pin, or tie it to 3.3V
* /RESET pin

And all those need to be level shifted to 3.3V.

You need to provide 3.3V to VCC1/2 and VCI.  The LED A connects to 5V (since it has more current capacity than the 3.3V) and each LED Kx pin through a suitable resistor (220Ω maybe) to ground.

The touchscreen needs the X- and Y- pins connecting to a digital IO pin, and the X+ and Y+ pins to analog IO pins that can also double as digital IO pins (so not A6/A7 on boards that have them).

And then you need to obtain or write the software to drive the ILI9320 through the 16-bit interface.

Driving the interface is simple enough:

Initially:

1. Set /CS HIGH
2. Set /WR HIGH
3. Set /RD HIGH (if not tied to 3.3V)
4. Set /RESET HIGH
5. Short delay
6. Set /RESET LOW
7. Short delay
7. Set /RESET HIGH

Then to transfer a group of 16-bit words:

1. Set /CS LOW
2. Set the value to write on the 16 data pins
3. Pulse /WR LOW then HIGH
4. Repeat from 2 for each word
5. Set /CS HIGH

Refer to the ILI9320 datasheet for how to control the chip, or use existing library code (does uTFT or u8glib support it?).

For the touch screen it's a case of setting Y- LOW and Y+ HIGH, and X- and X+ to INPUT, then reading the analog value from X+.  Repeat with X- set LOW and X+ set HIGH, and both Y set to INPUT, and read the analog value from Y+.

You can also get better results by reading multiple inverted settings:

* Y- = LOW, Y+ = HIGH, X- = INPUT, Read X+.
* Y- = HIGH, Y- = LOW, X- = INPUT, Read X+.
* Subtract the second reading from 1023
* Add the first and (modified) second reading
* Divide by two.
* Repeat for X-/X+ reading from Y+.

You can also take multiple readings and average them out to reduce noise and stabilise the output somewhat.

And of course on top of all that you need to find a way to connect to a 0.5mm pitch connector. Normally a 0.5mm pitch FPC socket is used, which means a PCB with one on.  You may be able to find 37 pin adaptor for it, but 37 pins isn't a common format.  Normally 50 pin is more common to accommodate a more general purpose interface including the M0-M2 pins that allow you to select the interface type, as well as an 18-bit data bus to allow full RGB6/6/6 interfacing, and even buffer-less clocking of raw display data for very high speed display updates by MCUs that support such an interface.


message:
Arduino Nano /Uno USB is not getting recognized

I have multiple Unos and Nano and recently due to some bad configuration the USBs are not getting recognised on my Mac Air Laptop. These were working models for almost 1-2 years. I used it to control motors and something must have happened and it stopped.

But strangely the small boot up LEDs on the Nano/Uno light up when connected so it seems that the connection from the laptop USB to the device is good - but the driver ports are not showing up on the Arduino IDE.
How do I go about resolving that it is not just a software issue and is a hardware issue ?

I reinstalled the CH340G driver.img and yet the device when plugged in - does not show the USB port on the IDE ?
Any thoughts or ideas on how to resolve this.

The Uno/Nano are Chinese Clones and have CH340 chipset on them.
Is there some firmware that may have gone wrong and can be reset ? or new boot loader that can be burnt to bring them back to life.

I want to be able to see the Tools-> Port -> /dev/cu.usbserial1410
and also be able to see /dev/cu.usbserial on the command xterm prompt .

body: Assuming that the atmega328p still works fine, you can still use the Nano. I have solved this a few times by just using a FTDI breakout board (remember to set it to 5V, though 3V3 upload works on a Nano), and connecting RX to TX, TX to RX. Press reset before each upload.


message:
arduino, exit status 1. can't compile to arduino uno

#include <LedControl.h>

    void setup() {
    // put your setup code here, to run once:

    }

    void loop() {
    // put your main code here, to run repeatedly:

    }

This is my code with LedControl.h it gives me exit status 1 can't compile to arduino uno. Please help.

if I remove #include it works as normal.

also aruino says that the library has been installed.

what I have tried (and didn't work)

re-installing the library.
re-downloading arduino.

body:
I tried compiling your code with Arduino 1.6.12. As you found, without the #include, it compiles OK. With the #include, it fails. Here is the error message I got:

    /var/folders/bl/s5kzhm3s0lb2rcvp3md8c7040000gp/T/untitled1814027053.tmp/sketch_may17a/sketch_may17a.ino:1:24: fatal error: LedControl.h: No such file or directory
     #include <LedControl.h>
                            ^
    compilation terminated.
    exit status 1
    Error compiling for board Arduino/Genuino Uno 115.2.

The error - at least in my case - is that the library, LedControl.h, was not found. Try to find out why not.

> also aruino says that the library has been installed.

It's easy to check: "Installing" library `foo.h`, only means your sketchbook folder contains a library folder called `libraries` (all lower case); `libraries` contains a folder `foo`; and `foo` contains the file `foo.h` and any other files necessary for that library, such as a `foo.cpp` if needed:

    - Sketchbook - libraries - foo
                                 foo.h
                                 foo.cpp
                                 anything.else.you.like

Update:

The library documentation [is on github][1] and has links to some sample code. Sorry I can't be more help - I haven't used the library or those LED devices.

  [1]: http://wayoda.github.io/LedControl/


message:
Concatenate integers as string

How can i concatenate integers as a single string?

    int out1, out2, out3 = 0;

        out1 = digitalRead(r1);
        out2 = digitalRead(r2);
        out3 = digitalRead(r3);

I tried like so, between others, with no luck.

    Serial.write(out1 + "" + out2 + "" + out3);

For example the expected result when all outputs are `HIGH` should be `111`, while when only the `r3` output is `HIGH` it should be `001`

All i want, is reporting to the sender of the serial command, the pins state

body:
If you're just outputting to serial you don't need to concatenate - just print each bit separately, such as:

    Serial.print(out1);
    Serial.print(",");
    Serial.print(out2);
    Serial.print(",");
    Serial.println(out3);

You should avoid using String as it's not good on devices with small amounts of memory like Arduinos. Instead if you really need to concatenate numbers you should use a C string and maybe `snprintf` to format the numbers into it:

    char out[30];
    snprintf(out, 30, "%d,%d,%d", out1, out2, out3);


body:
I second Majenko's points about just printing the bits separately if
possible, and avoiding `String` objects.

However, if you do need to build such a string (not String object, just
plain C string), you don't need `sprintf()`, which is quite a big
function: you can build the string character by character. For example:

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

    char out[4];  // 3 + 1 char for the termination character
    out[0] = out1==HIGH ? '1' : '0';
    out[1] = out2==HIGH ? '1' : '0';
    out[2] = out3==HIGH ? '1' : '0';
    out[3] = '\0';  // add NUL termination
    Serial.println(out);

This is using the [ternary operator][], which here means “if `out1` is
`HIGH`, then use the character `'1'`, otherwise use `'0'`”.

Now, it just happens that in Arduino `HIGH` means 1 and `LOW` means 0.
And single digit numbers can be converted into character by just adding
the numeric code of character “0”, which is 48 but can written as `'0'`
in C++. Thus you can write:

    out[0] = out1 + '0';  // convert number to character

And you can put all together as:

    char out[4];  // 3 + 1 char for the termination character
    out[0] = digitalRead(r1) + '0';
    out[1] = digitalRead(r2) + '0';
    out[2] = digitalRead(r3) + '0';
    out[3] = '\0';  // add NUL termination
    Serial.println(out);

[ternary operator]: https://en.wikipedia.org/wiki/?:#C


body:
Serial.write(b) prints one byte not a string. Use print() to print strings and numbers.

    Serial.print(digitalRead(r1));
    Serial.print(digitalRead(r2));
    Serial.println(digitalRead(r3));


message:
Reducing Clock Speed increases sketch size?

I just lowered the clock speed of my arduino promini 3.3v - 328p from 8Mhz to 1Mhz on the external clock disabling the brounout detection and when I compiled I my old sketch it wouldn't upload any more because suddenly the size has increased from 31KB to 35KB.

Does anyone know why this could happen. I didn't make any changes in the code and it still loads into the 8Mhz Arduino without any problems.

I used these low power config files: https://github.com/joe-speedboat/Arduino-LowPower

body: Does your code have delays in it? If you changed the clock speed, then the compiled assembly for the delays may require more NOP instructions or something similar to achieve the same real-time delay. As a result, the size of the compiled sketch could increase.


message:
Connecting two sensors with bluetooth

I am new with Arduino. Im working in a school project, and I decided to create a glove with shock sensor for goalkeepers and need a ultrasonic sensor next to the ball, so i can know when the ball was kicked.

I need the data from both sensor.

Is this possible with only 1 arduino?, where the arduino is with the ultrasonic sensor and the shock sensor is connected with a bluetooth module to send it to the arduino.

Or, I have to use 2 arduinos?, one with with the glove and the other with the ultrasonic sensor and connect both with bluetooth?

If this is not the best way, can you help me with some ideas to do it? Thank you.

body:
This to be possible with only 1 Arduino depends in your sensor. It is most likely not possibpe without another microcontroller (not nesessarily an Arduino) because of the following reason.

Most bluetooth modules on the market (linke the HC-05 vor HC-06) are bluetooth serial modules, meaning that they build a serial connection over bluetooth and provide the corresponding two pins (RX and TX). Yet most sensors don't implement an UART interface (the `Serial` interface in Arduino), but only give an analog or digital output voltage. With much work you might be able to tweak the firmware of the bluetooth chip for reading and sending a digital value, but this would be more work, than the price of a second microcontroller would justify.

So I would try to add a small microcontroller (like an ATTiny85) to the sensors side. It can measure the sensors output voltage and then send it via `Serial` to the bluetooth module. You might also want to use another Arduino here, though this might be an overkill. Maybe a really small version.

---

After some thinking I had the idea, that it might be possible to send an analog voltage from the sensor through a audio bluetooth module without using another Arduino. Though I'm not sure if this really would work and which module you need for that.

All in all I still would go for the extra microcontroller and serial interface bluetooth, because it is much easier for a beginner.

EDIT:

Above I mentioned using `Serial` on an ATTiny85, which is not directly possible, since it does not have a full UART hardware (but only a USI). Though you can use the standard `SoftwareSerial` library on it. If the rest of your code isn't to big, it should still fit in the small memory of the Tiny.


message:
Sending a character 'A' through blinking led

>How do i code to send a character 'A' to the arduino through a blinking led?
 i am doing a project about data transmission. i really need help&some guide.
 Material used are arduino uno r3,white led and a resistor.

MY OUPUT IN SERIAL MONITOR

Insert letter:

01000001 65  - Character A

00001010 10  - when i send/enter

   CODE

     int LEDTrans = 13;
    int timeWaitOn = 1000; //milisec (1 sec)
    int timeWaitOff = 1000; // milisec (1 sec)
    byte byteRead;

    void setup() {
    // Turn the Serial Protocol ON
      Serial.begin(9600);

     Serial.print("Insert letter:");
     Serial.println(" ");
    }

    void loop() {

    digitalWrite(LEDTrans,HIGH); //turn the led on
    delay(timeWaitOn); //delay in millisec (1 sec)
    digitalWrite(LEDTrans,LOW); //turn the led off
    delay(timeWaitOff); //wait a sec

       /*  check if data has been sent from the computer: */
      if (Serial.available()) {

         byteRead = Serial.read();
        // will print the binary representation of 'byteRead' as 8 characters of '1's and '0's, MSB first.
    for ( uint8_t bitMask = 128; bitMask != 0; bitMask = bitMask >> 1 ) {

          if ( byteRead & bitMask ) {

        Serial.write('1');
      } else {
        Serial.write('0');
      }
    }

    Serial.write("    ");
    Serial.println(byteRead);    //send back the actual ASCII code
    }

    }

body:
Instead of printing '0' or '1' set the LED pin off or on, like this:

    const int LEDTrans = 13;
    const int timeWaitOn = 1000;  // millisec (1 sec)
    const int timeWaitOff = 1000; // millisec (1 sec)

    void setup() {
      // Turn the Serial Protocol ON
      Serial.begin(115200);
      Serial.println("Send letter:");
      pinMode (LEDTrans, OUTPUT);
    }

    void loop() {
      /*  check if data has been sent from the computer: */
      if (Serial.available()) {
        byte byteRead = Serial.read();
        // will print the binary representation of 'byteRead' as 8 characters of '1's and '0's, MSB first.
        for ( uint8_t bitMask = 128; bitMask != 0; bitMask >>= 1 ) {
          if ( byteRead & bitMask ) {
            digitalWrite(LEDTrans, HIGH); //turn the led on
            delay(timeWaitOn); //delay in millisec (1 sec)
            digitalWrite(LEDTrans, LOW); //turn the led off
          } else {
            delay(timeWaitOff); //wait a sec
          } // end of if
        } // end of for loop
      } // end of if something available
    } // end of loop

---

> how do i count the flashes? is it based on the binary 01000001?

Here's the problem ... according to what your question seems to ask for, you are wanting an LED to flash for a 1 and be off for a zero. So the results (which my code provides) would look like this:

[![Example 1][1]][1]

So, you get two flashes, the first one second after it starts, then there is a gap of 5 seconds, and then another flash. That would be 01000001.

However, how do you know when to start counting flashes? It might be:

[![Example 2][2]][2]

That would be 00000001.

Or even:

[![Example 3][3]][3]

That would be 10000010.

You can see, can't you, that you can't make any meaningful deduction at the receiving end about what the character is?

---

So what asynchronous serial (normal serial on an Arduino) does is have a **Start Bit** which signals when to start counting, like this:

[![Serial with start bit][4]][4]

Normally the serial port is high (continuous 1s) and then when a 0 arrives that means "start counting". So, you wait 1½ bits of time and then sample at the known baud rate. In your example, where you want 1 second per bit, the baud rate would be 1 (one bit per second). Thus, you sample every one second. Normally baud rates are somewhat faster than that, like 9600 or 115200 samples per second.

Also there is a **Stop Bit** which is always a 1. This guarantees that there will be at least a single 1 at the end of each byte, so that we can tell when the next start bit arrives.

---

There are *other ways of doing this*, for example a short pulse might represent a zero, and a longer pulse represent a one. In that case, any pulse at all could represent the start of a byte, and then you just measure how many short pulses, and how many long pulses, you get (for some definition of "short" and "long").

  [1]: https://i.stack.imgur.com/U5Eii.png
  [2]: https://i.stack.imgur.com/psjFT.png
  [3]: https://i.stack.imgur.com/oYpcz.png
  [4]: https://i.stack.imgur.com/zrBke.png


message:
Turn on LEDS one after another

I am trying to turn on LEDs one after the other so that I can start at one end and slowly turn the LEDs until it reaches the middle of the strip. The code works coming from the end of the LED strip, but not when coming from the start of the strip. From the start of the strip, it just turns on all the LEDs up until the midpoint.
<!-- language-all: lang-cpp -->

    int midpoint = 30;
    int R = 255;
    int G = 0;
    int B = 0;
    for(int j = 0; j<midpoint; j++){
         //starting from the end, filling towards the middle
            for(int k = NUM_LEDS-j; k < NUM_LEDS; k++){
               leds[k] = CRGB (R, G, B);
            }
    //there's some other code here in the interim
    FastLED.show();
    delay(20);
         //starting from the beginning, filling towards the middle
         //this is the section of code that doesn't work correctly
            for(int l = j - 1; l < midpoint; l++){
               leds[l] = CRGB (R, G, B);
               }
    //more interim code
    FastLED.show();
    delay(20);
    }

body:
Okay so i figured it out. The problem is that the `for` loop is starting at 0 and counting all the way up to the midpoint. What I wanted is for it to light all the LEDs that are at `j` and below. So I changed it to iterate down instead of up. Here's the new loop:

    for(int l = j; l < midpoint & l > -1; l--){
       leds[l] = CRGB (R, G, B);
    }

The extra qualifier `l > -1` is to make sure that it doesn't try to go below `leds[0]`


message:
Scan Bluetooth devices using HC-05

Basically, I want to connect the HC-05 to a specific mobile Bluetooth(whose address is known) and when the connection is established I want to turn on a LED on the breadboard.
I am totally clueless how to write the code. Can you please help me with it as it is a part of my project.

I know the various AT commands and have scanned the Bluetooth address with AT+INQ command.

body:
If you are using an Arduino board with HC-05 for AT commands over serial, you can follow the below flow :

1. Setup HC-05
2. Check for available nearby devices `AT+IRQ`
3. Check the response to check is the desired device is enlisted in the nearby devices
4. If device is enlisted, use `AT+BIND=<Bluetooth address>` to connect to the other device
5. Check the response of the `AT+STATE?` command until you receive “CONNECTED” (you can go for a while loop here)
6. Once the connection is successfully established here, you can send a confirmation now as per your requirement.

The above scenario is applicable only when you are sure with the Bluetooth address of the device you want to connect to. If the scenario is something different, comment and let us know with the actual requirement.


message:
Error: "undefined reference to ..." when calling non-void class' functions from within class

I haven't used an Arduino for anything as complicated as this project before (single sketch projects so far), and am struggling getting my code to compile now that I'm creating my own libraries for the project.

I can see that it's the class' methods that return something that cause an issue, those that directly edit the classes variables instead don't appear to cause issues when compiling (i.e. void functions).

I can't share the actual code, but here's an altered and stripped down version that shows the same issue.

The sketch:

    //Issues.ino

    #include "CmdLib.cpp"

    void setup() {
      //Setup USB
      Serial.begin(19200);
      Serial.flush();

      //Setup Bluetooth
      Serial0.begin(9600);
      Serial0.flush();
    }

    void loop(){
      CheckForPCMessages();       //Parses any messages from USB and Bluetooth
      //All the other things we need to do
    }

    void CheckForPCMessages(){
      CheckForMessages(&Serial);  //Check USB first
      CheckForMessages(&Serial0); //Then check Bluetooth
    }

    template <class T> void CheckForMessages(T *port){
      //Using function template so that works for USB and Hardware Serial
      if(port->available() != 0){
        String received_string = port->readStringUntil('\n');
        port->flush();
        Serial.print(received_string);
        Serial.println(" was received.");
        Command received_cmd(received_string);
        //Do stuff with the command (add it to a Q, etc, etc)
      }
    }

The Header:

    //CmdLib.h

    #ifndef CmdLib_h
    #define CmdLib_h

    #include "Arduino.h"

    enum CommandLabel{
      //Not a command
      NO_COMMAND = 0,

      //...
      //A whole bunch of other options that I can't share
      //...
    };

    enum CommandType{
      NA = 0,
      //...
      //A whole bunch of other options that I can't share
      //...
    };

    class Command{
      public:
        Command(String msg);
        String GetCmdStringFromMessageString(String full_string);
        CommandLabel GetLabelFromString(String labelstr);
        void SetLabelAndType(String labelstr);
        void SetLabel(CommandLabel label);
        void SetType(CommandLabel label);

      private:
        String _x = "";
        String _y = "";
        String _z = "";
        CommandLabel _label = NO_COMMAND;
        CommandType _type = NA;
    };

    #endif

The cpp file:

    //CmdLib.cpp

    #include "CmdLib.h"

    Command::Command(String msg){
      String labelstr = Command::GetCmdStringFromMessageString(msg); //Separates label from msg
      Command::SetLabelAndType(labelstr); //Sets _label & _type vars
    }

    String GetCmdStringFromMessageString(String full_string){
      //Pulls out everything before first comma
      int first_comma = full_string.indexOf(',');
      String output;
      if(first_comma != -1){
        output = full_string.substring(0,first_comma);
      }
      else{
        output = full_string;
      }
      return output;
    }

    void Command::SetLabelAndType(String labelstr){
      CommandLabel label = GetLabelFromString(labelstr);  //Get label from string
      Command::SetLabel(label);                           //Set label
      Command::SetType(label);                            //Set type based on label
    }

    CommandLabel GetLabelFromString(String labelstr){
      //...
      //Cleverness to determine which to return...
      //...
      return NO_COMMAND;
    }

    void Command::SetLabel(CommandLabel label = NO_COMMAND){
      _label = label;
    }

    void Command::SetType(CommandLabel label){    //Set _type to appropriate type based upon label
      //...
      //Cleverness to determine which to return...
      //...
      _type = NA;
      return;
    }

And here's the Error:

>sketch\CmdLib.cpp.o: In function `Command::SetLabelAndType(String)':
>
>[REDACTED]/temp/arduino_build_557572/sketch/cmdlib.cpp:24: undefined reference to `Command::GetLabelFromString(String)'
>
>sketch\CmdLib.cpp.o: In function `Command::Command(String)':
>
>[REDACTED]/temp/arduino_build_557572/sketch/cmdlib.cpp:6: undefined reference to `Command::GetCmdStringFromMessageString(String)'
>
>collect2.exe: error: ld returned 255 exit status
>
>exit status 255
>Error compiling for board Fubarino Mini.

I've found previous answers where the same compile error occurred with class *variables* that were called to without being given an initial value, but can't find similar solutions for the error when created by a call to a *function*.

Any help would be greatly appreciated.

body:
You forgot to put the function in the class:

    CommandLabel GetLabelFromString(String labelstr){

should be:

    CommandLabel Command::GetLabelFromString(String labelstr) {

Also, on a side note, if you *must* use `String` objects (ugh!) then *please* pass them as reference so as to avoid needless heap allocation and data copying:

    CommandLabel Command::GetLabelFromString(String &labelstr) {


message:
Find Elapsed Time on Serial Plotter

How do I find out the elapsed time from the serial Plotter graph? I am plotting sensor values from the Arduino Nano and would like to know the time scale on the x-axis in order to calculate settling time of oscillations.
I have tried the suggestions [here][1] but they do not seem to work in my case.

For example, in the graph below I would like to find out the time it took for the sensors to record their first movement at around point 190.

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

I am doing the following to print two values:

       //printData1();
       Serial.print(roll_err);
       Serial.print(" ");
       Serial.println(pitch_err);
       Serial.print(" ");

Baud Rate: 9600
Loop Time: 40ms

If my loop time is 40ms then I was thinking that the total time would be 180*40ms. Is this reasoning correct?

Is there a better way to read the time elapsed in the serial plotter?

**EDIT: Trying to get a 10ms 'grid'**

As per the suggestion in the answer below I have tried running something similar to the following but the loop does not run at a constant time.

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

I tried to add `Serial.print(((millis()/10)%2)*50);` but as can be seen, the loop time is not constant.
[![enter image description here][4]][4]

  [1]: https://arduino.stackexchange.com/questions/34854/x-and-y-axis-on-arduino-serial-plotter
  [2]: https://i.stack.imgur.com/hEg7F.jpg
  [3]: https://i.stack.imgur.com/7pj4E.jpg
  [4]: https://i.stack.imgur.com/Ey2Nc.jpg

body:
It depends on how precise you want your time-base to be. The plotter's x-axis is in sample-count, not time, so you have to emit samples at a fixed rate for it to have time-significance.

Your

    loop(){
       yadda();
       zadda();
    }

may or may not run at a constant rate, depending on what takes place in each iteration of the loop, as well as on your definition of "constant" (I don't believe I just said that...)

Even if none of your code is conditional, binary to ASCII conversion, clock and Serial interrupts, and other low-level code we don't see, may run slightly differently from iteration to iteration; e.g. the number of interrupts during any given iteration may well vary.

If you need to hold a tighter timebase, stalling at the bottom of the loop until millis() reaches (the previous millis() + an interval constant) will at least get you to within a millisecond of a fixed loop-rate. You could, of course, do the same thing with micros(), as long as you know for a fact that the loop can never take longer to execute than 1/frequency you need it to run at, and even then, it should take a fair slop-factor (that's a technical term! :) less than that, "just in case".

Update:

Though I wrote "stalling" at the end of the loop, a better technique is to call every job (in your case, 1 of them - for now ? ) as frequently as possible and let each job decide whether it needs to execute. So in your case:

    loop {
      maybeSampleAndPlot();
      // maybeDoSomeOtherThing();  // not implemented yet...
    }

    maybeSampleAndPlot(){
      time = millis();
      if time - previousSampleTime >= MSEC_040
        save (time + MSEC_040) as nextSampleTime;
        sample the data;
        plot the data;
      endif
    }


message:
Batteries and amps in parralel

So, i am about to buy a brushless motor a ESC and a 18650 batteries for my arduino.

The batteries "specs" is 3.7v and 20a, if i would to put 2 and more in parallel would i get 7.4v 20a or 7.4v 40a?

Thanks.

body:
In parallel you'd get 3.7V 40A

What I think you mean is in **series**. That way you get 7.4V 20A.


body: Series connection of battery adds voltage not current but parallel connection keeps the voltage same. Current may be increased with some condition.  One things should be remembered 20 a current is huge it is not required by arduino. May be for some welding device it needs that current which can be controlled by high current mosfet


message:
Optimal and Safe Water Pump Control

I'm using an Arduino Micro, a 12 V water pump, and a print relay to water a plant.

A water level switch monitors the the water tank to make sure the water pump does not run dry.

I tried different watering times and figured that when using longer watering times of 90,000 milliseconds and longer, the relay sometimes does not switch correctly and the pumps keeps running. I'm not sure if my code is optimal for that kind of purpose:

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

    const int Power_Water = 3; // Pin to turn the Pump On and Off via relay
    const int Watering_Time = 90000; // Time the water's supposed to run
    const int Water_Tank = 10; // Water Level Switch

    void setup() {
      Serial.begin(9600);
      pinMode(Power_Water,OUTPUT); // Pin that triggers the Relay as Output
      pinMode (Water_Tank,INPUT_PULLUP); // Pin of Water_Level Sensor as internal pullup
    }

    void loop () {
      unsigned long watering_Start = millis();

      while (millis() - watering_Start <= Watering_Time && (digitalRead (Water_Tank) == LOW)) {
        digitalWrite(Power_Water,HIGH); // Water Pump goes ON
        Serial.println(millis() - watering_Start);
      }

      if (millis() - watering_Start > Watering_Time || (digitalRead (Water_Tank) == HIGH)) {
        Serial.println("Pump OFF");
        digitalWrite(Power_Water,LOW);// Water Pump OFF
       }
       delay(100000000); // example "sleep" time the system is not supposed to water
    }

Any suggestions are appreciated.

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

    const int Power_Water = 3; // Pin to turn the Pump On and Off via relay
    const long Watering_Time = 90000; // Time the water's supposed to run
    const long Water_Tank = 10; // Water Level Switch

    void setup() {
      Serial.begin(9600);
      pinMode(Power_Water,OUTPUT); // Pin that triggers the Relay as Output
      pinMode (Water_Tank,INPUT_PULLUP); // Pin of Water_Level Sensor as internal pullup
    }

    void loop () {
      unsigned long watering_Start = millis();
      digitalWrite(Power_Water,HIGH);
      while (digitalRead(Power_Water) == HIGH) {
        Serial.println(millis() - watering_Start);
        if (millis() - watering_Start > Watering_Time || (digitalRead (Water_Tank) == HIGH)) {
          Serial.println("Pump OFF");
          digitalWrite(Power_Water,LOW);
        }
      }
      delay(100000000); // example "sleep" time the system is not supposed to water
    }

body: That delay statement totally defeats the purposes of your millis code.  If you want to enforce a minimum off time then you'll have to do that with millis as well.  Using millis in this way requires that you allow the loop function to repeat many thousands of times per second.  As written you only allow the loop function to run through once every eleven and a half days.


message:
Running dual Adafruit GPS at 10Hz on a Teensy 3.2

Excuse the crudity of this question but I'm having quite the trouble trying to run the two **Adafruit Ultimate GPS v3** modules at **10Hz** on the **Teensy 3.2 board**. The modules are connected over the hardware serial ports 1 and 3. There is also an **IMU (MPU6050)** connected over the I2C interface.

> Aim:
> -----
> -To determine the difference between the course over ground and the body attitude (yaw) of a vehicle
>
> Issues:
> --------
> -By default, the GPS modules only run at 1Hz and at 9600 baud. I'm sending the required PMTK commands over their respective serial ports
> 1 and 3 to increase those to 10Hz and 115200 baud. I'm using hardware
> serial because the SoftwareSerial library was messing up the
> interrupts for the I2C interface and wasn't reliable at the baud rate
> required for 10Hz.
>
> -When using the TinyGPS++ library, it seems that the received chars for the GPS 1 and 2 modules were the same, which led me to believe
> that it wasn't behaving correctly, and I was getting no fixes. Since I
> also need to run a Kalman filter for each GPS module at 10Hz (which
> might not work at that speed on the Teensy), I switched to the NeoGPS
> library, which I'm told, requires much less system resources and is
> much faster.
>
> -The NeoGPS library also does not return any successful fix messages due to possibly being misconfigured (I'm using the default
> configuration files)
>
> Below is the code I'm using with the TinyGPS++ library (sans the IMU
> parts)
>
> With this, I'm only getting stars (*), and the same number of received
> characters for both GPS 1 and 2, hence my assumption that it is
> faulty;

    #include <TinyGPS++.h>

        static const uint32_t GPSBaud = 115200;

        // The TinyGPS++ object
        TinyGPSPlus gps;

        void setup()
        {
          // The serial connection to the GPS device
          #define GPS_1_Serial Serial1
          #define GPS_2_Serial Serial3
          GPS_1_Serial.begin(9600);
          GPS_1_Serial.write("$PMTK220,100*2F\r\n");
         //switch the GPS baud rate to 115200
          GPS_1_Serial.write("$PMTK251,115200*27\r\n");
         //change baud rate of serial port to 38400
          GPS_1_Serial.flush();
          delay(10);
          GPS_1_Serial.end();

          GPS_2_Serial.begin(9600);
          GPS_2_Serial.write("$PMTK220,100*2F\r\n");
         //switch the GPS baud rate to 115200
          GPS_2_Serial.write("$PMTK251,115200*27\r\n");
         //change baud rate of serial port to 38400
          GPS_2_Serial.flush();
          delay(10);
          GPS_2_Serial.end();

          Serial.begin(115200);

          while (!Serial);
          Serial.println(TinyGPSPlus::libraryVersion());
          Serial.println();
          Serial.println(F("   Fix  Date       Time     Date    Course Speed Card  Chars Sentences Checksum"));
          Serial.println(F("   Age                      Age     --- from GPS ----  RX    RX        Fail"));
          Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

        }

        void loop()
        {
          static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
        //GPS________________________________________________________GPS_1___________________________________________________________________
          GPS_1_Serial.begin(GPSBaud);
          Serial.println("Listening to GPS_1");

          printDateTime(gps.date, gps.time);

          printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
          printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
          printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.deg()) : "*** ", 6);

          printInt(gps.charsProcessed(), true, 6);
          printInt(gps.sentencesWithFix(), true, 10);
          printInt(gps.failedChecksum(), true, 9);
          Serial.println();

          if (millis() > 5000 && gps.charsProcessed() < 10)
            Serial.println(F("No GPS data received: check wiring"));
          smartDelay(100);
          GPS_1_Serial.end();
        // ---------------------------------GPS_2----------------------------

          GPS_2_Serial.begin(GPSBaud);

          Serial.println("Listening to GPS_2");

          printDateTime1(gps.date, gps.time);

          printFloat1(gps.course.deg(), gps.course.isValid(), 7, 2);
          printFloat1(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
          printStr1(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.deg()) : "*** ", 6);

          printInt1(gps.charsProcessed(), true, 6);
          printInt1(gps.sentencesWithFix(), true, 10);
          printInt1(gps.failedChecksum(), true, 9);
          Serial.println();

          if (millis() > 5000 && gps.charsProcessed() < 10)
            Serial.println(F("No GPS data received: check wiring"));

          smartDelay1(100);
          GPS_2_Serial.end();

        }

        // This custom version of delay() ensures that the gps object
        // is being "fed".
        static void smartDelay(unsigned long ms)
        {
          unsigned long start = millis();
          do
          {
            while (GPS_1_Serial.available())
              gps.encode(GPS_1_Serial.read());
          } while (millis() - start < ms);
        }

        static void smartDelay1(unsigned long ms)
        {
          unsigned long start = millis();
          do
          {
            while (GPS_2_Serial.available())
              gps.encode(GPS_2_Serial.read());

          } while (millis() - start < ms);
        }

        static void printFloat(float val, bool valid, int len, int prec)
        {
          if (!valid)
          {
            while (len-- > 1)
              Serial.print('*');
            Serial.print(' ');
          }
          else
          {
            Serial.print(val, prec);
            int vi = abs((int)val);
            int flen = prec + (val < 0.0 ? 2 : 1); // . and -
            flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
            for (int i=flen; i<len; ++i)
              Serial.print(' ');
          }
          smartDelay(0);
        }

        static void printFloat1(float val, bool valid, int len, int prec)
        {
          if (!valid)
          {
            while (len-- > 1)
              Serial.print('*');
            Serial.print(' ');
          }
          else
          {
            Serial.print(val, prec);
            int vi = abs((int)val);
            int flen = prec + (val < 0.0 ? 2 : 1); // . and -
            flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
            for (int i=flen; i<len; ++i)
              Serial.print(' ');
          }
          smartDelay1(0);
        }

        static void printInt(unsigned long val, bool valid, int len)
        {
          char sz[32] = "*****************";
          if (valid)
            sprintf(sz, "%ld", val);
          sz[len] = 0;
          for (int i=strlen(sz); i<len; ++i)
            sz[i] = ' ';
          if (len > 0)
            sz[len-1] = ' ';
          Serial.print(sz);
          smartDelay(0);
        }

        static void printInt1(unsigned long val, bool valid, int len)
        {
          char sz[32] = "*****************";
          if (valid)
            sprintf(sz, "%ld", val);
          sz[len] = 0;
          for (int i=strlen(sz); i<len; ++i)
            sz[i] = ' ';
          if (len > 0)
            sz[len-1] = ' ';
          Serial.print(sz);
          smartDelay1(0);
        }

        static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
        {
          if (!d.isValid())
          {
            Serial.print(F("********** "));
          }
          else
          {
            char sz[32];
            sprintf(sz, "d/d/d ", d.month(), d.day(), d.year());
            Serial.print(sz);
          }

          if (!t.isValid())
          {
            Serial.print(F("******** "));
          }
          else
          {
            char sz[32];
            sprintf(sz, "d:d:d ", t.hour(), t.minute(), t.second());
            Serial.print(sz);
          }

          printInt(d.age(), d.isValid(), 5);
          smartDelay(0);
        }

        static void printDateTime1(TinyGPSDate &d, TinyGPSTime &t)
        {
          if (!d.isValid())
          {
            Serial.print(F("********** "));
          }
          else
          {
            char sz[32];
            sprintf(sz, "d/d/d ", d.month(), d.day(), d.year());
            Serial.print(sz);
          }

          if (!t.isValid())
          {
            Serial.print(F("******** "));
          }
          else
          {
            char sz[32];
            sprintf(sz, "d:d:d ", t.hour(), t.minute(), t.second());
            Serial.print(sz);
          }

          printInt(d.age(), d.isValid(), 5);
          smartDelay1(0);
        }

        static void printStr(const char *str, int len)
        {
          int slen = strlen(str);
          for (int i=0; i<len; ++i)
            Serial.print(i<slen ? str[i] : ' ');
          smartDelay(0);
        }

        static void printStr1(const char *str, int len)
        {
          int slen = strlen(str);
          for (int i=0; i<len; ++i)
            Serial.print(i<slen ? str[i] : ' ');
          smartDelay1(0);
        }

> This is the NeoGPS library version I've attempted, which does not
> output any indication that it is working successfully;

    #include <NMEAGPS.h>

    static const uint32_t GPSBaud = 115200;

    // NMEAGPS object
    NMEAGPS gps;

    void setup()
    {

      // The serial connection to the GPS device
      #define GPS_1_Serial Serial1
      #define GPS_2_Serial Serial3
      GPS_1_Serial.begin(9600);
      GPS_1_Serial.write("$PMTK220,100*2F\r\n");
     //switch the GPS baud rate to 115200
      GPS_1_Serial.write("$PMTK251,115200*27\r\n");
     //change baud rate of serial port to 38400
      GPS_1_Serial.flush();
      delay(10);
      GPS_1_Serial.end();
      GPS_1_Serial.begin(GPSBaud);

      GPS_2_Serial.begin(9600);
      GPS_2_Serial.write("$PMTK220,100*2F\r\n");
     //switch the GPS baud rate to 115200
      GPS_2_Serial.write("$PMTK251,115200*27\r\n");
     //change baud rate of serial port to 38400
      GPS_2_Serial.flush();
      delay(10);
      GPS_2_Serial.end();
      GPS_2_Serial.begin(GPSBaud);

      Serial.begin(115200);

      while (!Serial);
      Serial.println();
      //Serial.println(F("  Time     Date    Course Speed Card  Chars Sentences Checksum"));
      //Serial.println(F(""));
      Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

    }

    void loop()
    {

    //GPS________________________________________________________GPS_1___________________________________________________________________

      Serial.println("Listening to GPS_1");
      while (gps.available(GPS_1_Serial)) {
        gps_fix fix_1 = gps.read();
        if (fix_1.valid.location){
          Serial.println("Successful Location");
        }
        if (fix_1.valid.time) {
          Serial.println("Successful Time");

        }
      }

      Serial.println();

    // ---------------------------------GPS_2----------------------------

      Serial.println("Listening to GPS_2");
      while (gps.available(GPS_2_Serial)) {
        gps_fix fix_2 = gps.read();
        if (fix_2.valid.location){
          Serial.println("Successful Location");
        }
        if (fix_2.valid.time) {
          Serial.println("Successful Time");

        }
      }

    }

I'm still a beginner when it comes to programming with an Arduino, and I appreciate any assistance to get on the right track.

Thank you for reading

Yours faithfully,

Cem Huray

body:
What is processing_style in NMEAGPS ? My understanding is there is a PS_POLLING style that may not work well with two GPSes and PS_INTERRUPT, that I'm not sure can handle Teensy well.

Have you tried to read directly from the Serial without any library ? When it's working, you can try to plug the library back (or parse the strings from GPS, which is quite easy).


body:
You just need two instances of the parser, too:

    NMEAGPS gps_1, gps_2;

           ...

    //___________________GPS_1______________________

      //Serial.println("Listening to GPS_1");  <-- don't print too much!
      while (gps_1.available(GPS_1_Serial)) {
        gps_fix fix_1 = gps_1.read();
              ...

    //___________________GPS_2______________________

      //Serial.println("Listening to GPS_2");  <-- don't print too much!
      while (gps_2.available(GPS_2_Serial)) {
        gps_fix fix_2 = gps_2.read();
              ...

Also answered on the Arduino forum [here](https://forum.arduino.cc/index.php?topic=548264.msg3738878#msg3738878).


message:
Arduino Micro interference between analog inputs

I'm building a MIDI controller with the Arduino Micro, hooking a bunch of knobs up to the analog inputs. Currently, I'm getting analog in 9 being influenced by analog in 10: `analogRead(9)` returns a number close to `analogRead(10)` and doesn't give the voltage that I'm reading with a multimeter.

What could be causing this interference?

body:
I looked around for a while and eventually thought to put the multimeter probe on the top pin instead of on the soldered header, and got no voltage across it.

If you're experiencing a strange interference between two analog inputs, double-check your solder joints again, one of your inputs might be floating (not connected to high or ground).


message:
Atmel atmega32u4 not recognized when connected by usb after attempting to flash new bootloader

I am making a mechanical keyboard using Atmel's pro micro as the controller.  I decided I would try to replace it's bootloader, as the one it ships with doesn't seem compatible with QMK's RESET keycode (which is supposed to put the controller into DFU mode).

Clearly I didn't know what I was doing, as the controller no longer seems to be recognized when I plug it in via USB - MicroUSB.

If I recall correctly, this is the command I used to attempt to flash the bootloader:

"sudo avrdude -p atmega32u4 -P /dev/ttyACM0 -c avr109 -U flash:w:Caterina-promicro16.hex"

At this time, it seems likely to me that the issue is that I over-wrote the bootloader (or some portion of it) and failed to replace it with an appropriate alternative.  Is this correct?  Is there any way to correct my error through a USB-MicroUSB connection at this point, or will I need to buy some sort of programmer?  All the leds light up.

body:
You cannot load the bootloader over USB, that job needs to be done with an in-serial-programmer (ISP).  You could have stopped the board working if you wrote the wrong fuses, e.g. different clock frequency.

Flashing the bootloader via ISP can be done with the Arduino IDE and there are lots of tutorials on the web.  Try it, will probably work for you.


message:
how to use mouse.h library for arduino uno

I want to use mouse.h library with arduino but mouse.h library only for Leonardo not UNO . How to use mouse.h for UNO if not
can we convert arduino UNO to Leonardo ?

body:
The only way to use Mouse.h on an Arduino is to use it on a compatible Arduino. You cannot "convert" an Uno into a Leonardo, since you would have to not only replace the MCU on the board (with one that is SMD only), you would have to replace the PCB itself as well. I.e., throw away the Uno and replace it with a Leonardo.

The Mouse.h (and Keyboard.h) requires an MCU with a built-in USB interface, such as the ATMega32U4 that the Leonardo has. The ATMega328p does *not* have such an interface (note: the "U" in the name kind of gives it away...).

However, all is not lost.  The Uno *does* have a chip on it with a "U" in the name (as long as it's a *genuine* Arduino board and not a cheap Chinese clone with a CH340G chip).  That chip, used to interface the ATMega328p to the PC through USB, can be reprogrammed to look like different devices, however doing so can break your ability to then program the Arduino itself.

You can read more about hacking your Arduino to be a mouse [here](http://anhnguyen.me/2014/01/turn-arduino-uno-r3-into-a-mouse/).